Create and Load Targets in Unity

This article suggests methods for loading and activating targets from databases at runtime in Unity. It also presents how Image Targets can be created instantly from an image asset:

Image Targets can be created either directly from an image asset or from a database downloaded from the Vuforia Target Manager.

Your Vuforia developer account can be used to create and manage your target databases in the Target Manager on the Vuforia developer webpage. See the article Getting Started with the Vuforia Target Manager for more information.

If you are looking for loading targets in native, please refer to How to Create and Modify Targets in Native.

Create an Image Target from an Image Asset

There are two ways in which Image Target databases can be generated.

  1. Using an image asset in the Unity Editor to create an Instant Image Target
  2. Using the Vuforia Target Manager to generate a device database and load the target from it.

Create instant Image Target

  1. Open an empty Unity Project and enable Vuforia through the Package Manager.
  2. Create an ARCamera GameObject and insert a license from your Vuforia Developer account into the license key field found in VuforiaConfiguration in the ARCamera.
  3. Load a detailed JPG or PNG image into the assets folder.
  4. Create a new Vuforia Engine Image GameObject

  1. In the Inspector of the ImageTarget GameObject, make sure that Type is set to From Image.
  2. Drag the image file you wish to use to the empty box labeled Image and provide it with a name.
    1. It may that you need to set the image to “Read/Write Enabled” in the advanced import settings. The inspector will display a message if additional actions are required or if the image is in risk of being rescaled upon target creation.

NOTE: The expandable Advanced menu is for rescaling the ImageTarget GameObject.

  1.  Place your AR content as a child on the ImageTarget GameObject and use Vuforia's Play Mode by pressing Play or deploy the app to your device.

Create Instant Image Targets at Runtime from a file or Texture2D Objects

Alternatively, Instant Image Targets can be created at runtime in C#. Attach the following code to any GameObject in the scene. The script loads an image file from the Streaming Assets folder and creates an Image Target from it, at runtime.

NOTE: A license key must be added to use instant Image Targets.

Image Target from a file

using UnityEngine;
using Vuforia;

public class SideLoadImageTarget : MonoBehaviour
{
    public Texture2D textureFile;
    public float printedTargetSize;
    public string targetName;


    void Start()
    {
       // Use Vuforia Application to invoke the function after Vuforia Engine is initialized
       VuforiaApplication.Instance.OnVuforiaStarted += CreateImageTargetFromSideloadedTexture;
    }

    void CreateImageTargetFromSideloadedTexture()
    {
        var mTarget = VuforiaBehaviour.Instance.ObserverFactory.CreateImageTarget(
            textureFile,
            printedTargetSize,
            targetName);

        // add the Default Observer Event Handler to the newly created game object
        mTarget.gameObject.AddComponent<DefaultObserverEventHandler>();

        Debug.Log("Instant Image Target created " + mTarget.TargetName);
    }
}

Image Target from a texture2D source

The code example below will allow you to download a texture image from a web URL and generate an image target from it. Attach the script to the ARCamera GameObject.

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using Vuforia;

public class SideLoadFromWeb : MonoBehaviour
{
    Texture2D imageFromWeb;
    void Start()
    {
        VuforiaApplication.Instance.OnVuforiaInitialized += OnVuforiaInitialized;
    }

    void OnVuforiaInitialized(VuforiaInitError error)
    {
        StartCoroutine(RetrieveTextureFromWeb());
    }

    IEnumerator RetrieveTextureFromWeb()
    {
        using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture("https://library.vuforia.com/sites/default/files/vuforia-library/articles/solution/Magic%20Leap%20Related%20Content/Astronaut-scaled.jpg"))
        {
            yield return uwr.SendWebRequest();

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(uwr.error);
            }
            else
            {
                // Get downloaded texture once the web request completes
                var texture = DownloadHandlerTexture.GetContent(uwr);

                imageFromWeb = texture;

                Debug.Log("Image downloaded " + uwr);

                CreateImageTargetFromDownloadedTexture();
            }
        }
    }

    void CreateImageTargetFromDownloadedTexture()
    {
        var mTarget = VuforiaBehaviour.Instance.ObserverFactory.CreateImageTarget(
    imageFromWeb,
    0.1f,
    "Astronaut");

        // Add the DefaultObserverEventHandler to the newly created game object
        mTarget.gameObject.AddComponent<DefaultObserverEventHandler>();

        Debug.Log("Target created and active" + mTarget);
    }
}

Create an Image Target from a Device Database at Runtime

Similar to other instant Image Target creation method, you specify a storage path when loading from a local directory. For larger apps, the device database may be bundled with the application in StreamingAssets/Vuforia. See Building Large Vuforia Apps in Unity for more details on loading assets. The script below does the following.

  1. Check whether the file at the given storage location exists using File.Exists()
  2. Invokes the CreateFromDatabase when Vuforia is started.
  3. Creates a new target from the database with databasePath and targetName. These must be accurate. You can check the target names in the .xml file of the dataset.
  4. Activates the target.
using System.IO;
using UnityEngine;
using Vuforia;

public class CreateFromDatabase : MonoBehaviour
{
    string dataSetPath = "Vuforia/VuforiaMars_Images.xml";
    string targetName = "Astronaut";

    // Start is called before the first frame update
    void Start()
    {
        VuforiaApplication.Instance.OnVuforiaInitialized += OnVuforiaInitialized;

    }

    void OnVuforiaInitialized(VuforiaInitError error)
    {
        if (error == VuforiaInitError.NONE)
            LoadFromDatabase();
    }

    // Load and activate a data set at the given path.
    private void LoadFromDatabase()
    {
        // Check if the database set exists at the given path.
        if (!File.Exists(dataSetPath))
        {
            Debug.LogError("Data set " + dataSetPath + " does not exist.");
        }
        else
        {
            // Create an Image Target from the database.
            var mImageTarget = VuforiaBehaviour.Instance.ObserverFactory.CreateImageTarget(
                dataSetPath,
                targetName );
        }
    }
}

Setting the Size of an Image Target at Runtime

Modify targets at runtime and its child objects to enable users in the AR experience. In this example, an Image Target is scaled with a button press. Your Unity scene requires an Image Target GameObject with a cube as a child and a button UI for executing SizeMyTarget().

Attach the following script to the Image Target GameObject and assign it to the button’s OnClick() event with the method.

The sample code:

using UnityEngine;
using Vuforia;

public class SizeImageTarget : MonoBehaviour
{
    ImageTargetBehaviour mImageTarget;
    public float scale = 2;

    public void SizeMyTarget()
    {
        mImageTarget = GetComponent<ImageTargetBehaviour>();
        if (!mImageTarget)
        {
            Debug.LogError("Cannot set scale, missing target input");
            return;
        }

        // First deactivate the Image Target
        mImageTarget.enabled = false;

        // Query the current Image Target size
        Vector2 currentSize = mImageTarget.GetSize();

        // Set the new size with a scale factor to height or width
        float width = currentSize.x;
        float newSize = scale * width;

        mImageTarget.SetWidth(newSize);

        // Re-activate the Image Target
        mImageTarget.enabled = true;
    }
}

Activating Targets at Runtime

It is also possible to enable and disable your targets at runtime if you for example wish to switch between tracking targets.

Attach the script below to an ImageTarget GameObject with its Image Target Behaviour component disabled.

using UnityEngine;
using Vuforia;

public class ActivateTargets : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        VuforiaApplication.Instance.OnVuforiaStarted += ActivateTarget;
    }

    void ActivateTarget()
    {
        ImageTargetBehaviour imageTarget = GetComponent<ImageTargetBehaviour>();
        imageTarget.enabled = true;
    }

}