A quick hint on formatting code, type the backwards ’ key three times on it’s own line and press enter, then paste the code and follow it up with another backwards ’ key three times.
Sam’s code:
private void AwardExpericence(GameObject instigator)
{
Experience experience = instigator.GetComponent<Experience>();
if (experience == null) return;
experience.GainExperience(GetComponent<BaseStats>().GetExperienceReward());
}
Your code:
private void AwardExpericence(GameObject instigator)
{
float xpReward = gameObject.GetComponent<BaseStats>().GetExperienceReward();
instigator.GetComponent<Experience>().GainExperience(xpReward);
}
On the face of things, your method looks shorter, and under most circumstances will accomplish the exact same result without issue.
So here are the differences, and why ultimately, Sam’s code is likely the better solution:
- Sam’s code is running a check first to see if there in an experience component, only then doing the more expensive GetExperienceReward() method. Your code runs the more expensive GetExperienceReward() method first.
- Both methods run the risk that the character has no experience reward. Sam’s code assumes that a character with no experience component will always have an Experience Reward stat.
- As noted in the previous comment, your method will throw a null reference when an enemy kills the player (the enemies don’t have an experience component).
As the null reference check on the Experience component is vital (really, anywhere a component can be null, there should be a null reference check, even if we didn’t put one in there in the lessons), it’s better to get that null reference check out of the way in the beginning before running the extra code.
All of this being said, don’t be afraid to experiment with the code presented in the lessons, and see what works for you. For a large chunk of the code in these courses, there is more than one way to accomplish the same goal. Sometimes, design decisions can bring you to choose a different route as well. Suppose, for example, you’re game is one where even the enemies can gain experience, and you make it a rule that both enemies and the player have experience components and ExperienceReward stats… under these circumstances, your code wins out as it skips the extra null check and gets straight to the point.