Hi, I’d like to share my solution to the scoring mechanics.
NOTE that everything that is not mentioned here stays the same.
In my version of the game, I added a few different enemy types with different stats and difficulties, so I wanted to reward the player accordingly.
- Instead of putting the score value and the isPlayer check on a health script, I made a new one, called: PointsEvaluator.
This component is simple: It has:
-
[SerializeField] int pointsValue = 10;
Ammount of points you will get after destroying a different enemy.
public int GetPointsValue()
{
return pointsValue;
}
A method that just returns the value of the points.
-
I added this component to the enemy prefabs and entered the score for each one of them.
-
In
Health.cs
, inDie()
method I call another private method called AddPoints()
- AddPoints gets the reference to the component of type PointsEvaluator, but before that, it is initialized to null.
PointsEvaluator pointsEvaluator = null;
- After that, I used a new workflow that wasn’t covered so far in the course (I know of this because of my previous programming experiences). It is using
try
andcatch
keywords.
What they do essentially is telling the compiler to try and do a thing, and if it fails, that is: if we were to get some type of error in the console, it allows us to catch that error and handle it or do something else.
There I made it so that thetry {}
block tries to set thepointsEvaluator
, as:pointsEvaluator = gameObject.GetComponent<PointsEvaluator>();
And thecatch (Exception e) {}
if there is an exception, that is if the game fails to find thePointsEvaluator
on agameObject
, specifically: when the player gets destroyed as it doesn’t have that component. An there I simplyreturn
out of the method.
A small NOTE is thatcatch
part must have that(Exception e)
as this is the way it will accept the error and then we will be able to handle it.
Errors of the typeException
are from thesystem
namespace, so we must include it at the top of our script:using System;
Lastly, i check if mypointsEvaluator
variable is different from null and then if it is, I add the score through our score keeper:scoreKeeper.AddPoints(pointsEvaluator.GetPointsValue());
Full AddPoints method:
void AddPoints()
{
PointsEvaluator pointsEvaluator = null;
try
{
pointsEvaluator = gameObject.GetComponent<PointsEvaluator>();
}
catch (Exception e)
{
return;
}
if (pointsEvaluator != null)
{
scoreKeeper.AddPoints(pointsEvaluator.GetPointsValue());
}
}```