Detecting collisions of Cucumber Man and cherry trees

In this section, we will enable and test collisions between the Cucumber Man and cherry trees. Our first step is to ensure the cherry trees in our sandbox area all have the CherryTree tag. We previously created the tag name, so we only need to apply it to the trees in our sandbox. Here are the steps:

  1. In the Hierarchy panel, select a Cherry Tree that is inside your sandbox area
  2. In the Inspector panel, click the drop-down box to the left of the Tag label
  3. Select the CherryTree tag
  4. Repeat steps 1 through 3 for each Cherry Tree GameObject in your sandbox area
  5. Optionally, repeat steps 1 through 3 for all the Cherry Tree GameObjects in the Hierarchy view, not just the ones in your sandbox area

Next, we will create a CucumberManManager script to handle the collisions with the cherry trees. Here are the steps to create that script:

  1. In the Hierarchy panel, select the CumcuberMan player character
  2. In the Inspector panel, scroll to the bottom and click the Add Component button
  3. Select New Script
  4. Name the script CucumberManManager
  5. Click the Create and Add button
  6. In the Project panel, click Favorites | All Scripts
  7. Drag the CucumberManManager script to the Assets | Custom Scripts folder
  8. Double-click the CucumberManManager script to open it in an editor
  9. Edit the script so that it matches the code provided here:
     using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CucumberManManager : MonoBehaviour {

void OnTriggerEnter(Collider theObject) {
if (theObject.gameObject.CompareTag ("CherryTree")) {

// Do something

}
}
}

The preceding script is a C# script with an OnTriggerEnter() method. As you can see, we check the tag of what the Cucumber Man collided with to see if that game object has a tag of CherryTree.

Next, we need to do something when that collision is detected. We will handle that in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset