How to unload video with URL?

Hey! I’ve noticed that setting “videoPlayer.url” to null causes an error - it seems that it tries to load it as a URL.
I’m looking to unload the playing video and reset the state of the player for another video.

What is the correct way to reset a VideoPlayer?

Ta!
Tom

1 Like

Hi Tom!

Indeed, the VideoPlayer is pesky in that it doesn’t allow you to clear the url once it has been set. But just calling Stop() will clear any resource that has been allocated.

Hope this helps,

Dominique Leroux
A/V developer at Unity

Trying to clear the current video by:

videoPlayer.url = null;
-or-
videoPlayer.url = "";

results in:

ERROR: Can’t play movie [ ]

Is there any way around this? Or can I check if there is a loaded resource? Otherwise my code thinks the videoplayer is always loaded.

Checking videoPlayer.isPrepared does not work either, how do I fix this?

I managed to solve this by adding a new VideoPlayer and destroying the old one (while copying all parameters except for the URL).

Here’s an extension method that does all the work of copying the existing property values to the new VideoPlayer with the exception of the URL field:

using UnityEngine;
using UnityEngine.Video;
using System.Reflection;
public static class VideoPlayerExtensions
{
   public static VideoPlayer MakeCopy(this VideoPlayer original, bool copyURL=false)
   {
      var copy = original.gameObject.AddComponent<VideoPlayer>();
      PropertyInfo[] p = original.GetType().GetProperties();

      foreach (PropertyInfo prop in p)
      {
         if (!copyURL && prop.Name.Equals("url"))
            continue;
         try
         {
            prop.SetValue(copy, prop.GetValue(original));
         }
         catch
         {}
      }
    
      GameObject.Destroy(original);

      return copy;
   }
}

//Usage example:
class VideoPlayerExample : MonoBehaviour
{
   [SerializeField]
   private VideoPlayer m_videoPlayer;
 
   public void OnEnable()
   {
      m_videoPlayer = m_videoPlayer.MakeCopy(); //make a copy of the video player and all properties except for the URL
   }
}

It would be very nice if Unity would add a Unload() function to their video player, but since Unity doesn’t seem to be concerned about this I had to develop my own solution.

I hope this helps someone.

4 Likes