Join Kelley Hecker for an in-depth discussion in this video Creating an event, part of Scripting Unity with C#.
- Right now our enemies get destroyed when the player jumps on them. But nothing happens when the player touches the side trigger. Let's create and event that gets sent when the player enters the side trigger. If you're starting from the exercise files, instead of continuing from the previous video, remember that you'll need to import the standard assets for Unity 4.6 package which we imported in chapter 3, as well as the StoneFrogEnemy package which we did earlier in this chapter. Create a new C# script called DamagePlayerEvent.
Expand one of the enemy objects in the scene and find the side trigger object. Drag the script we just made onto it. Click Apply to apply to the prefab. Open the script... and go ahead and remove Start and Update. First, we'll create the delegate. The delegate holds the function that will be called by the event, and defines what arguments it takes.
This delegate, DamagePlayerAction, will take one GameObject argument. Next we create the event. This needs to be static so we can register for it from other classes. We type the name of the delegate we're using, DamagePlayerAction, and then the name of the event, OnDamagePlayer. That's all we need to do to create our event. Now we just need to send our event when the player enters the trigger.
Add the OnTriggerEnter function. Since we only want to send a message when the player enters the trigger, we'll check if the collider's game object is tagged with Player. We'll send the event by calling OnDamagePlayer. But before we do that, we have to make sure our event isn't null. An event will be null if no objects receive the event.
Once we're sure it's not null, we can call OnDamagePlayer with the player GameObject, which we can get from the collider. That's all that's needed to create and send an event. Now we just need to have another object register for the event.
- Defining classes and variables
- Attaching scripts to objects
- Understanding MonoBehaviour class
- Using the Unity Scripting API
- Importing assets
- Using a singleton pattern to manage game state
- Creating an event