- Home /
Multiple triggers/collisions
Game objects like trees or rocks have this script attached
using UnityEngine;
using System.Collections;
public class ColScript : MonoBehaviour {
public void OnTriggerStay(Collider other) {
if (other.gameObject.tag == "Cube")
{
Build._areaOverlay = true;
}
}
public void OnTriggerExit(Collider other) {
if (other.gameObject.tag == "Cube")
{
Build._areaOverlay = false;
}
}
}
_areaOverlay is a public static bool found in Build class
Whenever _areaOverlay is true, the Cube which penetrates game objects with the script attached turns red - if it's equal to false the cube is green.
The thing is, when I'm inside at least two objects - let's say there's a tree and rock next to each other and Cube collides with both at the same time, when I leave the tree but am still inside the rock, Cube changes color for a second (color change is just a cosmetic, there are many game changes depending on _areaOverlay).
How do I avoid this? In other words, how do I check if Cube collides with other scripted game objects as well?
Answer by KeithK · Jul 19, 2011 at 09:08 AM
You could keep a count of how many objects Cube is colliding with. Either a list of object references, or a simple int.
Then you would only set Build._areaOverlay = false
when your list is empty, or your count is zero.
You may also look at doing the collision checks on the Cube if possible? Since, it, is what is affected when there is a collision.
I changed the script so it's now attached to Cube and reacts on game objects with tags 'tree' 'rock' etc. This allowed me to make a counter inside the script. Thanks a lot!