Unity – Get Component

Get the values of others components.

1. Create an Object

2. Assign to this object -> AnotherScript.js:

1
2
3
#pragma strict
 
public var playerScore : int = 9001;

3. Assign to the SAME OBJECT -> MainScript.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma strict
 
private var anotherScript : AnotherScript;
 
function Awake ()
{
    anotherScript = GetComponent(AnotherScript);  
}
 
 
function Start ()
{
    Debug.Log("The player's score is " + anotherScript.playerScore);
   
}

The Result inside Console will be ‘The player’s score is 9001’

Notice:
Outside functions -> private var anotherScript : AnotherScript;
Inside Awake() -> anotherScript = GetComponent(AnotherScript); -> Statement: GetComponent(Component Name)
Inside Start() -> + anotherScript.playerScore -> Statement: variable of GetComponent.variable of Component