SecretIndividual
SecretIndividual

Reputation: 2549

Spawned object not updating

I am trying to spawn objects that have a component attached to them. The component is:

public class VehicleMover : MonoBehaviour
{
    private float headsetZPosition;

    public float speed = 2.5f;
    private OVRCameraRig cameraRig;   // The OVRCameraRig used in the scene   

    void Update()
    {
        // Get the new Z position of the headset
        headsetZPosition = cameraRig.centerEyeAnchor.position.z;

        if(!collidesWithHeadset() && !collidesWithOtherCar()) {
            transform.Translate(0, 0, speed * Time.deltaTime);
        }

    }

    private bool collidesWithHeadset() {
        return (headsetZPosition - this.transform.position.z) < 5; 
    }

    private bool collidesWithOtherCar() {
        return false; 
    }

    public void init(OVRCameraRig cameraRig) {
        this.cameraRig = cameraRig;
    }
    
}

The above code works great when I place a prefab on the scene and add this component. However when I try to spawn the prefab and set the OVRCameraRig from the spawner the Update() function seems to stop working (does no longer seem to be called). My spawner component (attached to an object in the scene) uses the following function to spawn:

private void spawn() {
        GameObject vehicle = getRandVehicle();
        vehicle.GetComponent<VehicleMover>().init(cameraRig);
        vehicle.GetComponent<VehicleMover>().enabled = true;
        Instantiate(vehicle, new Vector3(-5.7f, 0.05f, -166.0f), transform.rotation);
    }

Does anyone know what I am doing wrong? I added vehicle.GetComponent<VehicleMover>().enabled = true; after I read it could be possible the component is disabled.

Upvotes: 1

Views: 274

Answers (1)

Leoverload
Leoverload

Reputation: 1238

You are creating a copy of the actual vehicle with Instantiate() that's why all of your previous code is not working.

You should Instantiate a vehicle inside a new variable with GameObject vehicleSpawned = Instantiate () as GameObject and after that you can access the components inside it.

With your script, you were just changing the default vehicle from the Rand and then copying a new one.

EDIT EXAMPLE:

GameObject vehicleSpawned = Instantiate(vehicle, position, Quaternion.identity) as GameObject;

and then you could simply change the components of the vehicleSpawned

Upvotes: 3

Related Questions