transform postion , if statement not working

In my code I want to move an object right then left, my start method is working. However, my if statement in my update method is not. I have tried transform.position.x already and still the same

public float speed = 1;

void Start()
{

    transform.position = new Vector3(-4.02f, -3.86f, 0f);

}

void Update()
{

    // works
    transform.Translate(Vector3.right * speed * Time.deltaTime);

    // doesnt work
    if (transform.position == new Vector3(-0.23f, -3.86f, 0f))
    {
        transform.Translate(Vector3.left * speed * Time.deltaTime);
    }

}

The problem is that floating point numbers don’t allow for exact comparison. It might sound daft but think of it this way. What is 1/3 as a decimal? Doesn’t matter how many decimal places you have, you can’t write it as a decimal number.

Your best bet is to calculate the distance between your start and end position. Then, in your update, check how far the object has moved. As soon as it’s greater than the required distance, move the other way.

Mind you, I’m not convinced by your logic. You were going to move back but only for a very short time because you would have been on the other side of your vector 3 quickly, meaning you’d pretty much stay at your target position, jittering back and forth…

Now my code looks like this … the if works but the else doesn’t… however, in if it doesn’t stop where I want it to go left

public float speed = 1;

void Start()
{

    transform.position = new Vector3(-4.02f, -3.86f, 0f);
   

}

void Update()
{

    
    if (Vector3.Distance(transform.position, new Vector3(-0.23f, -3.86f, 0f)) <= 3.79)
    {
        transform.Translate(Vector3.right * speed * Time.deltaTime);
        
    }
    else
    {
        transform.Translate(Vector3.left * speed * Time.deltaTime);
    }
    
    

}

The reason it doesn’t go left is that as soon as it does the distance is less than 3.79 and so it goes right, then left, then right, then left, then right… The distances are so small that it looks as if it’s standing still. Here’s some code that works (though the object goes left forever afterwards…

    public float speed = 1;
    Vector3 direction = Vector3.right;
    Vector3 endPoint = new Vector3(-0.23f, -3.86f, 0f);

    void Start()
    {
        transform.position = new Vector3(-4.02f, -3.86f, 0f);
    }

    void Update()
    {
        if (direction == Vector3.right)
        {
            if (Vector3.Distance(transform.position, endPoint) >= 3.79)
            {
                direction = Vector3.left;
            }
        }
        transform.Translate(direction * speed * Time.deltaTime);
    }

By the way, I hope you don’t mind but I’ve converted your last entry to a comment, since it’s not an “answer”. Supplementary material should be entered as comments, not answers so as to help other people looking for similar questions.