I want to switch advanced model target database dynamically in runtime how can it be achieved?

70 Views Asked by At

I am building a hololens app using mrtk with vuforia and using advanced model target I am have multiple models in a database I want to switch those models in runtime.

I tried creating multiple model target behavior and enabling one by one and destroy the previous one I don't think this is the best practice to do this.

I have tried creating this script but it didn't work.

using System.IO;
using UnityEngine;
using UnityEngine.UI;
using Vuforia;

public class CreateFromDatabase : MonoBehaviour
{
    string[] dataSetPaths;
    string[] targetNames;
    int currentIndex = 0;
    ObserverBehaviour mModelTarget;


    void Start()
    {
        VuforiaApplication.Instance.OnVuforiaInitialized += OnVuforiaInitialized;
    }

    void OnVuforiaInitialized(VuforiaInitError error)
    {
        if (error == VuforiaInitError.NONE)
            OnVuforiaStarted();
        else
            Debug.LogError("Vuforia initialization error: " + error.ToString());
    }

    void OnVuforiaStarted()
    {
        LoadDataSetAndTarget();
    }

    void LoadDataSetAndTarget()
    {
        if (currentIndex < 0 || currentIndex >= dataSetPaths.Length)
        {
            Debug.LogError("Invalid currentIndex: " + currentIndex);
            return;
        }


        mModelTarget = VuforiaBehaviour.Instance.ObserverFactory.CreateModelTarget(
            dataSetPaths[currentIndex],
            targetNames[currentIndex]);

        if (mModelTarget == null)
        {
            Debug.LogError("Failed to create Model Target observer.");
            return;
        }

        mModelTarget.OnTargetStatusChanged += OnTargetStatusChanged;
    }

    void OnTargetStatusChanged(ObserverBehaviour behaviour, TargetStatus status)
    {
        Debug.Log($"Target status: {status.Status}");

        if (status.Status == Status.TRACKED)
        {
            // additional logic 
        }
    }

    public void OnChangeDatabaseButtonClick()
    {
        currentIndex = (currentIndex + 1) % dataSetPaths.Length;
        
        UnloadDataSetAndTarget();
        
        LoadDataSetAndTarget();
    }

    void UnloadDataSetAndTarget()
    {

        if (mModelTarget != null)
        {
            mModelTarget.OnTargetStatusChanged -= OnTargetStatusChanged;
            Destroy(mModelTarget);
        }
    }
}
0

There are 0 best solutions below