unity 打开本地文件夹 选中图片 赋给物体当作纹理贴图
时间: 2023-08-01 16:10:45 浏览: 63
你可以使用Unity自带的EditorUtility.OpenFolderPanel方法来打开本地文件夹,然后使用Unity的Texture2D类来加载选中的图片。以下是示例代码:
```csharp
using UnityEditor;
using UnityEngine;
public class AssignTexture : MonoBehaviour
{
[SerializeField] private Renderer _renderer;
public void OpenFolderAndAssignTexture()
{
string folderPath = EditorUtility.OpenFolderPanel("Select Folder", "", "");
if (string.IsNullOrEmpty(folderPath)) return;
string[] files = System.IO.Directory.GetFiles(folderPath, "*.png");
if (files.Length == 0) return;
string filePath = files[0];
Texture2D texture = new Texture2D(2, 2);
byte[] fileData = System.IO.File.ReadAllBytes(filePath);
texture.LoadImage(fileData);
_renderer.material.mainTexture = texture;
}
}
```
在上述示例代码中,我们首先使用EditorUtility.OpenFolderPanel方法打开文件夹,并获取选中的第一个.png文件。然后我们使用Texture2D类来加载该文件,并将其赋值给指定的Renderer的材质的主纹理。你可以将该脚本挂载到一个GameObject上,并在需要的时候调用OpenFolderAndAssignTexture方法来打开文件夹并将选中的图片赋值给材质。