简体   繁体   中英

How to change pixels per unit for sprite after importing with WWW in unity?

I am currently making a level editor where the user imports tiles from a file, and it currently works, except for the fact that I want the pixels per unit for each imported sprite to change to 32

Here is my code:

//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 ();
         }

Looking at the function Sprite.Create() we see that the function signature is

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);

We see that we can pass the pixelsPerUnit as an optional parameter into the function. You can only do this here, and you cannot change it later, because, as you have found out, the field pixelsPerUnit is readonly field (meaning it cannot be changed). So, you just need to pass in your 32f here. Correct code would be

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);
             }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM