目次
環境
- Unity 2020.3.12f1
- Native File Picker 1.2.9
導入
https://github.com/yasirkula/UnityNativeFilePicker
ソースコードをクローンし、ソースのPluginsフォルダをプロジェクトのAssetsフォルダに配置します。
https://assetstore.unity.com/packages/tools/integration/native-file-picker-for-android-ios-173238
アカウントにアセットを追加し、プロジェクトにインポートします。
https://github.com/yasirkula/UnityNativeFilePicker/releases
Githubのリリースから使用するバージョンのUnityPackageをダウンロードし、プロジェクトにインポートします。
画像を読み込むサンプル
ローカルから選択した画像を読み込んでuGUIに表示します。
Test.cs
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public RawImage image = default;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (NativeFilePicker.IsFilePickerBusy())
return;
#if UNITY_IOS
string[] fileTypes = new string[] { "public.image" };
#else
string[] fileTypes = new string[] { "image/*" };
#endif
NativeFilePicker.PickFile((path) =>
{
if (path == null)
return;
DisplayImage(path);
}, fileTypes);
}
}
private void DisplayImage(string path)
{
var rawImage = ReadFile(path);
var texture = BytesToTexture2D(rawImage);
SetTexture(texture);
}
private void SetTexture(Texture texture)
{
if(image.texture != null)
{
Destroy(image.texture);
}
image.texture = texture;
}
private byte[] ReadFile(string path)
{
var rawData = File.ReadAllBytes(path);
return rawData;
}
private Texture2D BytesToTexture2D(byte[] bytes)
{
Texture2D texture = new Texture2D(0, 0);
texture.LoadImage(bytes);
return texture;
}
}
uGUIのRawImageをシーン上に作成します。
適当なゲームオブジェクトに上記スクリプトをアタッチし、コンポーネントのインスペクターからRawImageをセットします。
画面をタップするとファイル選択のウィンドウが開き、選択を終えるとuGUIに画像が表示されます。