- Home /
Question by
BCCorporation · Sep 08, 2019 at 09:16 PM ·
c#npcpatrolchase
NPC won't move after adding chase code.
Hey there! I'm following a Pluralsight tutorial on Unity Fundamentals. I'm currently working on the NPC. The NPC moves fine from waypoint to waypoint until I add the code to chase the player, it won't move at all. Below is my NPCController script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NPCController : MonoBehaviour
{
public float patrolTime = 10f;
public float aggroRange = 10f;
public Transform[] waypoints;
private int index;
private float speed, agentSpeed;
private Transform player;
//private Animator anim;
private NavMeshAgent agent;
private void Awake()
{
//anim = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
if (agent != null) { agentSpeed = agent.speed; }
player = GameObject.FindGameObjectWithTag("Player").transform;
index = Random.Range(0, waypoints.Length);
InvokeRepeating("Tick", 0, 0.5f);
if (waypoints.Length > 0)
{
InvokeRepeating("Patrol", 0, patrolTime);
}
}
void Patrol()
{
index = index == waypoints.Length - 1 ? 0 : index + 1;
}
void Tick()
{
agent.destination = waypoints[index].position;
agent.speed = agentSpeed / 2;
if (player != null && Vector3.Distance(transform.position, player.position) < aggroRange)
{
agent.destination = player.position;
agent.speed = agentSpeed;
}
}
}
Comment
Answer by theonerm2_unity · Sep 08, 2019 at 10:25 PM
I'm going to try out your code and see what happens. After that I will update you. *Update: Your code works as intended for me. Make sure you tagged something as Player. It won't move until you tag something as Player.