Detect Touch on GUI.Button in Script?

I’m trying to tell the game that if the Character Controller is grounded, and the GUI.Button (that has a running icon texture within it) is pressed, the walking speed of the character will become running speed.

Here is the portion of the script:

function SetSpeed()
{
	var speed = walkSpeed;
	 
	if ( chCtrl.isGrounded && GUI.Button(Rect(1050, 350, 120, 100),btnTexture) )
	{
		speed = runSpeed;
	}
	 
	chMotor.movement.maxForwardSpeed = speed;
}

In the line “if ( chCtrl.isGrounded && GUI.Button(Rect(1050, 350, 120, 100),btnTexture) )” of course “GUI.Button(Rect(1050, 350, 120, 100),btnTexture)” doesn’t work at all. I’m just trying to show what I am trying to do.

Basically, have the script say: “… && GUI.Button is pressed”. Any help would be greatly appreciated! :slight_smile:

First of all hopefully you know that you can use GUI stuff only in OnGUI. It’s fine to use helper functions like your SetSpeed function but it needs to be called from OnGUI or the button won’t be displayed and can’t react to any event. For more information on how the GUI system works see GUI Basics or if you want to understand what happens inside the GUI controls and how the system works in detail, see my GUI crash course.

Next thing is GUI.Button returns true only once at the moment it is clicked (pressed down and released like a normal button). What you might want to use in your case is GUI.RepeatButton which returns true every frame as long as it is pressed down.

Last thing is that the GUI system and it’s event system does not support multitouch. On mobile it simply emulates a single mouse by taking the average position of all touches.

If you need multitouch support you have to do your own touch handling with the input class.

This is a RepeatButton that works with multitouch:

// UnityScript

public class RepeatButtonState
{
	static var hash = "RepeatButtonState".GetHashCode();
	var fingerId = -1;
}

function RepeatButton(position : Rect, content : GUIContent, style : GUIStyle) : boolean
{
	#if UNITY_IPHONE || UNITY_ANDROID
	var controlID = GUIUtility.GetControlID(RepeatButtonState.hash, FocusType.Native, position);
	var state = GUIUtility.GetStateObject(RepeatButtonState,controlID) as RepeatButtonState;
	var down = false;
	for (var touch : Touch in Input.touches)
	{
		var pos = touch.position;
		pos.y = Screen.height - pos.y;
		if (position.Contains(pos))
		{
			if (touch.phase == TouchPhase.Began)
				state.fingerId = touch.fingerId;
			if (touch.fingerId == state.fingerId)
				down = true;
		}
		if (touch.phase == TouchPhase.Ended ||touch.phase == TouchPhase.Canceled)
			if (touch.fingerId == state.fingerId)
				state.fingerId = -1;
	}
	if (Event.current.type == EventType.Repaint)
	{	
		style.Draw(position, content, down, down, false, false);
	}
	return down;
	#else
	return GUI.RepeatButton(position, content, style);
	#endif
}

I’ve just written it :smiley: but it’s tested on Android