Tasharen Entertainment Forum

Support => NGUI 3 Support => Topic started by: Zak Signal on October 14, 2014, 02:35:50 PM

Title: Assigning a "nested" Sprite reference to UI2DSprite destroys components.
Post by: Zak Signal on October 14, 2014, 02:35:50 PM
This is a strange one.

I have a class, HudHandler, which holds some serializable fields & a serializable class (relevant code below):

  1. class HudHandler
  2. {
  3.      [System.Serializable]
  4.      class ReticleIcons
  5.      {
  6.           [SerializeField] public Sprite Aiming;
  7.      }
  8.  
  9.      [SerializeField] public ReticleIcons _ReticleIcons = new _ReticleIcons();
  10.      private UI2DSprite _Reticle;
  11.  
  12.      void Awake()
  13.      {
  14.           GameObject obj = new GameObject("Reticle");
  15.           obj.transform.parent = _ReticleParent.transform;
  16.          
  17.           _Reticle = NGUITools.AddChild<UI2DSprite>(obj);
  18.           _Reticle.sprite2D = _ReticleIcons.Aiming;  // This looks like the culprit
  19.      }
  20.      //...
  21. }  
  22.  

What appears to be happening (running through the debugger) is that UI2DSprite.sprite2D.set() is working fine, but somewhere before UI2DSprite.mainTexture.get() is called, the _Reticle's gameObject is corrupted.

In the editor, the _Reticle gameObject is missing both its UI2DSprite component and it's transform component!

As a consequence, here is the run-time error:

  1. MissingReferenceException: The object of type 'Sprite' has been destroyed but you are still trying to access it.

I've tried to fix it through various means, playing with public vs. private access, Awake() vs. Start(), but nothing seems to work.

Lastly, I can fix this by simply taking the Sprite field out of the ReticleIcons class and into the HudHandler class. This isn't ideal, because I like to compartmentalize my fields through serializable classes for sanity's sake.

Any thoughts?
Title: Re: Assigning a "nested" Sprite reference to UI2DSprite destroys components.
Post by: ArenMook on October 14, 2014, 02:59:14 PM
1. Never do anything in Awake() that involves other components or creation of more objects. Use Start() for that.

2. Don't use "new GameObject". use NGUITools.AddChild.