-1

In my open world game, npcs should have all different look. There are lists with cosmetics Transforms. But when trying to add them to the List of Transforms named "style", there is exception:

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: I did not assign variable style. Would not post this if I sow it, but am working 13 hrs a day on this project. private List<Transform> style = new List<Transform>();

nobody.price
  • 221
  • 1
  • 14
Nikola
  • 43
  • 8

2 Answers2

0

You need to instantiate your lists before use.

I.e.

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

Joel Wiklund
  • 1,697
  • 2
  • 18
  • 24
  • That is correct. User @ZdeněkJelínek pointed that out. Thank you. – Nikola Jan 04 '20 at 16:37
  • 1
    You don’t need to instantiate the public Lists in a Monobehavior class. Unity will do that for you. You only need to instantiate the private one. – Topher Jan 04 '20 at 16:50
  • @Topher It's good C# practice though, if you move domain from Unity to web development for example. – Joel Wiklund Jan 05 '20 at 10:44
0

Your style variable is private, which means it isn't serialized so it will be null in your Start() method.

private List<Transform> style = new List<Transform>();
Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32