Answer the question
In order to leave comments, you need to log in
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;
}
}
}
}
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question