- Home /
Do something only "for" Gameobjects in trigger
Hey, I want to do something few times (in for) but only for gameobjects in trigger. (I'm using tag to determine gameobjects but I can't use OnTriggerEnter etc.) If something in this for will make gameobject leave the trigger i don't want it to participate in the next for. What should I use? ///// P.S. I don't need to use trigger if there's something better but idea is to randomly pick gameobject from the gameobject[] and teleport it somewhere in 1st "for" and don't use it in next "for" so it'll not be picked again.
Answer by AaronBacon · Feb 26, 2019 at 10:06 PM
So If I'm understanding this right you want to keep track of every GameObject that is touching a trigger, then pick a random item from this list of items, and then delete it from the list.
Your question isn't exactly worded clearly but assuming that's it, this is what I would do:
I'm not sure why you can't use OnTriggerEnter, it's the simplest way to tell if one thing is in the collision of another, so I would make something like this:
using System.Collections.Generic;
using UnityEngine;
public class ObjList : MonoBehaviour
{
public static List<GameObject> objects; // stores the objects currently in contact with the trigger
private void OnTriggerEnter(Collider2D collision)
{
if (collision.gameObject.CompareTag("Object")) // If the object is tagged as an object
{
objects.Add(collision.gameObject); // Add the Object to the List
}
}
private void OnTriggerExit(Collider2D collision)
{
if (collision.gameObject.CompareTag("Object")) // If the object is tagged as an object
{
objects.Remove(collision.gameObject); // Remove the Object from the List
}
}
}
That should track objects tagged "Object" currently touching the object and keep them in a list called objects. Then to select a random object from that list and remove it, write a function like this:
private GameObject PickRandom()
{
System.Random rnd = new System.Random();
int index = rnd.Next(0, (objects.Count)-1);
return objects[index];
}
And now you can use PickRandom() to pick a random GameObject from the ones currently touching the GameObject this script is on. From there you can teleport that Object or co whatever you need to iy
Your answer
Follow this Question
Related Questions
Do a collider only with certain taged objects 2 Answers
Use trigger with player but have a collider with everything else? 3 Answers
Is it possible to destroy a gameobject from a child gameobject's script? 1 Answer
Help with collide triggers and calls, please. 1 Answer
Collision by tag issues 1 Answer