some thing strange when i use static variable

i use a static variable when i want to increase it in the same class (script)as level++;
it doesn’t work i must write nameOfScript.level++;

public static int level=1;
so why this happen ?! thanks

Static variables are “owned” by the class, not an instance of a class. So, therefore, you shouldn’t be able to call level++ on an instance of a class but only on the class itself.

When you call new Spooky(); you’re making a new instance of that with totally separate variables from all other times you call new Spooky();. A static variable will NOT be on any new Spooky(); objects but only on the Spooky class itself.

If you want to access a static variable from your code, you have to explicitly say Spooky.myStatic. If you’re accessing it from within the Spooky class though, you don’t need to explicitly do this (as in the below example).

You could always do something like this though if you don’t like directly accessing the static variable from other parts of your code.

public class Spooky()
    public static myStatic=0;

    public IncrementMyStatic()
        //Don't explicitly need Spooky.myStatic because
        //we're accessing it from inside the class

Consider also setting your static to private so that only your class can modify it and do all your programmatic stuff in methods of that class. It’s good coding practices to encapsulte functionality of your classes.