Unity支持的播放视频格式有.mov、.mpg、.mpeg、.mp4、.avi和.asf。只需将对应的视频文件拖拽入Project视图即可,它会自动生成对应的MovieTexture对象。如下图所示,MOMO将default_video.mp4拖拽入Project视图中,如果视频中含有音频的话会对应生成audio文件,因为我的视频没有音频所以没有生成 audio文件。接着在Hierarchy视图中创建一个Plane对象视频将在它之上播放,Directional light世界定向光用于照亮整个游戏场景,最后Main Camera对象将直直的照射在Plane对象。
基于游戏对象纹理的播放视频:
在场景中我们可以创建一个Plane游戏对象,通过获取视频的MovieTexture,并将此视频纹理赋给游戏对象实现播放
参考代码如下:
using UnityEngine;
using System.Collections;
public class VidioTest : MonoBehaviour {
//音频播放器
private AudioSource m_audioSource;
//视频纹理
public MovieTexture m_Texture;
// Use this for initialization
void Start () {
//将视频纹理赋给游戏对象的纹理
this.GetComponent<MeshRenderer>().material.mainTexture = m_Texture;
//获取游戏对象上的音效播放器
m_audioSource = this.GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
GUI.backgroundColor = Color.red;
if (GUI.Button(new Rect(0,0,60,40),"播放"))
{
//如果视频没有播放 那么就播放视频
if (!m_Texture.isPlaying)
{
m_Texture.Play();
m_Texture.loop = true;
m_audioSource.Play();
}
}
//暂停视频
if (GUI.Button(new Rect(0, 45, 60, 40), "暂停"))
{
m_Texture.Pause();
m_audioSource.Pause();
}
//结束视频
if (GUI.Button(new Rect(0, 90, 60, 40), "停止"))
{
m_Texture.Stop();
m_audioSource.Stop();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
效果如下: