Who wants to score?

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:

  1. In the Inspector, click on Add Component near the bottom of the Component:
  1. Name the New Script ScorePoints:
  1. Double-click on the faded ScorePoints in the ScorePoints component. This will load up Visual Studio:
  1. Once Visual Studio loads, type in the following script. This is a very simple script:
  1. 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.
  1. 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.
  2. Open up ApplicationManager in Visual Studio. Somewhere around line 23, add the following line directly after:
public string debugInfoString = "DebugInfo:";
public int score = 0;
  1. 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:
  1. 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.
  1. Select the 10Collider, right-click on it, and click on the Duplicate option:
  1. Rename the new Duplicate 20Collider:
  1. Now, change its score value to the equivalent of its name. Repeat this process for colliders 30, 40, 50, 100, and 100:
..................Content has been hidden....................

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