A better solution for larger games!

if (gameObject.CompareTag("Unbreakable")) return;

Using CompareTag is a slightly better way to compare a string to a tag string.

2 Likes

For an explanation on why is better to use CompareTag check these comments from Unity forum:

http://answers.unity.com/answers/200836/view.html
http://answers.unity.com/comments/1096170/view.html

Visual Studio actually gave me that recommendation, so I had already switched to it.

However, my issue with tags is that you only seem to be able to assign one tag to an object. What if you have more than one property you need to assign?

Tags don’t seem to address that. In my case, I have made different color blocks and the color determines the point value when it is destroyed. This is easily handled by defining an enum list and making a SerializeField of that enum type. Each element of the list shows up in the Inspector and each one is assigned a number starting from 0.

It is also much faster to check an integer value, which is what an enum value is, than it is to compare a string.

So here is my enum definition for the colors:
public enum BlockColor
{
Red,
Green,
White,
Yellow,
Grey
} // enum BlockColor

And here is the method in GameStatus.cs to count the score:
public void AddToScore(Block block)
{
currentScore += pointsPerBlockDestroyed * ((int)block.blockColor + 1);
DisplayScore();
} // AddToScore()

You can add as many such properties as you want in a script to allow setting all sorts of characteristics. I am sure tags are useful in their own right, but consider enum values to add similar functionality when you need it and if you are finding performance is not very good when comparing tag values.

1 Like

This is great solution and you can combine it alongside tags to create very amazing systems, that being said, you over-engineered this, you can do the exact same thing with a single line of code, just expose the bonus multiplier in your code. This will grant you the ability to balance things out without having the need to go back to your code, remember, when balancing and designing your game the last thing you want to do is write code, if you’re making a level and are constantly going back to VS you probably need to expose certain variables, everything should be done in the inspector at some point.

[SerializeField] int pointBonusMultiplier;

public void AddToScore(Block block)
{
    currentScore += pointsPerBlockDestroyed * pointBonusMultiplier;
    DisplayScore();
}

You’ll even do less math with that solution, which is always nice.

Privacy & Terms