Unity 脚本中使用Scene中的GameObject需要注意的问题

本文探讨了在Unity中使用MonoBehaviour类时,如何确保GameObject在OnDestroy方法中被安全地销毁,避免因场景销毁顺序随机导致的问题。文章提供了两种处理方式,并推荐了一种更安全的做法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MonoBehaviour类中的public GameObject 对象,通过inspector绑定了scene中的对象的话,在OnDestroy时不能保证该GameObject!=null
例如:

/*
author  :   Jave.Lin
date    :   2018-08-06
*/

// 需要注意的方式:
public class TestingClass : MonoBehaviour {
 public GameObject Outter;
 private void OnDestroy()
 {
  // 保证Outter不会在任意地方有处理Outter = null的情况
  // 但这里有可能空,原因:Scene在Destroy时,对Scene中拥有的对象逐一Destroy,除了DontDestroyOnLoad的
  // 所以,如果你在对Outter做了一些:Dict<k,GameObject>或是Dict<GameObject,v>或是List<GameObject>或是
  // 直接其他类的引用了的话,那么这个对象就有可能泄漏了
  if (Outter != null) {
   // do something
   Outter  = null;
  }
 }
}
// 改进的方式:
public class TestingClass : MonoBehaviour {
 public GameObject Outter;
 private GameObject copyRef; // Outter的另个地址指定
 private List<GameObject> list;
 private void OnAwake()
 {
  copyRef = Outter;
 }
 private void OnDestroy()
 {
  // You Shouldn't do This:
  // Outter maybe null, due to destroy children randomly when scene destroy
  // You can testing logs
  if (Outter != null) {
   Debug.Log("Outter != null");
   Outter = null;
  } else {
   Debug.Log("Outter == null");
  }
  // You Should do That:
  if (copyRef!= null) {
   list.Remove(copyRef);
   copyRef  = null;
  }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值