Search Unity

Trying To Access Variables From A Parent GameObject

Discussion in 'Scripting' started by Hypocrita_20XX, Jul 28, 2014.

  1. Hypocrita_20XX

    Hypocrita_20XX

    Joined:
    Feb 8, 2014
    Posts:
    27
    Hello and good day!

    Currently, I'm a bit stuck. I need a non-static instance of a script attached to a parent object that I can then access via another script in a child of that same parent.


    Right now, this is what I have.

    Code (CSharp):
    1.  
    2.     public cubeAI Instance;
    3.  
    4.     void Awake ()
    5.     {
    6.         Instance = this;
    7.     }
    8.  
    This is in the parent script.

    Code (CSharp):
    1.     public cubeAI cubeInstance;
    2.  
    3.     void awake()
    4.     {
    5.         cubeInstance = gameObject.GetComponent<cubeAI>();
    6.     }
    This is in the child script.

    And to say the least, it's not quite working. I keep getting a null reference. Could anyone enlighten me on what I'm doing wrong? I can get this working by dragging and dropping in the parent into the instance in the inspector of the child during run-time, but this is obviously not a solution I'll consider.
    By the way, this parent and its children are being instantiated at run-time through some code, they're not present when everything first loads up. I don't know if that's helpful at all, but I figured I would mention it regardless.

    Thanks for your time, and have a great day!
    -Hypocrita_20XX
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
  3. Hypocrita_20XX

    Hypocrita_20XX

    Joined:
    Feb 8, 2014
    Posts:
    27
    Hello LeftyRighty,

    Thanks for your response!
    Good news and bad news.
    The good news is that your advice works perfectly!
    The bad news is that it only works if it's in the Update() function.
    I'll Investigate further, but I wanted to mention this just in case you or anyone else has any ideas as to what I need to correct.

    Thanks again!
    -Hypocrita_20XX

    PS. Oh dear, major duh moment! I forgot to capitalize the "Awake" function...
    Works perfectly now!
     
    Last edited: Jul 28, 2014