Tuesday, September 8, 2015

Unity Editor scripting: How to create levels

So in creating the levels I came across a problem.

It was really difficult to set up a level. Moving all of the tiles about was really difficult as they are inside a game object. Each parent objects has 4 sprites, a ceiling a floor, a top and a middle. These can all be assigned different Y axis positions.
What I really needed was a way to select multiple parent GameObjects then somehow manipulate them all in one go. So the way I’ve achieved this is by editor scripting.

To do this I created a script it that goes into a special folder called Editor in the Assets directory, if the folder isn’t there create it.

At the top of the script we need to add.

using UnityEditor;


We need to add the attribute for the menu item;

[MenuItem("Adz/Floor/UP/FloorUP")]

This allows us to change the IDE of unity to have our special function available as a menu item.
To run the function we select multiple GameObjects then click the FloorUp function.

Multiple GameObjects selected with new Menu items in IDE 

Here is the code for the FloorUp function, it loops through all of the items selected in the scene view, in order of the transform’s X position and increases their y by .1f.

   static void FloorUP()
        var items = Selection.gameObjects.OrderBy(go => go.transform.position.x);

        foreach (var item in items)
        {
            anchor p = item.GetComponentInChildren<anchor>();
            p.FloorTileY += .1f;
        }
    }

After clicking the menu item FloorUp we see the effect on the selected GameObjects, it gives us a ramp going upwards.

After the editor script FloorUp is run

So then all I did was create similar functions for the ceiling, Top, Middle sprites then I could easily create levels for the Shuffa ball: Endless roller game.



No comments:

Post a Comment