您当前的位置: 首页 >  unity

Jave.Lin

暂无认证

  • 2浏览

    0关注

    704博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

Jave.Lin 发布时间:2018-08-06 10:36:38 ,浏览量:2

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或是Dict或是List或是
  // 直接其他类的引用了的话,那么这个对象就有可能泄漏了
  if (Outter != null) {
   // do something
   Outter  = null;
  }
 }
}
// 改进的方式:
public class TestingClass : MonoBehaviour {
 public GameObject Outter;
 private GameObject copyRef; // Outter的另个地址指定
 private List 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;
  }
 }
}
关注
打赏
1664331872
查看更多评论
立即登录/注册

微信扫码登录

0.0455s