简体   繁体   中英

Unity 3D Instantiated Prefabs stop moving

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);
        }
    }
}

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);
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM