我正在創建一個玩家控制的對象,它的預制件中有一個腳本,可以突出顯示有效移動的圖塊。如果手動觸發,腳本可以正常工作,但在代碼中無法執行public GameObject player_prefab;Start(){ GameObject playerUnit = GameObject.Instantiate(player_prefab,PlayerPoss,player_prefab.transform.rotation); squadEvents squadScript = (squadEvents)playerUnit.GetComponent(typeof(squadEvents)); squadScript.ShowWalkRange();}在互聯網上挖掘告訴我我的問題是我試圖在啟動期間訪問腳本,但我找不到原因或想出解決方法,感謝您對這些問題的任何幫助
1 回答

慕哥6287543
TA貢獻1831條經驗 獲得超10個贊
需要注意的一點是,一個實例化對象的 Start() 方法直到它的第一次 Update() 方法調用之前才會被調用。如果您在其他對象的 Start() 方法中執行任何初始化,您可以將其移至 Awake() 方法。
也可能是您實際上沒有正確找到組件?如果您使用 GetComponentInChildren,您將在此對象或任何預制子對象上搜索組件。
private void Start()
{
GameObject playerUnit = GameObject.Instantiate(player_prefab,PlayerPoss,player_prefab.transform.rotation);
squadEvents squadScript = playerUnit.GetComponentInChildren<squadEvents>();
if ( squadScript == null )
{
Debug.Log("Could not get <squadEvents> component in this GameObject or any of its children.");
return;
}
squadScript.ShowWalkRange();
}
這是GetComponentInChildren<T>()的 Unity 參考。
- 1 回答
- 0 關注
- 310 瀏覽
添加回答
舉報
0/150
提交
取消