组织Unity按钮的OnClick活动的最佳方法?

发布于 2025-01-28 02:55:44 字数 447 浏览 3 评论 0原文

在此处输入图像描述

Unity在其UI系统的一部分中拥有一个名为“按钮”的组件,您可以使用它,您可以使用它通过检查员订阅点击事件,这非常有用。

但是,当项目变大时,我在许多情况下遇到麻烦:

  • 在检查员中以这种方式订阅的事件无法重新安排,这使得有很多事件的按钮难以管理
  • 更改用于事件的脚本的内容按钮无法识别用于事件的函数,这意味着您必须重新引用它,
  • 如果GameObject或Prefab发生任何事情,将按钮组件(例如损坏),那么所有已序列化的事件都将在按钮上进行被擦拭,您需要重新引用所有这些点
  • ,以上几点使调试非常困难,

我可以解决上面列出的问题的某些方法?

enter image description here

Unity has a component called Button as part of its UI system which you can use to subscribe on-click events to it through the inspector which is incredibly useful.

However, when projects get larger, I run into trouble in many situations:

  • events subscribed this way in the inspector are not rearrange-able which makes buttons that have lots of events difficult to manage
  • changing the contents of the scripts used for events can cause the button to not recognize a function that was used for an event which means you have to re-reference it
  • if anything happens to the GameObject or prefab that stores the Button component such as it getting corrupt then all your events that were serialized onto the button would be wiped and you would need to re-reference all of them
  • the above points make debugging very very difficult

What are some ways I can work around the problems I've listed above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心欲静而疯不止 2025-02-04 02:55:44

注射事件在代码中功能:

public Button playButton; // set button in inspector

public void Start()
{
    playButton.onClick.AddListener(() =>
    {
        transform.position = point1;
        
        // do something..
    });
}

Inject event functions inside the code:

public Button playButton; // set button in inspector

public void Start()
{
    playButton.onClick.AddListener(() =>
    {
        transform.position = point1;
        
        // do something..
    });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文