不同平台动态加载streamasset下图片

2019-12-03  本文已影响0人  凌晨还梦

动态加载图片,主要是不同平台WWW访问streamingAssetsPath 不同,需要注意:

    public UITexture m_logoLoadTexture;
    public string m_texturePath;
    void Awake()
    {
         StartCoroutine(ChangeTexture(m_texturePath));
    }

    IEnumerator ChangeTexture(string texturePath)
    {
        //先检查指定路径是否有该枚举资源,有就替换
        m_logoLoadTexture.gameObject.SetActive(false);
        string path = Application.streamingAssetsPath + "/" + texturePath + ".png";       
        if (!File.Exists(path))
        {
            Debug.LogError("ios 环境下动态加载xy_mask_game_logo 资源不存在");
            yield return null;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
        path = path;
#elif UNITY_IPHONE && !UNITY_EDITOR
        path ="file://" + path;
#elif UNITY_STANDLONE_WIN||UNITY_EDITOR
        path = "file://" + path;
#endif
        WWW www = new WWW(path);
        while (!www.isDone)
        {
            yield return www;
        }
        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError("动态加载资源错误");
        }
        if (!string.IsNullOrEmpty(www.text))
        {
            Texture loadedTexture = www.texture;
            int widthpix = loadedTexture.width;
            int heithpix = loadedTexture.height;
            m_logoLoadTexture.mainTexture = loadedTexture;
            m_logoLoadTexture.width = widthpix;
            m_logoLoadTexture.height = heithpix;
            m_logoLoadTexture.gameObject.SetActive(true);
        }
    }

附上byte数组转为texture的方法

    public static Texture2D byte2texture(byte[] bytes)
    {
        if (bytes == null)
        {
            return null;
        }
        Texture2D t2d;
        t2d = new Texture2D(0, 0, TextureFormat.RGB24, false);
        t2d.LoadImage(bytes);
        t2d.wrapMode = TextureWrapMode.Clamp;
        return t2d;
    }
上一篇 下一篇

猜你喜欢

热点阅读