So I see that Rick actually went ahead and hardcoded in that the projectile damages only attackers. I personally wanted to make the projectile script universal so it could be thrown easily onto either an ally or an enemy projectile. I was wondering if this was the most efficient format for doing so. I created dummy scripts called “Ally” and “Enemy” that were simply used for classification purposes.
When the projectile is instantiated, it checks to see if it is an ally or enemy. If it is an ally, it sets the bool “ally” to true. During TriggerEnter2D, it then checks the other collider to see if it is an ally. If it is an ally, it sets the bool “other” to true. If both bools match, then the CheckIfOtherIsAlly condition will be true, which disables the if statement in TriggerEnter2D.
bool ally = false;
private void Start()
{
CheckIfAlly();
}
private void CheckIfAlly()
{
if (GetComponent<Ally>())
{
ally = true;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
// If it is not an ally, deal damage.
if (!CheckIfOtherIsAlly(other))
{
DamageHandler damageHandler = GetComponent<DamageHandler>();
Health healthOfOther = other.GetComponent<Health>();
healthOfOther.DealDamage(damageHandler.GetDamage());
Destroy(gameObject);
}
}
// This checks to see if the colliding creature is an ally or enemy. If it's an ally, it will return true.
private bool CheckIfOtherIsAlly(Collider2D other)
{
bool otherIsAlly = false;
//Find if there is enemy or ally script on it.
if (other.GetComponent<Ally>())
{ otherIsAlly = true;}
if (ally == otherIsAlly)
{ return true; }
else
{ return false; }
}