Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Detect when UI object enters or leaves the screen

Discussion in 'UGUI & TextMesh Pro' started by diegoadrada, Dec 6, 2017.

  1. diegoadrada

    diegoadrada

    Joined:
    Nov 27, 2014
    Posts:
    59
    ui.jpg


    Hello, I'm working on a scene in which the user can scroll vertically up and down, all the elements of the scene are UI objects: images and text (Green blocks in the image).

    The objective is that when the scroll goes down and the elements that are not initially on the screen appear, an action is executed, in this case a sound is played.

    My question is about what will be the best way to detect when a UI element enters or leaves the screen as I scroll up or down.

    I was trying with colliders, having one in the lower limit of the screen that will be the "Trigger" and a collider in each UI element, but I'm not sure about how optimal this solution is.

    Thanks and best regards!
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Have you tried OnBecameVisible/Invisible? I've never actually tried if that works in the UI or not.

    Another option might be to just check the object's position compared to see if it's off screen. You could delay this in a Coroutine so it checks often, but not every frame, perhaps.
     
  3. diegoadrada

    diegoadrada

    Joined:
    Nov 27, 2014
    Posts:
    59
    Hi, thanks for your answer!
    OnBecameVisible and OnBecameInvisible don't works with CanvasRenderer, this class doesn't send any messages unlike the Renderer class.
    The other option I tried a few days ago but it is not precise, doing it with the delay as you say, while if it is done each frame can work but it doesn't seem very optimal, and equally, it is not very accurate :(
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, good to know about the first part..

    When I was talking about a delay, I meant really small, like .2 - .5 seconds. Just so it's not polling so much.
    However, I'm not sure what you mean by not very accurate? You weren't able to get good results?
     
    diegoadrada likes this.
  5. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,227