c# - 统一导入 WWW 后如何更改 Sprite 的每单位像素?

标签 c# unity3d import sprite

我目前正在制作一个关卡编辑器,用户可以在其中从文件中导入图 block ,并且它目前可以正常工作,除了我希望每个导入的 Sprite 的每单位像素更改为 32

这是我的代码:

//Get tiles from file
         StreamReader reader = new StreamReader(Application.dataPath + "/../Maps/" + mapName + "/Tiles/tiles.txt");
         string line = reader.ReadLine ();

         while (!string.IsNullOrEmpty (line)) {
             string[] param = line.Split (',');
             foreach (TileTexture t in tileTextures) {
                 if (t.name == param [0]) {
                     Sprite sprite = Sprite.Create (t.texture, new Rect (0, 0, t.texture.width, t.texture.height), new Vector2 (0, 0));
                     sprite.pixelsPerUnit = 32;//THIS LINE DOESNT WORK, GIVES READONLY ERROR
                     Tile tile = new Tile (param[0], sprite, new Vector2(float.Parse(param[1]), float.Parse(param[2])));
                     tile.sprite.texture.filterMode = FilterMode.Point;
                     tiles.Add (tile);
                 }
             }

             line = reader.ReadLine ();
         }

最佳答案

查看函数Sprite.Create()我们看到函数签名是

public static Sprite Create(Texture2D texture, 
                            Rect rect, 
                            Vector2 pivot, 
                            float pixelsPerUnit = 100.0f, 
                            uint extrude = 0, 
                            SpriteMeshType meshType = SpriteMeshType.Tight, 
                            Vector4 border = Vector4.zero);

我们看到我们可以将 pixelsPerUnit 作为可选参数传递给函数。您只能在此处执行此操作,以后不能更改它,因为正如您所发现的,字段 pixelsPerUnitreadonly 字段(意味着它不能更改)。所以,你只需要在这里传入你的32f。正确的代码是

if (t.name == param [0]) {
                 Sprite sprite = Sprite.Create (t.texture, new Rect (0, 0, t.texture.width, t.texture.height), new Vector2 (0, 0), 32f);
                 Tile tile = new Tile (param[0], sprite, new Vector2(float.Parse(param[1]), float.Parse(param[2])));
                 tile.sprite.texture.filterMode = FilterMode.Point;
                 tiles.Add (tile);
             }

关于c# - 统一导入 WWW 后如何更改 Sprite 的每单位像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364242/

相关文章:

c# - 按 Enter 键而不是单击 C# 中的按钮

c# - 在应用程序退出时创建单独的线程

c# - 如何让 C# WebSocketClient 持续监听消息

c# - 迭代模型集合以在 MVC 中保存多条记录

c# - 从数据库到文本框的数据

c# - Unity 中的 Firebase - 禁用持久性

algorithm - Unity 销毁对象及其对象列表

python - `_ast` 中导入函数的名称

python - 在 python 包中添加和读取 config.ini 文件

python - 导入整个 Python 标准库