Very weird problem in scripting. Result is always twice of assigned value

hello everyone,
I am writing this script for car acceleration:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarAccelaration : MonoBehaviour
{
    private float car1MaxSpeed = 4.05f;
    private CarController cCPlayer;
    public LapCounter lc;
    private float defaultSpeed = 1.5f;

    void Start()
    {
        StartCoroutine (AccelarationCar ());
    }

    IEnumerator AccelarationCar()
        {
            yield return new WaitForSeconds(7.0f);
            cCPlayer = lc.carController[0];

            while (true)
                {
                    yield return new WaitForSeconds(1.0f);
                    if (cCPlayer.CurrentSpeed <= car1MaxSpeed && CarLock.carNumber == 0 && cCPlayer.b_btn_Acce  // b_btn_Acce check if Acceleration button is pressed by player)
                    {
                        cCPlayer.CurrentSpeed += 0.1f; // Add 0.1f acceleration speed if acceleration button pressed
                    }

                    else if (cCPlayer.CurrentSpeed > defaultSpeed && CarLock.carNumber == 0)
                    {
                        cCPlayer.CurrentSpeed -= 0.1f; // Decrease 0.1f speed if acceleration button not pressed
                    }
               
                }
        }
   
}

This code must add 0.1f to car speed every second when acceleration button pressed continuously but it’s adding twice 0.2f every second. while, if no button pressed it must decrease speed by 0.1f every second, but again it’s decreasing twice 0.2f. I changed values but result is always twice of assigned value. what thing can cause this bug?

Is it possible you have two copies of this script in the scene?

1 Like

First thing I’d check is make sure you don’t have the script in your scene twice. Next, I’d add some debug statements in the script to validate my values. Third would be to make sure nothing else is hitting the speed, but I suspect with what you said it’s a double copy of the script.

1 Like