Hello everyone, I am super excited about your course!
I’m currently working on Basic Combat and am having trouble moving within range.
Unfortunately, an error crept in for me and I just can’t find the solution for it. I am an absolute beginner and would appreciate a little help. Thank you in advance!
Unfortunately, my English is not very good, so please don’t be surprised.
NullReferenceException: Object reference not set to an instance of an object
RPG.Movement.Mover.UpdateAnimator () (at Assets/Script/Movement/Mover.cs:39)
RPG.Movement.Mover.Update () (at Assets/Script/Movement/Mover.cs:23)
Thats the Code:
Figther.cs
using UnityEngine;
using RPG.Movement;
namespace RPG.Combat
{
public class Fighter : MonoBehaviour
{
[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;
}
}
}
and
Mover.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
namespace RPG.Movement
{
public class Mover : MonoBehaviour
{
[SerializeField] Transform target;
NavMeshAgent navMeshAgent;
private void start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
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(ve
float speed = localVelocity.z;
GetComponent<Animator>().SetFloat("forword", speed);
}
}
}
and
PlayerControler.cs
using UnityEngine;
using RPG.Movement;
using RPG.Combat;
using System;
namespace RPG.Control
{
public class PlayerController : MonoBehaviour
{
private void Update()
{
if (InteractWithCombat()) return;
if (InteractWithMovement()) return;
}
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 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 static Ray GetMouseRay()
{
return Camera.main.ScreenPointToRay(Input.mousePosition);
}
}
}