单位奇数NullExceptionReference

问题描述 投票:-1回答:2

在我的开放世界游戏中,npc应该具有所有不同的外观。有化妆品转换列表。但是,当尝试将它们添加到名为“样式”的变形列表时,会出现例外:

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;
        }
    }
}

Object's Inspector tab where Script is assigned

FIX:我没有分配变量样式。如果我播种,将不会发布,但是每天在这个项目上工作13个小时。private List<Transform> style = new List<Transform>();

c# unity3d nullreferenceexception
2个回答
0
投票

使用前需要实例化列表。

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>();


0
投票

您的style变量是私有的,这意味着它没有序列化,因此在您的null方法中将是Start()

private List<Transform> style = new List<Transform>();
© www.soinside.com 2019 - 2024. All rights reserved.