Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Object moves much faster in editor than in build

Discussion in 'Getting Started' started by Tamzo15, Oct 19, 2023.

  1. Tamzo15

    Tamzo15

    Joined:
    Feb 18, 2023
    Posts:
    2
    Hello, maybe someone can help me. I'm brand new to it, follow a tutorial from a book

    I want a 2d game object to move from right to left and back. In the build, the object moves nice and slow, as intended, but in the editor it moves very fast.
    But its just that object that varies in its speed. the player moves at the same speed in editor and build.

    What's going on? Here is the code from the object's script.

    public class Gefahren : MonoBehaviour
    {
    float xStart;
    float xAenderung;


    void Start()
    {
    xStart = transform.position.x;
    xAenderung = (Random.Range(0.4f, 0.8f)) * Time.deltaTime;
    }

    void Update()
    {
    float xNeu = transform.position.x + xAenderung;
    transform.position = new Vector3(xNeu, transform.position.y, 0);

    if ((xNeu > xStart + 2) || (xNeu < xStart - 2))
    {
    xAenderung = -1 * xAenderung;
    }
    }
    }
     
  2. Tamzo15

    Tamzo15

    Joined:
    Feb 18, 2023
    Posts:
    2
    EDIT: It only runs to fast in Editor when i "Play Maximized"
     
  3. Reaktion

    Reaktion

    Joined:
    Nov 8, 2019
    Posts:
    53
    Hi,

    I can see that your code, you're moving the object from a specific distance every frame. So, depending on how much frames per second your game runs at, your object will never move at the same speed.

    If you want to correct this, you should always move your GameObject relative to the elapsed time between two frames, like this :
    transform.position = new Vector3(xNeu * Time.deltaTime, transform.position.y, 0);

    OR, in your calculation
    float xNeu = (transform.position.x + xAenderung) * Time.deltaTime;

    Of course, your object will be moving really slow after doing that, so you may want to increase your travelling distance. (which seems to be xAenderung here)


    NOTE: Please use code tags when posting code.