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

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;
  }
 }
}

猜你喜欢

转载自blog.csdn.net/linjf520/article/details/81450185