Loading game objects dinamycaly

Hello community!

I am trying to understand how can I load the game objects in the scene dynamically as it loads on loading screen?

I was thinking that I could load the scene with empty game objects and after parsing a XML file from witch I will load every game object in it’s place. All the assets that will be loaded will be pulled from a Asset Server. I want to keep the same screen and modify the game objects and how they are positioned in the scene.

Has anyone tried this method and has some experience with this, or is it possible to do something like this ? I am trying to understand how it works and what Unity has to offer for this kind of application.

First of all, look into XML serialisation, I find it easiest to serialise directly to a class. For example in my simple 2D game I use this class

public enum Map
{
	Alps,
	Canyon,
	Jungle,
	City,
	Space
}

public enum Tile
{
	Standard,
	Sliding,
	Breakable,
	Broken,
	Worm,
}

[System.Serializable]
public class LevelData
{
	public Map MapName { get; private set; }

	public Tile[] LeftWall { get; private set; }
	public Tile[] RightWall { get; private set; }

	public LevelData()
	{
		MapName = Map.Alps;

		LeftWall = new Tile[8];
		RightWall = new Tile[8];
	}
}

With Unity it’s best to use Resources.Load to load your xml as then it will get bundled into the final build. I ran into issues with this because I’m building on mobile devices.

LevelData data = null;

TextAsset text = Resources.Load(path, typeof(TextAsset)) as TextAsset;

// set up streams to read text asset
XmlSerializer serialiser = new XmlSerializer(typeof(T));
using (StringReader stringReader = new StringReader(text.ToString()))
{
	using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
	{
		// deserialise object
		data = serialiser.Deserialize(xmlReader) as LevelData;

		// close readers
		xmlReader.Close();
		stringReader.Close();
	}
}

This allows me to have an XML file that is easily readable and modifiable.

These files must be saved as .txt to be read in by Resources.Load however.

As whydoidoit mentioned, it’s best to only do this at level start up.

From this data, I can iterate through each tile and use GameObject.Instantiate() to instantiate prefabs at given locations. Personally I have the tiles already set up and then I simply iterate through and change the GUITexture. But the system is similar.

Hope that helps!