Unity支持的播放视频格式包括.mov、.mpg、.mpeg、.mp4、.avi和.asf。下面简单演示一下Unity播放视频的两种方式:
方式1:
在游戏对象中播放,通常是创造一个Plane面对象,MovieTexture类似贴图(Texture)一样附着在游戏对象上,比如做VR时可以在墙上挂电视机之类等等
①首先导入视频资源,直接拖拽入Porject视图,系统自动生成对应的MovieTexture对象,如下图。导入过程比较缓慢,30MB视频大概需要10分钟来处理
这里要注意的一点是在导入视频前电脑上必须装有QuickTime,否则Unity将无法对视频进行解析
因为时间关系还是拿之前就导入好的视频来讲解吧
导入成功后就像这样,audio是视频中的音频文件
②创建一个Plane对象,这个不用细说了,放在摄像机能看到的地方即可
③创建视频控制脚本
PlayerVideo.cs
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 | using UnityEngine; using System.Collections; public class PlayVideo : MonoBehaviour { public MovieTexture movTexture; // Use this for initialization void Start () { renderer.material.mainTexture = movTexture; movTexture.loop = true; } // Update is called once per frame void Update () { } void OnGUI() { if (GUILayout.Button("PLAY")) { if (!movTexture.isPlaying) { movTexture.Play(); } } if (GUILayout.Button("PAUSE")) { movTexture.Pause(); } if (GUILayout.Button("STOP")) { movTexture.Stop(); } } } |
④将脚步及视频文件拖拽至Plane对象上 如下图:
点击播放,效果如图:
方式2:
GUI层播放,可以做为全屏动画的播放。
和方式1的①③④步骤一样,只是免去创建Plane的步骤,同时绑定的对象变成了主摄像机,代码有一些小小的调整:
PlayerVideoGUI.cs
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 | using UnityEngine; using System.Collections; public class PlayVideoGUI : MonoBehaviour { public MovieTexture movTexture; // Use this for initialization void Start () { //renderer.material.mainTexture = movTexture; movTexture.loop = true; } // Update is called once per frame void Update () { } void OnGUI() { GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), movTexture, ScaleMode.StretchToFill); if (GUILayout.Button("PLAY")) { if (!movTexture.isPlaying) { movTexture.Play(); } } if (GUILayout.Button("PAUSE")) { movTexture.Pause(); } if (GUILayout.Button("STOP")) { movTexture.Stop(); } } } |
GUI全屏播放效果如下
补充:
GUI中播放视频的效率不如在GameObject中播放的效率,但是在GUI中可以随意修改视频尺寸,Plane是基于网格模型的,相比之下修改尺寸不如GUI的灵活。只能说两种方法各有优势吧。
以上为本人在项目中的一些Demo例子,有不足之处欢迎指正,意在分享,与君共勉之。
BeiTown
2012年11月20日
[笑哈哈]