简体   繁体   English

Unity 3D实例化预制件停止移动

[英]Unity 3D Instantiated Prefabs stop moving

I set up a pretty simple scene where a prefab is being instantiated every x seconds. 我建立了一个非常简单的场景,其中每x秒实例化一个预制件。 I applied a transform.Translate on the instances in the Update() function. 我在Update()函数的实例上应用了一个transform.Translate。 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: 这是我的脚本,附加到一个空的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. 您的移动发生在Update()中的prefabInstance对象上,但是,在创建第二个实例时该对象将被覆盖,因此只有您最后实例化的预制件将移动。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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