2

This is not something that would normally be desired but I need this for a research project.

How can I make a scene start and run as normal but make the screen output delayed by a fixed number of seconds. I.e. The game runs and responds to user input in real time, but the output to the screen is delayed by x seconds?

4
  • 2
    For sure it's not a usual need! I would use a Camera rendering only to a render target (render texture) with a Queue (as a frame buffer). Push the textures retrieved by your camera into the queue and "pop" them with a delay of X seconds. If I have time, I will try to create a script.
    – Hellium
    Jul 10, 2017 at 16:54
  • You might explain what you mean by "screen output". Do you just want the screen to be black and then have the black replaced by the normal rendering after a time, or do you want some base scene shown and then you want to add or change something after input is received? Jul 10, 2017 at 16:54
  • I guess something like a frame buffer on the camera, so the screen would be blank for say 2 seconds when you start the scene and then you will see the camera output as it was 2 seconds ago, so if I then move the player as soon as I see the scene, I will only see the results 2 seconds later.
    – ceteri
    Jul 10, 2017 at 17:28
  • Hellium any advice on how to create a script that would do that would be greatly appreciated
    – ceteri
    Jul 10, 2017 at 17:30

2 Answers 2

5

After some optimizations (asked on Unity Answer), I've reworked my solution.

I use an array with a fixed size and two integers used to keep track of the captured frame and the rendered one.

using UnityEngine;
using System.Collections;

public class DelayedCamera : MonoBehaviour
{
    public struct Frame
    {
        /// <summary>
        /// The texture representing the frame
        /// </summary>
        private Texture2D texture;

        /// <summary>
        /// The time (in seconds) the frame has been captured at
        /// </summary>
        private float recordedTime;

        /// <summary>
        /// Captures a new frame using the given render texture
        /// </summary>
        /// <param name="renderTexture">The render texture this frame must be captured from</param>
        public void CaptureFrom( RenderTexture renderTexture )
        {
            RenderTexture.active = renderTexture;

            // Create a new texture if none have been created yet in the given array index
            if ( texture == null )
                texture = new Texture2D( renderTexture.width, renderTexture.height );

            // Save what the camera sees into the texture
            texture.ReadPixels( new Rect( 0, 0, renderTexture.width, renderTexture.height ), 0, 0 );
            texture.Apply();

            recordedTime = Time.time;

            RenderTexture.active = null;
        }

        /// <summary>
        /// Indicates whether the frame has been captured before the given time
        /// </summary>
        /// <param name="time">The time</param>
        /// <returns><c>true</c> if the frame has been captured before the given time, <c>false</c> otherwise</returns>
        public bool CapturedBefore( float time )
        {
            return recordedTime < time;
        }

        /// <summary>
        /// Operator to convert the frame to a texture
        /// </summary>
        /// <param name="frame"></param>
        public static implicit operator Texture2D( Frame frame ) { return frame.texture; }
    }

    /// <summary>
    /// The camera used to capture the frames
    /// </summary>
    [SerializeField]
    private Camera renderCamera;

    /// <summary>
    /// The delay
    /// </summary>
    [SerializeField]
    private float delay = 0.5f;

    /// <summary>
    /// The size of the buffer containing the recorded images
    /// </summary>
    /// <remarks>
    /// Try to keep this value as low as possible according to the delay
    /// </remarks>
    private int bufferSize = 256;

    /// <summary>
    /// The render texture used to record what the camera sees
    /// </summary>
    private RenderTexture renderTexture;

    /// <summary>
    /// The recorded frames
    /// </summary>
    private Frame[] frames;

    /// <summary>
    /// The index of the captured texture
    /// </summary>
    private int capturedFrameIndex;

    /// <summary>
    /// The index of the rendered texture
    /// </summary>
    private int renderedFrameIndex;

    /// <summary>
    /// The frame index
    /// </summary>
    private int frameIndex;

    private void Awake()
    {
        frames = new Frame[bufferSize];

        // Change the depth value from 24 to 16 may improve performances. And try to specify an image format with better compression.
        renderTexture = new RenderTexture( Screen.width, Screen.height, 24 );
        renderCamera.targetTexture = renderTexture;
        StartCoroutine( Render() );
    }

    /// <summary>
    /// Makes the camera render with a delay
    /// </summary>
    /// <returns></returns>
    private IEnumerator Render()
    {
        WaitForEndOfFrame wait = new WaitForEndOfFrame();

        while ( true )
        {
            yield return wait;

            capturedFrameIndex = frameIndex % bufferSize;

            frames[capturedFrameIndex].CaptureFrom( renderTexture );

            // Find the index of the frame to render
            // The foor loop is **voluntary** empty
            for ( ; frames[renderedFrameIndex].CapturedBefore( Time.time - delay ) ; renderedFrameIndex = ( renderedFrameIndex + 1 ) % bufferSize ) ;

            Graphics.Blit( frames[renderedFrameIndex], null as RenderTexture );

            frameIndex++;
        }
    }
}

Original Answer

I made this script, but it's far from being optimized! Put the following script on an empty / your camera and drag & drop the camera gameobject to the renderCamera field in the inspector.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class DelayedCamera : MonoBehaviour
{
    [SerializeField]
    private Camera renderCamera;

    private RenderTexture renderTexture;

    private Queue<Texture2D> frames;

    private void Awake()
    {
        frames = new Queue<Texture2D>();

        // Change the depth value from 24 to 16 may improve performances. And try to specify an image format with better compression.
        renderTexture = new RenderTexture( Screen.width, Screen.height, 24 );
        renderCamera.targetTexture = renderTexture;
        StartCoroutine( Render() );
    }

    private IEnumerator Render()
    {
        WaitForEndOfFrame wait = new WaitForEndOfFrame();

        while ( true )
        {
            yield return wait;

            // Create new texture of the current frame
            RenderTexture.active = renderTexture;

            // Making this variable a class attribute may be more efficient
            Texture2D texture = new Texture2D( renderTexture.width, renderTexture.height );
            texture.ReadPixels( new Rect( 0, 0, renderTexture.width, renderTexture.height ), 0, 0 );
            texture.Apply();
            RenderTexture.active = null;

            // Add it to the queue to "delay" the rendering
            frames.Enqueue( texture );

            // If the queue is too big, render the first frame on the screen
            if ( frames.Count > 100 )
            {
                Graphics.Blit( frames.Dequeue(), null as RenderTexture );
            }
        }
    }
}
10
  • Thanks this is exactly the effect i am looking for and is a great help. I will need to find a way to improve performance. I need it the same or very close to a regular camera, but this is a great help, thank you
    – ceteri
    Jul 10, 2017 at 20:19
  • You can improve performance by not creating Textures every frame with new Texture2D. Do that outside the while loop then re-use it. Only create new texture if the dimension of theRenderTexture changes.
    – Programmer
    Jul 10, 2017 at 21:11
  • 1
    Yes, that's what I thought, and I added the comment in the code inviting the OP to make the texture variable a class attribute instead.
    – Hellium
    Jul 10, 2017 at 21:21
  • The script works very well initially, but performance degrades over time, eventually after about 20 seconds the scene crashes with a System out of memory error. any ideas how to fix this? memory issue appears to have happened at UnityEngine.Texture2D:ReadPixels(Rect, Int32, Int32)<Render>c_Iterator():MoveNext()
    – ceteri
    Jul 11, 2017 at 8:21
  • Maybe, you could create a fixed length array instead of using a Queue, filled with Textures you reuse (instead of creating and destroying each frame). Then, use an index to track the index of the last frame you captured. (index + 1) % array.Length will be the frame to render (if the frame has been captured previsouly)
    – Hellium
    Jul 11, 2017 at 9:11
0

You can execute every action as a Coroutine and use the function WaitForSeconds to wait x seconds

Documentation: https://docs.unity3d.com/ScriptReference/WaitForSeconds.html

1
  • That is not exactly the same thing, the difference will matter if there is any kind of networking involved. Jul 10, 2017 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.