- Home /
[AOE damage] Detect nearby objects
Hi! I want to detect if any objects with "cube" tag are around the player. -If yes spawning spikes bellow them. What is the sure way to do it?
I tried the following: creating cubes and attaching a script to them. Which would receive incoming calls. Upon the receiving, the cubes wouldinstantiate another gameobejct right bellow them.
The player, on the other hand, would invoke those calls. Unfortunatelly this doesn't work. Could you please suggest where I might be wrong. Here is the script attached to the cube:
using UnityEngine;
using System.Collections;
public class receivemessage : MonoBehaviour {
public GameObject damaged_prefab;
GameObject theNewcube;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void AddDamage(float damage) {
print(damage);
theNewcube = (GameObject)Instantiate (damaged_prefab, this.transform.position, this.transform.rotation);
}
}
Here's the script attached to the player:
using UnityEngine;
using System.Collections;
public class send_message : MonoBehaviour {
void Start(){
}
void Update(){
if (Input.GetButtonDown ("Fire2")) {
ExplosionDamage();
}
}
void ExplosionDamage(Vector3 center, float radius) {
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
int i = 0;
while (i < hitColliders.Length) {
hitColliders[i].SendMessage("AddDamage");
i++;
}
}
}
When I try to run the game, the console says there's an error: "No overload for method 'ExplosionDamage' takes '0' arguments". What arguments am I supposed to provide? I tried: ExplosionDamage(Vector3(0,0,0),1000f) - but it doesn't work.
Answer by DanSuperGP · Jan 15, 2015 at 07:35 PM
You probably want to call
ExplosionDamage( transform.position, yourRadius);
That way the explosion is centered on your player.
You should also call
hitColliders[i].SendMessage("AddDamage", yourDamageValue, SendMessageOptions.DontRequireReceiver);
Your calls need to match the method signatures of what you're calling. AddDamage takes a float parameter, but you aren't passing it.
Answer by Jrodz · Apr 03, 2019 at 06:28 PM
Using the optional LayerMask argument for the overlap sphere can be helpful for ignoring all colliders except the ones that can take damage. Depending on how many colliders are inside the sphere cast it can really improve performance.
LayerMask mask = LayerMask.GetMask("YourCustomLayer");
// now ignores all colliders that aren't in "YourCustomLayer
Physics.OverlapSphere(center, radius, mask.value);
Answer by hameed-ullah-jan · Apr 03, 2019 at 06:59 PM
The Perfect way to achieve this thing is through events & Delegates, watch some tutorials on it and you will get the best experience.