2D platformer: how to create and destroy levels?

I’m building a simple 2D platformer in C#.

I created all my levels in empty game objects in the hierarchy. Right now just the level-1 is visible, the others aren’t (I unchecked them in the inspector).

To destroy the current level, I just do: Destroy (GameObject.Find(“Level-1”));
But how do I display the next level? Instantiate (GameObject.Find(“Level-2”)); gives me an error: “ArgumentException: The thing you want to instantiate is null.”


Possible problems:

1: you’ve set level-2 as not active in the editor, in which case you will need to do something like this [C#]:

level2.enabled = true;

2: you’ve moved it to a really far place (outside the solar system), and can’t see it since it is not in the camera’s viewport. This means you would need to modify the level-2’s position like this [c#]:

Transform level2 = GameObject.Find("level-2") as Transform;
level2.position = new Vector3(x, y, z);

(x, y, z are coordinates where you want your level to be in your game)

BTW instancing and destroying levels like that is really dodgy. Use prefabs instead. Check out it here. It will be a lot nicer to work with.

For prefab you will need to assign the prefab in the editor to a public variable in your script like (C#):

class Foo{
    public GameObject Level-1;
    public GameObject Level-2;//so on...

    void start(){}//so on...

Now attach that script to something (I’m sure you already have). You will see extra options in your Script Component. Now drag the prefab (drag!) from your assets onto the option. Now you can use “Instance(Level-2)” to create it.