Home > front end >  Increasing variable gradually in Unity, the variable keeps reverting
Increasing variable gradually in Unity, the variable keeps reverting

Time:09-30

I am currently developing a 2d game in Unity, it is an endless level runner game. I am trying to increase the speed of the moving objects over time, however the speed keeps reverting. I have tried numerous different ways of changing this code but I cannot seem to get it to work. Does anyone have any ideas?

Here is my code:

public class pipeMove : MonoBehaviour
{
    public float speed = 6f;
    float targetSpeed = 12f;

    void FixedUpdate()
    {
        transform.position  = Vector3.left * speed * Time.deltaTime;
        Debug.Log("Speed: "   speed);
        if (speed < targetSpeed)
        {
            speed  = 2f * Time.deltaTime;
        }
    }
}

This is what I'm seeing in my log:

Speed: 7.599998
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

Speed: 12.00009
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

Speed: 12.00009
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

Speed: 11.62008
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

Speed: 9.620035
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

Speed: 7.619998
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

Speed: 12.00009
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)

I am not sure what is making the speed increase and decrease rather than just increase.

CodePudding user response:

try this one

using UnityEngine;
     
     public class pipeMove : MonoBehaviour
     {
         private float speed  = 6f;
         private float targetSpeed = 12f;
         
         void Update ()
         {
             if (speed < targetSpeed)
                 speed  = 2f * Time.deltaTime;
         }
     }

From Unity answers

CodePudding user response:

Thank you for all the responses. I did indeed find that something else was modifying it which shouldn't have been. I feel dumb, but you all helped. Thanks

  • Related