A question that I found interesting over on the Discord Unity channel. thought I would share a solution I came up with.
Engine : Unity
Question : how can I destroy a Door in my scene when certain key gameobjects have been destoyed
Hope this might be useful to someone, probably take a bit of tweaking but its rough and ready.
rather than iterating through each key to see if it has been destroyed or not, why not let the key do the heavy lifting of informing the door when it has been destroyed.
An event based approach would probably have been better, but to save anything too complicated ive done the following as a autonomous workaround.
Firstly create a new script, not attached to anything and call it “ImADoorKey.cs”
and paste in the following code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ImADoorKey : MonoBehaviour {
public DoorUnlock doorThisIsFor;
void OnDestroy()
{
doorThisIsFor.KeyUsed(this.gameObject);
}
}
this script will be called when that specific object it is attached to is destroyed and let the door know that a key has been destroyed.
for the door gameobject. create a new script called “DoorUnlock.cs”
and paste in the following code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorUnlock : MonoBehaviour {
// could drag your key gameobjects into the inspector to set them
public List KeysToDoorRemaining = new List();
void Start()
{
// so for each gameobject that you specify as a key, we add a script component to it
// and that component will say, once then object is destroyed
// call the KeyUsed method and remove that item from the list
foreach(GameObject go in KeysToDoorRemaining)
{
go.AddComponent();
go.GetComponent().doorThisIsFor = this;
}
}
// when a key is destroyed, call a method on the door passing in the gameobject that was destroyed
public void KeyUsed(GameObject keyGameObject)
{
KeysToDoorRemaining.Remove(keyGameObject);
if(KeysToDoorRemaining.Count <=0) Destroy(gameObject);}
}
now attach this DoorUnlock Script to the Door GameObject in your scene.
so if you look at the Door, and this script in the inspector, you will see a public exposed list of keys

now drag gameobjects from your heirarchy that need to be destroyed for this Door to be destroyed.
save and test.
what this ultimately does, is for each of the Key gameobjects you add to the list. it will add the “ImADoorKey” component. and set its public exposed reference to what door it applies to.
this will have the effect of when the key is destroyed, it will let the door it is tied to know that it has been destroyed, and remove it from that doors list of key objects, and once all the keys have been destroyed, destroy itself.
heres a quick example, green objects are keys the blue is the door. all green objects were dragged into the list attached to the door.

