一个脚本实现实时小窗口功能

        有时候我就在想,之前的实时小窗口都是通过摄像机来实现的,而unity自带截图功能,为什么我不能每帧生成一个截图然后调用他,把他赋值给image,然后就可以在场景上实现实时窗口的功能,同时我也可以加一条if判断来停止他,从而获得某一时刻的截图。

        说干就干,代码内容很简单:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ScreenShot : MonoBehaviour
{
    public Image image;
    public Camera screenshotCamera; // 用于截图的摄像机

    private void Update()
    {
        // if (Input.GetMouseButtonDown(0))
        // {
        StartCoroutine(ScreenShot_ScreenCapture());
        // }
    }

    private IEnumerator ScreenShot_ScreenCapture()
    {
        // 禁用Image组件
        image.enabled = false;

        // 创建RenderTexture来渲染截图
        RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
        screenshotCamera.targetTexture = renderTexture;
        screenshotCamera.Render();

        // 保存RenderTexture为截图
        RenderTexture.active = renderTexture;
        Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();
        byte[] bytes = texture.EncodeToPNG();
        string screenshotPath = "D:/jietu.png";
        System.IO.File.WriteAllBytes(screenshotPath, bytes);

        // 恢复Image组件状态
        image.enabled = true;

        // 释放渲染相关资源
        RenderTexture.active = null;
        screenshotCamera.targetTexture = null;
        renderTexture.Release();

        // 加载截图并将其转换为Sprite
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);

        // 将Sprite赋值给Image组件
        image.sprite = sprite;
        yield return null;
    }
}

        写好代码后,只需要把代码挂载到一个空物体上,然后把image和摄像机赋值就会得到效果

        运行结果如下:

         当然,我们只需要在update中添加if条件便可以实现自己想要的效果,是不是非常简单。