As far as I can tell Unity doesn't have a mechanism natively that tells you all the objects that are currently collided (triggered) in your collider. The most common approach seems to be managing the list on your own using the OnTriggerEnter and OnTriggerExit:
void OnTriggerEnter(Collider other)
{
if (other.tag == "enemy")
{
allCollisions.Add(other.gameObject);
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "enemy")
{
allCollisions.Remove(other.gameObject);
}
}
One extra point to note, that this approach breaks down if your objects are "exiting" because they are destroyed. In my case, I wanted to destroy the entire list of objects via an event. At first I used List.Clear(), however I found that this only nulls all the elements, but doesn't actually clear the elements. Better was to blow away the list with a new instance.
if (Input.GetButtonDown("Fire1"))
{
foreach (GameObject enemy in allCollisions)
{
SeekToKill newBullet = (SeekToKill)Instantiate(bullet, bulletStart.transform.position, bulletStart.transform.rotation);
newBullet.SetTarget(deadbug);
}
// clear list including indicies
allCollisions = new List<GameObject>();
}
Showing posts with label Physics. Show all posts
Showing posts with label Physics. Show all posts
Saturday, July 8, 2017
Friday, February 5, 2016
Add Bounce
To add bounce to an object, first you need to create a Physic Material, and this can be done in the Assets > Create > Physic Material menu. Note that upon creation, you should name the material.
Attach the material to the Collider component on your game object.
Subscribe to:
Comments (Atom)