- Home /
Using Sprite as Button
Hello everyone...
I'm new to unity, and i want to ask about sprite. Can we use sprite as touch button? If we can, how can we do that?
Thanks for your help, and sorry for my bad english.
Yes, you can do that. You should read a bit up on the documentation here http://docs.unity3d.com/Documentation/ScriptReference/GUI.Button.html
where we can place our sprite in that script? the script says that it needs texture as image, not sprite.
A little late, and with no help from @ Simon :P
GameObject gameObject = new GameObject();
Button button = gameObject.AddComponent<Button>();
Image image = gameObject.AddComponent<Image>();
image.sprite = sprite;
Answer by Blayer98 · Apr 05, 2014 at 04:16 PM
Like Simon stated, just read the documentation, it'll help you a lot!
Answer by RubenD056 · Jan 08, 2017 at 09:58 AM
Here you go, although you would need to make some modifications for touch input.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
public class ButtonCustom : MonoBehaviour{
public RectTransform rt;
public MaskableGraphic buttonIcon;
public Color buttonNColor = Color.grey;
public Color buttonHColor = Color.white;
public bool isWorldSpace = false;
public UnityEvent onClicked;
private Rect rectangle;
void Start(){
rt = gameObject.GetComponent<RectTransform> ();
if (buttonIcon == null)
buttonIcon = gameObject.GetComponent<MaskableGraphic> ();
if(!rt)rt = gameObject.GetComponent<RectTransform> ();
buttonIcon.color = buttonNColor;
}
void Update(){
if (!isWorldSpace) {
rectangle = rt.rect;
Vector3 mPos = Input.mousePosition;
if (mPos.x > rt.position.x - (rectangle.width / 2) && mPos.x < rt.position.x + (rectangle.width / 2)) {
if (mPos.y > rt.position.y - (rectangle.height / 2) && mPos.y < rt.position.y + (rectangle.height / 2)) {
handleHit ();
} else
buttonIcon.color = buttonNColor;
} else
buttonIcon.color = buttonNColor;
} else if (hit) {
handleHit ();
hit = false;
} else buttonIcon.color = buttonNColor;
}
void handleHit(){
buttonIcon.color = buttonHColor;
if (Input.GetMouseButtonUp (0)) {
Action ();
}
}
void Action(){
onClicked.Invoke();
}
private bool hit = false;
void beingHit(){
hit = true;
}
}
Your answer
Follow this Question
Related Questions
Button Touch for Android 2 Answers
(Unity 4.6) Button animations 1 Answer
GUI Button, Sprite Swap on Timer (Flashing) 0 Answers
Image Sprite doesn't change with Button Onclick 0 Answers
If you help me, i make you 3d object 1 Answer