FIXED: Inconsistent object rotation after pressing "R" key

Hello, so I’m building my first RTS game (cause I love them) and I have a super-simple code for rotating a building before placing it. However sometimes (quite often) when I press “R”, the building does not rotate and when I press the button again it rotates twice (it rotates double the ammount it should). Help would be highly appreciated.

My code:

private int rotationAngle = 0;

if(Input.GetKeyDown("r"))
            {
                rotationAngle += 90;
            
                currentBlueprint.transform.rotation = Quaternion.Euler(0, rotationAngle, 0);

                currentBuilding.transform.rotation = Quaternion.Euler(0, rotationAngle, 0);
        
            }

ok looks like I fixed it. I made a simple and weird change, no idea why its having an effect, but Im not complaining.

public int rotationAngle = 0;
public int buildingAngle;

if(Input.GetKeyDown("r"))
            {
                rotationAngle += 90;
                buildingAngle = rotationAngle;
              
                currentBlueprint.transform.rotation = Quaternion.Euler(0, buildingAngle, 0);
                currentBuilding.transform.rotation = Quaternion.Euler(0, buildingAngle, 0);
          
            }

(I made the ints public just so I could watch them in the editor)

Make sure the code above only runs from being called in Update(), not FixedUpdate() or anything else.

1 Like

Yep, it’s running in Update() (and has been the whole time), but is not working.
thanks for replying!

I suspect something else is sometimes setting the rotation. So like:
start at rotation 0
hit R, “rotationAngle” set to 90, transform rotation set to 90
But immediately, another function or script sets transform rotation back to 0
hit R again, “rotationAngle” set to 180, the other script is no longer changing transform rotation, so it gets set to 180

1 Like

Ok ok I will investigate

It is race condition problem. Don’t declare private int rotationAngle = 0; under Update method. Declare it under class.

OP has clearly pulled different lines from different parts of the code. If they had line 1 inside Update, they’d be getting a compiler error. Also, that wouldn’t be anything remotely like a race condition.

the int RotationAngle is declared at the top of the code and in Update() I have a RotateWhenClicked (or something like that) method that is defined below.

the int RotationAngle is declared at the top of the code and in Update() I have a RotateWhenClicked (or something like that) method that is defined below. so yeah you right

@StarManta always right… he dat gud.