When I am clicking on Enemy capsule then the game stops and throws a Null reference exception.
Fighter Script :
[SerializeField] float weaponRange = 2f;
Transform target;
private void Update()
{
bool isInRange = Vector3.Distance(transform.position, target.position) < weaponRange;
if(target != null && !isInRange)
{
GetComponent<Mover>().MoveTo(target.position);
}
else
{
GetComponent<Mover>().Stop();
}
}
public void Attack(CombatTarget combatTarget)
{
target = combatTarget.transform;
}
}
Player Controller Script:
public class PlayerController : MonoBehaviour
{
private void Update()
{
if (InteractWithCombat()) return;
if (InteractWithMovement()) return;
print(“do Nothing”);
}
private bool InteractWithMovement()
{
RaycastHit hit;
bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
if (hasHit)
{
if (Input.GetMouseButton(0))
{
GetComponent<Mover>().MoveTo(hit.point);
}
return true;
}
return false;
}
private bool InteractWithCombat()
{
RaycastHit[] hits = Physics.RaycastAll(GetMouseRay());
foreach(RaycastHit hit in hits)
{
CombatTarget target = hit.transform.GetComponent<CombatTarget>();
if (target == null) continue;
if (Input.GetMouseButtonDown(0))
{
GetComponent<Fighter>().Attack(target);
}
return true;
}
return false;
}
private static Ray GetMouseRay()
{
return Camera.main.ScreenPointToRay(Input.mousePosition);
}
}
}
Movement Script
public class Mover : MonoBehaviour
{
NavMeshAgent navMeshAgent;
private void Start()
{
navMeshAgent = GetComponent();
}
void Update()
{
UpdateAnimator();
}
public void MoveTo(Vector3 destination)
{
navMeshAgent.destination = destination;
navMeshAgent.isStopped = false;
}
public void Stop()
{
navMeshAgent.isStopped = true;
}
private void UpdateAnimator()
{
Vector3 velocity = navMeshAgent.velocity;
Vector3 localVelocity = transform.InverseTransformDirection(velocity);
float speed = localVelocity.z;
GetComponent<Animator>().SetFloat("ForwardSpeed", speed);
}
}