Load game objects at runtime?

Hi Guys!

I’m very new to unity3D, would someone please tell me what things i need to do to, load game objects as we play the game, for example let’s say there’s a parent object with several spheres in it each containing one child entity that is a 3Dtext, and ofcourse these are not in the hierarchy but in a separate XML file or stored in different similar fashion. Any guidance is very much appreciated.

When you talk about the XML files I assume you’re storing data that ultimately ends up in a script. The gameobject themselves can be created multiple ways. The easiest scenario:

Say you have a FighterTank object with an XML data backing for it’s stats. You could create a gameobject give it a tank mesh and add a FighterTank script to it that has, let’s say, Health, Damage and Range variables. Save your gameObject as a prefab. Your XML might look something like:

<xml>
 <fightertank>
    <health>100</health>
    <damage>200</health>
    <range>75</range>
 </fightertank>
</xml>

After reading in the xml, you can create your prefab at runtime using the Instantiate function. Once created, call GetComponent on the created prefab to request your FighterTank script you added. From there, you can simply assign your Health, Damage and Range variables.

The standard solution for this within Unity are “Prefabs.” It works like this:

  • First you design your game object as you want it directly in the Unity Editor (including child objects, as you described)
  • Then you create a Prefab (right-click in Project tree, CreatePrefab and drag the game object you built from the Hierarchy tree onto the Prefab.

You can now delete the game object from the scene. The Prefab is like a blueprint - you can “clone” this Prefab into your scene via script, any number of times, wherever you want.

For example, an Enemy Spawner script might have a slot onto which you can drag a enemy Prefab of the kind of enemy that should be spawned. Or a weapon script might have a slot onto which you drag a prefab for the kind of projectile (bullet, rocket, whatever) the weapon should create when it is fired.