Unity3D视频播放动态加载组件

上一篇文章中说到的U3D视频播放的MovieTexture是手动拖拽赋值的,但在游戏中往往需要通过代码改变MovieTexture的值,所以本篇将讲解一下如何进行视频资源的动态加载,即通过代码来对MovieTexture进行赋值。

具体步骤如下(以游戏对象播放为例):

①创建一个Plane对象

②创建一个MovieTexture加载及播放的组件脚本,这里我已经封装好了一个组件,代码如下:
MoviePlayer.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using UnityEngine;
using System.Collections;

public class MoviePlayer : MonoBehaviour
{
    public MovieTexture Texture;

    public void PlayMovie(string movieName)
    {
        //在这里资源加载,movie是视频的文件名不需要后缀名
        Texture = (MovieTexture)Resources.Load(movieName, typeof(MovieTexture));
        renderer.material.mainTexture = Texture;
        Texture.loop = true;
        Texture.Play();
    }

}


③创建一个测试类:
MovieTest.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
using UnityEngine;
using System.Collections;

public class MovieTest : MonoBehaviour
{
    public MoviePlayer Movie;//定义一个播放器组件

    void Start()
    {
        Movie = GetComponent("MoviePlayer") as MoviePlayer;//获取播放器组件
    }
    void OnGUI()
    {

        if (GUILayout.Button("PLAY"))
        {
            Movie.PlayMovie("test");
        }

        if (GUILayout.Button("PAUSE"))
        {
            Movie.Texture.Pause();
        }

        if (GUILayout.Button("STOP"))
        {
            Movie.Texture.Stop();
        }
    }
}

④此将MovieTest、MoviePlayer绑定至Plane对象上:

⑤Bingo!

补充:注意步骤④,需要将Test脚步和组建脚本一同绑定至GameObject上,否则Test脚步运行至GetComponent时将无法获取到对应组件。另外对于Resources.Load的一点补充,务必在Project视图下建立Resources文件夹,并将资源文件放入其中,否则Resources.Load时无法找到资源对象。

以上大致这些,意在分享,与君共勉之。

BeiTown
2012-11-21

本文链接:Unity3D视频播放动态加载组件

转载声明:BeiTown原创,转载请注明来源:BeiTown's Coder 编码之源,谢谢


Tags: , , ,

One Response to Unity3D视频播放动态加载组件

  1. 匿名 说道:

    怎么才能播放流媒体网络视频?

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>