- Home /
Comparing variable from other script
Hello, after few days I gave up and came to you guys :D What I am trying to do is:
In Script 1 I want to compare variable:
if(Variable WOOD from Script2 >= 50)
DoSomething
In Script2 which is attached to another object I have variable WOOD.
var WOOD = 100;
I need to compare Variable wood I tried to ask my friend, I searched whole google, Found few posts tried every one of them Still the same Error: NullReferenceException: Object reference not set to an instance of an object
Pleasee help
Answer by whebert · Mar 20, 2013 at 08:23 PM
// You can find a reference to Script2 like this, assuming it is attached to some game object in your scene.
var script2 : Script2 = FindObjectOfType(Script2);
// You should always check to make sure script2 was found before trying to use it
if(script2)
{
if(script2.WOOD >= 50)
{
// Do Something
}
}
else
{
// You didn't find a Script2 in your scene
}
It did not find that object in a scene. I tried:
if(script2)
Debug.Log("Found");
else
Debug.Log("did not found");
and ofc it printed did not found.
Be sure to replace "Script2" in my example with whatever the name of your script is.
Of Course I did I am not that stupid :) This is really paranormal activity jesus, how that it is not working? Impossible.
Sorry, was not implying you were. :)
And you're sure there is a game object with your second script attached in the scene? That should work then... You could put Debug.Log statements in the Start function of you scripts just to verify they are in the scene and active, "Script 1 started", "Script 2 started", etc.
I believe you need to name your script something other than "Resources". That is an already existing utility class defined for Unity.
Your answer
![](https://koobas.hobune.stream/wayback/20220613094758im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Random number on game start for a variable 1 Answer
Unexpected token: if 1 Answer
ANOTHER Boolean Problem 1 Answer