Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Change FacePrefab in ARFaceManager programmatically

Discussion in 'AR' started by DJ_XYZ, Feb 28, 2023.

  1. DJ_XYZ

    DJ_XYZ

    Joined:
    Feb 24, 2023
    Posts:
    2
    Hi!

    I just started learning AR and started with face masks. I managed to add a mask, but I don't understand how to change it in runtime.

    I wrote this code to change the mask, but when I call the "ChangeFaceMask" method, I see that it has changed in ArFaceManager (arFaceManager.facePrefab), but the mask does not change visually.

    What am I doing wrong?

    Code (CSharp):
    1. public class FaceMaskHelper : MonoBehaviour
    2. {
    3.     public GameObject[] faceMasks;
    4.     ARFaceManager arFaceManager;
    5.  
    6.     void Start()
    7.     {
    8.         arFaceManager = gameObject.GetComponent<ARFaceManager>();
    9.     }
    10.  
    11.     void Update()
    12.     {
    13.      
    14.     }
    15.  
    16.     void ChangeFaceMask(String maskName)
    17.     {
    18.         for (int i = 0; i < faceMasks.Length; i++)
    19.         {
    20.             GameObject go = faceMasks[i];
    21.  
    22.             if (go.name == maskName)
    23.             {
    24.                 arFaceManager.facePrefab = go;
    25.                 break;
    26.             }
    27.         }
    28.     }
    29. }
     
  2. DJ_XYZ

    DJ_XYZ

    Joined:
    Feb 24, 2023
    Posts:
    2
    I solved the problem with dynamically changing the mask in runtime. It turns out that you need to change the material at ARFace, and not the prefab at ARFaceManager.

    Code (CSharp):
    1. [RequireComponent(typeof(ARFaceManager))]
    2. public class FaceMaskHelper : MonoBehaviour
    3. {
    4.     public Material[] faceMasks;
    5.  
    6.     private ARFaceManager arFaceManager;
    7.  
    8.     void Start()
    9.     {
    10.         arFaceManager = gameObject.GetComponent<ARFaceManager>();
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.        
    16.     }
    17.  
    18.     void ChangeFaceMask(String faceMaskName)
    19.     {
    20.         for (int i = 0; i < faceMasks.Length; i++)
    21.         {
    22.             Material faceMaskMaterial = faceMasks[i];
    23.  
    24.             if (faceMaskMaterial.name == faceMaskName)
    25.             {
    26.                 foreach (ARFace arFace in arFaceManager.trackables)
    27.                 {
    28.                     arFace.GetComponent<MeshRenderer>().material = faceMaskMaterial;
    29.                 }
    30.  
    31.                 break;
    32.             }
    33.         }
    34.     }
    35. }
     
    andyb-unity likes this.