Unity World Events on Player Collision using Arrays

## What will I be learning here?

When making any game, or even an interactable scene in Unity, all events that occur will need to use code. The code I am providing is a script I put together for activating world events when a player collides with an event zone setup by the developer. This page will explain how to setup the **Player**, and **Event Zones** to fully utilize this script. (This tutorial will be assuming you are using **Unity 3D** and **not 2D**, as things work slightly different between the two. However the script can be modified to work in a 2D environment fairly easily).

## The Player

If you do not have any experience with Unity, or limited coding experience, there are thankfully many options for easily implementing some form of player controller into your scene, environment, or game. One of which is the example Unity FPS Controller that comes part of Unity's standard/example assets.

For this tutorial, I will be assuming that you are using the Unity FPS Controller (Although this can be applied to any character controller in Unity with the exact same steps). You can download the official standard assets for free from this link: https://assetstore.unity.com/packages/essentials/asset-packs/standard-assets-for-unity-2018-4-32351

## Tags

Tags are an important part in organization, detection, collisions, and event triggers in Unity. The two most important being "MainCamera" and "Player". In our case, we will only be looking at **the "Player" tag**. If you are using any form of character controller asset, whether it be an official Unity standard asset character controller, or one you have downloaded elsewhere, it is very likely they are already tagged with the "Player" tag. However, it is important to be able to check for yourself, and ultimately add tags for future or current reference.

Tags appear in the Inspector window, of which the Inspector window usually on the right side of the screen, and contains all the information of GameObjects when selected. Within the Inspector window itself, tags can be found on the top left corner (of the Inspector window only, not the top left corner of the entire program). (See the Image on The Inspector Window for reference).

**Important:** If the Tag drop down says "Untagged" or something other than "Player", open the dropdown menu and select the "Player" tag. If there is no "Player" tag already defined, which there *should* be by default, create a tag yourself called "Player" (Minus the quotation marks, but ensure the P is capitalized).

Since I am assuming that you are using the FPS Controller, or any of Unity's standard player controller assets, then no further steps need to be taken on the player itself. It is important to note, that the capsule collider and/or character controller components are important for movement, and detecting collisions. These will need to remain on the player for the script to function properly.

## The Event Zone(s)

Now that our player has been vetted to work with our custom event zone script, we can now setup our event zone GameObject.

*(The script itself can be copied and pasted below, and will be explained by the end of the article. I recommend reading everything once before following along in Unity in order to understand how to bring the script into Unity without issue)*.

I will be assuming that you want to create an invisible event zone trigger for this section of the tutorial. If you wish for it to be a visible object, simply follow these steps using some form of visible model, or add our end-result invisible event zone trigger as a child object to the model.

To begin, add an Empty GameObject, which can be found by using the GameObject quick menu at the top left menu in Unity. (To the right of **File** and **Edit**, etc). With our Empty in the scene, rename it using the Inspector to something along the lines of "Event Trigger".

Now that it is named and in our scene, click the button at the bottom of the Inspector window labeled **Add Component**. This should open a small popup window with a search bar. Search **Sphere Collider** (Although Box, and Capsule colliders will work exactly the same), and click on the green Sphere Collider icon to add it to our Empty Event Trigger. **Do Not Use Mesh Colliders, as that will NOT work!**

Inside the 3D Scene View of our Trigger, you should see a green wireframe sphere appear around the center of the Event Trigger. Use the **Radius** input section inside the Sphere Collider component to resize the range of your event. For reference, whenever the player enters that green sphere, the script will be triggered and the events will occur.

Once you have the size perfected, it is **imperative** that we tell Unity this collider is for triggering events and NOT as a big round wall. To do this, make sure the Boolean tick-box labeled **Is Trigger** in the sphere collider component has a checkmark on it. This way our player can walk through it, and trigger the event. Otherwise our players will hit an invisible wall, and the script will not trigger. (Reference the Sphere Collider image to see roughly what your Sphere collider should look like. And yes, you only need **one Sphere Collider**).

Now that the collider component has been added to our Event Trigger, we can finally **add our custom script**. (*Once again, how to bring the script into Unity will be added below, this section assumes we already have the script accessible inside Unity*). In order to do this, all we need to do is go back to the button at the bottom of the Inspector window labeled **Add Component** and use the popup windows search function to find our script. Since I had created it for a board game *game*, the script you are looking for is called MinigamePieceActivator. (The name can be changed, however I will not explain how to do that in this tutorial. If not done properly, you will receive errors and Unity will not function as expected).

With the script added, **drag** the GameObject from the Scene into the **Asset Explorer** window (typically at the bottom of Unity) to create a reusable and drag-and-droppable copy of your Event Trigger.

## Setting Up The Trigger For Use

You can now place as many triggers as you like! You can either duplicate the trigger in the scene already, or drag it into the scene from the Asset Explorer to place several triggers for different purposes. Make sure to place the triggers exactly where you want the events to trigger from (as in, where the player needs to stand/walk into for the trigger to activate).

All you need to do now is **tell the script how many objects you will start and end by using the array inputs** for **ToStartObj** and **ToEndObj** in the Inspector. Once you have created the number GameObject selectors required for each array, you can now select which objects you want to start or end when the event is triggered by either dragging them into the input fields, or clicking the circles next to the input fields to select them from the Scene. **You can also change the timer float variable to delay the events occurring** from the moment the player touches the trigger zone. **Leave the number as 0 if you want it to be instant**.

## Play Testing Your Creation

If all the steps have been followed as I intended them to be, (I know understanding other peoples steps and descriptions can feel confusing sometimes, it is okay to be lost. Try try again, or eventually ask for help!) then you should be able to now play your scene and trigger the event by walking the character into where you placed the Event Zone Triggers!

**If you have any questions, feel free to reach out to Scott Warren (Sayincraft Studios) on Discord through "*Michael Nixon's Server"*** or finding me some other way. Perhaps through my Discord, or school email (of which you can find in our Quercus classroom).

I hope to hear some of you were able to make use of this script and tutorial! And remember, *we all need a little CONSOLATION*!

## The Script: (MinigamePieceActivator)

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Game Script by Sayincraft Studios (Scott Warren)
public class MinigamePieceActivator : MonoBehaviour
{

//Variables that will be defined in Unity Inspector:

 public GameObject[] ToStartObj; //Array of Objects that will appear on Player Collision.

 public GameObject[] ToEndObj; //Array of Objects that will disappear on Player Collision.

 public float timetowait; //Float timer that will count down once player touches parent object.

// Routine that will detect when Player enters collider.
 void OnTriggerStay(Collider other)
 {
 if (other.gameObject.tag == "Player") //Will detect any collider with tagged as "Player"
 {
 StartCoroutine(MinigameStart()); //Activates the coroutine with our main code

 }
 }

 // Use this for initialization
 IEnumerator MinigameStart() //IEnumerator required for our float timer.
 {

 yield return new WaitForSeconds(timetowait); //This waits for the float timer to reach 0

 foreach (GameObject obj in ToStartObj)//Selects every GameObject in the Start Array to apply code inside the brackets below
 {
 obj.SetActive(true); //Sets the GameObjects active from the array!
 }

 foreach (GameObject obj in ToEndObj)//Selects every GameObject in the End Array to apply code inside the brackets below
 {
 obj.SetActive(false); //Disables the GameObjects in the array.
 }

 }
}

```

## I Need Help Adding This Script Into Unity!

In order to bring the above script into Unity, you need to create a C# script called **MinigamePieceActivator** and opening it up in an IDE such as Visual Studio. To do this, right click an empty space in the **Asset Explorer** window (typically at the bottom of Unity) which will open a popup right-click menu. Select **Create C# Script**, and it will immediately give you an opportunity to name it (of which it should be named MinigamePieceActivator).

With the named C# script open in your IDE, copy and paste the entire C# script selection shown above into the IDE where **MinigamePieceActivator** is open (Make sure you **copy everything from here**, and **overwrite all the existing code that was automatically written in the newly created script** from Unity).

Scott Warren, 2021-11-05