Nowadays each and every game has a video inside it to showcase its product, organization or advertise their goods.Today we are going to learn something which demonstrating movie player inside unity.
There are several ways to play a movie inside unity, but here we are discussing 2 best ways.
Handheld Class from unity provides functionality like full-screen movie player, vibrate, activity indicator.This can stream a movie from the device storage.Thus, you have to provide movie in a separated file with extensions such as mp4,3gp,mov, and mpv with compression standard of H.264 and MPEG-4.This will play video on iOS, android, and windows.
public static bool PlayFullScreenMovie(string path, Color bgColor = Color.black, FullScreenMovieControlMode controlMode = FullScreenMovieControlMode.Full, FullScreenMovieScalingMode scalingMode = FullScreenMovieScalingMode.AspectFit);
This is the syntax of Handheld.PlayFullScreenMovie.
- path – Clearly indicating the folder named StreamingAssets inside your Unity project (inside your Assets folder).
- bg-color – Background color.
- FullScreenMovieControlMode – Movie playback control.
- FullScreenMovieScalingMode – scaling modes for displaying movies.
Handheld.PlayFullScreenMovie("Akki.mp4", Color.black, FullScreenMovieControlMode.CancelOnInput, FullScreenMovieScalingMode.Fill);
Akki.mp4 is a movie file inside StreamingAssets folder.
Unity introduces a new feature called video player from unity 5.6.It will help you to play video in Camera render texture, Render texture, Materials and much more.It is a gameobject component for playback movie in your Unity scene.
Let’s see how we can do it.
- Import your movie clip in Unity store in any folder.
- Go to Hierarchy→Create→Video→VideoPlayer and it will create an object in the hierarchy.
- Assign your movie clip.
- Assing audio Source to movie player component.
This component has different render mode for playing a movie on it, we can here play a movie on RawImage component.
public class StreamVideo: MonoBehaviour
public RawImage image;
public VideoPlayer videoPlayer;
Application.runInBackground = true;
videoPlayer.playOnAwake = false;
//Wait until Movie is prepared
WaitForSeconds waitTime = new WaitForSeconds(1);
yield return waitTime;
Debug.Log("Done Preparing Movie ");
//Assign the Texture from Movie to RawImage to be displayed
image.texture = videoPlayer.texture;
yield return null;
Debug.Log("Done Playing Movie ");
For script to run successfully,
- Assign script to empty Gameobject.
- Assign RawImage and VideoPlayer Component to script.
- You did it, Play Now.
You can also play any movie from its URL only, To do so change VideoPlayer Component Source from VideoClip to URL and Setup a proper URL to play the movie.
More helpful assets: