Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按钮单击是否有常规事件?_C#_Unity3d - Fatal编程技术网

C# 按钮单击是否有常规事件?

C# 按钮单击是否有常规事件?,c#,unity3d,C#,Unity3d,我想为UI按钮单击添加声音,但我不认为为每个按钮单击添加audio.Play()是合乎逻辑的。在unity中单击任何按钮时,EventSystem上是否会运行任何东西?@zafar建议了一个线程,我找到了如下解决方案: void Update() { if(Input.GetMouseButtonDown(0)) if (EventSystem.current.currentSelectedGameObject.GetComponent<Button

我想为UI按钮单击添加声音,但我不认为为每个按钮单击添加audio.Play()是合乎逻辑的。在unity中单击任何按钮时,EventSystem上是否会运行任何东西?

@zafar建议了一个线程,我找到了如下解决方案:

void Update()
{
    if(Input.GetMouseButtonDown(0))
                if (EventSystem.current.currentSelectedGameObject.GetComponent<Button>())
                    soundManager.Play("Tap");
}
void Update()
{
if(Input.GetMouseButtonDown(0))
if(EventSystem.current.currentSelectedGameObject.GetComponent())
soundManager.Play(“Tap”);
}

子类化可能是一种比您提出的更有效的方法

//subclass the button
class LoudButton : Button {
    //constructor
    public LoudButton() : base () {
        //Have the constructor add the Event.
        //Optionally, hand the specific sound in as a argument and store it in a property
        base.OnClick += /**/;
    }
}

看到这篇文章,你可以注册多个事件处理程序到一个按钮。同一个处理程序可以在单击时注册到多个按钮。充其量,您可能会找到一个其他人的代码为您执行事件处理的案例。@Christopher我想他的目的是避免在整个过程中对现有代码进行更改app@zafar:如果这是WPF,我相信我们可以找到一种方法,用按钮所在的容器注册该事件。或者是所有按钮的模板。有点像你会应用CSS但这是统一,我的经验停留在“他们真的很喜欢工厂模式”和“他们把游戏循环隐藏得有点太好了”@Christopher是的,我想避免对每个按钮进行更改。点击一个按钮也是很常见的事情。一个接一个地添加声音对我来说没有意义。这可能是低效的,但一个接一个地向每个单音按钮添加声音对我来说没有意义。我可能也会这样做。但是请注意,Unity的内置
按钮
有一个自定义编辑器(),因此,如果您要添加任何序列化字段,它们将不会显示在检查器中,直到您为您的类型创建自己的自定义编辑器,例如
[CustomEditor(typeof(LoudButton))]公共类LoudButtonEditor:ButtonEditor{/*添加字段的附加实现*/}