- Home /
Trying to track the BoxColliders of 2 Different Sets of Instantiated GameObjects
Basically I have dynamically spawning (instantiated) "enemies" that will each have their own BoxCollider2D's. I also have instantiated projectiles coming from my player with their own unique BoxCollider2D's as well. I have been trying to think of a way to dynamically track these colliders, since they have no unique properties to track individually. Is it possible to group them? For example: "if a collider from the group of projectile boxcolliders touches a collider from the group of enemy colliders ..etc". I am still learning the in's and out's of Unity Engine, so I may just be overlooking a tool they already provided. Can someone please give me insight on how to accomplish this, or at least where to start? Thanks! (Also if this code has a horrible flaw, please point it out so I can fix my mistake)
Here is my code for the projectile (animations are handled in another script):
public class Projectile : MonoBehaviour {
public GameObject projectilePrefab;
public float speed = 0f;
private Rigidbody2D playerRigid;
private Rigidbody2D cloneRigid;
private GameObject clone;
private MovementScript playerMove;
private Animator animate;
private Vector2 projectileSpeed;
private bool shot = false;
void Start () {
playerRigid = GetComponent<Rigidbody2D>();
playerMove = GetComponent<MovementScript>();
animate = GetComponent<Animator>();
}
void Update () {
//If Player is facing right, adjust projectile direction on x axis.
if (playerMove.faceDirection) {
projectileSpeed = new Vector2(1 * speed, 0);
}
//If Player is facing left, reverse projectile direction on x axis.
else if (!playerMove.faceDirection){
projectileSpeed = new Vector2(-1 * speed, 0);
}
//isThrowing is handled in another script. It basically handles the cooldown time between throws.
if (playerMove.isThrowing) {
if (!shot) {
shoot();
shot = true;
}
}
else if (!playerMove.isThrowing) {
shot = false;
}
}
//Instantiates the object using the projectile prefab, then rotates/scales it accordingly and projects it outwards.
void shoot() {
//Instantiates the projectile, and gets components of the clone to work with.
clone = (GameObject)Instantiate(projectilePrefab, playerRigid.position, Quaternion.identity);
cloneRigid = clone.GetComponent<Rigidbody2D>();
Transform cloneTrans = clone.GetComponent<Transform>();
//Rotates the sprite so it visually flies in the correct direction
if (playerMove.faceDirection) {
cloneTrans.Rotate(0, 0, 270);
}
else {
cloneTrans.Rotate(0, 0, 90);
}
//Scales the sprite to a feasable size
cloneTrans.localScale = new Vector3(15, 13, 1);
//Applies velocity and destroy clone after 3.5 seconds
cloneRigid.velocity = projectileSpeed;
Destroy(clone, 3.5f);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612061201im_/https://answers.unity.com/themes/thub/images/avi.jpg)