Reputation: 77
I want to activate/enable a TriggerCollider when the enemies in the area are killed. The enemies doesn't come in a certain order so can't add a script to a single enemy.
I created an empty game object and attached below (faulty) script. I want do if( the public game objects are destroyed) activate trigger
.
Would you know the correct for this?
public class ActivateDialogueTrigger : MonoBehaviour {
public GameObject DialogueTrigger;
public GameObject Enemy01;
public GameObject Enemy02;
public GameObject Enemy03;
public GameObject Enemy04;
public GameObject Enemy05;
public GameObject Enemy06;
void Start () {
DialogueTrigger.SetActive(false);
}
void Update () {
if(gameobjects.destroyed){
DialogueTrigger.SetActive(true);
}
}
}
Upvotes: 2
Views: 8007
Reputation: 7356
I see two options: a "fastidious", but clean one, and a quick, "dirty" and less efficient one.
You can attach to each of your objects a script responsible for dispatching an event when the object gets destroyed.
public class OnDestroyDispatcher : MonoBehaviour
{
public event System.Action<GameObject> OnObjectDestroyed ;
private void OnDestroy()
{
if( OnObjectDestroyed != null ) OnObjectDestroyed( gameObject ) ;
}
}
Then, in your script:
public class ActivateDialogueTrigger : MonoBehaviour
{
// Drag & drop the objects in the inspector
public OnDestroyDispatcher[] OnDestroyDispatchers ;
// You will be able to add a function once all the objects are destroyed
public UnityEngine.Events.UnityEvent OnAllObjectsDestroyed;
void Start ()
{
for( int i = 0 ; i < OnDestroyDispatchers.Length ; ++i )
OnDestroyDispatchers[i].OnObjectDestroyed += OnObjectDestroyed ;
}
private void OnObjectDestroyed (GameObject destroyedObject)
{
CheckAllObjectsAreDestroyed();
}
private void CheckAllObjectsAreDestroyed ()
{
for( int i = 0 ; i < OnDestroyDispatchers.Length ; ++i )
{
if( OnDestroyDispatchers[i] != null || OnDestroyDispatchers[i].gameObject != null )
return ;
}
if( OnAllObjectsDestroyed != null )
OnAllObjectsDestroyed.Invoke() ;
}
}
After an object is destroyed, an equality check with null will return true. The object is actually not really null but the "==" operator is overloaded so that you can check whether the object has been destroyed.
public class ActivateDialogueTrigger : MonoBehaviour
{
// Drag & drop the objects in the inspector
public GammeObject[] YourGameObjects ;
// You will be able to add a function once all the objects are destroyed
public UnityEngine.Events.UnityEvent OnAllObjectsDestroyed;
void Update ()
{
CheckAllObjectsAreDestroyed();
}
private void CheckAllObjectsAreDestroyed ()
{
for( int i = 0 ; i < YourGameObjects.Length ; ++i )
{
if( YourGameObjects[i] != null )
return ;
}
if( OnAllObjectsDestroyed != null )
OnAllObjectsDestroyed.Invoke() ;
}
}
Upvotes: 2