Get a gameObjects variable from another script

Hi there. In JavaScript / UnityScript, how do I get the variable of a gameobject in a different script.

For example, the Player gameObject has a script attached (which among other things), has:

var isholdingsomething = "false";

So in the inspector at runtime, there’s this property on the playerObject set to “false”

From a completely different JS script, I’m trying to do a find.gameObject to locate the player, but how would I do:

A: retrieve this player property in the other script.
B: change this player property to “true” if needed in the other script?

Thanks for any help.

Ok, after a LOT of googling, actually found a helpful answer instead at Accessing A Variable From Another Script - Questions & Answers - Unity Discussions

For anyone else looking how to do this in js/unityscript, here’s the most straightforward how-to guide, which even I can follow :slight_smile:

On the player object, there’s a simple script attached called “playerscript”
This script is a one liner. It’s:

var holdingsomething = "false";

This generates a value in the inspector inside Unity when you click on the player object.
“holdingsomething” and is set to false.

On another gameObject, I’ve got another script attached. Let’s call it “script2.js”
Inside “script2.js”, there’s this:

// check if player is holding something
var theplayerobj = GameObject.Find("player");
// get a reference to the target script (playerscript is the name of your script):
var targetScript: playerscript = theplayerobj.GetComponent(playerscript);
// use the targetScript reference to access the variable holdingsomething:
var isholding = targetScript.holdingsomething;
Debug.Log(isholding);

This will give you the property “false” which is applied to the other gameObject called “player” in the scene.

If that’s processor intensive (not sure if it is), you could put it in a repeating function every 3 seconds like this:

(inside the “script2.js”)

InvokeRepeating("isplayerholding", 1, 3); // check if player holding something every 3 seconds

Then, right at the bottom of the script (or at least outside the start function), you could have:

function isplayerholding() {
// check if player is holding something
var theplayerobj = GameObject.Find("player");
// get a reference to the target script (playerscript is the name of your script):
var targetScript: playerscript = theplayerobj.GetComponent(playerscript);
// use the targetScript reference to access the variable holdingsomething:
var isholding = targetScript.holdingsomething;
Debug.Log(isholding);
}