- Home /
Spawning sprite in for loop
Hey guys I've just started using unity, and I have a question. I am using 2d.
I am trying to do this:
Using for loop spawn sprite(which is already added to the assets in Unity). I want to fill area with sprites. I know how to implement for loop in C#, but how do I spawn an existing sprite(not from path)?
Thanks in advice.
Answer by Saad_Khawaja · Jul 25, 2014 at 10:33 PM
You have to use GameObject.Instantiate to create a copy of a game object.
The best way is as follows:
Drag the sprite onto the scene (make sure you are in 2D mode).
A new gameobject will be created in the hierarchy window with the name of that sprite
Create a new script and paste this in the code:
Assign this script to any gameobject (not the sprite as it will become recursive)
Drag the sprite gameobject to the spriteToDuplicate variable of the script in the inspector window
Play and your sprite will be duplicated - and placed at x+=1 distance
public GameObject spriteToDuplicate; void Start () {
Vector3 currentPosition = spriteToDuplicate.transform.position; for(int i=0;i<10;i++) { GameObject tmpObj = GameObject.Instantiate(spriteToDuplicate,currentPosition,Quaternion.identity) as GameObject; currentPosition += new Vector3(1f,0f,0f); } }
for a begginner you have to understand how unity works. everything is based on game objects. all game objects have components. components include your scripts. a sprite renderer is also considered a component to a gameobject. so what Saad_$$anonymous$$hawaja is suggesting is that you set up a game object with a sprite renderer component all set up. then duplicate the object with code. the answer to this question really has nothing to do with a sprite renderer. the appropriate answer duplicates anything reguardless of what components are attached google for: GameObject.Instantiate. it makes copies of anything in unity.
thanks for reply but set multiple objects and generate randomely like road? sometime object increment x direction and increment y direction
Your answer
Follow this Question
Related Questions
Unity 2D all objects mash together! 0 Answers
How can I set the position and size of a sprite from inside a script ? 1 Answer
I want to make a certain sprite spawn somewhere periodically, how? 1 Answer
Sprite flip movement script not working! HELP! 0 Answers
Implementing 2D Sprite Collisions 1 Answer