トマシープが学ぶ

Unity/VR/AR/デザイン好きのミーハー 記事内容は自分用のメモです

自分用はてな記法スクリプト

using System.Windows.Forms; // System.Windows.Forms.dll をインポートする
using UnityEngine;
using UnityEngine.Video;

public class SetFile : MonoBehaviour
{
    [SerializeField] private GameObject _Image;
    [SerializeField] private VideoPlayer _videoPlayer;

    public void OpenImageFile() // ファイル選択ボタンが押されたときに呼ばれる関数
    {
        OpenFileDialog dialog = new OpenFileDialog(); // ダイアログを作成する
        dialog.Filter = "Image files (*.png;*.jpeg;*.jpg)|*.png;*.jpeg;*.jpg"; // 画像ファイルのみ表示する
        dialog.Title = "画像ファイルを選択してください";
        if (dialog.ShowDialog() == DialogResult.OK) // ダイアログでOKが押されたら
        {
            string filePath = dialog.FileName; // 選択したファイルパスを取得する
            byte[] fileData = System.IO.File.ReadAllBytes(filePath); // ファイルデータをバイト配列として読み込む
            Texture2D texture = new Texture2D(2, 2); // 空のテクスチャを作成する
            texture.LoadImage(fileData); // テクスチャにファイルデータをロードする
            _Image.GetComponent<Renderer>().material.mainTexture = texture; // オブジェクトのマテリアルにテクスチャをセットする
        }
    }

    public void OpenMovieFile() // ファイル選択ボタンが押されたときに呼ばれる関数
    {
        OpenFileDialog dialog = new OpenFileDialog(); // ダイアログを作成する
        dialog.Filter = "Movie files (*.mp4)|*.mp4"; // 動画ファイルのみ表示する
        dialog.Title = "動画ファイルを選択してください";
        //dialog.ShowDialog();
        if (dialog.ShowDialog() == DialogResult.OK) // ダイアログでOKが押されたら
        {
            string filePath = dialog.FileName; // 選択したファイルパスを取得する
            StartCoroutine(PlayVideo(filePath));
        }
    }
    private System.Collections.IEnumerator PlayVideo(string filePath)
    {
        _videoPlayer.source = VideoSource.Url;
        _videoPlayer.url = "file:///" + filePath;
        _videoPlayer.Prepare();

        while (!_videoPlayer.isPrepared)
        {
            yield return new WaitForSeconds(0.1f);
        }

        _videoPlayer.Play();
    }
}