- Home /
Unity crashes
Collider2D[] colliders = Physics2D.OverlapCircleAll(_enemy.transform.position, 3f, LayerMask.GetMask("Enemy"));
foreach(Collider2D nearbyObject in colliders)
{
Vector2 direction = (nearbyObject.transform.position - _enemy.transform.position);
Vector2 directionNormal = direction.normalized; ;
Rigidbody2D rb = nearbyObject.GetComponent<Rigidbody2D>();
if (rb != null)
Debug.LogError("RB found");
rb.AddForce(30f*directionNormal, ForceMode2D.Impulse);
Enemy nearEnemy = rb.GetComponent<Enemy>();
nearEnemy.DamageEnemy(40f);
}
First off all, I'm finding the near enemy object colliders with Physics2D.OverlapCircleAll function and I can access their rigidbodies with their colliders and add force to them successfully. But when I'm trying to access them as enemies and damage them with my DamageEnemy function which only changes enemies' current health, Unity is crashing and closing by itself. I don't know what I'm doing wrong. Please help me.
maybe it is colliding with a lot of objects? can you put a try catch in the enemy damage eney line? associate visual studio with unity editor in the nearenemy line for making sure it is finding the reference.
It does collide with a lot of object of course but I'm using a layermask to avoid the problem you're assu$$anonymous$$g. I think it's having an infinite loop when I'm colliding with an enemy but I don't know why.
Unrelated question
what do the asterisks do? I just saw them in your code here
**Enemy nearEnemy = rb.GetComponent<Enemy>();
nearEnemy.DamageEnemy(40f);**
I've put them on purpose for you to see where is the actual problem... They definitely don't exist in the actual code.
I haven't tested this because I haven't got time but maybe it's contantly getting the enemies within your physics overlap every frame, then it iterating through your enemies in the foreach loop which just keeps getting bigger since its still adding the same enemies it already added. I can't say my wording is good but it's something.
Your answer
Follow this Question
Related Questions
Use 2D Effectors with Raycast Collision Method 0 Answers
My ground checker only works... sometimes 1 Answer
Problem with Falling Platform Script 3 Answers
Play and Stop Animation 1 Answer
"Dash-Move" only work some times. 1 Answer