Search Unity

Question Open UI Canvas when a trigger is entered

Discussion in 'Scripting' started by daniel6839, Jan 14, 2022.

  1. daniel6839

    daniel6839

    Joined:
    Dec 16, 2017
    Posts:
    14
    In an open world scene, I want to have multiple portals from where the player can go to different levels. I want each portal to have a menu that pops up when the player enters, from where you can use buttons to go to the new level or close that menu.
    The menu is a canvas that pops when the player enters a trigger. I'm using this for the trigger:

    Code (CSharp):
    1. public class LevelTrigger : MonoBehaviour
    2. {
    3.     public GameObject menu;
    4.  
    5.     void OnTriggerEnter(Collider other)
    6.     {
    7.         if (other.tag == "Player")
    8.         {
    9.             menu.SetActive(true);
    10.         }
    11.     }
    12. }
    This is the trigger:
    Screenshot 2022-01-14 111909.png

    This is the menu:
    Screenshot 2022-01-14 111649.png

    And this is the close button:
    Screenshot 2022-01-14 111210.png

    If I enter one of the portals, it opens the menu with no problems, but if I close it and go to a different portal after that, I get this error:

    MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object.
     
    Last edited: Jan 14, 2022
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Well, the error is self-documenting. You've destroyed something and are trying to access it again. You must Destroy() the menu GameObject in your "close the menu" code instead of disabling it, but you haven't shared that code so it's purely conjecture.
     
  3. daniel6839

    daniel6839

    Joined:
    Dec 16, 2017
    Posts:
    14
    Thank you for your quick reply.
    I did not make a script for disabling the menu GameObject, that's why I've posted the screenshot of the button.
    If I destroy it using a script, do I need to take a different approach to enable it?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Detach the parts here, divide and conquer.

    First make some UI that can pop up and go away anytime.

    Put that in a scene and test it with a script that gives you:

    - a key to make it appear
    - a key to make it disappear.

    Make absolutely sure it works with APPEAR pressed multiple times, eg., it doesn't stack a bunch of copies up (use a boolean or something).

    Don't move past that until it is rock solid.

    Once that's working, check it into source control and move onto connecting up the trigger portal part everywhere it needs to be, connecting that to the "bring up UI" function.