c# - 如何从字节数组制作 Sprite ?

标签 c# firebase unity3d firebase-storage

我有一个 Unity 游戏,玩家在开始游戏后从数据库中获取一个人的元素栏。 我得到了存储在 Firebase Storage 中的项目的图片,我可以下载它们。 但是,我不知道如何从我通过下载获得的 byte[] (fileContents) 制作 Sprite 。 (稍后我会将这些 Sprite 加载到玩家的元素栏中)

我得到了以下 C# 脚本:

private void getPlayersInventory()
{
  FirebaseDatabase.DefaultInstance.GetReference("users").Child(auth.CurrentUser.UserId)
    .Child("inventory").GetValueAsync().ContinueWith(task => 
    {
      if (task.IsFaulted)
      {
        print("unable to get snapshot for the inventory");
      } 
      else if (task.IsCompleted) 
      {
        snapshot = task.Result;
        if(snapshot.HasChildren) 
        {
          foreach(var current in snapshot.Children)
          {
            string currentName = current.Value.ToString();
            print(currentName.ToLower() + ".png");
            const long maxAllowedSize = 10 * 1024 * 1024;
            storageReference.Child(currentName.ToLower() + ".png")
              .GetBytesAsync(maxAllowedSize)
              .ContinueWith((Task<byte[]> task_) => 
              {
                if (task_.IsFaulted || task_.IsCanceled) 
                {
                    Debug.Log(task_.Exception.ToString());
                } 
                else 
                {
                    byte[] fileContents = task_.Result;
                    Debug.Log("Finished downloading!");
                }
              });
          }
        }
      }
    });
}

最佳答案

我相信您正在寻找 ImageConversion.LoadImage

您的完整代码如下所示:

var tex = new Texture(1,1); // note that the size is overridden
tex.LoadImage(task_.Result);
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width/2, tex.height/2));

您也可以pack textures如果这是您的最终目标,则在运行时。一旦你完成了 tex.LoadImage block ,你应该能够计算出 Texture2D.PackTextures

--帕特里克

关于c# - 如何从字节数组制作 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578314/

相关文章:

c# - 如何从 VB6 应用程序向我的 C# 应用程序发送消息

c# - 登录并检查账户类型

unity3d - 变量声明中的冒号

c# - 如何以编程方式随机生成游戏对象?

c# - 'System.Windows.Controls.Image' 不包含 'FromFile' 的定义

c# - ApiController 扩展方法 - 无法访问 ResponseMessage

javascript - 如何在 firebase 中实时删除特定子项(Angular 7)

java - 无法解决 FirebaseOptions.Builder().setCredentials()

Python Firebase 问题 No module named firebase_admin

c# - Unity C# 中的泛型