GUITexture Touch Problem

I am trying to make a button for Android Input.Touch. But it doesn’t work. Anyone can help please?

Here is the code:

`using UnityEngine;
using System.Collections;

public class AnInp : MonoBehaviour {

public Texture2D myButton;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
	Touch touch1;
if(Input.touchCount > 0) {
	touch1 = Input.touches[0];
	guiTexture.texture = myButton;
if(touch1.phase == TouchPhase.Began && guiTexture.HitTest(touch1.position)) {
	
		Application.Quit();

}

}
}

void OnGUI() {
GUI.DrawTexture(new Rect(60,60,60,60), myButton, ScaleMode.StretchToFill, true, 10.0F);

}
///////////////////////////////////////////
}
`

I'm not sure HitTest works in Android, since it has no MouseInput and HitTest is based on Mouse inputs. You should raycast your touch OR and much easier, use if(GUI.Button(new rect(x,y,w,h),textureButton)){ Application.Quit(); } p.s. this must of course be inside OnGUI() method.

Thanks for all. I need multitouch functions for a car and this will be the throttle in fact.

2 Answers

2

You’re mixing different creatures: GUITexture and HitTest belong to the old gui system, while GUI.DrawTexture belongs to the new one - these systems are incompatible with each other, thus you should stick with one or the other.

To use a GUITexture, select the button texture in the Project view and click menu GameObject/Create Other/GUI Texture, than add this modified version of your code to it:

using UnityEngine; 
using System.Collections;

public class AnInp : MonoBehaviour { 

  void Update () { 
    Touch touch1; 
    if(Input.touchCount > 0) { 
      touch1 = Input.touches[0]; 
      if(touch1.phase == TouchPhase.Began && guiTexture.HitTest(touch1.position)) {
        Application.Quit(); 
      }
    } 
  }
}

To use the new GUI system, just follow @J.D.'s suggestion: use GUI.Button instead of GUI.DrawTexture:

using UnityEngine; 
using System.Collections;

public class AnInp : MonoBehaviour { 

  public Texture2D myButton;

  void OnGUI() { 
    if (GUI.Button(new Rect(60,60,60,60), myButton){
      Application.Quit();
    }
  }
}

Thanks for the advice but the button will not quit the app indeed. It will be a throttle button for a car and i need a multitouch script. I will try the new gui system. P.S: Sorry for my bad english.

I just tried the new gui system and the script. It was great man. Thanks a lot. I loved it. Now the question is can i put multiple guitextures from the gameobject/create menu and does it function multitouch(of coures until you answer me i will be testing:)). P.S: I am trying to make 4 touch buttons for accelaret, brake, left and right actions.

I'm on it at the moment. I will write the result. Thanks for helping me in this project. I have made a good car working on pc but i want to run it on Android and i am working for 10 ten days and had no proper result until your help. You are great :)

I tried it right now and having this error: Assets/Scripts/AnInp.cs(16,38): error CS0120: An object reference is required to access non-static member `UnityEngine.GUILayer.HitTest(UnityEngine.Vector3)' I think (maybe i'm thinking wrong) GUILayer touch position has to be defined in vectors but how, or the "button" must be an object?

No, that was my bad! GUILayer.HitTest makes no sense, a reference to the actual instance is needed - and must be got like you've done (or with Camera.main.GetComponent< GUILayer>())

using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Drivetrain))]

public class CarController : MonoBehaviour {

	public Wheel[] wheels;
	public Transform centerOfMass;
	public float inertiaFactor = 1.5f;
	public float brake;
	public float throttle;
	float throttleInput;
	float steering;
	float lastShiftTime = -1;
	float handbrake;
	
	Drivetrain drivetrain;
	CarController carengine;
	
	public float shiftSpeed = 0.8f;
	public float throttleTime = 1.0f;
	public float throttleTimeTraction = 10.0f;
	public float throttleReleaseTime = 0.5f;
	public float throttleReleaseTimeTraction = 0.1f;
	public bool tractionControl = true;
	public float steerTime = 1.2f;
	public float veloSteerTime = 0.1f;
	public float steerReleaseTime = 0.6f;
	public float veloSteerReleaseTime = 0f;
	public float steerCorrectionFactor = 4.0f;
	//lights
	public Light solFren;
	public Light sagFren;
	public Light solFar;
	public Light sagFar;
	public Light solStop;
	public Light sagStop;
	public GUITexture accelTouch;
	public GUITexture brakeTouch;
	public GUITexture leftTouch;
	public GUITexture rightTouch;

	public float slipVelo {
		get {
			float val = 0.0f;
			foreach(Wheel w in wheels)
				val += w.slipVelo / wheels.Length;
			return val;
		}
	}

	// Initialize
	void Start ()
	{
		if (centerOfMass != null)
		rigidbody.centerOfMass = centerOfMass.localPosition;
		rigidbody.inertiaTensor *= inertiaFactor;
		drivetrain = GetComponent (typeof (Drivetrain)) as Drivetrain;
	}
	
	public void Update () {
		if (Input.touchCount > 0){
		foreach (Touch touchControl in Input.touches){
		GUILayer touchLayer = Camera.current.GetComponent(typeof(GUILayer)) as GUILayer;
		GUIElement button = touchLayer.HitTest(touchControl.position);
		    		// Steering
		Vector3 carDir = transform.forward;
		float fVelo = rigidbody.velocity.magnitude;
		Vector3 veloDir = rigidbody.velocity * (1/fVelo);
		float angle = -Mathf.Asin(Mathf.Clamp( Vector3.Cross(veloDir, carDir).y, -1, 1));
		float optimalSteering = angle / (wheels[0].maxSteeringAngle * Mathf.Deg2Rad);
		if (fVelo < 1)
			optimalSteering = 0;
				
		bool steerLeft = (button == leftTouch);
		bool steerRight = (button == rightTouch);
		float steerInput = 0;

		if (steerLeft)
			steerInput = -1;
		if (steerRight)
			steerInput = 1;
				
		if (steerInput < steering)
		{
			float steerSpeed = (steering>0)?(1/(steerReleaseTime+veloSteerReleaseTime*fVelo)) :(1/(steerTime+veloSteerTime*fVelo));
			if (steering > optimalSteering)
				steerSpeed *= 1 + (steering-optimalSteering) * steerCorrectionFactor;
			steering -= steerSpeed * Time.deltaTime;
			if (steerInput > steering)
				steering = steerInput;
		}
		else if (steerInput > steering)
		{
			float steerSpeed = (steering<0)?(1/(steerReleaseTime+veloSteerReleaseTime*fVelo)) :(1/(steerTime+veloSteerTime*fVelo));
			if (steering < optimalSteering)
				steerSpeed *= 1 + (optimalSteering-steering) * steerCorrectionFactor;
			steering += steerSpeed * Time.deltaTime;
			if (steerInput < steering)
				steering = steerInput;
		}
				
		// Throttle/Brake
		bool accelKey = (button == accelTouch);
		bool brakeKey = (button == brakeTouch);
		
		if (drivetrain.automatic && drivetrain.gear == 0)
		{
			accelKey = (button == brakeTouch);
			brakeKey = (button == accelTouch);
		}

		if (accelKey)
		{
			if (drivetrain.slipRatio < 0.1f)
				throttle += Time.deltaTime / throttleTime;
			else if (!tractionControl)
				throttle += Time.deltaTime / throttleTimeTraction;
			else
				throttle -= Time.deltaTime / throttleReleaseTime;

			if (throttleInput < 0)
				throttleInput = 0;
			throttleInput += Time.deltaTime / throttleTime;
			brake = 0;
		}
		else 
		{
			if (drivetrain.slipRatio < 0.1f)
				throttle -= Time.deltaTime / throttleReleaseTime;
			else
				throttle -= Time.deltaTime / throttleReleaseTimeTraction;
		}
		throttle = Mathf.Clamp01 (throttle);
				
		if (brakeKey)
		{
			if (drivetrain.slipRatio < 0.1f)
				brake += Time.deltaTime / throttleTime;
			else
				brake += Time.deltaTime / throttleTimeTraction;
			throttle = 0;
			throttleInput -= Time.deltaTime / throttleTime;
			solFren.light.intensity = 5;
			sagFren.light.intensity = 5;
		}
		else 
		{
			if (drivetrain.slipRatio < 0.1f)
				brake -= Time.deltaTime / throttleReleaseTime;
			else
				brake -= Time.deltaTime / throttleReleaseTimeTraction;
			solFren.light.intensity = 0;
			sagFren.light.intensity = 0;
		}
		brake = Mathf.Clamp01 (brake);
		throttleInput = Mathf.Clamp (throttleInput, -1, 1);

		// Handbrake
		handbrake = Mathf.Clamp01 ( handbrake + (Input.GetKey (KeyCode.Space)? Time.deltaTime: -Time.deltaTime) );
		
		// Gear shifting
		float shiftThrottleFactor = Mathf.Clamp01((Time.time - lastShiftTime)/shiftSpeed);
		drivetrain.throttle = throttle * shiftThrottleFactor;
		drivetrain.throttleInput = throttleInput;
		
		if(Input.GetKeyDown(KeyCode.A))
		{
			lastShiftTime = Time.time;
			drivetrain.ShiftUp ();
		}
		if(Input.GetKeyDown(KeyCode.Z))
		{
			lastShiftTime = Time.time;
			drivetrain.ShiftDown ();
		}

		// Apply inputs
		foreach(Wheel w in wheels)
		{
			w.brake = brake;
			w.handbrake = handbrake;
			w.steering = steering;
		}
	}
		}
	}
	// Debug GUI. Disable when not needed.
	void OnGUI ()
	{
		
		GUI.Label (new Rect(0,60,100,200),"km/h: "+rigidbody.velocity.magnitude * 3.6f);
		tractionControl = GUI.Toggle(new Rect(0,80,300,20), tractionControl, "Traction Control (bypassed by shift key)");
		
	}
}

Any more suggestions???

I still need the answer, anyone can help please???