Angelica cruz Angelica cruz - 22 days ago 13
C# Question

Button `OnSelect` not functioning in Unity.UI Canvas situation

I have three buttons, when you tap one button, a panel with a text appear.

The problem is when I attached the script, nothing happens.
The "click" is registered but the the panel never appears.

My script is attached to each of the button and is something like this:

public GameObject panel; //i use to put the panel in unity
bool selected = false;

void Start () {
panel.SetActive(false);
}

void OnSelect() {
selected = !selected;
panel.SetActive(true);
}


I probably have to do something else with the panel but I can't figure it out.

Answer

Do it like this:

(1) Add the canvas to your project

(2) BIG TIP - be sure to select Scale with screen size.

That's the only one you ever use. Unity accidentally set the wrong default there, they have not fixed it yet.

(3) In your Canvas, add a BUTTON Make it say perhaps "Test"

(3) In your Canvas, add another BUTTON Make it say perhaps "Another Test"

(4) Make a script something like this...

public class MainScreen:MonoBehaviour
    {
    public void UserClickedTest()
        {
        Debug.Log("test..");
        }
    public void UserClickedAnotherTest()
        {
        Debug.Log("another test..");
        }
    }

(5) put ONE copy of that script on ANY object you like. You can put it on your camera, on the canvas, or anywhere else that makes sense

For now let's say you put it on your CAMERA object, for example.

(6) Click on the button "Test" .....

enter image description here

And do this ...

  1. click the PLUS button under OnClick

  2. you see the slot that says "_main" in this example. DRAG your CAMERA item from HEIRARCHY, to that slot

  3. Using the drop down menu:

select the "UserClickedTest()" function ...

good eh?

  1. Now for the other button, do the same but select the "UserClickedAnotherTest()" function.

  2. You're done! Run and test!

You can't use the OnSelect system unless you use ISelectHandler and more stuff: it is difficult for beginners. I strongly recommend the OP masters the simpler technique I explain here. Enjoy!