Unity将函数转换为Coroutine

时间:2017-05-30 19:15:13

标签: c# unity3d coroutine

我的图像有问题我试图写入光盘(图像尺寸应为1280x1024,但它将其保存为512x512),我想知道是否一个Coroutine可以解决这个问题吗?如果是这样,我对Coroutines来说是全新的,有人可以说明我下面编写的代码将如何转换为Coroutine吗?非常感谢。

// Saves texture as PNG file.
using UnityEngine;
using System.Collections;
using System.IO;

public class SaveTexture : MonoBehaviour {

    public RenderTexture tex;
    int tWidth, tHeight;

    int getTextureWidth(int texWidth)
    {
        return tex.width;
    }

    int getTextureHeight(int texHeight)
    {
        return tex.height;
    }

    public void Start()
    {
        tWidth = getTextureWidth(tex.width);
        tHeight = getTextureHeight(tex.height);

        Debug.Log("RenderTexture Width: " + tWidth + ", RenderTexture Height: " + tHeight);
    }

    Texture2D toTexture2D(RenderTexture rTex)
    {
        Texture2D tex = new Texture2D(tWidth, tHeight, TextureFormat.ARGB32, false);
        RenderTexture.active = rTex;
        tex.ReadPixels(new Rect(0, 0, tWidth, tHeight), 0, 0);
        tex.Apply();
        return tex;
    }

    // Save Texture as PNG
    public void SaveTexturePNG()
    {
        Texture2D myTexture = tex.toTexture2D();

        tWidth = getTextureWidth(myTexture.width);
        tHeight = getTextureHeight(myTexture.height);

        Debug.Log("Texture2D Width: " + tWidth + ", Texture2D Height: " + tHeight);

        // Encode texture into PNG
        byte[] bytes = myTexture.EncodeToPNG();
        Object.Destroy(myTexture);

        Debug.Log(bytes.Length);

        // For testing purposes, also write to a file in the project folder
        File.WriteAllBytes(Application.dataPath + "/../AnimalTexture/AnimalTexture.png", bytes);
    }
}

0 个答案:

没有答案