There are a few ways you could handle this. You could either watch for the keys as you’ve been doing, then keep count of the quantity/type of keys as necessary, or you could watch for a player instead (as applicable) and deliver/wait for them to possess the total required number of keys.
// Keeping count
int basicKeyCount = 0;
int fancyKeyCount = 0;
public int requiredBasicKeyCount = 1;
public int requiredFancyKeyCount = 1;
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.CompareTag("Basic Key"))
{
basicKeyCount++;
}
else if(other.gameObject.CompareTag("Fancy Key"))
{
fancyKeyCount++;
}
if(basicKeyCount >= requiredBasicKeyCount && fancyKeyCount >= requiredFancyKeyCount)
{
GameControl.instance.youWin();
}
}
// If taking a key away is also supported
void OnTriggerExit2D(Collider2D other)
{
if(other.gameObject.CompareTag("Basic Key"))
{
basicKeyCount--;
}
else if(other.gameObject.CompareTag("Fancy Key"))
{
fancyKeyCount--;
}
}
// Player-focused, no need to keep count of nearby "keys"
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.CompareTag("Player"))
{
PlayerScript player = other.GetComponent<PlayerScript>();
if(player.basicKeyCount >= requiredBasicKeyCount && player.fancyKeyCount >= requiredFancyKeyCount)
{
GameControl.instance.youWin();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExampleOne : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.name == "Key1" && other.gameObject.name == "Key2")
{
Debug.Log("Opening Doors...");
}
}
}
Or, if you want to use triggers, here is that code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExampleTwo : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.name == "Key1" && other.gameObject.name == "Key2")
{
Debug.Log("Opening Doors...");
}
}
}
Hope this helps! And don’t forget to put this scripts onto the door, add to the door collider that is trigger and to the key normal box collider and rigidbody (I don’t think you need rigidbody, but still put it just in case). Remember, this is for 2D only, if you want 3D you need to remove 2D from OnTriggerEnter2D and OnCollisionEnter2D, as well as Collision2D and Collider2D