Having Trouble Incrementing an Integer
Hi, I'm trying to make a breakout clone using Javascript. There's an item that needs to add one extra life when the player collects it, but it's not incrementing right at all. It doesn't add one life during the current play session, but it adds one after I stop running the game and play again, as if incrementing how many lives the player should start the game with next time the game runs. It's hard to explain, but apparently somebody had the exact same problem six years ago: UnityAnswers
Here is my code, simplified:
//This script is attached to the item//
var ball:GameObject;
var paddle:GameObject;
function OnTriggerEnter (c:Collider) {
//I'd like either the ball or paddle to collect the item
if(c.gameObject.tag == "ball" || c.gameObject.tag == "paddle"){
ball.GetComponent(BallScript).balls++;
Destroy(gameObject);
}
}
.
//This script is attached to the ball//
var balls:int; //basically "lives"
function OnCollisionEnter(col:Collision){
if(col.gameObject.tag == "floor"){
balls--; //this works exactly how it should
ResetBall();
}
}
If anyone has had/solved this issue before, I'd really appreciate some help!
right now only the current ball has lives. If it dies, the value is gone. If you want to keep it make the variable static, OR save lives in a different script that stays during the whole game
Hi hexagonius, I am not destroying the ball when it "dies", but just resetting it back in front of the paddle.
Answer by mrlafle · Dec 01, 2016 at 01:49 PM
I don't really post about my bugs here on Unity Answers to get help from anyone. Instead, I rely on the fact that I will inevitably find the solution myself shortly after posting, and that's what happened here :)
So I think the bug occurred because I assigned the "ball" and "paddle" variables on the Item prefab in the Project panel, and not the instance in the Scene. I was also assigning the ball and paddle prefabs instead of their corresponding instances in the scene.
To fix this, I hid the variables in the inspector for simplicity, and I assigned those variables using this on the Item's script:
function Start () {
ball = GameObject.FindWithTag("ball");
paddle = GameObject.FindWithTag("paddle");
}
This does not seem like a very common issue whatsoever, but if anyone thinks they're having a similar problem, I hope they find this helpful :)