< Back to Game Dev, Unity

Reusable Move Function in Unity

Similar to the Fade Function, here’s the Move one:

public IEnumerator move(GameObject obj,Vector2 targetPosfloat speed = 1){

        Vector2 startingPos = obj.transform.position;

        while(startingPos.x != targetPos.x || startingPos.y != targetPos.y){
            Vector2 curPos = obj.transform.position;
            if(curPos == targetPos){
                yield break;    
            obj.transform.position = Vector2.MoveTowards(curPostargetPosspeed*Time.deltaTime);
            print ("moving "+curPos +" - "+targetPos );
            yield return null;

This function assumes you’re moving a game object from it’s current position to another. It’s parameters are the GameObject, the position it wants to move to and a speed that’s set to 1 by default.

An example of using it:

StartCoroutine (move (gameObjectnew Vector2 (0, 0),2));

In this example the gameObject is moving towards the centre with a speed of 2.

Leave a Reply

Your email address will not be published. Required fields are marked *