c# - EncodeToPNG 挂起脚本

标签 c# unity-game-engine sprite texture2d

我想要的是将 png 文件读取为 byte[] 数组。我需要该数组才能通过 HTTP POST 请求将其发送到远程服务器。我的代码如下所示:

Sprite sprite = Resources.Load<Sprite>("Images/" + _filename);
print("Sprite loaded.");
print("Texture size: " + sprite.texture.width + ", " + sprite.texture.height);
byte[] bytes = sprite.texture.EncodeToPNG();
print("Done.");

日志如下所示(我在统一编辑器中运行该应用程序):

Sprite loaded. 
Texture size: 750, 1334

它从不打印“完成”。我已经等了几分钟了。 Unity控制台没有错误。 文件大约 1MB,所以不是一张很大的照片。看起来 Sprite 加载没有问题,但无法转换为 byte[] 数组(如 png)。 这是怎么回事?

最佳答案

@KingGary 感谢您的提示!

我从来没有想过,当没有 try-catch 时,它会引发异常。

异常(exception)情况是:

System.ArgumentException: Texture 'test_image' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.

解决方案是在Unity编辑器中选择该文件,并在属性窗口中启用“Read/Write Enabled”。

关于c# - EncodeToPNG 挂起脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60484595/

相关文章:

c# - 动画停止后直接调用函数 - Unity

c# - 更新特定行的字符串,这样它就不会更新字符串中的重复项?

c# - 改进 SortedDictionary 的访问时间

c# - 在 C# 应用程序中使用 LINQ to SQL 的最佳实践方法是什么? [设计模式]

c# - "correct"将 Voronoi 图与 Perlin 噪声结合起来生成纹理的方法是什么?

unity-game-engine - 在 unity3D 应用程序中显示 Twitch.tv 流

c# - UnityARAlignment 在 Unity ARKit 插件中意味着什么?

java - 从 Sprite 表导入 Sprite

python - 左边的pygame Sprite 碰撞

ios - 如何设置 SKScene 的背景图片?