Delete objects in CircleCollider2D (OnTriggerStay2D)
Hello there! I want want to delete all objects with a specific tag all around one object with this script, but it just deletes one of them all 10 seconds, how can i do it that it deletes all in the CircleCollider2D (☑ IsTiggered) ?
public class _Destroy_Script_ : MonoBehaviour
{
public float Destroy_Timer = 10f;
void Start()
{
Destroy_Timer = 10f;
}
void OnTriggerStay2D(Collider2D other)
{
Destroy_Timer -= Time.deltaTime;
if (Destroy_Timer <= 0)
{
if (other.gameObject.CompareTag("Destroy_Tag"))
{
Destroy(other.gameObject);
}
Destroy_Timer = 10f;
}
}
}
Ty for reading and coming answers, excuse my bad english.
Answer by See_Sharp · Mar 16, 2016 at 12:21 PM
You'll need a specific timer for each new object entered.
You could create a dictionary (import System.Collections.Generic) and map a time with a gameobject. Something like this:
Dictionary<GameObject, float> mappedTimers = new Dictionary<GameObject, float>();
public float Destroy_Timer = 10f;
void OnTriggerStay2D(Collider2D other) {
//add to dictionary if it has the destroy tag and if it's no in there
if (other.gameObject.CompareTag("Destroy_Tag") && !mappedTimers.ContainsKey(other.gameObject)) {
//add with a timer value of 10
mappedTimers.Add(other.gameObject, Destroy_Timer);
}
//now if we have this gameobect, substract time
if(mappedTimers.ContainsKey(other.gameObject)) {
mappedTimers[other.gameObject] -= Time.deltaTime;
//check after substracting
if (mappedTimers[other.gameObject] <= 0) {
//remove from dictionary, because euhm, we're about to destroy it i guess ;)
mappedTimers.Remove(other.gameObject);
Destroy(other.gameObject);
}
}
}
Didn't compile the code tho. But my instinct tells me this seems ok :)
It worked fine! Im pretty new to c# and unity, have just worked with .net and delphi, have never worked with dictionairies before, great to know! :D i also added a dic. with alpha-value so the objekts become more and more transpary. ty :-)
Awesome :D Yes, Generics are super sweet! Can't live without them ;)
Hey there! I need this script u gave me now for all objects with a specific tag but not in range of an collider, how can i ask for all objects with one tag? if (gameObject.CompareTag("Spawn_Gold_Tag") ?
Your answer
Follow this Question
Related Questions
CompareTag vs gameObject for best perfmormance? 0 Answers
How to write an overlap sphere 2D 0 Answers
How to remove/freeze timer on Destroy() 2 Answers
How to suspend an action? 1 Answer