- Home /
 
JS Setting int value from another script
Hi. Im making a game in which the player moves around w/ a flashlight. Over time the flashlight dies, unless the player collides with 'batteries'. The battery lvl of the light is set in batt_lvl int in my flashlight script, but i need to access the var and set it back, upon colliding with battery FROM a different script. I have collision working, but im having trouble accessing/changing the var in the move_player script. Please help, thanks.
FLASHLIGHT SCRIPT
 public var batt_lvl : int;
 
 function Update () {
 
     batt_lvl -= Time.deltaTime;
 }
 
               MOVE SCRIPT
 public var lightScript : flashlight; //trying to access the script??
 
 function OnCollisionEnter2D(batt: Collision2D)
 {
     if(batt.collider.name == "battery")
     {
         Destroy(batt.gameObject);
         
         lightScript.batt_lvl = 7000; //**problem (wont change
     }
 
              Answer by spalt_er · Jan 12, 2014 at 05:00 PM
Access the component via the GameObject with the attached flashlight script. You can get the component via the GetComponent method.
http://docs.unity3d.com/Documentation/ScriptReference/Component.GetComponent.html
In case the script is attached to the same GameObject you can acces it via
 var script : FlashLightScript;
 script = GetComponent ( FlashLightScript );
 script.IncreaseBattLvlBy ( 7000 );
 
              You're welcome. Please mark the answer as right if it is helpful for others too.
Your answer