-1
\$\begingroup\$

I have a code that I want to use to change levels everytime the player kills a certain amount of enemies, but it gives me this error:

An object reference is required to access non-static member `enemyCount.nextLevelName'

Here's my script (this is attached to an empty game object)

public class enemyCount : MonoBehaviour {

public static int enemiesCount;
public int targetCount; 
public string nextLevelName; 
void Start()
{
    enemiesCount = targetCount;
}
public static void DecreaseCount()
{
    enemiesCount--;
    print("Enemy Count is " + enemiesCount); 
    if(enemiesCount <= 0)
    {
        Debug.Log("Load level: " + nextLevelName);
        Application.LoadLevel (nextLevelName);
    }
}

}

and this is inside the bullet script

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

1 Answer 1

4
\$\begingroup\$

Your nextLevelName member variable is not static, meaning there could be a different name set on each instance of the enemiesCount class, of which you could have dozens or thousands if you wanted.

The DecreaseCount method, on the other hand, is static, meaning it's shared across the whole enemiesCount type and not attached to any one instance.

That means when you tell it to use a non-static member variable, it doesn't know which instance it should read it from. You need to give it an instance to work from. Even if you only have one instance in your scene, this method doesn't know that unless you store that instance somewhere it can find it (for example using a Singleton pattern). Some additional patterns for referencing one object from another are described in this answer.

Another way to approach this "trigger something when all entities of this type are gone" (be they coins or enemies or something else) is described in this answer.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .