Unity3D – Access another object’s script values

This is useful to share information between game objects. Specifically, show the life of a player (tracked in script) on the HUD… you can set the UI element’s content to the value from the player’s script component that tracks the life value.

public class OtherScript MonoBehaviour
{
    public int VariableOne = 2;
    public int VariableTwo = 1;

    public int Result;

    void Start()
    {
        Result = VariableOne + VariableTwo;
    }
}
public class SomeOtherScript : MonoBehaviour
{
    void Start()
    {
        GameObject otherObject = GameObject.Find("OtherObjectThatHasScript");
        OtherScript otherObjectsScriptComponent = (OtherScript)otherObject.GetComponent(typeof(OtherScript));

        Debug.Log(string.Format("Result: {0}", otherObjectsScriptComponent.Result));
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: