C# 游戏对象被销毁后缺少参考的问题
在我的游戏中,假设npc攻击并摧毁一座房子,这座房子在脚本中被指定为目标,但当房子被摧毁时,一个错误说缺少一个参考,我预计会发生这种情况 但是我怎么才能解决这个问题呢?有没有办法在游戏对象被销毁后禁用目标变量 这段代码在npc脚本上C# 游戏对象被销毁后缺少参考的问题,c#,unity3d,destroy,C#,Unity3d,Destroy,在我的游戏中,假设npc攻击并摧毁一座房子,这座房子在脚本中被指定为目标,但当房子被摧毁时,一个错误说缺少一个参考,我预计会发生这种情况 但是我怎么才能解决这个问题呢?有没有办法在游戏对象被销毁后禁用目标变量 这段代码在npc脚本上 void Start () { force = 1000; enemyHealth = 100; enemyAttack = 20; enemyDefense = 2; bigFont= new GUIStyle();
void Start () {
force = 1000;
enemyHealth = 100;
enemyAttack = 20;
enemyDefense = 2;
bigFont= new GUIStyle();
bigFont.fontSize = 20;
target = GameObject.FindGameObjectWithTag("Player").transform;
targetHouse = GameObject.FindGameObjectWithTag("house").transform;
animator = GetComponent<Animator>();
}
void Start(){
力=1000;
enemyHealth=100;
灌肠攻击=20;
灌肠防御=2;
bigFont=新的GUIStyle();
bigFont.fontSize=20;
target=GameObject.FindGameObjectWithTag(“Player”).transform;
targetHouse=GameObject.FindGameObjectWithTag(“house”).transform;
animator=GetComponent();
}
这是家里的剧本
void Update () {
if(houseHp<= 0){
Destroy(GameObject.FindWithTag("house"));
}
}
void更新(){
如果(houseHp您可以检查null
并避免该问题
GameObject temp = GameObject.FindGameObjectWithTag("house");
if(temp != null)
targetHouse = temp.transform;
因此,当房子
被摧毁时FindGameObjectWithTag()
将返回null
我尝试插入此代码,但它不起作用,只是为了澄清一下,看看我做得是否正确://我声明变量temp public GameObject temp;//然后在start void start(){temp=GameObject.FindGameObjectWithTag(“casa”);}//if语句必须插入到何处?注意:im使用带有enum@GabrielFerraztemp
应该声明在我放置它的地方,在类似Start()
或Update()的函数中
。这意味着您可以将我的代码放在已经执行此代码的任何位置:targetHouse=GameObject.FindGameObjectWithTag(“house”).transform;