- Home /
How do I set up a GUITexture as a functional button?
I wrote details on what I'm trying to do with notes in the script:
//This is the script from Unity's FPS tutorial.
function Start () {
SelectWeapon(0);
}
function Update () {
//Works fine with the touch input, but I want my GUITexture do that job
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.Began)
//I don't need weapon switching
if (Input.GetKeyDown("1")) {
SelectWeapon(0);
}
else if (Input.GetKeyDown("2")) {
SelectWeapon(1);
}
}
function SelectWeapon (index : int) {
for (var i=0;i<transform.childCount;i++) {
// Activate the selected weapon
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
// Deactivate all other weapons
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
I'd highly appreciate a reply. I hope you understand my question.
Answer by Noah-1 · Jan 19, 2012 at 06:36 PM
Here you go bro:
var fireButton : GUITexture;
function Update(){
for (var evt : Touch in Input.touches) {
var HitTest1 = fireButton.HitTest(evt.position);
if (evt.phase == TouchPhase.Began) {
if(HitTest1){
//do something when button is hit
Debug.Log ("ButtonGUI Clicked");
fireButton.enabled = false;
} } } }
Just rememberto set a texture in the inspector ;)
Thanks! :D Is there a way to activate another script with a GUI? Btw, your GUI works perfect! :D
$$anonymous$$mm if you mean to activate a code in a certain moment when you click a button, look up for enable in Unity Script reference, that shoul make it ;)
Answer by casimps1 · Jan 18, 2012 at 10:45 PM
All you need to do is create a new script and add that script to your GUITexture object. Then add an OnMouseDown( ) method to the script and do whatever you want to do inside that.
Answer by mehowe7 · Jan 18, 2012 at 03:21 PM
var btnTexture : Texture;
function OnGUI() {
if (GUI.Button(Rect(10,10,50,50),btnTexture)){
Debug.Log("Clicked the button with an image");
}
He is referring to GUITextures, which are GUIElement objects, and not UnityGUI objects created/handled in OnGUI().
Thanks! I didn't think you can add textures to normal Unity GUI Buttons! :D
Answer by Wolfram · Jan 18, 2012 at 03:43 PM
Use GUILayer.HitTest():
http://unity3d.com/support/documentation/ScriptReference/GUILayer.HitTest.html
Or if you want to implement your own hit test, you can compare the current mouse position on a click with a GUIElement using GUIElement.GetScreenRect().