Home > database >  why is there no scene transition using this code? (unity C# question with Scene manager)
why is there no scene transition using this code? (unity C# question with Scene manager)

Time:11-04

I figured out the issue with a previous question on here, but now it's still not working. Luckily I think I have figured out the issue. It's not detecting that an enemy has been killed/destroyed.

The way I have my code set up is that when an enemy is out of health the object is deactivated. But I assumed it would detect when an instance of the object was deactivated. But apparently not (at least from what I have seen).

I think that the best course of action is to make my enemy's "death script" connected to my win condition in some way (unless that isn't the proper way to go about it, in which case let me know what that proper action is).

I assume it would be to make the enemies variable global, but I am uncertain of how to do that or if it would even work for certain.

To reiterate, I am completely new to C# and unity, so if its solution is obvious or if the question is just stupid, remember that I have no clue where to go from this point (which is why this question is being created in the first place). If there is an existing question that can address this please link it, otherwise, anything helps.

here is the code for the win condition

public class GameWinner : MonoBehaviour
{
    public GameObject[] enemies;
    public Font font;

    void OnTriggerEnter(Collider other)
    {  
        enemies = GameObject.FindGameObjectsWithTag("Enemy"); // Checks if enemies are available with tag "Enemy". Note that you should set this to your enemies in the inspector.
        
        if (enemies == null)
        {
            SceneManager.LoadScene(2);
        }
    }
}

here is the code for enemy destruction (note, this was ripped from a tutorial, specifically "let's try shooter", let me know if it would be beneficial to rework it completely)

public class ShootableBox : MonoBehaviour
{
    //The box's current health point total
    public int currentHealth = 3;

    public void Damage(int damageAmount)
    {
        //subtract damage amount when Damage function is called
        currentHealth -= damageAmount;

        //Check if health has fallen below zero
        if (currentHealth <= 0) 
        {
            //if health has fallen below zero, deactivate it 
            gameObject.SetActive (false);
        }
    }
}

CodePudding user response:

There's a difference between an empty array, and a null reference.

In your case, you should check to see if the array is empty:

enemies = GameObject.FindGameObjectsWithTag("Enemy"); // Checks if enemies are available with tag "Enemy". Note that you should set this to your enemies in the inspector.
        
if (enemies.Length == 0)
    SceneManager.LoadScene(2);
  • Related