- Home /
Multiple objects sharing a boolean variable in a script.
In my 2D game, I have multiple GameObjects that represent ladders. I have a script named "LadderClimb.js" attached to these objects. In that script, there is a boolean variable that determines if the player is on the ladder. I am accessing this variable in another script used to animate the player (play climbing animation when onLadder is true) but the boolean variable onLadder is only affected by the last GameObject added to the scene with the script attached.
Here is my LadderClimb.js code
var onLadder : boolean;
private var player : GameObject;
function Start () {
player = GameObject.FindGameObjectWithTag("Player");
}
function Update () {
if (onLadder) {
if (Input.GetKey('w') && player.transform.position.y) {
//Climb up
player.transform.position.y += 0.21;
}
if (Input.GetKey('s') && player.transform.position.y) {
//Climb down
//Debug.Log("Climbing DOWN");
player.transform.position.y -= 0.21;
}
}
}
function OnTriggerEnter (other : Collider) {
if (other.tag == "Player") {
onLadder = true;
}
}
function OnTriggerExit (other : Collider) {
if (other.tag == "Player") {
onLadder = false;
}
}
//end LadderClimb.js
I am trying to access the boolean onLadder from this script:
var ladderClimb : LadderClimb;
var climbing : boolean;
function Update () {
ladderClimb = GameObject.FindGameObjectWithTag("Ladder").GetComponent(LadderClimb);
climbing = ladderClimb.onLadder;
//climbing is only true for last object added to scene... why?
if (climbing) {
//Code to animate player
}
}
//end PlayerAnimate.js
I have also tried doing this with prefabs but I get the same results. Why is the boolean variable onLadder only affected by the last object added to the scene?
Answer by GameVortex · Jan 07, 2015 at 09:22 AM
GameObject.FindGameOBjectWithTag will only find one GameObject, and unless something changes, it will find the same GameObject everytime, and it will be the first one Unity finds, which just so in you instance happens to be the last ladder you added to the scene.
The GameObject.Find functions are really slow and should not be used in the Update function. They should be used to find an object once and then store the reference to it.
In your case I would recommend you to have the ladder tell the player that the player is on it by calling a function in the player when the player enters the ladder in the OnTriggerEnter. And have the ladder tell the player it exited it as well in the OnTriggerExit. That would be the easiest solution at the moment.
Functionality wise it usually makes more sense to have the player check what it has entered and react accordingly, but both methods work fine.