- Home /
Question by
gettinjacob · May 12, 2021 at 09:37 AM ·
unity 2drigidbody2dtimertopdown
The object of type 'Rigidbody2D' has been destroyed but you are still trying to access it. with StartCoroutine
im having a problem with my knockback feature with StartCoroutine timer, it does the work but this error always show up, anyone know how to fix this?
object of type 'Rigidbody2D' has been destroyed but you are still trying to access it.
heres the code
//! Attack
Collider2D[] _enemiestohurt = Physics2D.OverlapCircleAll(attackpos.position, _Attacksize, _Whatenemy);
for (int i = 0; i < _enemiestohurt.Length; i++)
{
Rigidbody2D EnemyRb = _enemiestohurt[i].GetComponent<Rigidbody2D>();
_Knockback(EnemyRb);
StartCoroutine(KnockbackTimer(EnemyRb));
_enemiestohurt[i].GetComponent<Enemy>().Takedamage(_Damage);
}
_TimeBtwAttk = _StartTimeBtwAttk;
//!Knockback
private void _Knockback(Rigidbody2D _AenemyRb)
{
Vector2 _KbDifference = _AenemyRb.transform.position - transform.position;
_KbDifference = _KbDifference.normalized * _KnockbackForce;
//_AenemyRb.velocity = new Vector2(_KbDifference.x * _KnockbackForce, _KbDifference.y * _KnockbackForce);
_AenemyRb.AddForce(_KbDifference, ForceMode2D.Impulse);
}
private IEnumerator KnockbackTimer (Rigidbody2D _AenemyRbTimer)
{
if(_AenemyRbTimer != null)
{
yield return new WaitForSeconds(_KnockbackTimer);
_AenemyRbTimer.velocity = Vector2.zero;
}
}
//!Enemy
public void Takedamage(int _Damage)
{
Health -= _Damage;
if (Health <= 0)
{
Death();
}
Debug.Log("aghhh" + Health);
}
Comment
Answer by gettinjacob · May 12, 2021 at 01:01 PM
Update: I fixed it all you had to do is this, ive read another forum about how coroutines work with gamecomponents even after you destroyed the component from another script it will still send a garbage component to the parameter causing errors such as this.
if (_AenemyRbTimer != null)
{
_AenemyRbTimer.velocity = Vector2.zero;
}