- Home /
Accessing a Boolean variable from another script
Hello, Would you please correct my mistake. Thank you for your help.
public class firstScript : MonoBehaviour
{
public bool DoorIsOpen = false;
}
public class secondScript : MonoBehaviour
{
firstScript boolVariable;
void Update ()
{
boolVariable = GetComponent< firstScript >();
if (boolVariable.DoorIsOpen == false)
{
Debug.Log("Door is not open");
}
}
}
Updated this one myself. Please use the 101 010 button to post code, as it will format it properly.
Do you have an error ? If yes it is supposed to help us so you should post it too.
GetComponent is a very heavy function, so you don't want to put it into an "Update" method. A better use is :
public class secondScript : $$anonymous$$onoBehaviour
{
firstScript boolVariable;
void Start ()
{
boolVariable = GetComponent< firstScript >();
}
void Update ()
{
if (boolVariable.DoorIsOpen == false)
{
Debug.Log("Door is not open");
}
}
}
You need to explain what problem you are having. Your script will only work if the component is on the same game object as the above script. If it is on another game object, you will need to find that game object:
boolVariable = GameObject.Find("OtherObject").GetComponent< firstScript >();
...where 'OtherObject' is a unique name for the object that contains the script. And @$$anonymous$$iraSensei's comment is a nice performance change.
Your answer
![](https://koobas.hobune.stream/wayback/20220613153359im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
trigger is not working 0 Answers
Randomly setting a boolean to true? 3 Answers
Can't translate bool from C# to unityscript 2 Answers
Performance Question, Change Boolean or Enable-Disable Script 0 Answers
Open and close doors by pressing 'E' 2 Answers