Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单位奇数NullExceptionReference_C#_.net_Unity3d_Nullreferenceexception - Fatal编程技术网

C# 单位奇数NullExceptionReference

C# 单位奇数NullExceptionReference,c#,.net,unity3d,nullreferenceexception,C#,.net,Unity3d,Nullreferenceexception,在我的开放世界游戏中,NPC应该有完全不同的外观。有化妆品的清单。 但当尝试将它们添加到名为style的变换列表中时,会出现异常: NullReferenceException: Object reference not set to an instance of an object. PeopleStyle.Start () (at Assets/Scripts/PeopleStyle.cs:15) PeopleStyle.cs using System.Collections; using

在我的开放世界游戏中,NPC应该有完全不同的外观。有化妆品的清单。 但当尝试将它们添加到名为style的变换列表中时,会出现异常:

NullReferenceException: Object reference not set to an instance of an object. PeopleStyle.Start () (at Assets/Scripts/PeopleStyle.cs:15)
PeopleStyle.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PeopleStyle : MonoBehaviour {
    public List<Transform> heads;
    public List<Transform> bodys;
    public List<Transform> arms;
    public List<Transform> legs;
    public List<Transform> shoes;

    private List<Transform> style;

    private void Start() {
        style.Add(heads[Random.Range(0, heads.Count)]);
        style.Add(bodys[Random.Range(0, bodys.Count)]);
        style.Add(arms[Random.Range(0, arms.Count)]);
        style.Add(legs[Random.Range(0, legs.Count)]);
        style.Add(shoes[Random.Range(0, shoes.Count)]);
        foreach (Transform item in heads) {
            GameObject obj = Instantiate(item.gameObject, transform.position, transform.rotation) as GameObject;
            obj.transform.localScale = GameObject.FindWithTag("ScaleExample").transform.localScale;
            obj.transform.parent = this.transform;
        }
    }
}
修正: 我没有指定变量样式。如果我播种它,我不会发布这个,但我每天在这个项目上工作13小时。
私有列表样式=新列表

您需要在使用前实例化列表

您的样式变量是私有的,这意味着它没有序列化,因此在Start方法中为null


样式在开始方法的开头有什么价值?谢谢@ZdeněkJelínek,我没有注意到。这是正确的。用户@ZdeněkJelínek指出。谢谢。您不需要在Monobehavior类中实例化公共列表。团结会为你做到这一点。您只需要实例化私有的。@Topher这是一个很好的C实践,例如,如果您将域从Unity移动到web开发。
public List<Transform> heads = new List<Transform>();
public List<Transform> bodys = new List<Transform>();
public List<Transform> arms = new List<Transform>();
public List<Transform> legs = new List<Transform>();
public List<Transform> shoes = new List<Transform>();

private List<Transform> style = new List<Transform>();

private List<Transform> style = new List<Transform>();