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!