Search Unity

Help with EventSystem IsPointerOverGameObject

Discussion in 'Scripting' started by nmizrahi, Sep 26, 2017.

  1. nmizrahi

    nmizrahi

    Joined:
    Aug 6, 2013
    Posts:
    45
    I'm using Unity 2017.1.0f3 and I'm trying to block ui touches in a UI canvas from moving through to the game objects and came across the boredmormongames tutorial but am having trouble with the first example.

    When I add the below code as a monobehaviour to the cubes in my scene I get the error:

    NullReferenceException: Object reference not set to an instance of an object
    MouseDetection.OnMouseUp () (at Assets/MouseDetection.cs:9)
    UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

    I've researched and don't see an explanation.

    Also, is there an equivalent to isPointerOverGameObject for mobile or will this work with both mouse and mobile touch? Thank you.

    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4.  
    5. public class MouseDetection : MonoBehaviour {
    6.  
    7.     bool isRed;
    8.     public void OnMouseUp(){
    9.         if(!EventSystem.current.IsPointerOverGameObject ()){
    10.             isRed =! isRed;
    11.             if(isRed){
    12.                 GetComponent<Renderer>().material.color=Color.red;
    13.             }
    14.             else{
    15.                 GetComponent<Renderer>().material.color=Color.white;
    16.  
    17.             }
    18.         }
    19.     }
    20. }
    21.  
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,444
    do you have EventSystem in your scene hierarchy?

    upload_2017-9-26_12-6-36.png
     
    lupin87 likes this.
  3. nmizrahi

    nmizrahi

    Joined:
    Aug 6, 2013
    Posts:
    45
    That was it. Thank you.