I know this is probably a common question. Can someone explain to me the difference between public and private? Then what does having none of those before a variable? Other answers say its one or the other but i can write variables without them. I know that with public variables I can see them in inspector.
int i = 1;
private int a = 2;
public int o = 3; //whats the difference?
If none is specified, then by default it’s private. Basically, public variables can be access by other classes and code. private variables can only be accessed within the class they are declared in. Public variables are also accessible from the Inspector.
You should really watch the Unity tutorials or something, google for C# basics, etc.
You can’t use ‘private’ or ‘public’ outside of a class.
Declaring a variable as private will make it visible only within the scope of the class. So within methods and constructors inside the { and } of the class definition.
Declaring a variable as public will make it visible outside the class as well.
The same applies for methods defined within a class.
public class A {
private int number1;
public int number2;
}
A method outside of this class will only have access to variable ‘number2’.
void someMethod() {
A objectA = new A();
A.number2 = 5; //This will work
A.number1 = 0; //But this will not work
}
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private - Only the current class will have access to the field or method.
protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public - Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
Hey, but I have seen while writing c# scripts that if I add private in front of a void it shows error and if I remove it,it works completely fine. So any explanation for that?