IsPointerOverGameObject() returns Object reference not set to an instance of an object
Hi guys,
I have a GUI button and every time, when I try to click on this button, my player moves. So I'm trying to use IsPointerOverGameObject() to "block" the click movement.
I don't know why, but when I click, I got this error in line 23, the Debug.Log line.
NullReferenceException: Object reference not set to an instance of an object
Here is my code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class PlayerMovement : MonoBehaviour
{
NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Debug.Log(EventSystem.current.IsPointerOverGameObject());
agent.SetDestination(hit.point);
}
}
}
}
Anybody knows why?
Seems like the EventSystem is null. You could add an EventSystem to your hierarchy and drag it in to a public reference to make sure you are getting it.
You should probably check if EventSystem.current is null or not. And make sure you have a gameobject with an eventsystem component in the scene.
Answer by salsa · Jun 10, 2016 at 07:15 PM
Thanks,
I add the component to my player object and now looks like its working. No error messages.
player.AddComponent<EventSystem>();
I'm not getting errors but, I'm always receiving FALSE, even if I click inside the close button.
Answer by LSPressWorks · Oct 03, 2017 at 09:24 PM
I would sincerely like to thank you for a no BS answer on this my man. Adding an event system to the calling scripts object did it just fine. I am though, a little perturbed that this is documented no where, and in both the hex tutorials I am watching the instructor was not forced to do this.
Your answer
Follow this Question
Related Questions
Movement with joystick ,Moving object with the Joystck 0 Answers
Player teleport not working 0 Answers
Can anyone help me with the dash please? 0 Answers
How to unable player to move on GUI buttons 0 Answers
Can someone please tell me whats wrong with this?, because when i put it says error in the GetAxis 1 Answer