https://blog.csdn.net/puppet_master/article/details/72669977
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class CommandBufferTest : MonoBehaviour
{
private CommandBuffer commandBuffer = null;
private RenderTexture renderTexture = null;
private Renderer targetRenderer = null;
public GameObject targetObject = null;
public Material replaceMaterial = null;
void OnEnable()
{
targetRenderer = targetObject.GetComponentInChildren<Renderer>();
renderTexture = RenderTexture.GetTemporary(512, 512, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default, 4);
commandBuffer = new CommandBuffer();
commandBuffer.SetRenderTarget(renderTexture);
commandBuffer.ClearRenderTarget(true, true, Color.gray);
Material mat = replaceMaterial == null ? targetRenderer.sharedMaterial : replaceMaterial;
commandBuffer.DrawRenderer(targetRenderer, mat);
this.GetComponent<Renderer>().sharedMaterial.mainTexture = renderTexture;
Camera.main.AddCommandBuffer(CameraEvent.AfterForwardOpaque, commandBuffer);
}
void OnDisable()
{
Camera.main.RemoveCommandBuffer(CameraEvent.AfterForwardOpaque, commandBuffer);
commandBuffer.Clear();
renderTexture.Release();
}
}