用WWW统一导入后,如何更改精灵的每单位像素数?

时间:2016-05-21 14:35:42

标签: c# unity3d import 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 ();
         }

1 个答案:

答案 0 :(得分:4)

查看函数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);
             }