Рендирование текстуры рендеринга вне цикла рендеринга URP
Чтобы запустить камеру для рендеринга текстуры рендеринга вне цикла рендеринга Universal Render Pipeline (URP), используйте SingleCameraRequest и SubmitRenderRequest APIs в сценарии C#.
Выполните следующие действия:
-
Создайте запрос на отображение типа
UniversalRenderPipeline.SingleCameraRequest. Например:UniversalRenderPipeline.SingleCameraRequest request = new UniversalRenderPipeline.SingleCameraRequest(); -
Проверьте, поддерживает ли камера тип запроса рендеринга, используя
RenderPipeline.SupportsRenderRequestAPI. Например, чтобы проверить основную камеру:Camera mainCamera = Camera.main; if (RenderPipeline.SupportsRenderRequest(mainCamera, request)) { ... } -
Установите цель камеры на объект
RenderTexture, используя параметрdestinationзапроса на рендирование. Например:request.destination = myRenderTexture; -
Рендирование текстуры рендеринга с помощью SubmitRenderRequest API. Например:
RenderPipeline.SubmitRenderRequest(mainCamera, request);
Чтобы убедиться, что все камеры закончили рендеринг до того, как вы рендеринг текстуры рендеринга, используйте один из следующих подходов:
- Короутина, которая ожидает окончания кадра. Дополнительные сведения см. в WaitForEndOfFrame API.
- Обратный вызов. Дополнительную информацию см. в RenderPipelineManager.endContextRendering API.
Пример
В следующем примере несколько камер отображаются в нескольких текстурах рендеринга. Чтобы использовать этот пример, выполните следующие действия:
- В вашем проекте Unity добавьте код в новый скрипт C# под названием
SingleCameraRenderRequest.cs. - Добавьте скрипт к GameObject в вашей сцене.
- В окне Inspector программы GameObject назначите камеры и текстуры рендеринга. Убедитесь, что количество камер соответствует количеству текстур рендеринга.
- Введите режим воспроизведения.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
public class SingleCameraRenderRequest : MonoBehaviour
{
public Camera[] cameras;
public RenderTexture[] renderTextures;
void Start()
{
// Make sure all data is valid before you start the component
if (cameras == null || cameras.Length == 0 || renderTextures == null || cameras.Length != renderTextures.Length)
{
Debug.LogError("Invalid setup");
return;
}
// Start the asynchronous coroutine
StartCoroutine(RenderSingleRequestNextFrame());
// Call a method called OnEndContextRendering when a camera finishes rendering
RenderPipelineManager.endContextRendering += OnEndContextRendering;
}
void OnEndContextRendering(ScriptableRenderContext context, List<Camera> cameras)
{
// Create a log to show cameras have finished rendering
Debug.Log("All cameras have finished rendering.");
}
void OnDestroy()
{
// End the subscription to the callback
RenderPipelineManager.endContextRendering -= OnEndContextRendering;
}
IEnumerator RenderSingleRequestNextFrame()
{
// Wait for the main camera to finish rendering
yield return new WaitForEndOfFrame();
// Enqueue one render request for each camera
SendSingleRenderRequests();
// Wait for the end of the frame
yield return new WaitForEndOfFrame();
// Restart the coroutine
StartCoroutine(RenderSingleRequestNextFrame());
}
void SendSingleRenderRequests()
{
//Iterates over the cameras array.
for (int i = 0; i < cameras.Length; i++)
{
UniversalRenderPipeline.SingleCameraRequest request =
new UniversalRenderPipeline.SingleCameraRequest();
// Check if the active render pipeline supports the render request
if (RenderPipeline.SupportsRenderRequest(cameras[i], request))
{
// Set the destination of the camera output to the matching RenderTexture
request.destination = renderTextures[i];
// Render the camera output to the RenderTexture synchronously
RenderPipeline.SubmitRenderRequest(cameras[i], request);
// At this point, the RenderTexture in renderTextures[i] contains the scene rendered from the point
// of view of the Camera in cameras[i]
}
}
}
}