- Home /
how to limit the counting of multiple trigger collisions
I have recently encountered a problem while coding a prototype for a game. I have 3 counters set up for 3 different variables, they are: the number of red cubes, the number of blue cubes, and the number of total cubes. I'm currently having trouble with the red and blue counters. I want to have it set up as to where a "blank" cube turns into a red or blue cube, it is counted once (and only once) and that one point per red / blue cube is put up on the score. What is currently happening is that whenever a red / blue cube enters the trigger collider, it is counted every time. I would like for it to only be counted once per cube, but I'm not sure how to do that. Thats where you come in! Code below (warning, its a bit messy)
var isBlue = false;
var isRed = false;
static var BlueNum = 0;
static var RedNum = 0;
static var TotalNum = 0;
function Start () {
TotalNum++;
}
function Update () {
if(TotalNum > 100){
}
if(isBlue == true){
Blue();
}
if(isRed == true){
Red();
}
}
function OnTriggerEnter(thisTrigger : Collider) {
if(thisTrigger.gameObject.tag == "Finish"){
Debug.Log("t_blue");
BlueNum++;
renderer.material.color=Color.blue;
isBlue = true;
if(isRed == true){
renderer.material.color=Color.red;
Red();
Debug.Log("red");
}
}
if(thisTrigger.gameObject.tag == "Respawn"){
Debug.Log("t_red");
RedNum++;
renderer.material.color=Color.red;
isRed = true;
Red();
if(isBlue == true){
renderer.material.color=Color.blue;
Blue();
Debug.Log("blue");
}
}
}
function Blue(){
isRed = false;
renderer.material.color=Color.blue;
}
function Red(){
isBlue = false;
renderer.material.color=Color.red;
}
Answer by whydoidoit · Feb 25, 2014 at 03:46 AM
You could put a script on the cube that has a variable called "counted" on it and get that script using GetComponent - then only count if it is set to false and update it to true immediately.
Counted.js
var counted = false;
Main script
if( thisTrigger.GetComponent(Counter).counted == false ) {
RedNum++;
thisTrigger.GetComponent(Counter).counted = true;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Adding 1 point after collison 1 Answer
The problem with the change of position and colliders. 1 Answer
Need help with some OnTrigger Scripting 2 Answers