- Home /
Get bool value from one script to another (C#)
Hey guys. I have 2 GameObjects. I want to transfer a bool value from the script of object 1 to the script of object 2.
So say I have bool1 = false in script 1 to transfer over to bool2 in script 2. I want this to be dynamic so as bool1 becomes true bool2 becomes true as well.
Here is what I have tried. I have set a tag called Object1 to the first object and gave the first object a script called Obj1. This is the code in the 2nd object.
bool2 = GameObject.Find("Object1").GetComponent<Obj1>().bool1;
Debug.Log(bool2);
This compiles just fine but when I change the value of bool1 from false to true, bool2 just stays as false. No clue why it won't change.
Is this running in an Update method? And you aren't getting any errors in your console?
Answer by crunchyoverseas · Jun 26, 2014 at 06:24 AM
If you have a tag set up you should be using findobjectwithtag. You'll be tagging the script that the bool is in. make sure at the beginning of the class (before start and update) where you want to change you have...
GameObject example;
Then in your start function you want...
example = GameObject.FindGameObjectWith Tag ("example_tag");
Then in Update or where you want to change it...
example.example_bool = false;
That should do it...
Answer by rohitanshu · Jun 26, 2014 at 06:24 AM
Your line of code will just execute once if not placed in a repeating function like Update() or FixedUpdate() etc.
Furthurmore, you should consider creating a function in Obj2-script that will update bool2 to bool1 as a passed parameter. Then, call that function using SendMessage(), like this:
gameObject2.SendMessage("updateBool2", bool1);
also, I haven't tried this myself, but may be you could use Properties.
Your answer
Follow this Question
Related Questions
gameObject.GetComponent("Script").enabled = true not working 5 Answers
Creating a single-line function for GameObject.Find and GetComponent (for multiple components) 3 Answers
Get components of multiple instantiated objects? 2 Answers
Setting a bool is not working with objects that have already spawned.. 1 Answer
GetComponent vs AddComponent 3 Answers