Search Unity

GetComponent

Discussion in 'Scripting' started by alterus, Dec 10, 2015.

  1. alterus

    alterus

    Joined:
    Sep 9, 2012
    Posts:
    59
    Hello

    Suppose you have two scripts :

    Example1 and Example2

    which are attached to the same object

    in Example2 you declare

    Example1 _example ;

    then you call :

    name = _example.name;

    In my code I get an error msg
    I must first call :

    _example = GetComponent<Example1>();

    While in some tutorials it seems that the call to GetComponent is not needed
    Why?
     
  2. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Basically the rule is a variable _example, must not be empty when you try to use it. Or it will throw a warning like that. What is likely to have happened, is they've already filled the variable before the start of play.

    You can do that by making the variable:

    Code (CSharp):
    1. public Example1 _example;
    By doing that, when you go to the Inspector window in the Editor, you'll find that there's now an empty area for a Example1 to be dragged in, on the object's script. By dragging it there the reference is already made, before you even start playing. This is called serialization. It means that Unity has serialized (collected) the reference for that variable already, before play has started.

    By doing
    Code (CSharp):
    1. GetComponent<Example1>();
    you're in effect doing the same thing, but collecting the reference at the point that this piece of code is called, not while you're editing the game outside of play mode.
     
  3. alterus

    alterus

    Joined:
    Sep 9, 2012
    Posts:
    59
    Thanks Nigey

    The point is that the Editor does not allow me to drag "Example1" in the empty area
    Can you guess why ?
     
  4. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    It's probably because you're dragging the object from the project folder into the script in the scene, not from the hierarchy. You need an 'instance' of the script, not a blueprint of it. Drag the GameObject that contains Example1 into the script with the other script, which is attached to a GameObject too.

    Watching this will really help you at this stage:
    Code (CSharp):
    1. http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/coding-for-the-absolute-beginner
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    some of the "quick accessors" were removed in unity 5, pretty much need GetComponent, or a specific instance dragged into the inspector from the scene hierarchy for most things now. "gameObject" and "transform" being a noticeable exception.