Unity On Trigger Enter



This is a beginners video tutorial for Unity in which I explain what colliders and triggers are and how to use them.I demonstrate the use of triggers and C#. Notes: Trigger events are only sent if one of the Colliders also has a Rigidbody attached. Trigger events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions. OnTriggerEnter occurs on the FixedUpdate after a collision. The Colliders involved are not guaranteed to be at the point of initial contact.' The given other Collider has details about the trigger event, such as the name of its GameObject. Either of the two GameObjects must have a Rigidbody component. The Rigidbody component has both Rigidbody.useGravity and Rigidbody.isKinematic set to false. These prevents the GameObject from falling under gravity and having kinematic behavior.

This section explains how to make things happen in the Dialogue System.

Note: If you are making a 2D project, see Enable Physics2D Support in Unity 2018+.

The Dialogue System Trigger component has three main parts:

Make sure you check trigger in the collider component and add rigidbody into it. The capsule object must have rigidbody on it. Use OnTriggerEnter(Collider collider) if you want to use triggerenter. Collision enter work if trigger is not checked. OnTriggerEnter Unity c# trigger not registering. When a GameObject collides with another GameObject, Unity calls OnTriggerEnter. OnTriggerEnter happens on the FixedUpdate function when two GameObjects collide. The Colliders involved are not always at the point of initial contact.

  • Trigger: The event that causes the Dialogue System Trigger to fire.
  • Conditions: States that must be true for the Dialogue System Trigger to perform its actions.
  • Actions: Things the Trigger should do, such as starting conversations or setting quest states.

Trigger

You can set the Trigger dropdown to these values:

Trigger Description
On Use The player’s Selector or Proximity Selector sent an OnUse message to the GameObject, or the Dialogue System Trigger’s OnUse() method was called manually in a UnityEvent or script.
On Start The component started (e.g., at scene start).
On Enable The component was enabled.
On Disable The component was disabled.
On Destroy The component was destroyed.
On Trigger Enter The component received an OnTriggerEnter message. To use this trigger, the component’s GameObject should have a trigger collider. You may want to set Conditions → Accepted Tags to restrict this trigger to GameObjects with specific tags such as Player.
On Trigger Exit The component received an OnTriggerExit message.
On Collision Enter The component received an OnCollisionEnter message.
On Collision Exit The component received an OnCollisionExit message.
On Bark Start The GameObject started playing a bark (one-off line of dialogue).
On Bark End The GameObject finished playing a bark.
On Conversation Start The GameObject just started as a primary participant in a conversation.
On Conversation End The GameObject just ended a conversation.
On Sequence Start The GameObject just started as a primary participant in a cutscene sequence. This event is not called for in-conversation sequences unless you’ve ticked the Dialogue Manager’s Subtitle Settings → Inform Sequence Start And End checkbox.
On Sequence End The GameObject just ended a sequence.

Conditions

Conditions allow you to specify states that must be true for the Dialogue System Trigger to fire, including:

Condition Type Description
Lua Conditions Lua expressions such as checking the value of a variable.
Quest Conditions Required quest states.
Accepted Tags For OnCollision and OnTrigger events, the other GameObject must have one of these tags. If Accepted Tags is empty, all GameObjects are allowed.
Accepted GameObjects For OnCollision and OnTrigger events, the other GameObject must be in this list. If Accepted GameObjects is empty, all GameObjects are allowed.

Actions

To add actions to perfom, click the Add Action button. You can add these actions:

Action Description
Set Quest State Sets quest and/or quest entry states. (See Quests.)
Run Lua Code Runs Lua expressions. Lua Variable['Actor'] and Variable['ActorIndex'] are set to the interactor's info. (See Logic & Lua.)
Play Sequence Plays a cutscene sequence. Sequence speaker is set to the interactor's info. (See Cutscene Sequences)
Show Alert Shows an alert message through the dialogue UI.
Send Messages Uses Unity’s SendMessage() method to send messages to targets.
Bark Plays a bark (one-off line of dialogue) on a GameObject.
Start Conversation Starts a conversation.
Set GameObjects Active/Inactive Works on entire GameObjects.
Set Components Enabled/Disabled Works on specific components of a GameObject.
Set Animator States Sets animator states on GameObjects. Useful to idle characters when conversations start.
OnExecute() UnityEvent Allows you to specify other actions using a UnityEvent.

Character GameObject Assignments

Note: Actor GameObjects used in runtime conversations don't have to be the same as the actors assigned to the conversation in your dialogue database! See below for an explanation.

Conversation Actor & Conversant

When you create a conversation in the Dialogue Editor, you'll assign an actor and a conversant from the dialogue database's list of actors. Typically, the actor is the player and the conversant is the primary NPC involved in the conversation. To view or change the conversation's actor and conversant, click on empty canvas space to inspect the conversation's properties.

Dialogue Entry Node Actor & Conversant

As you add dialogue entry nodes, the editor will automatically assign an actor and conversant to the node. The node's actor is the character who is speaking. The node's conversant is the character being spoken to. To change a node's actor or conversant, click on the node to inspect its properties.

Dialogue System Trigger Actor & Conversant

When you set up a Dialogue System Trigger, you can assign GameObjects to the Start Conversation > Conversation Actor and Conversation Conversant fields. These GameObjects can represent different actors than those assigned to the conversation in your dialogue database.

The conversation will use these GameObjects even if they don't match the actors assigned to the conversation. This allows you to reuse conversations for different characters – for example, reusing the same shopkeeper conversation for all shopkeepers in your game world. (Tip: In your dialogue database, you can create a generic actor named 'Shopkeeper' with a generic conversation such as: 'Hello, I'm [var=Conversant]. Welcome to my shop!' etc. Then reuse the same shopkeeper conversation for each village's shopkeeper and simply assign the specific village shopkeeper to the Conversation Conversant field.)

Conversation Actor

If you don't assign the Conversation Actor field, the Dialogue System Trigger will try to choose an appropriate GameObject:

  • If the trigger type is OnTriggerEnter/Exit or OnCollisionEnter/Exit, it will use the GameObject that collided with the trigger.
  • If the trigger type is OnUse, it will use the GameObject that sent the 'OnUse' message, typically the GameObject with a Selector or Proximity Selector component.
  • Otherwise it will look for a GameObject that has a Dialogue Actor component whose actor dropdown matches the conversation's actor. Failing that, it will look for a GameObject whose name matches the conversation's actor.

Conversation Conversant

If you don't assign the Conversation Conversant field, the Dialogue System Trigger will generally try to choose an appropriate GameObject:

  • It will look for a GameObject that has a Dialogue Actor component whose actor dropdown matches the conversation's conversant.
  • Failing that, it will use the Dialogue System Trigger GameObject.

Other Participants

If a dialogue entry node is assigned to an actor that is not the conversation's primary actor or conversant, it will look for a GameObject that has a Dialogue Actor component whose actor dropdown matches the node's actor. Failing that, it will look for a GameObject whose name matches the node's actor.

Bark On Idle

Use Bark On Idle to play barks on a GameObject at a random frequency between Min Seconds and Max Seconds. See the Barks section for more information about barks.

Range Trigger

Use Range Trigger to activate GameObjects and enable components OnTriggerEnter when specified Conditions are met. When OnTriggerExit occurs, the GameObjects are deactivated and components disabled. This component is useful to enable components such as Bark On Idle only when the player enters a trigger collider that represents proximity to the barker. You can also configure UnityEvents to run on enter and exit.

Trigger Event, Collision Event, Timed Event

The Trigger Event, Collision Event, and Timed Event components are general-purpose components that run UnityEvents on trigger collisions, regular physics collisions, and elapsed durations, respectively.

Unity On Trigger Enter Only Once

The Dialogue System Events component runs UnityEvents when Dialogue System activity occurs. Each foldout has a section of events that the component can handle when its GameObject receives the corresponding message, such as OnConversationStart. Note that many events, such as OnConversationStart, are only called on the two primary participants and the Dialogue Manager. If you want to run an event regardless of who the participants are, put the Dialogue System Events component on the Dialogue Manager.

You can also handle events in your own scripts by adding special methods described Scripting.

The Dialogue System provides an optional interaction system that can interact with GameObjects (e.g., NPCs) that have Usable components. You can add one of two components to the player:

Selector

The Selector component detects Usables by raycasting from a specified position, such as the mouse position or center of screen. When the player presses the use button, it sends an OnUse Message to the Usable. Note: In 2D mode, the camera must be orthographic.

Proximity Selector

The Proximity Selector component detects Usables when entering trigger colliders. When the player presses the use button, it sends an OnUse Message to the Usable.

OnUse Message

When the player targets a Usable and presses the Use Key or Use Button, the Selector will send an OnUse(Transform player) message to the usable GameObject. The Dialogue System's triggers, such as Dialogue System Trigger, respond to this message. Your own scripts can also respond to this message by adding an OnUse method such as:

Debug.Log('I'm being used by ' + player);

Usables also have UnityEvents that run when selected, deselected, and used. You can configure these events in the inspector.

Interactive conversations usually have a back-and-forth flow, where the actor says a line, then the conversant says a line, and so on. Barks, on the other hand, are one-off lines of dialogue that don't involve a player response menu or any back-and-forth. They're typically spoken by an NPC for atmosphere (e.g., 'Nice weather today') or to give the player an idea of the NPC's internal state (e.g., 'Reloading. Cover me!'). The content of barks can come from text strings or conversations.

Bark Conversations

To create a bark conversation, add all bark entries as children of the START node. In other words, the conversation tree will only be one level deep. When an actor barks, the Dialogue System will evaluate all children of the START node to generate a list of currently-valid entries. It will then choose an entry from this list and bark it. By setting Conditions on the bark conversation's dialogue entries, barks can be aware of the current game state. For example, an NPC could bark different things based on its health level.

Bark Priority

You can specify priority levels on your bark entries to prevent lower-priority entries from interrupting higher ones. To do this, add a custom Number field named 'Priority' to your dialogue entry. Higher values have higher priority. If you don't want to have to add this custom field on each entry, you can add it to the template on the Dialogue Editor Templates Tab. If the dialogue entry doesn't have a custom field named 'Priority', it uses a default of 0. When a bark is triggered, if the NPC is already barking, the Dialogue System will only interrupt it to play the new bark if the new bark's Priority is greater than or equal to the current bark's Priority.

Bark Display

Barks don't use the dialogue UI. Instead, barks are played through a bark UI on the barker, which usually appears as text over the NPC's head and/or as audio played through the NPC's audio source. The Dialogue UIs section covers bark UIs.

Bark Groups

If you want only one barker in a group to show bark text at time, configure them as Bark Group Members by adding a Bark Group Member component to each. When one member of the group barks, the others will hide any active barks to reduce onscreen clutter.

If you tick a Bark Group Member's Queue Barks checkbox, then when another member is currently barking, it will queue its bark to play after the other member instead of playing immediately and hiding the other member's bark.

The Dialogue System supports 2D physics as well as 3D physics. In Unity 2018+, the 2D physics package (Physics2D) can be enabled or disabled, so the Dialogue System's code for Unity 2018+ doesn't assume that Physics2D is available in your project. To tell the Dialogue System that Physics2D is available if you’re using Unity 2018+, open the Welcome Window (Tools → Pixel Crushers → Dialogue System → Welcome Window) and tick Enable 2D Physics or select menu item Tools → Pixel Crushers → Common → Misc → Enable Physics2D Support.... If you're using Unity 2017 or older, this menu item will not be visible.

If you want to enable Physics2D support manually instead, select menu item Edit → Settings → Player, add the scripting symbol USE_PHYSICS2D as shown below:

If you're having trouble getting the Selector component to detect your 2D Usables, please see Why isn't 2D detection working?.

If you’re using Unity 2017 or older, you can skip this step.

<< Welcome to the Dialogue System for Unity! | Dialogue UIs >>

SOVEREIGN MOON PRESENTS…

In this tutorial we’ll learn how to add triggers and switches to your game using Unity’s bolt add-on. Triggers allow you to open doors, turn on lights, change music and much more.

Sovereign Moon Studios is dedicated to helping game enthusiasts bring their creative visions to life by teaching them how to make a video game from scratch without having to know how to code or draw.

Today, Sovereign Moon Studios, the makers of your favorite NoCode game development course, are excited to bring you a new tutorial that will show you how to use triggers and switches within Unity’s free visual scripting add-on called Bolt.

Let’s jump in!

Introduction to Triggers

In our previous two tutorials we walked you through both how to rotate an object as well as how to move an object using Bolt. In today’s tutorial, we take things a step further by teaching you how to use triggers and switches in order to help you create more interesting game mechanics.

So let’s work towards getting your triggers set up.

Step 1: Begin By Setting Up Your Object

Triggers are powerful tools in the world of game design because you often use triggers to accomplish common game objectives. For example, you might want your character to trigger any of the following:

1. Opening or closing of a door

Unity On Trigger Enter 2d

2. The unlocking of a scene

3. Turning on or off of a light switch

4. Manage game collectibles like gold, money or points

By the end of the tutorial, this is what we’ll have.

Notice when my character is outside of the object’s range, the object does not move. However, as my character approaches and triggers the object’s collider, the object begins to rotate.

However, I’m just using rotate as a simple example. After the trigger has been activated you can insert whatever unit makes the most sense for your game. For example, imagine you had a cave in your game and as your character entered the cave you wanted to play dark and dreary cave music. The logic I’m going to show you today is the exact same logic you would use to accomplish that task.

So let’s take a look at what we need to do.

Step 2: Add a Box Collider (Trigger)

With our object selected we need to add a box collider component. With this component added, I’ll collide with the object and won’t be able to pass through it.

However, if we jump back into our inspector tab and select “is trigger”, essentially, we’re changing this object from a collision object to a trigger object.

So now, when I play my game, I can walk through the object. Oftentimes you’ll want your trigger to be invisible, and if you want your trigger to be invisible, you can just turn off the mesh renderer of the object here, and that will remove the mesh of the cube.

Now notice when playing my game, the object is not visible, but the trigger area is still set. But let’s imagine we want to keep the object visible, while keeping the trigger active. We can do this by adding a 2nd box collider and not setting it to trigger. So now, one box collider is acting as a collider and the other one is acting as a trigger. Now for the box collider that’s acting as the trigger, let’s move out the trigger away from the object so that it’s bigger than the object. This will make it so that the character doesn’t need to walk very close to the object to trigger it.

We can hit the “edit bounding volume” button here and then just scale our invisible trigger up. So that’s all we need to do for the object

Step 3: Edit Your Flow Graph

Now we need to set up our flow graph.

Trigger 2d Unity

So in our previous tutorials we were using an update event, which was forcing our object to rotate constantly with each frame of the game.

Now however, we only want our object to rotate if we move into it’s trigger area.

So if you’ve been following along with the series so far just delete everything you have in your flow graph to be able to start from scratch.

If you’re just tuning into this tutorial for the first time, what you’ll need to do is ensure that you have the object you want to trigger selected, and then add a new flow machine component to the object. Once you’ve done that you’ll need to create a new macro and then drag and drop that macro into your flow machine like this.

So now we should all be on the same page with an empty flow graph.

Step 4: Trigger the Event (Enter, Stay, Exit)

So we need to trigger and event and there are three common event types of trigger.

They are

On trigger enter – which will trigger an event to take place when the character first enters the trigger area.

On trigger stay – which will trigger an event to continuously run when the character stays within the trigger area.

On trigger exit – which will trigger an event to stop when the character exits the trigger area.

For this tutorial, we’re going to use “on trigger stay” because we want to make this object rotate while we are in the trigger area.

So what we’re going to do is we’re going to look for a unit called “on trigger stay”. Here it is. One really important thing to take note of here. Notice this event is part of Unity’s physics system. This means that a lot of use cases for his unit will require that one of our objects has a rigid body component attached to it. So you can just select your character or game object and add a rigid body, you can turn off gravity and then you’re done. Now back in the graph we can search for “on trigger stay again “ and now we’ll select it and bring it into our flow graph now.

Step 5: Target the Character Tag

Next, we only want this trigger to be activated if our character walks within the area of the object. We don’t want it to trigger if an enemy or NPC walks within the area, so let’s set up a Unit which will allow for the identification of our player.

The unit we’ll use to do this is the “game object compare tag”. So what we’re saying here essentially, is that “on collision” we want Bolt to look for the tag of this particular game object. In our case, the game object we want to check is our character. So we need to find the tag of our game’s character.

To do this is very simple, we simply need to find our character in our hierarchy tab and then select it. Because we’re using 3D Game Kit, our character is named “Ellen”. Once selected look over in the inspector tab to see if your character currently has a “tag”. If your character doesn’t have a tag you can simply add one by clicking on “add tag” and then hit this “+” button and then name and save your tag. I’ve already done this and my player tag is set to “player”. But you can set your tag to whatever you want.

Once that is done, we can select our object again and navigate to the flow graph we’re working on. Now, we can simply add the tag of the player in this input field. Be sure to write the tag properly as this tag is case sensitive.

Also, as a side note I just want to draw your attention to a few unit details. Notice the compare tag unit is showing an orange circle. This color coding can really help you out. Let me pull up our final graph that we’ll be working towards to show you why color coding is so helpful.

In previous tutorials over on our no-code game development blog, I talked to you about the different types of input and outputs. We talked about the differences between strings, floats, integers, Booleans,

Enter

Unity On Trigger Enter Play Sound

Here you’ll notice that everything is color coded to make things really easy for you. Strings are orange, Booleans are purple, and floats are blue. If this doesn’t’ make any sense to you, simply go back to our previous tutorials to learn more about unit types.

But as you can see here, icons and colors really help make the connecting of ports much easier on you because you’re given hints as to what you need to connect. Here for instance, we see the icon for the collider, here is the icon for a game object, here is the transform component icon, because remember, rotate is part of the transform components settings and here we have a music icon showing that bolt is looking for a music clip.

So hopefully this will help guide you along the way as you try to master Bolt.

Okay, let’s rewind now and get back to where we were.

Step 6: Add a Branch

So here, we have our compare tag added. Now we need to create a branch to figure out if our previous statement is true or false. So we simply drag this wire up and look for “branch”. Once you find it, add it to your flow graph.

The branch unit will determine if the object that entered into the trigger has this player tag associated with it. If it does, it will fire whatever we set to be true, if the object that entered the trigger area does not have a tag that is set to player, we’ll fire the “false” section of this branch.

Actually, we can leave false empty, because we don’t want anything to happen if a non player enters this region.

But let’s set up what we want to have happen, if this statement is true.

Step 7: Determine What You Want to Trigger or Switch On / Off

So this is where things get really interesting, because this is where you determine what will trigger. For example, you could play a song, open a door, increase your player’s gold, transfer your player to a new map, turn on a light, destroy an object or change levels. The possibilities are endless. My goal with this tutorial is just to show you the logic, so we’re just going to do two simple things right now. We’ll make the object rotate and we’ll play a song.

So let’s set object rotation first. So from the true port, wire up a new unit called transform rotate, what we’ll do here is set our yAngle to 1. Now when we play our game, we’ll be able to walk in and out of our trigger area and we’ll notice the object moves and stops based on if we fall inside our outside the trigger zone.

Unity On Trigger Enter 2d

Now, we could even make this a little more interesting, by maybe adding music to the trigger as well. We could jump into our flow graph again and to make this really easy just search for “audio source” and “Play clip at point. All you have to do now is search for the audio clip you want to play and add it here. I’ll set my volume to 1 and I’ll play my game again.

Notice this time when I enter into the trigger zone, the object rotates and some audio plays.

Conclusion

So that’s all I have for you for today’s tutorial. I hope you found this helpful and remember, if you want to dive deeper and take your no-code game dev skills to the next level, we offer a comprehensive course were we go into much more detail than we do in our free YouTube videos, so if you’re interested in that course, visit our homepage now!

Thanks for stopping by today!

Sovereign Moon Studios is dedicated to helping game enthusiasts bring their creative visions to life without having to know how to code or draw. Our NoCode game development course teaches indie game devs how to build breathtaking games from scratch.

Do you love game design? So do we! For this reason, we created a no-code video game development course that walks you through the process of bringing your game visions to life without needing to know how to program and without having to be an artist. We will teach you how to bring your game to life in our 4 hour 36 module no-code game development course.