Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Somehow counter in c# unity script adds 2 instead of 1

I have this piece of code which detects when the wall passes the player, and increases the counter. For some reason, the chunk sometimes stays in the same position twice, adding to the counter twice. I think there is nothing wrong, and the problem is in Unity itself.

for (int i = 0; i < SpawnedChunks.Count; i++)
{   
    float playerX = Player.transform.position.x;
    float chunkX = SpawnedChunks[i].bot_wall.position.x;

    if (chunkX < playerX && chunkX > -4.5f && GameObject.Find("player"))
    {
        PassedChunks.Add(SpawnedChunks[i]);
        PointsCounter.PointsCount++ ;
    }
}

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you’re using a Rigidbody to move the walls, you have to place this loop inside of FixedUpdate, instead of Update.

Anything that relies on the physics system (or the results of the physics system) needs to run inside of FixedUpdate. The physics system runs at a set interval (ex. 60 times a second), while Update runs once a frame, which can be higher or lower than 60 times a second. This is why the position only didn’t update occasionally, it depends on the ever-changing framerate of your game.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading