Unity支持的播放视频格式有.mov、.mpg、.mpeg、.mp4、.avi和.asf。只需将对应的视频文件拖拽入Project视图即可,它会自动生成对应的MovieTexture对象。如下图所示,MOMO将default_video.mp4拖拽入Project视图中,如果视频中含有音频的话会对应生成audio文件,因为我的视频没有音频所以没有生成 audio文件。接着在Hierarchy视图中创建一个Plane对象视频将在它之上播放,Directional light世界定向光用于照亮整个游戏场景,最后Main Camera对象将直直的照射在Plane对象。
基于游戏对象纹理的播放视频:
在场景中我们可以创建一个Plane(单面)或者Cube(六面)游戏对象,通过获取视频的MovieTexture,并将此视频纹理赋给游戏对象实现播放
操作步骤:
1首先导入视频资源(这个操作视较耗时的,请耐心等待)
2创建游戏对象(灯光调暗)
3创建一个Render Texture
4创建一个材质球,并添加纹理
再将材质球添加到游戏对象上效果如下;
接下来就是添加脚本了
using UnityEngine;
using System.Collections;
public class MovieTest : MonoBehaviour {
private Texture texture;
public MovieTexture movieTexture;
private AudioSource m_audio;
// Use this for initialization
void Start () {
texture = GetComponent<MeshRenderer>().material.mainTexture = movieTexture;
m_audio = GetComponent<AudioSource>();
movieTexture.Play();
}
// Update is called once per frame
void Update () {
//表示视频总时长
Debug.Log(movieTexture.duration);
if (Input.GetKeyDown(KeyCode.Q))
{
if (movieTexture.isPlaying == false)
{
movieTexture.Play();
m_audio.Play();
}
else
{
//这是暂停
movieTexture.Pause();
m_audio.Pause();
}
}
if (Input.GetKeyDown(KeyCode.Return) && movieTexture.isPlaying)
{
//这是停止之后,再次点击Play就会重新开始
movieTexture.Stop();
m_audio.Stop();
}
}
}