Now we have an invisible collision box waiting for something to hit it. Unfortunately, without a script to tell it how to respond, it will do nothing when it is triggered. Let's fix that by following these steps:
- In the Inspector, click on Add Component near the bottom of the Component:
- Name the New Script ScorePoints:
- Double-click on the faded ScorePoints in the ScorePoints component. This will load up Visual Studio:
- Once Visual Studio loads, type in the following script. This is a very simple script:
- Let's go over the code and see exactly what it does:
- On line eight, we declare a public integer, called scoreValue. This is where we will store the numeric value for each trigger. A 50-point trigger will have a scoreValue of 50.
- Unity has a few events associated with colliders, although they are not part of the collider class technically.
- OnTriggerEnter, when another object collides with the object this script is attached to, this method is called. It also sends a reference to the object that collided with it. What we are doing here is calling our ApplicationManager singleton to add the scored amount to the total.
- OnTriggerExit runs when the triggering object leaves its collider. In our case, we destroy the other.gameObject or the ball that hit it when that happens.
- If you go back to Unity at this point, you will get an error message. Currently, there is no variable in ApplicationManager called score. So, let's alleviate that really quick.
- Open up ApplicationManager in Visual Studio. Somewhere around line 23, add the following line directly after:
public string debugInfoString = "DebugInfo:";
public int score = 0;
- Alright, now that error is out of the way; if you click on the 10Collider object, you should see a newly formed Score Value = 0 in the ScorePoints component:
- Well, since this is the 10Collider object, we need it to equal 10. Type that into the box:
- Alright! That one down, six to go, but the rest are just duplicates.
- Select the 10Collider, right-click on it, and click on the Duplicate option:
- Rename the new Duplicate 20Collider:
- Now, change its score value to the equivalent of its name. Repeat this process for colliders 30, 40, 50, 100, and 100: