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)
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 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.
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.