I want the code to immediately go to else when hitting a game object

if (Input.GetKey(KeyCode.Space))
        {
            transform.Translate(new Vector2(0, 2) * Speed * Time.deltaTime);
        }
        else
            transform.Translate(new Vector2(0, -1) * Speed * Time.deltaTime);

oh i forgot the thread is not right i want to go in the other direction when hitting a game object

Code tags.

What?

https://discussions.unity.com/t/481379

Read up on OnCollisionEnter

When you say GameObjects do you mean colliders?

You could put your transform.Translate bit into a Method and call it when raycast collides on a certain layer.

public LayerMask obstacle; //assign this from inspector

OnCollisionEnter2D(Collider2D hit){                      //hits another collider
if(hit.gameObject.Layer=obstacle){                        //with the layer you've assigned
WalkAway();                                                           //and executes the code you've set in method.
}
}

public void WalkAway(){
transform.Translate(new Vector2(0, -1) * Speed * Time.deltaTime);
}

Please let me know if I’m wrong, or misunderstood what you’re after here :confused: