Issue With GUI Texture Button

I am hoping some of you more experienced developers can chime in and help me out a bit. I have buttons that are GUI Textures, and I use the following code to make them “touchable.”

using UnityEngine;
using System.Collections;


public class TouchController : MonoBehaviour {
   
    GUIElement FindGUIElement(Camera camera, Vector3 mousePosition){
   // Is the mouse inside the cameras viewport?
   Rect rect = camera.pixelRect;
   if (!rect.Contains (mousePosition))
      return null;

   // Did we hit any gui elements?
   GUILayer layer = (GUILayer)camera.GetComponent (typeof (GUILayer));
   if (!layer)
      return null;

   return layer.HitTest (mousePosition);
    }
   
   

   void Update () {
      
 
   
   if (Input.GetMouseButtonDown(0))
{
   GUIElement element = FindGUIElement( Camera.main, Input.mousePosition);
   if (element)
    element.SendMessage("OnMouseDown"); 
}

   if (Input.GetMouseButtonUp(0))
{
   GUIElement element = FindGUIElement( Camera.main, Input.mousePosition);
   if (element)
    element.SendMessage("OnMouseUp");
}


}
}

Using the above code, I have created buttons that must be “held” to work. To accomplish this, I just set a boolean to true when OnMouseDown() is called, and set it to false when OnMouseUp() is called. This works well about half the time, but often, onMouseUp() doesn’t get called when I stop touching the button, and the boolean gets “stuck” on true. OnGUI is such a performance killing on the iPhone that GUI.RepeatButton is not an option. Any other ideas?

you are missing the most important event there.

Thats dragging.

If the mouse is moved out of the rect while it is down, you need to send an event for mouseup as well, so you must have a list that contains the currently “active elements” and checks the newly found one(s) against that list.

If its always only a single element at a time, you don’t need a list, just a references to a single element and check if element = oldElement

Simply Fantastic! Thanks dreamora, I didn’t even stop to think about that. That will most certainly do the trick.