Search code examples
c#unity-game-enginepositioninstantiationgameobject

How can i use MoveTowards method in Unity for more than one object


I am planning to create GameObjects on random position and then slide to target position every frame.

I create one object onstart() manually and I used MoveTowards method in update() and it worked but i want to do same with many objects at the same time (about 10 objects): If i create more than one object it doesn't work.

This is what i have:

GameObject Go = Instantiate(M1, new Vector3(-5, 10, 0), Quaternion.Euler(0, 0, 0)) as GameObject;
Go.transform.position = Vector3.MoveTowards(Go.transform.position, new Vector3(10, -20, 0), 0.05f);

Solution

  • Make a new script, let's call it Mover. Give it public Vector3 destination and public float rate fields and an Update method that edits its position with MoveTowards:

    public class Mover: MonoBehaviour
    {
        public Vector3 destination;
        public Vector3 rate;
    
        void Update()
        {
            transform.position = Vector3.MoveTowards(transform.position, destination, rate * Time.deltaTime);
        }
    }
    

    Attach a Mover to the M1 prefab.

    Then, when you instantiate each M1, set the destination and rate of its Mover component:

     GameObject Go = Instantiate(M1, new Vector3(-5, 10, 0), Quaternion.Euler(0, 0, 0)) as GameObject;
     Mover goMover = Go.GetComponent<Mover>();
     goMover.destination = new Vector3(10, -20, 0); 
     goMover.rate = 3f;