How do I check if bool is true from another script?
Hi I have one script that says:
public bool IsLightOn = true;
and then I have another script, that should be something like this:
If (IsLightOn = true)
{
// Do Stuff
}
But that wont work because the IsLightOn bool is in another script, how can I make the other script "get" the bool from the other script?
Thanks, Andreas.
You need GetComponent Check this one http://unitygems.com/script-interaction1/
Also, If is if, low i on the front and finally
if(IsLightOn = true) should be if(IsLightOn == true)
Answer by dorpeleg · Mar 17, 2013 at 02:14 PM
if (GameObject.Find("name of the gameobject holding the script with the bool").GetComponent<name of the script holding the bool>().IsLightOn) //will check if true
if (!GameObject.Find("name of the gameobject holding the script with the bool").GetComponent<name of the script holding the bool>().IsLightOn) //will check if false
If your both scripts are on the same gameobject. don't use Find.
if (gameObject.GetComponent<name of the script holding the bool>().IsLightOn)//will check if true
if (!gameObject.GetComponent<name of the script holding the bool>().IsLightOn)//will check if false
Thank you so much for your answer, it worked perfectly :D
Note that if you do that in the Update that is quite bad. It will go fine until you have many objects on your scene. Then it will go slow, real slow.
I have it in the Update "void/function", how can I prevent that?
Create reference to the script (did you read the link I gave in the first place?)
ScriptType script;
void Start(){
script = GameObject.Find("Name").GetComponent<ScriptType>();
}
void Update(){
if(script.isLightOn)//Light is on
}
Do not be think of creating a boolean variable in your script like this:
bool isOn;
void Start(){
isOn = GameObject.Find("Name").GetComponent<ScriptType>().isLightOn;
}
That won't do. Booleans are value type so without getting too deep, it would copy the original value but would not update it if the light would change.
Your answer
Follow this Question
Related Questions
If statement not working 1 Answer
Call a function When a bool changes value? 2 Answers
Building a Face Generator, need to destroy previous instance after pressing key a second time 0 Answers
Trying to establish turn order in my game but bool will not toggle properly 0 Answers
Boolean somehow becomes false. And an Integer zero. 0 Answers