简体   繁体   中英

How to add a new object to a list without a variable?

I am trying to add a new instance of my asd class to a list by constructing a new asd and then adding that, but Unity gives an Object not set to instance of object error.

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

public class asd {
    public int a = 0;
    public string s = "asd";

    public asd (int apop, string ssdf) {
        a = apop;
        s = ssdf;
    }
}

public class test : MonoBehaviour {

    public List<asd> list;

    // Use this for initialization
    void Start () {
        list.Add (new asd(1, "yeee"));
        list.Add (new asd(456, "oooo"));
    }

    // Update is called once per frame
    void Update () {

    }
}

Instantiate your list correctly as below then add asd to it

public List<asd> list = new List<asd>();

// Use this for initialization
void Start () {
      list.Add(new asd(1, "yeee"));
      list.Add(new asd(456, "oooo"));
    }
public List<asd> list;

This says what list is, it doesn't instantiate it:

public List<asd> list = new List<asd>();

Note that class-names should start with a capital letter (PascalCase).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM