Want to check bool from another script but it's not working
Hey guys. Im new in scripting, and I need little help :) I want to receive the bool from another script. I read forum and found solution of user @dorpeleg . Here is this solution.
So, i tried it. This is simple example of my script that should receive bool:
public class example : MonoBehaviour
{
// Use this for initialization
void Start()
{
gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (GameObject.Find("Object, that have bool").GetComponent<Script with bool>().thisbool) //will check if true
{
Debug.Log("Bool from other script is working."); //I don't receive this debug log. But bool is set to true;
gameObject.SetActive(true);
}
}
}
Please, help. Bool is "public bool on;". Why I don't receive bool?
Answer by dorpeleg · Sep 01, 2017 at 03:56 PM
@IXeller Do you have only one "Object, that have bool" in the scene? GameObject.Find will bring you the first one it finds, so if you have more then one, the first one might be set to false.
Also, it is bad practice to use GameObject.Find or GetComponent in the Update method.
Your problem is, you are turnnig the gameObject off at Start method. So the Update method is not called at all.
Please try this code:
public class example : MonoBehaviour
{
private ScriptWithBool _myScript;
// Use this for initialization
void Start()
{
var tempObject = GameObject.Find("Object, that have bool");
if(tempObject == null)
{
Debug.Log("could not find object");
return;
}
_myScript = tempObject.GetComponent<ScriptWithBool>();
if(_myScript == null)
{
Debug.Log("could not find script on object");
return;
}
}
// Update is called once per frame
void Update()
{
if (ScriptWithBool .thisbool) //will check if true
{
Debug.Log("Bool from other script is working."); //I don't receive this debug log. But bool is set to true;
}
}
}
Your answer
Follow this Question
Related Questions
How to enable/disable an Icon depending on the bool state of a toggle. 0 Answers
Boolean somehow becomes false. And an Integer zero. 0 Answers
Need help with writing a bool to call a function 0 Answers
My Bool function is returning False but it should be true in my opinion. Csharp C# 0 Answers
Static bool 1 Answer