static and public variables

I use statics variables because i can acces to it without getcomponent, like this :

AScript.aStaticvariable = whateverILike;

And can change them. Can we do the same with public variables or do they require GetComponent to be accessed?

By the way i only use static on variables that have only one instance.

Public variables require a reference to the instance, but that doesn’t necessarily mean it needs to use GetComponent.

Otherwise no, you cannot access them in the same way you access a static variable.

static and public have to do with different things.

You can be BOTH static AND public at the same time.

public is one of 4 access modifier for a member (field, prop, method) or a type:

public - access to is unrestricted. In the case of a member, I am permitted to access this member from anywhere else that has a reference to the object I’m a member of.

private - access is restricted. In the case of a member, only place that the member can be accessed is from within the scope of the type that the member is a member of.

protected - access is limited to the scope of the type, or a type that inherits from this type.

internal - access is limited to the scope of the assembly this member/type is part of.

(note - when you don’t type an access modifier, it defaults to private)

Static on the other hand is more about where the member exists. Is it a member of an object created from a type, or is it a member of the type itself. When static it’s a member of the type itself. If it’s public static, that means it can be accessed from ANYWHERE. Thing about statics is that because they’re a member of a class, and not the member of an object, that they persist in memory always. And that there is one of this member, no matter how many objects you have.

For instance, you have a class called ‘MonsterChaseAI’, this is a script you attach to all monsters. And you have a field member of it that is type ‘float’ and is called ‘Speed’. This is to represent the speed of the monster. If it’s static, then ALL monsters with this script will have the same exact speed. If you change the speed on one monster, then all monsters will get that new speed, because static members persist for ALL instances of ‘MonsterChaseAI’.

In C# this is correct, however in Unity JavaScript it defaults to public.