- Home /
Area of Effect (AoE) Stun Issue
I've tried to create a trigger which causes an area of effect stun towards my enemies. This is what I got so far.
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Enemy")
{
Collider2D[] enemies = Physics2D.OverlapCircleAll(transform.position, 10, 1 << LayerMask.NameToLayer("Foreground"));
foreach(Collider2D en in enemies)
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
EnemyBehaviour stun = rb.GetComponent<EnemyBehaviour>();
stun.EnemyStunned();
}
Destroy(this.gameObject);
}
}
I get this error: NullReferenceException: Object reference not set to an instance of an object HunterTrapBehaviour.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/RPG Project - R&T/_Scripts/HunterTrapBehaviour.cs:19)
Answer by Kciwsolb · Apr 24, 2018 at 07:27 PM
On line 10 of the code you posted, you are setting rb to the value of GetComponent. GetComponent will try to return a Component on the GameObject you run it on. You probably need to try Rigidbody2D rb = en.GetComponent<Rigidbody2D>();
Also, you are assuming that rb is not null. You probably should check for that possibility before trying to get your EnemyBehaviour script. And before you try to call EnemyStunned(), you might want to be sure that stun is not null as well.
Even though you are checking for a tag for the Collider passed into OnTriggerEnter2D, you still need to check if those Components exist because OverlapCircleAll is returning an array of all Colliders in a radius. This array is unrelated to the one Collider you already checked. So, the Colliders being returned might not all be enemies.
Answer by Trappedlol · Apr 25, 2018 at 03:42 PM
Thank you! I can't believe I missed that. For anyone dealing with a similar issue in the future this is the working script.
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Enemy")
{
Collider2D[] enemies = Physics2D.OverlapCircleAll(transform.position, 10, 1 << LayerMask.NameToLayer("Foreground"));
foreach(Collider2D en in enemies)
{
Rigidbody2D rb = en.GetComponent<Rigidbody2D>();
if(rb != null && rb.tag == "Enemy")
{
EnemyBehaviour stun = rb.GetComponent<EnemyBehaviour>();
stun.EnemyStunned();
}
}
Destroy(this.gameObject);
}
}
Your answer
Follow this Question
Related Questions
Object is not colliding with wall colliders 0 Answers
Can you check again something that is already in the IsTrigger collider ? 2 Answers
OnTriggerEnter2D works without being actually triggered. 0 Answers
OnTriggerEnter2D - am I getting it wrong? 2 Answers
OnTriggerEnter2D & OnCollisionEnter2D Not Responding 1 Answer