How to get proper version of script from another object?
So, I have been trying to make a minimalistic shooter to improve my skills with Unity (version 5.0.0f4). The problem I’m trying to solve is how the player bullets don’t do damage to the boss. Looking at the debug logs, I assume this has to do with how the Boss class inherits from the __Enemy class, which itself inherits from the MovingEntity class, which is what the bullet accesses right before doing damage.
So, how do I programmatically make the bullet access the proper script instance the target has, so it does damage to the actual enemy instance? As it is now, the debug logs say it did damage, but the editor says the boss is still at full HP. I could just use an if-else statement, but I’m sure there must be a better way.
Here is the code for the bullet’s collision:
protected virtual void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(this.name + " is colliding with " + collision.name);
//if this bullet hits something it is meant to hit, do damage to it
if (collision.tag.Contains(TargetTag)) //
{
Debug.Log(this.name + " damaging a(n) " + TargetTag + "! Target: " + collision.name);
MovingEntity en = collision.gameObject.GetComponent<MovingEntity>();
en.TakeDamage(this.Damage);
Destroy(this.gameObject);
}
}
Extra info, in case it helps:
I also have an Asteroid class, which inherits from __Enemy. The bullets damage the Asteroid objects just fine, despite the prefabs not specifically having any instances of MovingEntity. The TakeDamage function is also virtual, so I know that lacking virtualization isn't the problem.
Answer by TBruce · Dec 26, 2016 at 07:25 PM
Try this to see where your problem lies
protected virtual void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(this.name + " is colliding with " + collision.name);
//if this bullet hits something it is meant to hit, do damage to it
if (collision.tag.Contains(TargetTag)) //
{
if (collision.gameObject.GetComponent<MovingEntity>() != null)
{
Debug.Log(this.name + " damaging a(n) " + TargetTag + "! Target: " + collision.name);
MovingEntity en = collision.gameObject.GetComponent<MovingEntity>();
en.TakeDamage(this.Damage);
}
else
{
Debug.Log("GameObject " + collision.gameObject.name + " with the tag " + collision.gameObject.tag + " does not have an attached GameObject of type MovingEntity. Please add one and try again");
}
Debug.Log("Destroying the current object - " + this.gameObject.name);
Destroy(this.gameObject);
}
}
I'm really sorry for the late reply; I don't know how I missed your answer until now ._. Anyway, I did find my own solution. I just tested yours, though, and it works, too. So, thanks!
Your answer
Follow this Question
Related Questions
Survival Shooter problems 0 Answers
UNITY shooting script does nothing 1 Answer
How do I make a script for camera recoil recovery? 0 Answers
Unity 5.1 networking 0 Answers
Tag doesn't work when gameObject is a child of the Main camera? 1 Answer