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