Rundown これで少し助けが必要です。基本的に私は、プレハブから開いた状態でhealthPackをインスタンス化しています。一定の時間が経過すると、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;
}
}
あなたは1つのオブジェクトを作成しようとしていますか?あなたのコードの 'open position'と 'spawnUntilFull'は、複数のコードを生成したいように思えますが、healthExistをtrueに変更したためコードが作成されるようにしか見えません。 –
時間と敵が破壊されてランダムに作成されるように、今は開いたままにしておきます。そのため、それがプレーヤー(別のスクリプト)によって破棄され、healthExist = falseに変更された後、もう一度上記のスクリプトでタイマーが切れると、後で別の作成を可能にするために破棄されるはずです。 – Phillipv20