I am very new to coding and working with Unity. So don’t blame me for very obvious things or mistakes. Thanks.
So what I was basically trying to do: I toss a coin and depending on the result the amount of points a user has is doubled or not. Let’s say I chose head and I get head → my points go from 20 to 40.
My script however does something totally weird. It makes from 1000 points 16000:
Second, be sure to use code tags when sharing code. It makes it a lot easier for us to read and consequently, more likely to help you find the solution. I’ve taken the liberty of reformatting your code (using my personal preferences for curly brace placement in the process) here:
The best I can guess is that you’re calling headOrTail() multiple times per flip. The logic in that function alone can’t be causing the problem, so you have to look outside this section of script for the error.
Other than your head and tail bools being redundant as you are setting them to true before they are checked in an if statement, I can only assume the script is being called more than once.
Thanks for your message! I will use the code function from now. I also assume that my headOrTail function is called several times. But I don’t know why. This is my complete Toss.script. I only left out the many variables.
Ah. There it is. OnCollisionEnter isn’t guaranteed to only execute once in this case. If the coin is bouncing at all, each time a part of it touches the plane, that function will execute. You’ll want to set a flag that only runs headortail if it hasn’t been called yet for that flip.
If that’s not it, make sure you don’t have the script attached to the coin object multiple times.
I can’t follow What do you mean by setting flags? Is there another way to tell my script to only run headortail on collision once? Because you are right, sometimes it bumps on the surface and thus jumps.
Sorry, ‘flag’ is another term for a boolean variable that keeps track of some activity or other. So something like this:
private bool hasFlipped = false;
void HeadOrTail() {
if (! hasFlipped) {
hasFlipped = true;
/// Your existing method code here
}
}
should ensure that the HeadOrTail method only executes once. Bear in mind, you’ll have to set that hasFlipped variable back to false before you go to do your next coin flip, then.