Unity3D Camera.targetTexture 目标纹理

Unity3D Camera.targetTexture 目标纹理_第1张图片



using UnityEngine;
using System.Collections;
using System.IO;

public class Move : MonoBehaviour
{
    public RenderTexture test;
    Texture2D image;

    // Use this for initialization
    void Start()
    {
        test = new RenderTexture(512, 512, 24);
        image = new Texture2D(512, 512);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Camera.mainCamera.targetTexture = test;
            StartCoroutine(SaveImage());
        }
    }

    IEnumerator SaveImage()
    {

        //yield return new WaitForEndOfFrame();
        image.ReadPixels(new Rect(0, 0, 512, 512), 0, 0, true);
        image.Apply();
        byte[] imageBytes = image.EncodeToPNG();
        File.WriteAllBytes(Application.dataPath + "/image.png", imageBytes);
        yield return null;
    }
}

虽然会保存图片,但是报错

ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
UnityEngine.Texture2D:ReadPixels(Rect, Int32, Int32, Boolean)
<SaveImage>c__Iterator0:MoveNext() (at Assets/Move.cs:31)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
Move:Update() (at Assets/Move.cs:23)

你可能感兴趣的:(unity3d)