Search Unity

parent object references on destroyed objects

Discussion in 'Scripting' started by San_Holo, Sep 22, 2015.

  1. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Hi...

    I want to remove a reference to a parent transform on a disabled object.

    My attempt to solve this is below:

    Code (csharp):
    1. void OnEnable ()
    2.     {
    3.         this.transform.parent = null;
    4.         if (GameObject.FindGameObjectWithTag ("SF_Island") != null) {
    5.             this.transform.parent = GameObject.FindGameObjectWithTag ("SF_Island").transform;
    6.         }
    7.     }
    The error : MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

    I'm trying to find an object at a certain point, once found I want my object to attach itself to my target then it'll disable itself back to the pool but my target object would of been destroyed by the time I re-enable my object again and so the error, I thought I could simply find my target object again afresh but before all that just uncouple it's parent, but always the error, the target object is destroyed and I assume the disabled/deactivated object is still attached to that destroyed object perhaps, please advise
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    can I buy a "."?

    which line in that snippet is causing the error?

    what is being destroyed? the parent? the SF_Island tagged object? what?
     
    San_Holo likes this.
  3. HiddenMonk

    HiddenMonk

    Joined:
    Dec 19, 2014
    Posts:
    987
    San_Holo likes this.
  4. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Thank you, did the trick, I added the function to the code below and all is fine, thanks again

    Code (csharp):
    1. void LateUpdate ()
    2.     {
    3.         if (_scManager.levelState == LevelState.Playing) {
    4.             destroyDelay -= Time.deltaTime;
    5.         }
    6.         if (destroyDelay <= 0) {
    7.             if (destroyThisObject != null) {
    8.                 transform.DetachChildren ();
    9.                 Destroy (this.destroyThisObject);
    10.             } else {
    11.                 transform.DetachChildren ();
    12.                 Destroy (this.gameObject);
    13.             }
    14.         }
    15.     }
     
    HiddenMonk likes this.
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    HiddenMonk was suggesting putting it into the OnDestroy function because its a little safer. You don't have to remember to add the detachchildren line before calling destroy, it cleans up itself before being destroyed... and you only need to code it once, not every time :)
     
    San_Holo and HiddenMonk like this.
  6. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Thanks