- Home /
accessing a variable from another script.
I am very new to programming and struggling with a problem. I am trying to access the variable "score" from one script and use "score" to determine the height of a guitexture on another script. I have tried it a couple ways but i keep getting this error: Null Reference Exception: Object reference not set to an instance of an object.
This is how my script is written.
//this is my first script, which is named: stonyScript
var score : float = 0;
function OnCollisionEnter(col : Collision){
if(col.gameObject.name == ("asteroid")){
score += 10;
}
//here is the second script.
currentHeight = stonyScript.js.score;
function Update(){
guiTexture.pixelInset.width = 20;
guiTexture.pixelInset.height = 10 + currentHeight;
}
Thank you jbarba_ballytech. I was able to fix my problem thanks to your reference :)
Answer by landon912 · Mar 09, 2013 at 01:30 AM
You have to tell it where to get stonyScript from.
stonyScript = GameObject.Find("Insert the name of the object that stonyScript is located").GetComponent(stonyScript);
currentHeight = stonyScript.score
Answer by Jonster · Mar 09, 2013 at 03:30 AM
I gave that a try but I am still getting the same error for some reason. Did i implement your method wrong?
stonyScript.js = GameObject.Find("Stony").GetComponent(stonyScript.js);
currentHeight = stonyScript.js.score
"Stony" is the name of the gameObject associated with stonyScript
Answer by RyanZimmerman87 · Mar 09, 2013 at 03:31 AM
The easiest way I believe is to just make your variables public static if you want to easily access them.
for example:
Script #1 is called PlayerMoveScript and contains:
public static int playerHealth = 10;
You can access this variable from any other script by using:
PlayerMoveScript.playerHealth += 1;
or:
int newPlayerHealth;
newPlayerHealth = PlayerMoveScript.playerHealth;
You're right Ryan. In the link Jbarba posted I read about another question similar to $$anonymous$$e where the solution was to make the variable public static. $$anonymous$$y code is working correctly now, thanks to you guys :)
Your answer
Follow this Question
Related Questions
Accessing A Variable From Another Script 4 Answers
Accessing another var on another script 1 Answer
Accessing variable of script on an instance. 1 Answer
Is it possible to change a variable, into a script not assigned to any game object? 3 Answers
Problem with accessing variable form other scripts. 1 Answer