在 Unity 中,可以使用以下代码将 Image 组件显示为项目的 Asset 文件夹中名为'Lilian' 的文件夹中的名为'Lilian' 的图片:

using UnityEngine;
using UnityEngine.UI;

public class ImageLoader : MonoBehaviour
{
    public Image imageComponent;
    public string folderName = 'Lilian';
    public string imageName = 'Lilian';

    private void Start()
    {
        LoadImage();
    }

    private void LoadImage()
    {
        string path = 'Assets/' + folderName + '/' + imageName + '.png';
        Texture2D texture = Resources.Load<Texture2D>(path);

        if (texture != null)
        {
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
            imageComponent.sprite = sprite;
        }
        else
        {
            Debug.LogError('Failed to load image: ' + path);
        }
    }
}

请确保在 Asset 文件夹中有一个名为'Lilian' 的文件夹,并在该文件夹中有一个名为'Lilian.png' 的图片。将此脚本添加到场景中的一个空 GameObject 上,并将 Image 组件分配给imageComponent变量。然后,运行游戏,Image 组件将显示'Lilian' 文件夹中的'Lilian' 图片。


原文地址: https://www.cveoy.top/t/topic/pEem 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录