- Home /
How to all GameObjects in array or 2 objects collide with 1 object at the same time
I don't know how to put this and it's the middle of the night here and i'm tired lol
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeverMove : MonoBehaviour
{
public Animator LeverAnim;
public DoorScript door;
public GameObject[] Players;
void Update()
{
Players = GameObject.FindGameObjectsWithTag("Player");
}
private void OnTriggerStay2D(Collider2D collision)
{
if (Players[0 & 1] && Input.GetKey(KeyCode.Q))
{
LeverAnim.SetTrigger("LeverMoves");
door.DoorOpen();
}
else
{
return;
}
}
}
so this is my code and what I wanna achieve is I want the players to all be (or only 2 of them) be at a single trigger at the same time and whilst that's happening the player should be able to press a key for the command to execute, anyone know how I can achieve this, Thanks!
Answer by Llama_w_2Ls · Jul 18, 2021 at 08:06 AM
You should use OnTriggerEnter and OnTriggerExit, to keep game objects in a list, then compare the lists for similar items. For example:
public GameObject[] Players;
public List<GameObject> PlayersInTrigger;
void OnTriggerEnter2D(Collider2D collision)
{
PlayersInTrigger.Add(collision.gameObject);
}
void OnTriggerExit2D(Collider2D collision)
{
PlayersInTrigger.Remove(collision.gameObject);
}
void Update()
{
foreach (var player in Players)
{
if (!PlayersInTrigger.Contains(player))
return;
}
// If code reaches this spot, all the players are in the trigger
}
If your trigger is more simple, like a sphere or box collider, use Physics2D.OverlapCircleAll
, (which returns all colliders within a circle trigger of said radius), and check if each player is in that array of colliders. If so, they are in the trigger. Hope that helps @yousifalsewaidi