/// <summary> /// Fills in gltfTexture.unityTexture with a Texture2D. /// </summary> /// <param name="gltfTexture">The glTF texture to convert.</param> /// <param name="loader">The IUriLoader to use for loading image files.</param> /// <returns>On completion of the coroutine, gltfTexture.unityTexture will be non-null /// on success.</returns> private static IEnumerable ConvertTextureCoroutine( GltfTextureBase gltfTexture, IUriLoader loader) { if (gltfTexture.unityTexture != null) { throw new InvalidOperationException("Already converted"); } if (gltfTexture.SourcePtr == null) { Debug.LogErrorFormat("No image for texture {0}", gltfTexture.GltfId); yield break; } Texture2D tex; if (gltfTexture.SourcePtr.data != null) { // This case is hit if the client code hooks up its own threaded // texture-loading mechanism. var data = gltfTexture.SourcePtr.data; tex = new Texture2D(data.colorWidth, data.colorHeight, data.format, true); yield return(null); tex.SetPixels32(data.colorData); yield return(null); tex.Apply(); yield return(null); } else { #if UNITY_EDITOR // Prefer to load the Asset rather than create a new Texture2D; // that lets the resulting prefab reference the texture rather than // embedding it inside the prefab. tex = loader.LoadAsAsset(gltfTexture.SourcePtr.uri); #else tex = null; #endif if (tex == null) { byte[] textureBytes; using (IBufferReader r = loader.Load(gltfTexture.SourcePtr.uri)) { textureBytes = new byte[r.GetContentLength()]; r.Read(textureBytes, destinationOffset: 0, readStart: 0, readSize: textureBytes.Length); } tex = new Texture2D(1, 1); tex.LoadImage(textureBytes, markNonReadable: false); yield return(null); } } tex.name = SanitizeName(gltfTexture.SourcePtr.uri); gltfTexture.unityTexture = tex; }