I found a nice prefab on the Unity store of a nuclear explosion. I’ve got it all working, kinda.
They player can die when it explodes too close, but the enemies I have setup do not take any damage. They take damage from everything else I have, but not this explosion so I think it might be something with the explosion code.
Is anyone able to help me with this?
Any help is very much appreciated.
Here’s my explosion code:
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class nukeExplosion : MonoBehaviour
{
[SerializeField] float duration;
[SerializeField] int damage;
[SerializeField] float damageRadius;
[SerializeField] float maxDamageDistance;
SphereCollider explosionCollider;
float currentRadius;
[SerializeField] float expandSpeed;
[SerializeField] float targetRadius;
// Start is called before the first frame update
void Start()
{
explosionCollider = GetComponent<SphereCollider>();
currentRadius = 1f;
Destroy(gameObject, duration);
StartCoroutine(ExpandCollider());
}
IEnumerator ExpandCollider()
{
while (currentRadius < targetRadius)
{
currentRadius += expandSpeed * Time.deltaTime;
explosionCollider.radius = currentRadius;
yield return null;
}
}
// OnTrigger method to detect nearby objects and apply damage
private void OnTriggerEnter(Collider other)
{
Debug.Log("Collider Stayed: " + other.name);
IDamage dmg = other.GetComponent<IDamage>();
if (dmg != null)
{
float distance = Vector3.Distance(transform.position, other.transform.position);
float damageMultiplier = Mathf.Clamp01(1f - (distance / maxDamageDistance));
int calculatedDamage = Mathf.RoundToInt(damage * damageMultiplier);
dmg.TakeDamage(damage);
}
}
// Draw the damage radius gizmo for visualization
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, damageRadius);
}
}
The nuke script checks the units entering it’s trigger and inflicts damage, this mean the nuke trigger should be able to interact with the units, so for a first lead you can check if your enemies are on a different layer that the player and if yes you can check the collision matrix to see if a collision can occur (Unity - Manual: Layer-based collision detection)
On a second step you can check what differ between the player and the enemy units and based on the collider interaction matrix, see if the collision is possible