gpt4 book ai didi

c# - 从相机截取屏幕截图然后在 (WaitForEndOfFrame) 上禁用它是否正确?

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:30 25 4
gpt4 key购买 nike

我制作了这个非常简单的脚本,它应该附加到带有 renderTexure 的非事件相机游戏对象。如果相机 Gameobject 处于事件状态,则假设仅将一帧记录到 renderTexure,然后以 .png 格式保存到路径。之后应该禁用相机。

    public static string path;

void Update()
{
StartCoroutine(SSOT());
}

public static void SaveRTToFileToSharing()
{
RenderTexture rt = Resources.Load<RenderTexture>(@"Render Texure/ScreenShot") as RenderTexture;

RenderTexture.active = rt;
Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
//RenderTexture.active = null;
tex.Apply();
byte[] bytes;
bytes = tex.EncodeToPNG();

path = Application.persistentDataPath + "Test Shot.png";
System.IO.File.WriteAllBytes(path, bytes);
Destroy(tex);
}

IEnumerator SSOT()
{
yield return new WaitForEndOfFrame();
SaveRTToFileToSharing();
gameObject.SetActive(false);
}

该脚本按我的预期工作,但我不确定它是否真的只记录一帧或更多帧。如果你要改变什么,你会改变什么?

最佳答案

应该没问题,因为您在启用它的同一帧中停用了该对象。

无论如何,只是为了确保我不会使用每帧调用的 Update,只需将 StartCoroutine 调用移动到 OnEnable 即可。每次游戏对象被激活时都会调用它。

private void OnEnable()
{
StartCoroutine(SSOT());
}

为了提高性能,有些事情你只能做一次并重复使用它们——当然取决于你的优先级:如果你的优先级是很少的内存使用,而性能对屏幕截图来说无关紧要,那么你就很好当然。否则我可能会这样做

private RenderTexture rt;
private Texture2D tex;
private string path;

private void Awake ()
{
// Do this only once and keep it around while the game is running
rt = (RenderTexture) Resources.Load<RenderTexture>(@"Render Texure/ScreenShot");

tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);

path = Application.persistentDataPath + "Test Shot.png";
}

private void SaveRTToFileToSharing()
{
RenderTexture.active = rt;

tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
//RenderTexture.active = null;
tex.Apply();
byte[] bytes;
bytes = tex.EncodeToPNG();

// This happens async so your game can continue meanwhile
using (var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write))
{
fileStream.WriteAsync(bytes, 0, bytes.Length);
}
}

关于c# - 从相机截取屏幕截图然后在 (WaitForEndOfFrame) 上禁用它是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56841391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com