NullReferenceException: Object reference not set to an instance of an object

,

Hi Guys,

I hope someone can help I am having the above issue. I get this messageNullReferenceException: Object reference not set to an instance of an object and my game wont even start. Lecture is Unity RPG Core Combat Creator: Learn Intermediate C# Coding - Swappable control systems when the error started.

thanks in advance



I saw another similar post with some debug info.
using System.Collections;

using System.Collections.Generic;
using RPG.Combat;
using UnityEngine;

namespace RPG.Control
{
    public class AIController : MonoBehaviour
    {
        [SerializeField] float chaseDistance = 5f;

        Fighter fighter;
        GameObject player;

        private void Start()
        {
            fighter = GetComponent<Fighter>();
            if(fighter==null)
            {
                Debug.Log($"{name} does not appear to have a Fighter component");
            }
            GameObject player = GameObject.FindWithTag("Player");
            if (player == null)
            {
                Debug.Log($"{name} was unable to locate the player!");
            }
            else
            {
                Debug.Log($"{name} located the player on {player}");
            }
        }
      
        private void Update()
        {
            if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
            {
                fighter.Attack(player);
            }
            else
            {
                fighter.Cancel();
            }
        }

        private bool InAttackRangeOfPlayer()
        {
            float distanceToPlayer = Vector3.Distance(player.transform.position, transform.position);
            return distanceToPlayer < chaseDistance;
        }
    }
}

I suspect your problem is here… player is a global variable declared earlier in the script, but here, you’ve declared a local variable player which hides the global player. This leaves the global player null. Remove the “GameObject” declaration from before player = GameObject.FindWithTag(“Player”); and you should be golden.

1 Like

Everything is Golden thanks Brian I have spent a good few hours wrapping my brain around that.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.