How can I count the number of objects touching a collider and then destroy them?
Hello all,
I have a simple game where tennis balls fall down from off the screen and into a bucket. The player is on the side shooting projectiles at the balls trying to knock them out of the bucket's path. I want to create a script where every 30 seconds the bucket gets "emptied" only if 7 or less balls are allowed in, if at the 30 second mark 8 or more balls are allowed in, then the game ends, you lose and its game over. It's fairly simple. I'm fairly new to Unity and also to c# so the simpler the better.
Thank you so much for taking the time to read this!
Answer by ShimonKinkajoo · Jan 29, 2018 at 05:46 PM
A simple solution would be to trigger counts on collisions. Your bucket already has colliders on it i guess, so just look at the collisions, take the collider that is not the bucket, and see if it's in your "Scored" list. if not, add it. The problem is a ball can bounce of the bucket and not get in. so you can place a horizontal plane collider in the middle of the bucket, so a ball that touches it, is for sure stays in the bucket.
Another approach is to go over all the balls, and see which ones occupy a specific x,y,z limitations (the position and size of the bucket give or take).
Both solutions have different problems, and advantages. But this should give you a way to think about this.
Answer by Obsessi0n · Jan 29, 2018 at 06:57 PM
There are multiple ways to do this, one could be: Create a script that every 30 seconds checks all the balls ingame and check how many are colliding with the bucket if there are the desired number to empty then empty it. For exemple:
1- Add a tag "ball" to the ball prefab
2- Every 30 seconds (with the IEnumerator function) check all objects ingame with tag ball and if they are colliding with the bucket
3- If there are more than X empty bucket.
Not sure how to use the IEnumerator function, is there any way you can explain this or show me further?
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
while (true)
{
yield return new WaitForSecondsRealtime(30f);
#Check the bucket here
}
}
This will execute a while cycle every 30 seconds
This won't work because not all of the balls will be touching the bucket, some will be on top of each other, is there a way to check for the balls at a certain location (the buckets transform)?
Follow this Question
Related Questions
How can I change the controls of a game in a certain area? 2 Answers
Audio Zone, that covers a Square Area? 0 Answers
Getting a timer to go to 0 1 Answer
Capture Zone Timer 0 Answers