Author Topic: NGUI HUDText - Instantiate with a prefab and destroy with it  (Read 2628 times)

Karthik

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 1
    • View Profile
NGUI HUDText - Instantiate with a prefab and destroy with it
« on: September 01, 2014, 12:46:01 AM »
Hi,

I recently bough NGUI and HUDText. I ve been trying to create a new HUDText for every instance of a prefab and destroy it as and when the prefab's instance gets destroyed.


Ive been trying to use the following code inside the prefab im instantiating

          dt = Instantiate(dmgTextPrefab) as GameObject;

          ft = dt.GetComponent<UIFollowTarget>();
         ft.target = gameObject.transform;
         NGUITools.AddChild(GameObject.Find("DamageTextContainer"), dt);

         dmgText = dt.GetComponent<HUDText>();
         dmgText.Add("+15", Color.white, 0f);



and destroying the 2, with :

   void Update () {

      if (renderer.isVisible)
         seen = true;

      if (!renderer.isVisible && seen) {
                        Destroy(dt); //DOESNT GET DESTROYED
         Destroy (gameObject);


            }



But the Destroy(dt); doesnt seem to destroy the HudText gameobj instance. Cos I get the following error:
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.get_position ()
UIFollowTarget.Update () (at Assets/HUD Text/Scripts/UIFollowTarget.cs:87)

I even tried DestroyImmediate(ft); // for follow text..

Still not working. Please let me know the best way of creating objects from a prefab and create a new hudtext with it and destroy it. It will be really helpful. I am reallyyyy stuck!!!!! Pls help..

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: NGUI HUDText - Instantiate with a prefab and destroy with it
« Reply #1 on: September 01, 2014, 12:21:30 PM »
1. Use NGUITools.AddChild. Never use Instantiate. Look inside the function to find out all the things it does that you aren't doing.

2. Never use GameObject.Find. It's SUPER slow, and finding something by name is a terrible practice.

3. You are first instantiating the object, then you are instantiating it again via AddChild. Why? Get rid of the AddChild you have, and replace Instantiate with the AddChild.