Use same script in different scenes to change level

Hello! My game has three levels, and i have a code that changes from level 1 to level 2 after killing 5 enemies. In the second level, the level should change to the third one after killing 10 enemies. I want to use the same script, but the public variables are not showing in the inspector so i can’t change it. Thanks in advance for the help.

This code is attached to an empty game object:

public class enemyCount : MonoBehaviour {

	public static int enemiesCount = 5;

	void  Update (){
		print("Enemy Count is " + enemiesCount); 

		if(enemiesCount <= 0)
		{
			Debug.Log("Level 2!!!");
			Application.LoadLevel ("level2");
		}
	}

}

And this is attached to the bullet script:

private void OnCollisionEnter (Collision collision){

		if (collision.transform.tag == "Enemy") {

			Destroy (collision.gameObject);
			gameObject.SetActive (false);
			Destroy (this.gameObject);

		}

		if (collision.gameObject.tag == "Enemy") {
			enemyCount.enemiesCount --; 
		}
	}

1 Answer

1

You can’t use static variables if they should be editable in the inspector. The Inspector can only show variables that belong to this instance of the class. Static variables do not belong to a certain instance. They only exist once in the whole application.

You may want to simply use a “targetKillCount” variable which you use to initialize your static variable in Start.

I also would recommend to not use Update for this. It’s way better to use a method which is called when you actually decrease the enemy count. You can check if you reached the target there.

public class EnemyCount : MonoBehaviour
{
    public static int enemiesCount;
    private static string nextLevel;
    public int targetCount; // set this in the inspector
    public string nextLevelName; // set the name of the next level in the inspector
    void Start()
    {
        enemiesCount = targetCount;
        nextLevel = nextLevelName;
    }
    public static void DecreaseCount()
    {
        enemiesCount--;
        print("Enemy Count is " + enemiesCount); 
        if(enemiesCount <= 0)
        {
            Debug.Log("Load level: " + nextLevel);
            Application.LoadLevel (nextLevel);
        }
    }
}

In your other script you would use this instead:

if (collision.gameObject.tag == "Enemy") {
    enemyCount.DecreaseCount(); 
}

Thank you, now i understand what my mistake was but i don't know why i get this error (sorry i'm new to Unity): An object reference is required to access non-static member `enemyCount.nextLevelName'

–