Hello,i trying to make granade deal damage.First i try to make if grenade hit something to debug ,
Congralations you hit it!“.But when I throw grenade to hit cube that have box collider.It don’t calculate cube as object and don’t debug ,Congralations you hit it!” Can you help me please?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grenade : MonoBehaviour
{
public float delay = 3f;
public float radius = 5f;
public float force = 700f;
public float damage = 10f;
public GameObject explosionEffect;
float countdown;
bool hasExploded = false;
// Start is called before the first frame update
void Start()
{
countdown = delay;
}
// Update is called once per frame
void Update()
{
countdown -= Time.deltaTime;
if(countdown <= 0f && !hasExploded)
{
Explode();
hasExploded = true;
}
}
void Explode()
{
GameObject grenadeffect = Instantiate(explosionEffect, transform.position, transform.rotation);
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in colliders)
{
// Add Force
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if (rb != null)
{
RaycastHit hit;
rb.AddExplosionForce(force, transform.position, radius);
if(Physics.Raycast(nearbyObject.transform.position, nearbyObject.transform.forward, out hit))
{
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
Debug.Log("Congralations you hit it!");
}
}
}
}
Destroy(gameObject);
Destroy(grenadeffect, 1.5f);
}
}