检测其UI按钮被$ P $画布内pssed? [英] Detecting which UI button was pressed within canvas?

查看:208
本文介绍了检测其UI按钮被$ P $画布内pssed?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的UI像10按钮和我要检查哪一个被感动了。我用下面的逻辑,它工作正常,但现在我收到此错误因为某些原因:

 的NullReferenceException:未将对象引用设置到对象的实例
 DetectButton.Start()(在资产/脚本/ DetectButton.cs:14)

任何想法可能是怎么回事?这里是我的code(附着在画布上),而且我在使用统一版本5.1.0f3。如果您需要任何其他信息,我会很乐意提供,在此先感谢

 无效的start()
 {
     this.GetComponent<按钮和GT;()onClick.AddListener(()=>                                                     {         如果(this.name ==btnJogadores2)
         {
             打印(2 jogadores);
             jogadores = 2;
         }
         //QuantidadeJogadores(this.name);
         //QuantidadePartidas(this.name);
     });
 }


解决方案

您不必这一切你正在做的方式。

这是更容易和良好做法将是为你的画布内的每个按钮创建10个独立的GameObjects。然后在所有这些按钮创建具有10个独立的功能的单个脚本。安装该脚本来你的画布。然后在按钮游戏对象选择上所需要的功能的脚本。下面的示例

 无效的start(){}
无效更新(){}公共无效按钮1()
{
    的debug.log(将Button3);
}公共无效按钮2()
{
    的debug.log(Button1的);
}公共无效按钮3()
{
    的debug.log(将Button3);
}

注意:按钮1,按钮2和按钮3是功能3个独立的按钮

那么你的统一督察里面:


  1. 与您的按钮功能选择脚本。

  2. 分配你想要的方式给你按钮。

在这之后运行场景,你的按钮将正确地调用指定的方法。

I have like 10 buttons on my UI and I gotta check which one was touched. I was using the following logic and it was working fine, but now I am getting this error for some reason:

 NullReferenceException: Object reference not set to an instance of an object
 DetectButton.Start () (at Assets/Scripts/DetectButton.cs:14)

Any ideas what could be going on? Here is my code (attached to the canvas), and I am using Unity version 5.1.0f3. If you need any other info I will gladly provide, thanks in advance

void Start()
 {
     this.GetComponent<Button>().onClick.AddListener(() => 

                                                     { 

         if (this.name == "btnJogadores2")
         {
             print ("2 jogadores");
             jogadores = 2;
         }
         //QuantidadeJogadores(this.name);
         //QuantidadePartidas(this.name);
     }); 
 }

解决方案

You don't have to all this the way you are doing.

An Easier and good practice would be to create 10 separate GameObjects for each button inside your canvas. and then create a single script with 10 separate functions for all those buttons in it. Attach that script to you canvas. and then on the button GameObject select the script on the desired function. Sample below

void Start() { }
void Update() { }

public void button1()
{
    Debug.Log("Button3");
}

public void button2()
{
    Debug.Log("Button1");
}

public void button3()
{
    Debug.Log("Button3");
}

NOTE: button1, button2 and button3 are the functions for 3 separate buttons

Then inside your unity Inspector:

  1. Select your script with you button functions.
  2. Assign you desired method to you button.

After this run your scene and your button will call the assigned methods properly.

这篇关于检测其UI按钮被$ P $画布内pssed?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆