unity通过StreamingAssets 从excel表获取text值和获取指定图片改变UI中的图片

using System.IO;
using UnityEngine;
public class DataReader : MonoBehaviour
{
    private string filePath;
    private string[] lines;
    private Sprite sprite;
    private string imagePath;
    private Texture2D texture;

    public void UpdateUIText(string inputCode)
    {
        filePath = Application.streamingAssetsPath + "/Excel/你的excel.csv"; // 替换为你的CSV文件路径
        lines = File.ReadAllLines(filePath);
        foreach (string line in lines)
        {
            string[] data = line.Split(',');
            string code = data[0]; // 获取识别码
            string value = data[1]; // 获取值
            if (code == inputCode)
            {
                xx类.Instance.UItext.text = value; // 更新UI的Text值
                break;
            }
        }
    }

    public void UpdateUIImage(string inputCode)
    {
        imagePath = Application.streamingAssetsPath + "/图片所在的streamingAssets子文件夹/" + inputCode+ ".png";
        LoadLocalTexture(imagePath);
        if (texture != null)
        {
            sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
        }
        if (sprite!=null)
        {
            // 将加载的图片赋值给UI Image组件的Source Image字段
            xx类.Instance.UIImage.sprite = sprite;
            xx类.Instance.UIImage.color = new Color(255, 255, 255, 255);
        }
    }

    private Texture2D LoadLocalTexture(string path)
    {
        try
        {
            byte[] bytes = File.ReadAllBytes(path);
            texture = new Texture2D(2, 2);
            if (texture.LoadImage(bytes))
            {
                return texture;
            }
            else return null;
        }
        catch (System.Exception)
        {
            if(texture!=null) Destroy(texture);
            if (sprite != null) Destroy(sprite);
            return null;
        }            
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值