Unity Trigger Random Destroy

Posted on: February 1st, 2015 by tdc_user
This Unity Trigger Random Destroy tutorial will demonstrate how we can combine a simple random destroy with a trigger event to make an even more powerful and flexible game mechanic. In Unity Triggers, I showed how to simply create an OnTriggerEnter function that would destroy a game object. In Random Mechanics in Unity, I showed how you can invoke random destruction (or other behaviors for that matter) at the start of any game level. Here’s a video that walks you through most of the steps: This time I will add a random calculation to the mechanic so that any of three cylinders will destroyed, causing a “bridge” to collapse, and thus demonstrating how you can influence the player’s environment randomly through their own actions. To set this up, you will need a First Person Controller tagged as Player, three cylinders named Cylinder1, Cylinder2, and Cylinder3, two cubes named bridge1 and bridge2, and a cube named triggerCube. Position the three cylinders next to each other with the cubes over top of them, as shown in the figure at right. Resize the “bridges” so that they are flatter and longer. Add a RigidBody to each bridge game object. For the triggerCube, we need to size its box collider a bit larger, and make sure that the box collider “Is Trigger” box is checked (again, see figure at right. Note that the image can be enlarged by clicking on it)Unity trigger random destroy. Next, create a new Javascript program called TrigRandDestroy.js: Drag TrigRandDestroy.js onto the triggerCube. Start the game and walk towards the triggerCube. You should see one of the three cylinders get destroyed, causing a collapse of one or both of the bridges. The value of this is much wider than a simple bridge collapse; using this same technique, you could cause enemies to spawn in random locations, pickups to appear, entire landscapes to change, based entirely on player movement. A key factor here is that we do not need to have the Mesh Renderer for the triggerCube turned on; this means the player is triggering events they have no idea about, just by moving around. The applications are limitless. Tags: , , , , ,

Comments are closed.