- Home /
Unable to modify a variable in another script
I've tried reading other questions, the documentation, another tutorial, but no matter what, I just can't get one script to modify a variable in another.
I'm trying to make a power bar like in Global Agenda but when the weapon fires, nothing is subtracted. In that game, multiple things, such as jetpacks, weapons, and enemy debuffs all modify your power level.
There's no real code I can copy and paste because I've tried PlayerPower.playerPower (ScriptName.variableName), GetComponent, using static modifier, etc. but nothing so far has worked.
Could someone write a simple example of how to do it? Thanks in advance.
Answer by Griffo · Aug 04, 2012 at 07:49 AM
Hi, I have a script called globalVars where I keep all my global variables, here is a bit of the code.
#pragma strict
// ----------------------------------------------------------------------------------------
// Global variables for the game, shared varables stored here to be called from any script
// ----------------------------------------------------------------------------------------
// --------------- PLAYER ----------------
static var playerHealth : int = 100; // Players health
static var playerBeingHit : boolean = false; // Is the player taking damage
static var rayCastHit : String; // Tag of the gameObject the Raycast is hitting
// ---------------------------------------
Then from any other script I call them like below, hope this helps.
#pragma strict
private var globalVars : GameObject; // var for the GameObject with the GlobalVars.js on
function Awake(){
// This is an empty gameobject I called Global Vars with the GlobalVars.js attached to it
globalVars = GameObject.Find("Global Vars"); // Find the gameObject with the GlobalVars attached to it
}
function Start(){
}
function Update(){
}
function trackTarget(){
// Here is where I call the var, the rest of the script around this I have taken out.
globalVars.GetComponent(GlobalVars).playerBeingHit = true;
globalVars.GetComponent(GlobalVars).playerHealth -= 1;
}
This isn't really correct; the variables should be public only, not static. Or if they are static, then there's no reason to use GetComponent.
Answer by Eric5h5 · Aug 04, 2012 at 08:11 AM
Just make variables public, and use GetComponent. Read Accessing Other Game Objects in the docs for explanations, which are about as clear as they can be, plus there are code examples. Avoid static variables unless you know what that means and intend for variables to have only one instance.
Thanks for pointing that out, as you can see I'm still new to Unity and script, well at least I've learned something new today .. :)
Your answer
Follow this Question
Related Questions
Global Varible Problem 2 Answers
Changing static variables from another script? 1 Answer
Howto access global var from other script? 2 Answers