Spawning a GameObject in Unity 2D

In the following example, we will be spawning a sprite image of a turtle into the game.

  1. Create an Empty GameObject and name it TurtleSprite. This GameObject will be the object being spawned in the game.
  2. Drag and drop a PNG or GIF of a turtle image to the Game and make it a child of the GameObject, TurtleSprite.
  3. Create a New C# Script (MonoBehaviour) and name it TurtleSpriteScript.cs.
  4. Open script and add code for the Turtle GameObject such as having the object get removed/destroyed if it hits the game’s borders or to add points to a player’s score. For example, the code below will add 200 points to the player’s score and then disappear if the player touches it.

5. Save the TurtleSpriteScript.cs file and attach to the TurtleSprite Game Object.
6. Add RigidBody 2D and Box Collider 2D to the GameObject as shown below.

7. Click Edit Collider in Box Collider 2D Component and make adjustments so that the box collider covers entire character.
8. Set Gravity on RigidBody 2D to 0 so that it does not fall to the bottom.
9. Drag the entire TurtleSprint GameObject to your Prefab folder.
10. Delete the TurtleSprint GameObject from the game (not the Prefab folder).

11. Create an empty GameObject and name it TurtleSpawnPoint.
12. Create a New C# Script and name it SpawnTurtle.cs.
13. Modify script to provide information on when the Turtle sprites should spawn in the game. For example ,the code below adds 6 attributes we can specify for the spawning action:

maxX = X Coordinate of the left-side of the game
minX = X Coordinate of the right-side of the game
maxY = Y Coordinate of the top of the game
minY = Y Coordinate of the bottom of the game
timeBetweenSpawn = how many seconds when the last turtle was spawned
spawnTime = how many seconds to elapse before another turtle is spawned

14. Save script and attach it to the TurtleSpawnPoint GameObject.
15. Drag the TurtleSprite GameObject created earlier and add to the Sprint attribute.
16. Fill in the values for the attributes specified in the TurtleSprint.cs script that is now showing in the Script component of game as shown below.

17. Once information is filled, run the game.
18. Video below shows an example of Turtles spawning into the game using this method.