Accessing code from other scripts in Unity

Posted on

in

,

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;
newInstanceName.updateScore();

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 *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

September 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30