✅ I might be stupid, but my score system adds two every time a collision happens instead of one.

I can't figure out why. Then again, I don't know what I'm doing. I'm following a tutorial and this is the code he used, only his worked.
public void addScore()
{
playerScore = playerScore + 1;
scoreText.text = playerScore.ToString();
}
}
public void addScore()
{
playerScore = playerScore + 1;
scoreText.text = playerScore.ToString();
}
}
11 Replies
BooBearGoose
BooBearGoose3w ago
I would have expected it to work like this: Player Score = 0 + 1 Player Score = 1+1 But it doesn't. It just goes 2, 4, 6, 8 and so on
Buddy
Buddy3w ago
We need to see your collision code Your issue isn't the addScore code but the collision code.
BooBearGoose
BooBearGoose3w ago
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}

// Update is called once per frame
void Update()
{

}
private void OnTriggerEnter2D(Collider2D collision)
{
logic.addScore();
}
}
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}

// Update is called once per frame
void Update()
{

}
private void OnTriggerEnter2D(Collider2D collision)
{
logic.addScore();
}
}
Buddy
Buddy3w ago
Assuming it is Unity, it might call collide multiple times Do you only want to add score one time? If so then you can add a state whether score was given or not. If it hasn't been given then add score and then set the given state to true.
BooBearGoose
BooBearGoose3w ago
One point per collision
Buddy
Buddy3w ago
Do you have multiple triggers?
BooBearGoose
BooBearGoose3w ago
No. There is only one thing that causes the score to go up
Buddy
Buddy3w ago
What you could do is have a state as I mentioned. Set false on trigger exit and true on enter
private bool hasEntered;
private void OnTriggerEnter2D(Collider2D collision)
{
// return if it already has entered trigger
if (hasEntered) return;
hasEntered = true;
logic.AddScore();
}

private void OnTriggerExit2D(Collider2D collision)
{
hasEntered = false;
}
private bool hasEntered;
private void OnTriggerEnter2D(Collider2D collision)
{
// return if it already has entered trigger
if (hasEntered) return;
hasEntered = true;
logic.AddScore();
}

private void OnTriggerExit2D(Collider2D collision)
{
hasEntered = false;
}
Something like that
BooBearGoose
BooBearGoose3w ago
Ah that is easier then my work around. I don't fully understand all of it though so I'll have to do some readiing
Buddy
Buddy3w ago
Changed it so you don't have to worry about properties .. For now. 😛 Whoops, I accidentally had it as an int datatype when it should've been a boolean, my apologies
BooBearGoose
BooBearGoose3w ago
Ahhh that makes more sense I found a scummier work around though. It's ugly but I just needed inspiration I suppose Testing it now Never mind Even if it worked it would have been idiotic