Unity WebGL端选择浏览本地图片并在界面显示 本文借鉴:https://www.cnblogs.com/yzxhz/p/13274634.html
1.首先在Unity里面搞个WebGl.jslib文件,放到unity的plugins文件夹下。这个文件是与webgl交互用的。
mergeInto(LibraryManager.library, {
clickSelectFileBtn:function () {
console.log("Enter");
clickSelectFileBtn();
},
});
2.在Unity里面搞个C#交互脚本,去调用这里面的 clickSelectFileBtn() 方法
[DllImport("__Internal")]
private static extern void clickSelectFileBtn();
public static void ClickSelectFileBtn()
{
clickSelectFileBtn();
}
public Button btn;
private void Start()
{
btn.onClick.AddListener(() =>
{
ClickSelectFileBtn();
});
}
3.在发布的出来index.html里添加 在<script> </script> 片段里添加
var gameInstance = UnityLoader.instantiate("gameContainer", "Build/loadimage.json", {onProgress: UnityProgress});
function sendMessageToUnity(s) {
gameInstance.SendMessage("TestObj", "GetBase64", s);
}
function clickSelectFileBtn() {
var tempFileLayout = document.getElementById('files');
tempFileLayout.click();
}
function fileImport() {
var selectedFile = document.getElementById('files').files[0];
if (selectedFile != null) {
var reader = new FileReader();
reader.readAsDataURL(selectedFile);
reader.onload = function (e) {
var base64Str = e.currentTarget.result.substring(e.currentTarget.result.indexOf(',') + 1);
arr = [];
step = 3000;
for (var i = 0, l = base64Str.length; i < l; i += step)
{
arr.push(base64Str.slice(i, i + step))
}
sendMessageToUnity("Start");
for (i = 0; i < arr.length; i++)
{
sendMessageToUnity(arr[i]);
}
sendMessageToUnity("End");
}
}
}
在<body> </body> 片段里添加
<input type="file" id="files" style="display:none" onchange="fileImport()">
4.最后,在index.html里的方法 gameInstance.SendMessage(“TestObj”, “GetBase64”, s);
TestObj这个在我场景中的物体名 GetBase64这个是TestObj上挂了个代码,代码有个方法叫GetBase64,s是参数。
拿到图片的byte[] 数组后赋值给场景中的图片
public Image image;
StringBuilder stringBuilder = new StringBuilder();
public void GetBase64(string base64Str)
{
if (base64Str == "Start")
{
stringBuilder.Clear();
}
else if (base64Str == "End")
{
byte[] bs = Convert.FromBase64String(stringBuilder.ToString());
***image.sprite = GetSprite(bs);
}
else
{
stringBuilder.Append(base64Str);
}
}
public Sprite GetSprite(Byte[] bytes)
{
Texture2D texture = new Texture2D(10, 10);
texture.LoadImage(bytes);
Sprite sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
return sp;
}
收工!
|