Hey guys, I have a script that create guiTextures on the scene, and i would like to execute a function when these guiTextures are clicked. I can do it making a script in these objects, but i don’t want to use a script for each object just for callback. I think it’s possible to receive the event of the object somehow… maybe creating a monoBehaviour component at runtime and listening to it, idk.
It’s possible to do that?
Thanks.
In order to detect mouse events on GUITextures, you want to utilize the GUILayer.HitTest method. This code is taken directly from the Unity Documentation at:
http://unity3d.com/support/documentation/ScriptReference/GUILayer.HitTest.html
// Tests if the mouse is touching a GUIElement.
// Add a GUITexture and put the mouse over it and
// it will print the GUITexture name.
private var test : GUILayer;
test = Camera.main.GetComponent(GUILayer);
function Update() {
if(test.HitTest(Input.mousePosition) != null) {
Debug.Log(test.HitTest(Input.mousePosition).name);
}
}
If you want to detect on click, then here are my changes to do so:
if( Input.GetMouseButtonDown(0) )
{
if( test.HitTest( Input.mousePosition ).name )
{
switch( test.HitTest( Input.mousePosition).name )
{
case "buttonName1":
break;
case "buttonName2":
break;
default:
break;
}
}
}
}