简体   繁体   English

如何为Unity C#中的现有按钮编写脚本

[英]How to write a script for an existing button in Unity C#

I'm absolutely positive this has already been asked somewhere, but I'm fairly new to scripting and Unity in general so I'm having a lot of trouble parsing through the information on google and here in a way I can use it. 我绝对肯定这已经在某个地方被问到了,但是对于脚本和Unity来说,我还是相当陌生,因此我在解析Google信息以及在这里可以使用它的方式时遇到很多麻烦。

I have created a button in the Unity editor and placed it where I want it to go. 我已经在Unity编辑器中创建了一个按钮,并将其放置在我想要的位置。 I've also written a class with methods to perform a function, But I just can't figure out how to attach the functions I want to the button clicks. 我还编写了一个类,该类具有执行功能的方法,但是我只是想不出如何将我想要的功能附加到按钮单击上。

I've created a new script for my button, but I'm not sure how to format the code for the button's use, and I'm not sure what to call in the script to attach the button's click to the function. 我已经为按钮创建了一个新脚本,但是我不确定如何格式化按钮的使用方式,也不确定要在脚本中调用什么以将按钮的点击附加到函数中。

I've seen people post using "MyButton" and others creating a new button object "Button foo = new Button()" but how do I make the script recognize the button I'm trying to attach it to? 我见过有人使用“ MyButton”发布消息,其他人则创建新的按钮对象“ Button foo = new Button()”,但是如何使脚本识别要附加到按钮的按钮?

Thanks for your help! 谢谢你的帮助!

In general, what you can do are the following steps 通常,您可以执行以下步骤

  1. Create a button 创建一个按钮
  2. Attach a Monobehaviour to the button, with a method that contains what you want to execute on the button's click 将Monobehaviour附加到按钮,其方法包含要在按钮单击时执行的内容
  3. Drag this Monobehaviour into the button's OnClick action list. 将此Monobehaviour拖动到按钮的OnClick操作列表中。
  4. Select the method you wrote in Step 2 in the button's OnClick action 选择您在按钮的OnClick操作中在第2步中编写的方法

In the image below, I've set this button to change the name of "Main Camera" to "A Button" 在下图中,我已将此按钮设置为将“主摄像机”的名称更改为“ A按钮”

按钮样本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM