- Home /
Change a Variable with another script not working (C#)
I am trying to change a boolean variable that is in ScriptA with ScriptB. Here is a small example:
 public class ScriptA : MonoBehaviour {
   public bool followBall;
   void Update() {
      if(followBall)
          Make camera follow ball;
   }
 }
 
 public class ScriptB : MonoBehaviour {
 
 public ScriptA a;
   void Update() {
      if(space is pressed) {
            create object to follow;
            a.followBall = true;
       }
   }
 }
When I try to change the boolean variable in scriptA with scriptB it stays false. I made sure that I dragged the ScriptA component onto ScriptB. I don't know what I am doing wrong?
Answer by whydoidoit · Jul 06, 2012 at 07:44 PM
You are doing that correctly - are you sure you are checking the right ScriptA when you see that it is still false? Are you sure the code here is executing?
Yeah I am positive Its executing the code and from the right script. It never changes it. $$anonymous$$y code is almost the exact same as what I posted above. I made the variable static and I could change it, but I rather not have to use a static variable.
I think you should post your exact code. The mix of pseudo-code you posted looks alright, as $$anonymous$$ike said, so something else must be going on.
In the document I found this.
 public class ScriptB : $$anonymous$$onoBehaviour {
 
 public ScriptA a;
 
   void Start()
   {   
    a = gameObject.GetComponent<ScriptA>(); 
   }
 
   void Update() {
      if(space is pressed) {
            create object to follow;
            a.followBall = true;
       }
   }
 }
That says both scripts must be attached to the same object - it would set them that way on startup.
Answer by blenderblender · Dec 27, 2014 at 04:14 PM
 public GameObject MyGameObject;
 YourScript myScript;
 void Start()
 {
 myScript = MyGameObject.GetComponent<YourScriptName>();
 }
 void Update()
 {
 //for example  See is a bool in the script YourScriptName
 if(myScript.See==true)
 {
 // do Something
 }
 }
Answer by Snownebula · May 18, 2015 at 08:36 AM
How do you change the var in the js from the c# script?
Answer by sas_88 · May 18, 2015 at 09:11 AM
Hi,
Follow the link: http://www.41post.com/1935/programming/unity3d-js-cs-or-cs-js-access
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                