Can't get Vector3.MoveTowards to work

This is probably a silly mistake, but for the life of me I can’t figure out why this isn’t working. When I run the game, the object doesn’t move, and trying to move it through the editor just doesn’t work. Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Zombie : MonoBehaviour
{
    private Animator anim;
    public Transform target;
    public float speed = 1;
    //public bool locked;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
}

Thank you!

Well, first of all your code would only work for 2d graphics and it will explicitly move the object to 0 on the z axis. Since the position of a transform is a Vector3, I would highly recommend that you use the Vector3 version of MoveTowards. Besides that I don’t see any issue in your code. However there are several other possible issues. So make sure:

  • the object as well as the component is active / enabled.
  • your speed variable in the inspector is not 0
  • you did not mark the object as static in the inspector
  • you actually referenced the correct target. To check this, just select your object while in playmode in the hierarchy. Now you can simply click on the target field once and Unity should “ping” / highlight the object that is referenced. Make sure that’s really the correct object and not a prefab.
  • Finally if everything above is correct, make sure you don’t set Time.timeScale to 0 somewhere.

If nothing of the above reveals the error, just add some temporary Debug.Logs to your code to further investigate, Something like this added in Update:

Debug.Log("Update -  curPos:" +transform.position+" target: " + target.position+
"dist: " + Vector3.Distance(transform.position, target.position) +
" speed: " + speed + " dt: "+Time.deltaTime, target);

This would tell you:

  • if the code is actually executed or not.
  • the current position and the target position as well as the distance between them
  • the actual speed value that is used as well as the value for deltaTime.
  • which target object is actually used. Since I passed “target” as second parameter to Debug.Log you can not simply click on the log message in the console and Unity will ping / highlight that object.