< Back to Game Dev, Unity

Accessing code from other scripts in Unity

For example in one script we store the number for the score as well as the function to update the score on screen. In this example it’s called gameCode.cs and it would go something like this:

public int score = 0;
public void updateScore(){
        GameObject labelScore = GameObject.Find ("labelScore");
        labelScoreText = labelScore.GetComponent<GUIText> ();
        labelScoreText.text = "SCORE: "+score /*score.ToString ()*/;

To access this code in another script, you would do something like this:

gameCode newInstanceNameGameObject.Find ("gameObjectName").GetComponent<gameCode>();
newInstanceName.score += 1;

In this example ‘gameCode’ the is a component in the empty game object called ‘gameObjectName’.

Leave a Reply

Your email address will not be published. Required fields are marked *