Saturday 16 April 2011

Scripting the level finish point

I decided to script the end point I had just created, so that when the player reaches it they are taken to the next level. It made sense to script this early on so that I would simply be able to re-use the same prefab, every time I needed to end a level. First of all I tried using a script, which would recognise objects with the tag "LevelExit" and react to the player colliding with them. To test the collision I used "print" to bring up a message in the console window, when the collision takes place.

function OnControllerColliderHit(hit: ControllerColliderHit)
{
if(hit.gameObject.tag == "LevelExit")
{
print("yes");
}
}


This was okay, however the collisions weren't 100% accurate and this method involved tagging each individual wall to make it all work properly. So I searched around online to see if there was a more practical and efficient method of achieving this. I found a post in the Unity forums (http://answers.unity3d.com/questions/9097/move-to-next-level-on-collide), which answered my question perfectly. In the Unity inspector, it is possible to mark an object as a trigger if it has a Rigid Body. So using this as a reference I created the following script and attached it to a cube in the centre of the exit point. The only thing I would need to do was alter the currentLevel variable on each level, so that the levels followed each other correctly.

var currentLevel = 0;
function OnTriggerEnter ()
{
currentLevel++;
Application.LoadLevel (currentLevel);
}


This worked nicely and I was happy that this element was complete, so I saved it as a prefab, which I would then be able to drag in to any level, where I needed an exit point.

No comments:

Post a Comment