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

☆樱花仙子☆ 提交于 2019-12-11 04:56:50

问题


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.


回答1:


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" .....

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!




回答2:


Maybe you attached the script to the panel. If so, your scripts can not be executed as long as your GameObject is SetActive(false).

I hope I was able to help you.



来源:https://stackoverflow.com/questions/40526504/button-onselect-not-functioning-in-unity-ui-canvas-situation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!