私はゲーム (2D プラットフォーマー) を作成しており、プレイヤーがリスポーンしたときに敵をリスポーンさせようとしています。レベルのロード時にロードされるオブジェクトがいくつかあるため、単純にレベルをリロードすることはできず、問題が発生する可能性があります。代わりに、プレーヤーをリスポーンするために、開始位置に戻します (失われたライフやその他の詳細を処理します)。
プレイヤーは、次のように (プレイヤーの OnTriggerEnter で) 敵の頭を叩いて敵を破壊します。
if(otherObject.CompareTag("Minion")) //hit by minion
{
if(hitFromTop(otherObject.gameObject)) //if player jumped on enemy
{
otherObject.GetComponent<Minion>().setMoving(false); //stop moving
playSound(KillEnemySound); //play killing enemy sound
jump();
Destroy(otherObject.gameObject); //kill minion
}
//else hurt player
}
As you can see, I destroy the enemy object entirely. In order to maintain which enemies are where, I add them to a list (stored in a separate GameObject) on creation. The list is created in the separate enemy respawning object, as follows:
void Start ()
{
enemyList = GameObject.FindGameObjectsWithTag("Minion");
Debug.Log ("Adding all minions to list");
}
I'm attempting to call a function respawning all minions in the list at their original location by going through the list. The function is as follows:
public void RespawnAll()
{
foreach(GameObject minion in enemyList)
{
Destroy(minion); //make sure to respawn ALL minions
}
Debug.Log ("Respawning all");
foreach(GameObject minion in enemyList)
{
Debug.Log ("instantiating minions from list");
Instantiate (minion, minion.GetComponent<Minion>().origPosition, Quaternion.identity);
}
}
I know that it isn't the most time-optimal method to delete all enemies and respawn them all, and if this logic is wrong or if you know a better way, I'm open to new ideas.
The problem with this idea is, I get an error:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
It seems I'm adding a reference to the existing minion to the list rather than a copy. How can I respawn the enemies properly, at their original position?