うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】 UnityProject 外から画像をロードして表示する

f:id:hacchi_man:20200410004102p:plain:w500

using UnityEditor;
using UnityEngine;
 
public class SampleEditorWindow : EditorWindow
{
    private Texture2D _texture;
 
    private void OnGUI()
    {
        if (GUILayout.Button("画像をロードする"))
        {
            // ロード先を取得
            var sourcePath = EditorUtility.OpenFilePanel("Select Image", "", "png,jpg,jpeg");
            if (!string.IsNullOrEmpty(sourcePath))
            {
                // LoadImage をしたタイミングで画像のサイズが変更されるのでサイズはなんでもよい
                _texture = new Texture2D(0, 0);
                _texture.LoadImage(System.IO.File.ReadAllBytes(sourcePath));
            }
        }
 
        if (_texture != null)
        {
            var rect = GUILayoutUtility.GetRect(_texture.width, _texture.height, GUILayout.MaxWidth(_texture.width), GUILayout.MaxHeight(_texture.height));
            EditorGUI.DrawTextureTransparent(rect, _texture);
        }
    }
}