Rundown 好吧,傢伙和gals需要一點幫助。基本上我是從一個開放的位置預製一個健康包。經過一段時間後,我試圖摧毀HealthPack,如果它沒有拿起,則將bool healthPackExist設置爲false,並在免費位置實例化另一個HealthPack。銷燬由腳本Unity3d C#中的腳本創建的對象#
問題: 當我試圖訪問遊戲對象被實例化我最終要麼摧毀整個父層次結構或只是擦腳本出來。
解決方案 我試圖破壞根對象,搜索創建的對象的名稱,添加標籤的對象(健康套餐),並尋找它總是得到錯誤。
代碼如下:
public GameObject healthPackPrefab;
public GameObject health;
private float healthTimer;
private bool healthExist;
// Use this for initialization
void Start()
{
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;
}
// Update is called once per frame
void Update()
{
//first check to see if a health pack exist, if not call method to spawn a health pack
//otherwise check to see if one exist and if it does is it's timer created with it
//has been passed by Time.time (returns game clock time), if yes destroy the created
//health pack.
if (healthExist == false)
{
spawnUntilFull();
}
else if (healthExist == true && Time.time > healthTimer)
{
//Error occuring here when trying to destroy
//Destroy(transform.root.gameObject) //destroys script, object scripts on, and prefab
Destroy(this.gameObject); //does same as Destroy(transform.root.gameObject
healthExist = false;
}
}
Transform NextFreePosition()
{
//free space
foreach (Transform childPositionGameObject in transform)
{
//if no health packs located return location of child object to spawn new health pack
if (childPositionGameObject.childCount == 0)
{
return childPositionGameObject;
}
}
return null;
}
void spawnUntilFull()
{
//returns next free position in space
Transform freePosition = NextFreePosition();
//if free slot is available
if (freePosition && healthExist == false)
{
//instantiates health object and places it in scene at coordinates received from
//freePosition
health = Instantiate (healthPackPrefab, freePosition.position, Quaternion.identity) as GameObject;
//spawns enemy onto a position under the Parent (Enemy Formation)
health.transform.parent = freePosition;
//set bool to true to stop spawning
healthExist = true;
//seat HealthTimer to 5 seconds after creation for use in Update method
healthTimer = Time.time + 5.0f;
}
}
你只是試圖創建一個對象?你的代碼'打開位置'和'spawnUntilFull'使得它聽起來像你想生成多個,但你的代碼似乎只允許創建一個,因爲你將healthExist更改爲true。 –
我現在將它打開,根據時間和敵人的情況隨機創建它們。這就是爲什麼當它被玩家拾起(不同的腳本)時,它會被銷燬並更改爲healthExist = false,然後在上面的腳本中,當定時器耗盡時,它應該被銷燬以允許稍後再創建。 – Phillipv20