Search Unity

Instantiated objects losing script references.

Discussion in 'Scripting' started by pyjamaslug, Mar 17, 2018.

  1. pyjamaslug

    pyjamaslug

    Joined:
    Jul 5, 2017
    Posts:
    51
    I am instantiating characters at runtime from a list of prefab prototypes that have a bunch of scripts attached. The characters are controlled by collisions with pre-placed objects in the scene; generally, I check the object tag to see what it is and then GetComponent<script_name>() to find the attached script. It works most of the time but sometimes it doesn't. By which I mean that some of the prefabs find the script and some come up with a null reference, even when the prefab being used as a prototype is the same. I have an Assert() at the point of instantiation that checks for the absence of the script: it never gets fired.When I chase down one of these rogue characters, sure enough, the script is there but disabled.
    Does anyone have any experience of something similar?
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I can't be certain from your description. If the scripts are on the prefabs, and you instantiate them and look for scripts only on the same game object, that should be working.
    If you are referencing something in the scene, from a prefab, that will not work.

    If you think posting some relevant code might be illuminating, please feel free to do that.
     
  3. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Hasn't happened to me. You should check if the script is enabled right after instantiation. I think you will find it always is.
     
  4. pyjamaslug

    pyjamaslug

    Joined:
    Jul 5, 2017
    Posts:
    51
    Ack! Never mind: my own script was deleting them! It's been a long day (my only excuse). Sorry for wasting your time.