简体   繁体   中英

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.

I have created a button in the Unity editor and placed it where I want it to go. 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?

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
  3. Drag this Monobehaviour into the button's OnClick action list.
  4. Select the method you wrote in Step 2 in the button's OnClick action

In the image below, I've set this button to change the name of "Main Camera" to "A Button"

按钮样本

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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