Unity script for enemy to follow player

The following script will let an object follow a player when it is within a certain range and will stop following it once it is out of a certain range

The following variables can be adjusted from the Inspector.

Attack Speed = How fast the game object moves
Attack Distance = How close does the player need to be to start moving
Buffer Distance = How far away from the player should the game object stop
Player = Game player to target

To use script, create a new C# script named FollowPlayer and paste in the following.

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

public class FollowPlayer : MonoBehaviour
{

    public float attackSpeed = 4;
    public float attackDistance;
    public float bufferDistance;
    public GameObject player;

    Transform playerTransform;

    void GetPlayerTransform()
    {
        if (player != null)
        {
            playerTransform = player.transform;
        }
        else
        {
            Debug.Log("Player not specified in Inspector");
        }
    }

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

    // Update is called once per frame
    void Update()
    {
        var distance = Vector3.Distance(playerTransform.position, transform.position);
        // Debug.Log("Distance to Player" + distance);
        if (distance <= attackDistance)
        {
            if (distance >= bufferDistance)
            {
                transform.position += transform.forward * attackSpeed * Time.deltaTime;
            }
        }
    }
}

Helpful Links

https://forum.unity.com/threads/c-get-transform-of-another-gameobject.177216/
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

Unity/Playmaker create 1 second loop

The following picture shows the basics for create a loop that runs every second. You’ll need to create a float variable (Named oneSecond in the screen shot) that has a value of 1 for one second. Changed if desired.

Put your actions in the “Execute every 1 Second” state

For more info on Get Time Info, visit https://hutonggames.fogbugz.com/default.asp?W496