Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Unity's component referencing scheme.

Discussion in 'Scripting' started by MisterNifty, Oct 6, 2013.

  1. MisterNifty


    Oct 6, 2013
    I'm having a little difficulty wrapping my head around Unity's component hierarchy referencing scheme, from within scripts.

    In particular, I have a question about the following. The Unity tutorial, Scripting: #20-GetComponent, describes referencing other components from within a script. They show these 2 lines declaring references to 2 other custom scripts.

    private AnotherScript anotherScript;
    private YetAnotherScript yetAnotherScript;

    My question is this: Why are they declared as 2 different types; 'AnotherScript', and 'YetAnotherScript' ? Why are these 2 other scripts not of the type 'Script' instead ? Aren't all scripts that I create of type 'Script' ? Why are they not declared like so :

    private Script anotherScript;
    private Script yetAnotherScript;

    Their example implies that every time I create a new script in the editor, I'm creating a whole new Script sub-type. That doesn't make any sense to me. I'm just creating a new script, not a new type of script...

    I'm coRnfused...
  2. Wobak


    May 21, 2013
    When you are creating a new script you are indeed making a completely new type of script. Every script you write is a seperate class. If you create a c# script you can see this at the top:
    Code (csharp):
    2. public class Scriptname : MonoBehaviour
    This means that the following script is actually the Class "Scriptname" which is a child of the class "MonoBehaviour". Now when you add this script to a gameobject, unity create a new object of the class "Scriptname" and attaches it to the gameobject.
    Each script is a class because otherwise you could not acces its variables and methods.
    The script AnotherScript might have the variable "health" and the method "TakeDamage()".
    The script YetAnotherScript might have the variable "time" and the method "CoundDown()".
    If you would store both scripts in a variable of a single type like this (MonoBehaviour is the universal parent class of all scripts attached to gameobjects, basically like "Script" you put in your example):
    private MonoBehaviour anotherScript;
    private MonoBehaviour yetAnotherScript;

    Now you could not write " = 4" or "yetAnotherScript.CoundDown()" because they are objects of the class "MonoBehaviour" and it does not have these methods and variables.

    But if you define the Variables like that:
    private AnotherScript anotherScript;
    private YetAnotherScript yetAnotherScript;

    You can write " = 4" because the class "AnotherScript" has this variable and so on.