Autofocus script in Unity Vuforia for Ar camera

Unity Vuforia Augmented Reality, Autofocus functionality

·

2 min read

Vuforia ARCamera prefab’s focus mode in Unity. There are different camera modes be found in Unity Vuforia.

When you use the Ar camera for Augmented reality or for 3d models rendering, the default camera does not support autofocus in case you want to change the focus, the script is used to implement a change of the focus mode in the Ar camera.

The first step is to remove the default camera from the Hierarchy tab on the left-hand side and add Arcamera prefabs. Now we will add the script below to the Arcamera components.

Select the Arcamera, on the right side an inspector panel should open in the inspector panel there will be an "Add Component" button.

Click on "Add Component" and add "new script" to the panel.

image.png

Name the file “CameraFocusController” and check the language selected is Csharp in the dropdown and then click on the “Create and Add” button.

Now a new script will be created in the Assets folder, open the file in the IDE by double-clicking or show in explorer on right-click.

Once the file is open, Add the following line into CameraFocusController.cs

using UnityEngine;
using System.Collections;
using Vuforia;
public class CameraFocusControllerNew : MonoBehaviour
{
    private bool mVuforiaStarted = false;
    void Start()
    {
        VuforiaARController vuforia = VuforiaARController.Instance;
        if (vuforia != null){
            vuforia.RegisterVuforiaStartedCallback(StartAfterVuforia);
        }
    }
    private void StartAfterVuforia()
    {
        mVuforiaStarted = true;
        SetAutofocus();
    }
    void OnApplicationPause(bool pause)
    {
        if (!pause)
        {
            // App resumed
            if (mVuforiaStarted)
            {
                // App resumed and vuforia already started
                // but lets start it again...
                SetAutofocus(); // This is done because some android devices lose the auto focus after resume
                // this was a bug in vuforia 4 and 5. I haven't checked 6, but the code is harmless anyway
            }
        }
    }
    private void SetAutofocus()
    {
        if (CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO))
        {
            Debug.Log("Autofocus set");
        }
        else
        {
            // never actually seen a device that doesn't support this, but just in case
            Debug.Log("this device doesn't support auto focus");
        }
    }
}

Note you can change the focus mode according to your need on function void OnApplicationPause(bool pause) and private void SetAutofocus().

For further details( developer.vuforia.com/forum/unity-extension.. ).