AI Follow and Wait

I’m making a shepherding game and I’ve been trying to write a script to make the sheep follow the player if they are within range when the player calls them. I’d like the sheep to move towards the player for a set amount of time or until they reach stopping distance, or when the player uses the ‘call’ input again. Here’s what I have so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static RewiredConsts.Action;
using Rewired;
using UnityEngine.AI;

public class SheepController : MonoBehaviour
{

    public float lookRadius = 10f;  // Detection range for player

    Transform target;   // Reference to the player sheep
    NavMeshAgent agent; // Reference to the NavMeshAgent
    public static Rewired.Player player; // The Rewired Player
    public static int playerId = 0;

    // Use this for initialization
    void Start()
    {
        target = PlayerManager.instance.player.transform;
        agent = GetComponent<NavMeshAgent>();
    }


    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(target.position, transform.position);

        if (player.GetButtonDown("Lead"))
        {
            // If inside the lookRadius
            if (distance <= lookRadius)
            {
                // Move towards the target
                agent.SetDestination(target.position);

                // If within attacking distance
                if (distance <= agent.stoppingDistance)
                {
                    FaceTarget();   // Make sure to face towards the target
                }
            }
        }
    }

    // Rotate to face the target
    void FaceTarget()
    {
        Vector3 direction = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    }

    // Show the lookRadius in editor
    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}

I mostly used an old script from a Brackey’s tutorial and tried to modify it. I’m getting an error constantly while the game is running: object reference not set to an instance of an object. I’m very new at coding so any help would be appreciated!

If you are new to coding but can follow Brackey’s stuff, take a look at his video on State Machines. Writing one would be a good exercise in basic AI.

As for your script, object reference not set to an instance of an object usually means something that should be assigned, is not. I’m suspecting it’s either the public target or the agent variables not being set. This can happen for a multitude of reasons, for instance when you change variable names, or simply forgot to set them.

Concerning your content, object reference not set to an occasion of an article, as a rule, implies something that ought to be doled out, isn’t. I’m presuming it’s either the public objective or the specialist factors not being set. This can occur for a large number of reasons, for example when you change variable names, or basically neglected to set them.

Thanks for the resources and insights! I’ll try to apply those things to my project as I’m working. This function would make up a big chunk of my gameplay so I’m very keen to get it working, just so I can playtest other things like obstacles and enemy behavior.

1 Like

Good luck! We all need enemies that can move from A to B don’t we? All the more reason to stick with it. Can I make another suggestion? NavMeshAgents have a variable called updateRotation. It does exactly what it sounds like. Should you ever want to let enemies face the player independently of their agent, set it to false to prevent two things trying to affect the transforms rotation.

In your example you might not even spot that, but it’s useful to keep in mind going forward. For instance, when working with a StateMachine you might want to turn that on when approaching the player, but off once in melee range so you can manipulate enemy “tracking”. A typical use case is a windup animation that tracks the player, followed by contact frames that don’t.

1 Like