- Home /
How to make 2D-buttons right
I'm doing buttons for my 2d-game making sprites with OnMouse-events. I've decided to use animator component and switching states (normal, mouse over, pressed) with it like this:
     void OnMouseEnter()
     {
         GetComponent<Animator> ().Play ("Over");
     }
     
     void OnMouseExit()
     {
         GetComponent<Animator> ().Play ("Idle");
     }
     
     void OnMouseDown()
     {
         GetComponent<Animator> ().Play ("Pressed");
     }
     
     void OnMouseUpAsButton()
     {
         GetComponent<Animator> ().Play ("Over");
         //do something here
     }
The other way is to load every state in a sprite object and assign to sprite renderer's .sprite the needed one or something like this, I don't remember details, but did this way too and it worked ok.
The question is: which way is better and why? Are there any other ways to make buttons?
Answer by incorrect · Jun 23, 2014 at 05:20 PM
I've decided to make it the easy way. Hope it will not brings me any trouble.
     public Sprite normal;
     public Sprite onEnter;
     public Sprite onPressed;
 
     void OnMouseEnter()
     {
         GetComponent<SpriteRenderer> ().sprite = onEnter;
     }
     
     void OnMouseExit()
     {
         GetComponent<SpriteRenderer> ().sprite = normal;
     }
     
     void OnMouseDown()
     {
         GetComponent<SpriteRenderer> ().sprite = onPressed;
     }
     
     public virtual void OnMouseUpAsButton()
     {
         GetComponent<SpriteRenderer> ().sprite = normal;
     }
But you can face this problem: http://answers.unity3d.com/questions/748101/sprite-button-being-pressed-when-not-even-pointed.html Hope it will be solved in Unity 4.6.
Your answer
 
 
             Follow this Question
Related Questions
2D Animation does not start 1 Answer
How to create a 2D rig? 1 Answer
SpriteManager 2 1 Answer
Best way to do animate soldier? 1 Answer
Sprite animation 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                