Resources dynamically load pictures in Unity3D

Question: There is no need to say more about the dynamic loading of Unity's Resources. The problem here is that when I put the picture into the Resources folder, I use Resources.Load (datapath) but no picture appears.


Analysis: Since the image you put in the folder is a Texture2D type, but the sprite is actually used in u3d, so you need to convert the type.
Way:

1. Create a Texture2D variable in the code first, obtain an external image, and use the completed variable to create a sprite
2. Directly convert the image into a sprite in unity, and then call it directly

editor settings

 the code

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class LoadTest : MonoBehaviour
{
    public Image image;
    public Button btn_up;
    public Button btn_down;

    void Start()
    {
        btn_up.onClick.AddListener(Btn_up);
        btn_down.onClick.AddListener(Btn_down);
    }

    void Btn_up()
    {
        ShowImage("前");
    }
    void Btn_down()
    {
        ShowImage("后");
    }

    /// <summary>
    /// 显示图片
    /// </summary>
    /// <param name="imageName"></param>
    public void ShowImage(string imageName, bool isShow = true)
    {
        if (imageName == null)
        {
            Debug.Log("Panel_serverResponseImage:地址:ShowImage:服务器响应的图片名称为空");
            return;
        }
        else
        {
            string path = "Image/" + imageName;

            Texture2D imageLoad = Resources.Load(path) as Texture2D;

            Debug.Log("Panel_serverResponseImage:地址:ShowImage:imageLoad:" + imageLoad);

            if (imageLoad == null)
            {
                Debug.Log("Panel_serverResponseImage:地址:ShowImage:服务器响应的图片加载为空");
            }
            else
            {
                Sprite texSprite= Sprite.Create(imageLoad, new Rect(0, 0, imageLoad.width, imageLoad.height), new Vector2(0.5f, 0.5f));
                image.GetComponent<Image>().sprite = texSprite;
            }
        }
    }

}

actually run 

 

Guess you like

Origin blog.csdn.net/qq_40544338/article/details/129368135