如何统一销毁和创建相同的游戏对象

How to destroy and create same gameobject in unity

我正在尝试移动我的玩家来消灭怪物,但我第一次消灭怪物时出现以下错误:

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.

如何让它复制自己成为一个新的游戏对象?

这是我的脚本:

using System.Collections.Generic;
using UnityEngine;

public class TimeMap: MonoBehaviour {
    public GameObject selectedUnit;

    public GameObject selectedMonster;
    public TileType[] tileTypes;

    try{
        if(selectedMonster.GetComponent<Monster>().tileX == selectedUnit.GetComponent<Unit>().tileX && selectedMonster.getComponent<Monsters>().tileY == selectedUnit..GetComponent<Unit>())
            Destroy(selectedMonster);

    }

    public void SpawnMon() {
        if(counter % 5 == 0){
            Debug.Log(" counter % 5 == 0");
            Instantiate(selectedMonster.GetComponent<Monsters>().Monster, new Vector3(Random.Range(1,8), Random.Range(1,8), -1), Quaternion.identity);
        }
    }
}

所以我尝试每 5 步创建相同的对象或它的克隆,但在执行时出现错误。

问题:

您正在尝试像这样访问您的怪物:

selectedMonster.GetComponent<Monster>()

这意味着如果您的场景中有多个类型为 Monster 的 GameObject,Unity 将无法确定您指的是哪一个。

另外当你实例化一个怪物时,你只使用

Instantiate(selectedMonster.GetComponent<Monsters>().Monster, new Vector3(Random.Range(1,8), Random.Range(1,8), -1), Quaternion.identity);

因此您将无法在场景中区分一个实例和另一个实例。

解决方案:

如果您想继续使用这种方法,检查怪物的 tileX 和 tileY 是否与您的单位(我假设是您的英雄或类似单位)匹配,您应该将所有怪物放在一个数组中,这样您就可以以一种您可以轻松引用要销毁的方式对它们进行迭代。

您可以尝试 FindObjectsOfType 然后通过您的怪物类型:

Monster [] monsters= FindObjectsOfType(typeof(Monster )) as Monster [];

然后你迭代

foreach (Monster thisMonster in monsters){
   //check things here
}

另一种选择是在实例化怪物时将它们存储在数组中

//Define as global variable a list of Monsters
List<GameObject> monsterList = new List<GameObject>();

//Then you instantiate then like
monsterList .add((GameObject)Instantiate(selectedMonster.GetComponent<Monsters>().Monster, new Vector3(Random.Range(1,8), Random.Range(1,8), -1), Quaternion.identity));

然后您像以前一样使用 foreach 迭代它们

更好的解决方案(从我的角度来看)

但是,由于您的主要目标(如果我错了请纠正我)是检测单位的位置何时与怪物的位置匹配,以便稍后消灭该特定怪物。我会改用 colliders 。在你称为 Unit 的 GameObject 中,我会添加一个 TriggerEnter。因为你使用了 TileX 和 TileY 我怀疑你正在创建一个 2D 游戏,所以它会是这样的:

void OnTriggerEnter2D(Collider2D other) {
        Destroy(other.gameObject);
    }

有了这个你就可以消灭所有触及你的 "Unit" 的怪物并且你不会有参考问题。