- Home /
The question is answered, right answer was accepted
Issues sharing variable between 2 scripts
its been i while since ive used unity (or coded in general) and ive forgotten how to share a variable between 2 script. i have 2 scripts they both have a variable called underChunkX
my first script updates the variable frequently my second script need this variable, ive look up tutorials but nothing ive tried works, my second script with the variable returns 0
My first script (variables home):
public float underChunkX;
void OnCollisionEnter(Collision col){
underChunkX = col.gameObject.transform.position.x;
}
My second script(where i need the variable):
void Update(){
underChunkX = player.GetComponent<Player> ().underChunkX;
Debug.Log (underChunkX);
}
Note "player" is the gameobject that the "Player" class is attached to
@$$anonymous$$lasmic from the code you have posted, and IF everything is setup/configured properly, there's no issue, i.e. when first script is attached on the player GO, and it collides with something, then underChunkX
would be set to the transform.position.x
of the GO collided with. No problem there. Then, second script would have no problem reading/accessing the value of Player.underChunkX
since in every frame it gets a reference to Player
(actually, you should probably cache the Player component), and then set SecondScript.underChunkX = Player.underChunkX
. No problem with the code there either. So, it must be something with your setup, e.g. is SecondScript attached on an active GameObject, is the player variable in SecondScript setup properly, etc.
Answer by Klasmic · Dec 02, 2017 at 12:06 PM
i fixed it, for some reason if i moved it to a different function everything worked fine
Answer by IngeJones · Dec 02, 2017 at 12:20 PM
I don't think you want a GetComponent<>() in Update(). It's a relatively expensive process to have running 50 or so times a second. Best to get that in Start(). Assuming the value itself isn't changing 50 times a second also!
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Are C# Global Variables Safe In Unity? 5 Answers
Can I choose what to pass into .getcomponent<{VARIABLE}>(); 1 Answer