[英]Unity 3D Instantiated Prefabs stop moving
我建立了一個非常簡單的場景,其中每x秒實例化一個預制件。 我在Update()
函數的實例上應用了一個transform.Translate。 一切正常,直到生成第二個對象,第一個對象停止移動,所有實例停止在我的轉換值上。
這是我的腳本,附加到一個空的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);
}
}
}
您的移動發生在Update()中的prefabInstance對象上,但是,在創建第二個實例時該對象將被覆蓋,因此只有您最后實例化的預制件將移動。
您應該考慮將代碼分成兩個腳本,第一個腳本生成預制件,第二個腳本實際上在預制件上移動它。
public class Test : MonoBehaviour {
public GameObject prefab;
void spawnEnemy() {
Instantiate(prefab, transform.position, transform.rotation);
}
void Start() {
InvokeRepeating ("spawnEnemy", 1F, 1F);
}
}
並將此腳本放在您的預制件上:
public class Enemy : MonoBehaviour {
void Update () {
transform.Translate (new Vector3(4,0,0) * Time.deltaTime);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.