Translate

How to create a staircase using EditorScripts in unity3D

Editor Scripts in Unity3d allow us to extend the default unity editor according to our need.

Using the following editor script you can create a staircase as follows from a basic game object.

To create such a staircase you need:
A prefab of the basic building block here I am taking a cube(which i have converted into a rectangular slab)  and applied some texture over it.

The slab looks like this:


Now
step1> Create a new C# script named Stairs.cs.
step2>Open the script and replace the base class by "EditorWindow"
step3>In order to run the script you also need to include  "UnityEditor" library by adding "using UnityEditor;" on the top of your script.

now here is my complete script you can simply copy-paste into your script :



using UnityEngine;
using UnityEditor;
using System.Collections;

public class Stairs : EditorWindow {
public GameObject slabPrefab;
GameObject slab,stairCase;
int strHeight;
float offset=0.125f;//distance between two steps of stairs

[MenuItem("Stair/Create Stairs")]//creates a menu in the menubar
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(Stairs));//creates a gui to input the height and the basic building block of stairs
}
void OnGUI()
{

strHeight=EditorGUILayout.IntField("Height :",strHeight);
slabPrefab =(GameObject)EditorGUILayout.ObjectField("Base Game Object :",slabPrefab, typeof(GameObject), true);
if(GUILayout.Button("Create"))
{
stairCase=new GameObject("Staircase");

for(;strHeight>0;strHeight--)
{
for(int strLength=strHeight;strLength>0;strLength--)
{
for(int strWidth=strHeight;strWidth>0;strWidth--)
{
slab=GameObject.Instantiate(slabPrefab,new Vector3(0,strHeight,0),Quaternion.identity)as GameObject;
slab.transform.position=new Vector3(strWidth+offset, strHeight--,strLength);
slab.gameObject.name="Slab";//rename the slab so that it does not append ("clone") keyword with the name of each slab 
slab.transform.parent=stairCase.transform;//finally put every slab inside the staircase
}

}
}

}
}


}

Save this script inside a folder named "Editor". As you save this script a menu named "Stairs" appears on the menu bar and the "create stairs" will open a window like this


 
Here you select the base game object. In my case I selected the prefab of the slab I created and enter the height of the staircase you want. And click "Create" Button.  I created a 7 step staircase which looks as follows.

 

Compliments and suggestions  are always welcome, Please write in the contact form below.

Thanks,
Crackprac