Search code examples
c#unity-game-enginepositiontransformgameobject

Run an event when my GameObject has a chosen position in Unity3D


my GameObject (Rocket) does fly up when I start the level (Its a 2D Game).

Now I want code it so, that my Rocket will do something when it will arrive at the position for example (0,0,0) but it does not start at 0 it starts something like (0,-15,0).

I tried to code that but it does not work, I checked already that it arrives for 100% at (0,0,0) but I dont understand why it does not run my code when this happen.

My Code:

public class Flying : MonoBehaviour

{


    public float speed = 5f;
  
  

    private void FixedUpdate()
    {
        

        

        transform.position += new Vector3(0, 1, 0) * (Time.deltaTime * speed);


        //Check if my Rocket arrives at (0,0,0)

        if (transform.position == new Vector3(0,0,0))
        {

            Debug.Log("I'm here!");
            speed = 3f;


        }


    }


}

Any idea how to solve that?


Solution

  • I solve the problem with another GameObject that is invisible and have Collider2D on it with Rigidbody2D. Now when my Rocket touches the invisible GameObject the speed will change.

    I hoped that I could code that easier.

    My final code:

    public class Flying : MonoBehaviour
    {
    
    
        public float Speed = 5f;
      
    
        private void FixedUpdate()
        {
            
    
            
    
            transform.position += new Vector3(0, 1, 0) * (Time.deltaTime * Speed)
    
        }
    
    
        private void OnCollisionEnter2D(Collision2D collision)
        {
            if (collision.collider.name == "Slow")
            {
    
                Speed = 3f;
                
    
            }
    
    
        }
    
    
    }