简体   繁体   中英

Create a simple button in Unity3D 2D mode

I'm working on a 2D game in Unity 3D, v4.5. I have added some sprites to the Hierarchy. How do I add a button to the hierarchy? I already have a designated button.png that should display as the button. Should I turn a sprite into a button?

What I tried so far:

  • Someone noted GUI.Button, but

    1: It has to be done in code - I assume we can add buttons to the game UI inside Unity GUI (??)

    2: Even using GUI.Button from script, that class adds a border around the specified texture. I also haven't figured out how to use the existing image and size (width/height) of the sprite as the texture that is sent to GUI.Button.

you can useOnGUI for button and to disappear the rectangle you have to make a new GUIStyle

    private GUIStyle testStyle = new GUIStyle();
    public Texture2D Texture1;

    void OnGUI(){

    if( GUI.Button( new Rect (0, 0, 100, 100) , texture1 ,testStyle) )
        {
          //doSomething if clicked on   
        }
      }

if you dont want that you can do a raycasting your selfand give your buttons tags like below

 void Update () {
         if (Input.GetMouseButtonDown (0)) {
              Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             RaycastHit hit;
              if (Physics.Raycast(ray, out hit)) {
               if(hit.collider.tag=="play")
                   //DoSomething

              }
          }
      }

in unity 4.6 UI you can add listeners to buttons in script like below

 private Button MyButton = null; // assign in the editor

 void Start()
 {
   MyButton.onClick.AddListener(() => { somefunction(); });  
 }

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