Not taking damage.

Hello. I currently have an explosive barrel and I programmed it to make the player and nearby enemies take damage if it’s in the blast radius. I thought I did it right, but I guess not. Can anyone tell me what I did wrong and show the correct way?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExplosiveBarrel : MonoBehaviour
{
    private float health = 5f;
    public float radius = 10f;
    public float force = 700f;

    private float minDamage = 150;
    private float maxDamage = 500;

    private bool hasExploded = false;

    public GameObject explosionEffect;

    public void OnHit(float minAmount, float maxAmount)
    {
        health -= Random.Range(minAmount, maxAmount);

        if (health < 0)
        {
            Explode();
            hasExploded = true;
        }
    }

    void Explode()
    {
        GameObject explosion = Instantiate(explosionEffect, transform.position, transform.rotation);
        Destroy(explosion, 2f);

        /*
        Collider[] collidersToDestroy = Physics.OverlapSphere(transform.position, radius);

        foreach (Collider nearbyObject in collidersToDestroy)
        {
           
        }
        */

        Collider[] collidersToMove = Physics.OverlapSphere(transform.position, radius);

        foreach (Collider nearbyObject in collidersToMove)
        {
            Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();

            if (rb != null)
                rb.AddExplosionForce(force, transform.position, radius);
        }

        RaycastHit hit;

        if (Physics.Raycast(gameObject.transform.position, gameObject.transform.forward, out hit, radius))
        {
            Target target = hit.transform.GetComponent<Target>();

            if (target != null)
                target.TakeDamage(minDamage, maxDamage);

            PlayerStats player = hit.transform.GetComponent<PlayerStats>();

            if (player != null)
                player.TakeDamage(minDamage, maxDamage);
        }

        Destroy(gameObject);
    }
}

You would just move the Raycast code inside the foreach. Line 57-68.

Replace hit.transform with nearbyObject.

1 Like

i’ll give that a shot when i get home and post an update if it works.

it works. thank you.