在Unity中,Texture2D
的默认格式可能不支持透明度,因此你需要指定一个支持透明度的格式,例如TextureFormat.ARGB32
void LoadImageFromDirectory()
{
string directoryPath = "s/"; // 设定目录路径
string[] files = System.IO.Directory.GetFiles(directoryPath, "*.png"); // 获取目录下所有PNG文件
if (files.Length > 0)
{
string imagePath = files[0]; // 选择第一个PNG文件
Texture2D tex = new Texture2D(2, 2, TextureFormat.ARGB32, false); // 创建Texture2D对象,使用支持透明度的格式
if (System.IO.File.Exists(imagePath))
{
byte[] imageData = System.IO.File.ReadAllBytes(imagePath); // 读取图片数据
tex.LoadImage(imageData); // 加载图片到Texture2D
imageComponent.sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f)); // 创建Sprite并设置给Image组件
}
else
{
Debug.LogError("Failed to load image at path: " + imagePath);
}
}
else
{
Debug.LogError("No PNG files found in directory: " + directoryPath);
}
}