Hide gameobject until certain condition has been met,Hide an object until a condition is met.

Hello, I am trying to hide an object “door” until all the enemies have been destroyed. From other questions I saw on here I opted for using renderer, but I keep getting an error message.

thank you ahead of time


MissingComponentException: There is no ‘Renderer’ attached to the “Door_Prefab” game object, but a script is trying to access it.
You probably need to add a Renderer to the game object “Door_Prefab”. Or your script needs to check if the component is attached before using it.
Door.Update () (at Assets/Scripts/Door.cs:31)


void Update()
{
    if(GameObject.FindWithTag("Enemy"))
    {
        gameObject.GetComponent<Renderer>().enabled = false;
    }
      else
    {
        gameObject.GetComponent<Renderer>().enabled = true;
    }
}

I think you should create a GameManager, always enabled, responsible for detecting when your enemies are destroyed. Then, your Door script will be warned by the GameManager once all the enemies are destroyed.

// Enemy.cs
using UnityEngine;

public class Enemy : MonoBehaviour, IPointerClickHandler
{
    public event System.Action<Enemy> OnKilled;

    void OnDisable()
    {
        if ( OnKilled != null )
            OnKilled.Invoke( this );
    }
}

// GameManager.cs
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private int remainingEnemies = 0 ;
    public event System.Action OnLastEnemyKilled;

    private void Start()
    {
        Enemy[] enemies = FindObjectsOfType<Enemy>();
        for ( int i = 0 ; i < enemies.Length ; i++ )
        {
            AddEnemy( enemies *) ;*

}
}

private void AddEnemy( Enemy enemy )
{
remainingEnemies++ ;
enemy.OnKilled += RemoveEnemy ;
}

private void RemoveEnemy( Enemy enemy )
{
enemy.OnKilled -= RemoveEnemy ;
remainingEnemies-- ;
if( remainingEnemies == 0 && OnLastEnemyKilled != null )
OnLastEnemyKilled.Invoke() ;
}
}
// Door.cs
using UnityEngine;

public class Door: MonoBehaviour
{
// Drag & drop the object in the inspector
public GameManager GameManager ;

private void Awake()
{
GameManager.OnLastEnemyKilled += Show ;
Hide();
}

private void Show()
{
GameManager.OnLastEnemyKilled -= Show ;
gameObject.SetActive( true ) ;
}

private void Hide()
{
gameObject.SetActive( false ) ;
}
}
----
###ORIGINAL ANSWER
Simply disable the gameobject instead of disabling the Renderer component:
gameObject.SetActive( GameObject.FindWithTag(“Enemy”) == null ) ;
However, keep in mind that calling the FindXXX functions are not very efficient. If you have only few calls in your scene, it’s fine.

If you don’t want to disable the gameObject as @Hellium suggests, you need to enable & disable the MeshRenderer component.

gameObject.GetComponent<MeshRenderer>().enabled = true;

By the way: the GetComponent function is called every frame in the Update function. It’s terrible for performance. You should store the MeshRenderer in a variable.