Unity - How can I popup a GUI button when a target is detected

August 10, 2013 - 3:40am #1

This article describes how to show (popup) a GUI button overlaid on top of the 3D view in response to a target detection event, using thre Unity extension of the Vuforia SDK.

Steps:

  • create a C# script (e.g. called ButtonPopup) and attach it to the "Chips" ImageTarget object 
  • edit the script and enter the following code, which is meant to show a simple GUI button when the target is found, and hide when the target is lost
using UnityEngine;
using System.Collections;

public class ButtonPopup : MonoBehaviour, ITrackableEventHandler {
	
	private TrackableBehaviour mTrackableBehaviour;
	
	private bool mShowGUIButton = false;
	private Rect mButtonRect = new Rect(50,50,120,60);
	
	void Start () {
		mTrackableBehaviour = GetComponent<TrackableBehaviour>();
        if (mTrackableBehaviour)
        {
            mTrackableBehaviour.RegisterTrackableEventHandler(this);
        }
	}
	
	public void OnTrackableStateChanged(
                                    TrackableBehaviour.Status previousStatus,
                                    TrackableBehaviour.Status newStatus)
    {
        if (newStatus == TrackableBehaviour.Status.DETECTED ||
            newStatus == TrackableBehaviour.Status.TRACKED)
        {
            mShowGUIButton = true;
        }
        else
        {
            mShowGUIButton = false;
        }
    }
	
	void OnGUI() {
		if (mShowGUIButton) {
			// draw the GUI button
			if (GUI.Button(mButtonRect, "Hello")) {
				// do something on button click	
			}
		}
	}
}

You can then adapt this code to meet your specific needs (e.g. showing a label or a menu instead of a button, etc.).

 

 

 

Topic locked