Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Eventsystem.current.currentlyselectedobject Not Working For Image

Discussion in 'Scripting' started by xciter_, Apr 10, 2019.

  1. xciter_

    xciter_

    Joined:
    Apr 10, 2019
    Posts:
    6
    Hey all,

    I seem to have a problem trying to detect a click on a UI image.

    On the image itself, I added an 'EventTigger', added the 'PointerClick' event type, attached my script but I keep getting "NullReferenceException: Object reference not set to an instance of an object"

    I took a look on Google before coming to make a post and everything I found didn't work. It seems no matter what I try, I keep getting null.

    Am I missing something super obvious? Below is the code I am using to detect the click.

    Code (CSharp):
    1.  
    2. public void ToggleOption()
    3.     {
    4.         Debug.Log(EventSystem.current.currentSelectedGameObject.name);
    5.     }
    6.  
    As you can see, its very basic. I've also attached a screenshot of the image and the canvas so you can see the settings.
     

    Attached Files:

    • S1.png
      S1.png
      File size:
      313.7 KB
      Views:
      783
    • S2.png
      S2.png
      File size:
      323 KB
      Views:
      754
    M_R_M likes this.
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,833
    NullReferenceException means you are trying to use a variable that doesn't have a valid value. In this case, I would guess that currentSelectedGameObject is probably null.

    I'm not sure if EventTrigger is considered selectable. You might consider using a Button instead.

    You should definitely add some code that checks whether currentSelectedGameObject is null before you try to access its name.
     
    xciter_ likes this.
  3. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    The ui object needs to be interactable like a button what @Antistone said. Only raycasting options on the image wont make them selectable, only blocking raycasts.
     
    BAIZOR, Filter95 and xciter_ like this.
  4. xciter_

    xciter_

    Joined:
    Apr 10, 2019
    Posts:
    6
    Ah, no worries. Guess that's what I'll have to do!

    Thanks for the answers! :D
     
  5. HariharanVN5

    HariharanVN5

    Joined:
    Feb 24, 2021
    Posts:
    6
    AedanDaShaman likes this.