TakeDamage/dealDamage

Hey there. Im making a top down shooter game. Soo my question is I have an enemy script that has :

public void TakeDamage(float damage)
{
healt -= damage;
if(healt <= 0)
{
Destroy(gameObject);
}
}

And then I have a weapon script (pickupble weapon) and a bullet prefabe that I Instantiate.
So when bullet collide with enemy:

private void OnCollisionEnter2D(Collision2D other)
{
    Weapon weaponScript = other.gameObject.GetComponent<Weapon>();

    if (other.gameObject.TryGetComponent<Enemy>(out Enemy enemyComponent))
    {
      I WANT TO MAKE LIKE THIS BUT I CANT
      enemyComponent.TakeDamage(weaponScript.damage);

        LIKE THIS IS WORKING 
        enemyComponent.TakeDamage(1);
        Debug.Log("hitsomethings");
    }
    Destroy(gameObject);
}

Soo i want deal damage with the public float that weapon script has when bullet script collide with enemy then enemy take damage.
Is that possible? Im doing like this cause there is different weapons soo different fireRate,damage,etc…

From the looks of it, you’re trying to hurt the enemy with their own weapon.

Weapon weaponScript = other.gameObject.GetComponent<Weapon>();
other.gameObject.TryGetComponent<Enemy>(out Enemy enemyComponent)

Both of those come from the “other” in the collision, and I’m assuming that the “Enemy” doesn’t possess a “Weapon” in this context.

As a result, because the “Weapon” variable is null after it’s not found by GetComponent<>(), you haven’t been able to assign damage without a NullReferenceException.