X
X
XisterONE2019-02-20 23:26:18
C++ / C#
XisterONE, 2019-02-20 23:26:18

Why NullReferenceException error?

using UnityEngine;
using UnityEngine.EventSystems;

public class GameManager : MonoBehaviour
{
    [SerializeField]
    private Player player;

 
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
       ClickTarget();
    }

    private void ClickTarget()
    {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
            Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector3.zero, Mathf.Infinity, 512);

            if (hit.collider != null)
            {
                if(hit.collider.CompareTag("Enemy"))
                {
                    player.MyTarget = hit.transform.GetChild(0);
                }
            }

            else
            {
                player.MyTarget = null;
            }

        }
    }
}

What is wrong here. Here is the error:
NullReferenceException: Object reference not set to an instance of an object
GameManager.ClickTarget () (at Assets/Scripts/GameManager.cs:24)
GameManager.Update () (at Assets/Scripts/GameManager.cs:19)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2019-02-20
@GavriKos

We turn on the debugger and see that we have Null on line 24.
Most likely - EventSystem.current. It needs to be added to the stage. The rest is in the unity manual.

A
Armyashka, 2019-12-06
@Armyashka

How to add it to the scene?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question