Is protected variables protected in hierarchy ?

Hi all. I wonder if is protected variables in some class on gameobject available only in classes inherited from parent class or if is available in non - inherited classes in child gameobjects.
Thanks.

-Garrom

Any class member with the access modifier protected behaves like a private member from outside the class. The only difference to private members is, that derived classes can access them.

However note that private and protected apply to the “domain” of a class and not necessarily to one specific instance.

For example:

public class Test
{
    private int privateInt;
    protected int protectedInt;
    public Test(int aValue)
    {
        privateInt = aValue;
        protectedInt = aValue;
    }
    public bool HasSameValue(Test aOther)
    {
        return aOther.privateInt == privateInt;
    }
}

public class Test2 : Test
{
    public Test2(int aValue) : base(aValue) { }
    public void Print()
    {
        Debug.Log("protectedValue: " + protectedInt);
    }
    public void SetProtected(int aValue)
    {
        protectedInt = aValue;
    }
}

As you can see inside the “HasSameValue” method of the Test class we access the private variable of another Test instance. This is only possible because this code is inside the Test class.

The derived class Test2 can’t see or access “privateInt” but it’s still there. Methods or properties of the Test class might indirectly access the private variable. However the Test2 class as well as any other class can’t access it directly.

protectedInt can be accessed by Test2 since Test2 is derived from Test and therefore it sees all protected members. Though when a Test2 or Test instance is used in a class that is not derived from Test, “protectedInt” won’t be accessible.

Test2 obj1 = new Test2(42);
Test obj2 = new Test(42);


//Debug.Log("value: " + obj1.protectedInt); // this line WOULDN'T work

if (obj1.HasSameValue(obj2))  // this does work
    Debug.Log("same!");

HasSameValue will compare the “privateInt” variables of those two instances, even though it can’t be accessed from outside. The Test2 instance doesn’t even has access to it’s own privateInt but the method defined in Test can access it.

Hi,

Protected variables are only accessable and visible in the class in which they are declared and in all classes that inherit from that class. The access modifiers to use so that variables are also visible in non-inherited classes are “internal” and “public”. Do not confuse the concepts of access modifiers in C# with the Object Hierachy in Unity. I think all of your gameObjects scripts will inherit from MonoBehavior and they do not inherit from each other? Then protected variables are not visible in other gameObject scripts.

For more about access modifiers, you may have a look here: