Log in or register to post comments

How do clear Object when have new search results

July 17, 2014 - 11:56am #1

Hello everyone,

I have a problem when Creating Cloud Recognition Apps in Unity.

I can't clear old object when have new search result. Object will be overlap (Please see attached file)

Here is my code:

/*==============================================================================
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc.
All Rights Reserved.
==============================================================================*/

using System;
using UnityEngine;

/// <summary>
/// This MonoBehaviour implements the Cloud Reco Event handling for this sample.
/// It registers itself at the CloudRecoBehaviour and is notified of new search results as well as error messages
/// The current state is visualized and new results are enabled using the TargetFinder API.
/// </summary>
public class CloudRecoEventHandler : MonoBehaviour, ICloudRecoEventHandler
{
    #region PRIVATE_MEMBER_VARIABLES

    // ImageTracker reference to avoid lookups
    private ImageTracker mImageTracker;
    private ContentManager mContentManager;
	private CloudRecoBehaviour mCloudRecoBehaviour;
    // the parent gameobject of the referenced ImageTargetTemplate - reused for all target search results
  //  private GameObject mParentOfImageTargetTemplate;

    #endregion // PRIVATE_MEMBER_VARIABLES



    #region EXPOSED_PUBLIC_VARIABLES

    /// <summary>
    /// can be set in the Unity inspector to reference a ImageTargetBehaviour that is used for augmentations of new cloud reco results.
    /// </summary>
    public ImageTargetBehaviour ImageTargetTemplate;

    #endregion

    #region ICloudRecoEventHandler_IMPLEMENTATION

    /// <summary>
    /// called when TargetFinder has been initialized successfully
    /// </summary>
    public void OnInitialized()
    {
        // get a reference to the Image Tracker, remember it
        mImageTracker = TrackerManager.Instance.GetTracker<ImageTracker>();
        mContentManager = (ContentManager)FindObjectOfType(typeof(ContentManager));
    }

    /// <summary>
    /// visualize initialization errors
    /// </summary>
    public void OnInitError(TargetFinder.InitState initError)
    {
        switch (initError)
        {
            case TargetFinder.InitState.INIT_ERROR_NO_NETWORK_CONNECTION:
                ErrorMsg.New("Network Unavailable", "Please check your internet connection and try again.", RestartApplication);
                break;
            case TargetFinder.InitState.INIT_ERROR_SERVICE_NOT_AVAILABLE:
                ErrorMsg.New("Service Unavailable", "Failed to initialize app because the service is not available.");
                break;
        }
    }
    
    /// <summary>
    /// visualize update errors
    /// </summary>
    public void OnUpdateError(TargetFinder.UpdateState updateError)
    {
        switch (updateError)
        {
            case TargetFinder.UpdateState.UPDATE_ERROR_AUTHORIZATION_FAILED:
                ErrorMsg.New("Authorization Error","The cloud recognition service access keys are incorrect or have expired.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_NO_NETWORK_CONNECTION:
                ErrorMsg.New("Network Unavailable","Please check your internet connection and try again.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_PROJECT_SUSPENDED:
                ErrorMsg.New("Authorization Error","The cloud recognition service has been suspended.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_REQUEST_TIMEOUT:
                ErrorMsg.New("Request Timeout","The network request has timed out, please check your internet connection and try again.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_SERVICE_NOT_AVAILABLE:
                ErrorMsg.New("Service Unavailable","The service is unavailable, please try again later.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE:
                ErrorMsg.New("Clock Sync Error","Please update the date and time and try again.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_UPDATE_SDK:
                ErrorMsg.New("Unsupported Version","The application is using an unsupported version of Vuforia.");
                break;
        }
    }

    /// <summary>
    /// when we start scanning, unregister Trackable from the ImageTargetTemplate, then delete all trackables
    /// </summary>
    public void OnStateChanged(bool scanning)
    {
        if (scanning)
        {
            // clear all known trackables
            mImageTracker.TargetFinder.ClearTrackables(false);

            // hide the ImageTargetTemplate
            mContentManager.ShowObject(false);
        }
    }
    
    /// <summary>
    /// Handles new search results
    /// </summary>
    /// <param name="targetSearchResult"></param>
    public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
		GameObject newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;


		GameObject augmentation = null;

		string model_name = targetSearchResult.MetaData;

		if (augmentation != null)
						augmentation.transform.parent = newImageTarget.transform;
		


        // enable the new result with the same ImageTargetBehaviour:
        ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, newImageTarget) as ImageTargetBehaviour;
        
		Debug.Log ("metadata is: " + model_name);

		switch (model_name) {
		case "CHICKEN":
			Destroy(imageTargetBehaviour.gameObject.transform.Find("Horse").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("COW").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("GOAT").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("PIG").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("SHEEP").gameObject);
			break;
		case "COW":
			Destroy(imageTargetBehaviour.gameObject.transform.Find("Horse").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("CHICKEN").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("GOAT").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("PIG").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("SHEEP").gameObject);
			break;
		case "GOAT":
			Destroy(imageTargetBehaviour.gameObject.transform.Find("Horse").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("COW").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("CHICKEN").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("PIG").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("SHEEP").gameObject);
			break;
		case "PIG":
			Destroy(imageTargetBehaviour.gameObject.transform.Find("Horse").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("COW").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("GOAT").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("CHICKEN").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("SHEEP").gameObject);
			break;
		case "SHEEP":
			Destroy(imageTargetBehaviour.gameObject.transform.Find("Horse").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("COW").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("GOAT").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("PIG").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("CHICKEN").gameObject);
			break;
		case "Horse":
			Destroy(imageTargetBehaviour.gameObject.transform.Find("CHICKEN").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("COW").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("GOAT").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("PIG").gameObject);
			Destroy(imageTargetBehaviour.gameObject.transform.Find("SHEEP").gameObject);
			break;
		}

		if (imageTargetBehaviour != null) {
			mCloudRecoBehaviour.CloudRecoEnabled = false;
		}
        //if extended tracking was enabled from the menu, we need to start the extendedtracking on the newly found trackble.
        if(CloudRecognitionUIEventHandler.ExtendedTrackingIsEnabled)
        {
            imageTargetBehaviour.ImageTarget.StartExtendedTracking();
        }
    }

    #endregion // ICloudRecoEventHandler_IMPLEMENTATION



    #region UNTIY_MONOBEHAVIOUR_METHODS

    /// <summary>
    /// register for events at the CloudRecoBehaviour
    /// </summary>
    void Start()
    {
        // look up the gameobject containing the ImageTargetTemplate:
  //      mParentOfImageTargetTemplate = ImageTargetTemplate.gameObject;

        // intialize the ErrorMsg class
        ErrorMsg.Init();

        // register this event handler at the cloud reco behaviour
        CloudRecoBehaviour cloudRecoBehaviour = GetComponent<CloudRecoBehaviour>();
        if (cloudRecoBehaviour)
        {
            cloudRecoBehaviour.RegisterEventHandler(this);
        }
		mCloudRecoBehaviour = cloudRecoBehaviour;
    }

    /// <summary>
    /// draw the sample GUI and error messages
    /// </summary>
    void OnGUI()
    {
        // draw error messages in case there were any
        ErrorMsg.Draw();
    }

    #endregion UNTIY_MONOBEHAVIOUR_METHODS

    #region PRIVATE_METHODS
    
    // callback for network-not-available error message
    private void RestartApplication()
    {
        Application.LoadLevel("Vuforia-1-About");
    }
    #endregion PRIVATE_METHODS
}

 

 

/*==============================================================================
Copyright (c) 2010-2014 Qualcomm Connected Experiences, Inc.
All Rights Reserved.
Confidential and Proprietary - Qualcomm Connected Experiences, Inc.
==============================================================================*/

using UnityEngine;

/// <summary>
/// A custom handler that implements the ITrackableEventHandler interface.
/// </summary>
public class CloudRecoTrackableEventHandler : MonoBehaviour,
                                            ITrackableEventHandler
{
    #region PRIVATE_MEMBER_VARIABLES
 
    private TrackableBehaviour mTrackableBehaviour;
    
    #endregion // PRIVATE_MEMBER_VARIABLES



    #region UNTIY_MONOBEHAVIOUR_METHODS
    
    void Start()
    {
        mTrackableBehaviour = GetComponent<TrackableBehaviour>();
        if (mTrackableBehaviour)
        {
            mTrackableBehaviour.RegisterTrackableEventHandler(this);
        }
    }

    #endregion // UNTIY_MONOBEHAVIOUR_METHODS



    #region PUBLIC_METHODS

    /// <summary>
    /// Implementation of the ITrackableEventHandler function called when the
    /// tracking state changes.
    /// </summary>
    public void OnTrackableStateChanged(
                                    TrackableBehaviour.Status previousStatus,
                                    TrackableBehaviour.Status newStatus)
    {
        if (newStatus == TrackableBehaviour.Status.DETECTED ||
            newStatus == TrackableBehaviour.Status.TRACKED ||
            newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
        {
            OnTrackingFound();
        }
        else
        {
            OnTrackingLost();
        }
    }

    #endregion // PUBLIC_METHODS



    #region PRIVATE_METHODS


    private void OnTrackingFound()
    {
        Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
        Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);

        // Enable rendering:
        foreach (Renderer component in rendererComponents)
        {
            component.enabled = true;
        }

        // Enable colliders:
        foreach (Collider component in colliderComponents)
        {
            component.enabled = true;
        }

        // Stop finder since we have now a result, finder will be restarted again when we lose track of the result
        ImageTracker imageTracker = TrackerManager.Instance.GetTracker<ImageTracker>();
        if(imageTracker != null)
		{
            imageTracker.TargetFinder.Stop();
        }

        Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");
    }


    private void OnTrackingLost()
    {
        Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
        Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);

        // Disable rendering:
        foreach (Renderer component in rendererComponents)
        {
            component.enabled = false;
        }

        // Disable colliders:
        foreach (Collider component in colliderComponents)
        {
            component.enabled = false;
        }
		
        // Start finder again if we lost the current trackable
        ImageTracker imageTracker = TrackerManager.Instance.GetTracker<ImageTracker>();
        if(imageTracker != null)
		{
			imageTracker.TargetFinder.ClearTrackables(false);
            imageTracker.TargetFinder.StartRecognition();
        }

        Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
    }
	
    #endregion // PRIVATE_METHODS
}

Please help me

Thanks and Best regards

AttachmentSize
Image icon Screenshot_2014-07-18-01-52-44.png1.25 MB
Log in or register to post comments