- Home /
OverlapSphere not causing damage? - Solved
I've been trying to use Physics.OverlapSphere so my grenades do damage to the enemy. Unfortunately, I'm unable to cause damage to the enemies in my game, any help is appreciated.
Current Script (using JavaScript) :
public var explosion : GameObject;
public var timer : float = 10.0;
public var radius : float = 5.5;
public var force : float = 25.0;
public var throwForce = 150.0;
public var detonate : boolean = false;
function Start () {
rigidbody.AddRelativeForce(0, 0, throwForce);
}
function Update () {
if(detonate){
timer -= Time.deltaTime;
}
if(timer <= 0){
Explode();
}
}
function OnCollisionEnter () {
detonate = true;
}
function Explode () {
var explosionPos : Vector3 = transform.position;
var Cols : Collider[] = Physics.OverlapSphere(explosionPos, radius);
for (var hit : Collider in Cols){
if(!hit){
continue;
}
if(hit.rigidbody){
hit.rigidbody.AddExplosionForce(force, explosionPos, radius, 3.0);
}
if(hit.transform.tag == "Enemy"){
hit.transform.GetComponent("AiHealth").health -= 100;
}
}
Instantiate(explosion, transform.position, Quaternion.identity);
Destroy(gameObject);
}
Answer by Jamora · Aug 04, 2013 at 07:36 PM
You are using hit.transform.tag
, which won't work; only GameObjects have tags. So you need to replace that with hit.gameObject.tag
Same applies for the GetComponent below; use gameObject instead of transform.
Unless I missed something else (and assuming the rest of your code logic works) that should do it.
that didn't work, I'm still getting a NullReferenceException in the console.
I reviewed the RaycastHit documentation and it turns out you can't access the gameobject directly. You need hit.transform.gameObject.tag
What line are you getting the null reference on? A null reference means that a reference type variable is not set and thus points to empty (zero).
The only references I see in this code are explosion and hit.rigidbody.
Are you sure your clickable things have a rigidbody? Have you set the explosion GameObject in the inspector? Does the GameObject that script is attached to have a rigidbody?
Answer by P2ThatGuy · Aug 06, 2013 at 11:23 AM
If anybody else is having a similar issue, I figured it out. Rather than a GetComponent, I put a function inside the ai script :
function Damage (dmg : int) {
health -= dmg;
}
then in the script I previously posted replaced the enemy tag bit with this :
if(hit.collider.gameObject.tag == "Enemy"){
hit.collider.gameObject.SendMessageUpwards("Damage", 110, SendMessageOptions.DontRequireReceiver);
hit.collider.gameObject.rigidbody.AddExplosionForce(force, explosionPos, radius, 3.0);
}
}
thanks for all help that was previously given.
Your answer
Follow this Question
Related Questions
Help With Remote Explosive 1 Answer
How do I destroy all enemy game objects with a bomb? 2 Answers
Explosion Damage not being applied. 1 Answer
timed bomb, explosion detection 2 Answers