Unity 6.3
0 онлайн 111 гостей 3 в системе
Вход
Камера Шаг 61 из 82

Рендирование текстуры рендеринга вне цикла рендеринга URP

Чтобы запустить камеру для рендеринга текстуры рендеринга вне цикла рендеринга Universal Render Pipeline (URP), используйте SingleCameraRequest и SubmitRenderRequest APIs в сценарии C#.

Выполните следующие действия:

  1. Создайте запрос на отображение типа UniversalRenderPipeline.SingleCameraRequest. Например:

    UniversalRenderPipeline.SingleCameraRequest request = new UniversalRenderPipeline.SingleCameraRequest();
    
  2. Проверьте, поддерживает ли камера тип запроса рендеринга, используя RenderPipeline.SupportsRenderRequest API. Например, чтобы проверить основную камеру:

    Camera mainCamera = Camera.main;
    
    if (RenderPipeline.SupportsRenderRequest(mainCamera, request))
    {
        ...
    }
    
  3. Установите цель камеры на объект RenderTexture, используя параметр destination запроса на рендирование. Например:

    request.destination = myRenderTexture;
    
  4. Рендирование текстуры рендеринга с помощью SubmitRenderRequest API. Например:

    RenderPipeline.SubmitRenderRequest(mainCamera, request);
    

Чтобы убедиться, что все камеры закончили рендеринг до того, как вы рендеринг текстуры рендеринга, используйте один из следующих подходов:

  • Короутина, которая ожидает окончания кадра. Дополнительные сведения см. в WaitForEndOfFrame API.
  • Обратный вызов. Дополнительную информацию см. в RenderPipelineManager.endContextRendering API.

Пример

В следующем примере несколько камер отображаются в нескольких текстурах рендеринга. Чтобы использовать этот пример, выполните следующие действия:

  1. В вашем проекте Unity добавьте код в новый скрипт C# под названием SingleCameraRenderRequest.cs.
  2. Добавьте скрипт к GameObject в вашей сцене.
  3. В окне Inspector программы GameObject назначите камеры и текстуры рендеринга. Убедитесь, что количество камер соответствует количеству текстур рендеринга.
  4. Введите режим воспроизведения.
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]
            }
        }
    }
}

Дополнительные ресурсы