Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c# - What the function of "public" in unity other than as a access modifier and serialize field?

I refer to this video tutorial and tried out the code https://www.youtube.com/watch?v=rQyUACEyAVw&t=70s . Noticed for this code public List<GameObject> Onbelt; if I do not put the word "public" in front, unity warned field is never assigned to,and will always have its default value null. It crash return a nullreference exception error when I run it. So the public in public List<GameObject> Onbelt; initialize and create new instance of List in unity? As it does not throw any error even without List<GameObject> Onbelt;=new List<GameObject>()?If putting the word public infront.

question from:https://stackoverflow.com/questions/65858327/what-the-function-of-public-in-unity-other-than-as-a-access-modifier-and-seria

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, access modifiers nothing have to do with variable initialization in this case.

The fact that only when public it shows the warning is caused by the fact that if you have a public field (or a SerializedOne) you can assign it by the Editor, but if it's private, you can't, so the Engine is warning you about the default value.

If you make your list private, but you initialize the variable like:

private List<GameObject> Onbelt = null;

or

private List<GameObject> Onbelt = new List<GameObject>();

The warning will disappear, cause you are forcing the default value.

EDIT:

To be clear, in c# access modifiers nothing have to do with variable initialization, but in UNITY EDITOR the fact that having a public variable, let's the user fill this list, so by default, is created with new List() instead of default null.

So this won't work (NullReferenceException):

private List<int> list;

void Start()
{
    list.Add(2);
}

But this WILL work:

public List<int> list;

void Start()
{
    list.Add(2);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...