- Home /
Switching a GUIbuttons texture when holding your finger on it?
Hi! I have a GUIbutton from which i removed the standard background button frame, so the button is essentially a texture. My game is for Android, and I'd like to add the effect that the button is pressed down when you hold down your finger on it. Haven't had any luck with finding out how to do this, anyone got the answer? :)
You store the GUITextures in individual VARS and switch them out when you hold down the GUITexture. or you can manuipulate the $$anonymous$$aterial Color Alpha channal when holding down the GUITexture
He's not talking about a GUITexture, it's a GUIButton, which doesn't contain a material, it contains GUIContent.
Answer by clunk47 · Sep 23, 2013 at 10:01 PM
Here is one solution that works flawlessly on my end. You can use touch code, or mouse code. I prefer unity's mousePosition, since I'm just used to it, and it works for mobile as well. In this example (C#) I check if the Rect for my button contains the mouse or touch position. If it does, I check for touch or click. When the button is clicked or touched, the texture changes. In this example, the two texture choices are public and can be assigned in the inspector. I also set the GUI.skin.button background to match the GUIContent image and text, depending on the touch / click condition.
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour
{
GUIContent buttonContent;
Rect buttonRect;
public Texture2D tex1;
public Texture2D tex2;
//The mouse code in this example works for touch on android.
Vector2 mouse;
void Awake()
{
buttonContent = new GUIContent();
buttonRect = new Rect(0, 0, 64, 64);
}
void Update()
{
mouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if(buttonRect.Contains(mouse) && Input.GetMouseButton(0))
{
buttonContent.text = "Touching";
buttonContent.image = tex2;
}
else
{
buttonContent.text = "Not Touching";
buttonContent.image = tex1;
}
}
void OnGUI()
{
GUI.skin.button.normal.background = (Texture2D)buttonContent.image;
GUI.skin.button.hover.background = (Texture2D)buttonContent.image;
GUI.skin.button.active.background = (Texture2D)buttonContent.image;
if(GUI.Button(new Rect(0, 0, 64, 64), buttonContent))
{
//Code here what you want to affect by button press.
}
}
}
Your answer
Follow this Question
Related Questions
Android GUITexture Touch 0 Answers
Button reaction time problem 1 Answer
Why this simple code doesnt work? 0 Answers
Holding GUI Button Touch to Rotate Object 0 Answers
GUI Button for Android 1 Answer