Unity Version : 2022.3.16f1 LTS 2024 컴퓨터공학과 캡스톤디자인 - Next Reality

실시간으로 오브젝트 다운받기 (GLTF)

코드

// ObjectCRUD.cs
 
IEnumerator ChangeMyHand()
{
    while (Application.isPlaying)
    {
        string filename;
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            filename = "duck.glb";
            LoadGltfModel(filename); 
        }
 
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            filename = "wolf.glb";
            LoadGltfModel(filename);
        }
        yield return null;
    }
}
 
async void LoadGltfModel(string filename)
{
    string fullFilePath = Path.Combine(Application.persistentDataPath, localDirectory, filename);
    if (!File.Exists(fullFilePath))
    {
        StartCoroutine(DownGltfModel(filename));
        // while (!File.Exists(fullFilePath)) {continue;}
    }
 
    if (isLoaded)
    {
        Debug.Log("Loading...");
        byte[] byteData = File.ReadAllBytes(fullFilePath);
        var gltf = new GltfImport();
        bool success = await gltf.LoadGltfBinary(byteData);
        if (success)
        {
            GameObject gltfObj = new GameObject("gltfObj");
            success = await gltf.InstantiateMainSceneAsync(gltfObj.transform);
            if (success)
            {
                MeshCollider collider = gltfObj.AddComponent<MeshCollider>();
                if (collider != null)
                    collider.convex = true;
 
                Rigidbody rb = gltfObj.AddComponent<Rigidbody>();
                if (rb != null)
                    rb.mass = 1.0f;
 
                BoxCollider boxCollider = gltfObj.AddComponent<BoxCollider>();
 
                Debug.Log("Asset Load Success : " + fullFilePath);
                onMyHand = gltfObj;
            }
            else
            {
                Debug.Log("Failed to Load Asset");
            }
        }
        else
        {
            Debug.Log("Failed to Load Asset");
        }
        isLoaded = false;
    }
}
 
IEnumerator DownGltfModel(string filename)
{
    Debug.Log("Download Start. URL : " + gltfServer + filename);
    UnityWebRequest request = UnityWebRequest.Get(gltfServer + filename);
    yield return request.SendWebRequest();
 
    if (request.result == UnityWebRequest.Result.Success)
    {
        string fullPath = Path.Combine(Application.persistentDataPath, localDirectory, filename);
        
        FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create);
        fs.Write(request.downloadHandler.data, 0, (int)request.downloadedBytes);
        fs.Close();
 
        Debug.Log("Asset Down Success : " + fullPath);
        isLoaded = true;
    }
    else
    {
        Debug.LogError("Failed to Download GLTF File : " + request.error);
    }
    yield return null;
}

참고자료

팀원이 올려준 코드