- Home /
Get OnMouseUp event in other object's script
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.
Answer by dannyskim · Jan 18, 2012 at 07:45 PM
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;
}
}
}
}
Nice!, i did some alterations to the code be clean. thanks
Your answer
Follow this Question
Related Questions
How to access other Scripts and Components 1 Answer
Raytracing: Callback when Raytracing finished 0 Answers
2D Animation does not start 1 Answer
How do I change component properties without overriding them with parent component? 1 Answer
Login form: Do I have to set custom delegates to null in OnDestroy? 0 Answers