ぶろぐめんどくさい

技術系の記事と漫画レビューが入り混じった混沌

【供養】nGUIでVideoPlayerを使って動画を再生する【✙悔い改めて✙】

VideoPlayerから取得した動画をnGUIに貼り付けるソース覚え書き。 結局、複数動画を扱えず、使い道がなくなったので供養も兼ねて。

参考

[Unity]uGUI上で動画を再生する - Qiita

使用方法

  1. UIの作成

Canvas RawImage

  1. RawImageに下記のスクリプトを追加

  2. Inspecter内のVideoPlayerのソースに動画ファイルを指定

実行すると動画がUI内で再生される。

だいたいこんなんができる。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using UnityEngine.UI;

[RequireComponent(typeof(RawImage))]
[RequireComponent(typeof(VideoPlayer))]
public class VideoOnUI : MonoBehaviour {

    public bool isLooping;

    VideoPlayer m_videoPlayer = null;
    RawImage m_rawImage = null;
    RenderTexture m_renderTexture = null;

    public Vector2 textureSize;

    // Use this for initialization
    void Start () {

        m_videoPlayer = this.GetComponent<VideoPlayer>();
        m_rawImage = this.GetComponent<RawImage>();
        m_renderTexture = new RenderTexture((int)textureSize.x, (int)textureSize.y, 0);

        m_videoPlayer.renderMode = VideoRenderMode.RenderTexture;
        m_videoPlayer.targetTexture = m_renderTexture;
        m_videoPlayer.isLooping = isLooping;

        m_rawImage.material.mainTexture = m_renderTexture;

        m_videoPlayer.Play();

    }
    
    // Update is called once per frame
    void Update () {
        if (!m_videoPlayer.isPlaying)
        {
            m_videoPlayer.Stop();
        }
    }
}