Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

c# - What is the fastest method to create and render large number of 2d sprites in Unity?

I am creating an infinite terrain generator and I need to constantly update the terrain as the player moves around.

Everything is fine, but I am having trouble with finding information about the fastest method of creating and rendering sprites on the fly.

Information about sprites:

I am using 1 sprite sheet which has all the frames I need for my terrain. Grass, sand, water etc. all in 1 single .png file. All frames are stored in an array from which I can easily grab them.

Steps I need to do to display my sprite object correctly currently:

  1. Create new object.
  2. Set their position in 2d space.
  3. Add component.
  4. Scale them as needed.

Generated sprites get stored in a GameObject array called chunk. This is the way I am currently generating sprites.

        chunk[i] = new GameObject();
        chunk[i].gameObject.transform.position = new Vector2(spriteCoordX, spriteCoordY);
        chunk[i].AddComponent<SpriteRenderer>();
        SpriteRenderer renderer = chunk[i].GetComponent<SpriteRenderer>();
        renderer.sprite = tiles[calculatedFrameId]; //Set correct sprite frame.
        chunk[i].gameObject.transform.localScale = new Vector2(6.75f , 6.75f);

I don't know, adding component and scaling every single time I want to create a new sprite in code seems redundant and unnecessary and I am sure there is a better way to do that.

To sum up:

I need the best (fastest) possible way to generate large number of sprites, set their frame, position and proper scale.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Cannot help posting this image here, as this is really of thousands of words, thanks @AidenH for the "Object pooling" comment!

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...