Unity 3D Instantiated Prefabs stop moving

1.5k views Asked by At

I set up a pretty simple scene where a prefab is being instantiated every x seconds. I applied a transform.Translate on the instances in the Update() function. Everything works fine until a second object is spawned, the first one stops moving and all the instances stop at my translate value.

Here is my script, attached to an empty GameObject:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
    public GameObject prefab;
    private Transform prefabInstance;

    void spawnEnemy() {
        GameObject newObject = (GameObject)Instantiate(prefab.gameObject, transform.position, transform.rotation);
        prefabInstance = newObject.transform;
    }

    void Start() {
        InvokeRepeating ("spawnEnemy", 1F, 1F);
    }

    void Update () {
        if (prefabInstance) {
            prefabInstance.transform.Translate (new Vector3(4,0,0) * Time.deltaTime);
        }
    }
}
1

There are 1 answers

1
peterept On BEST ANSWER

Your movement is occuring on the prefabInstance object in your Update(), however, that object gets overwritten when the second instance is created, so only your last instantiated prefab will move.

You should consider splitting your code into 2 scripts, the first one to spawn the prefab, and the second script actually on the prefab to move it.

public class Test : MonoBehaviour {
    public GameObject prefab;

    void spawnEnemy() {
        Instantiate(prefab, transform.position, transform.rotation);
    }

    void Start() {
        InvokeRepeating ("spawnEnemy", 1F, 1F);
    }
}

and put this script on your prefab:

public class Enemy : MonoBehaviour {

   void Update () {
        transform.Translate (new Vector3(4,0,0) * Time.deltaTime);
        }
}