ProgrammingUnity

Unity Play Video On Canvas | Learn Unity Mir Imad Ahmed

Unity Play Video On Canvas

With the release of the new unity video player component, the problem of unity play video on canvas raised.

unity play video on canvas

unity play video on canvas

I have had hard time figuring out that how can one play video on canvas. Unity docs were not that good at the time I started on unity video player component.

Without further a do, I will come straight to the point:

First of all, you will have to add a video player component to the scene like this.

unity video player

unity video player

Then we can either select video clip or URL as the video source and the most important thing that we have to do is to select the render mode to be API Only like this:

unity video player component

unity video player component

Now lets add a Raw Image from UI menu to our scene like this:

unity ui raw image

unity ui raw image

Now you can resize the Raw Image to be however you want unity play video on canvas.

Now what you will have to do is to write a script that will tell unity to render the texture of the video upon this raw image’s texture.

Go on and add a script. I called mine StreamVideo. The code looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class StreamVideo : MonoBehaviour {
     public RawImage rawImage;
     public VideoPlayer videoPlayer;
     public AudioSource audioSource;
  // Use this for initialization
  void Start () {
          StartCoroutine(PlayVideo());
  }
  IEnumerator PlayVideo()
     {
          videoPlayer.Prepare();
          WaitForSeconds waitForSeconds = new WaitForSeconds(1);
          while (!videoPlayer.isPrepared)
          {
               yield return waitForSeconds;
               break;
          }
          rawImage.texture = videoPlayer.texture;
          videoPlayer.Play();
          audioSource.Play();
     }
}

Now it should render the video on our Raw Image on canvas. We can add custom play, pause, stop or any other buttons and then write code behinds in the same file for the video player component.

Thanks for reading!

Watch my All Unity Tutorials on youtube.