- Home /
Add to generic list on start problem
I'm doing tests with generic list so dont care about "Pokemon scripts" and don't bother me about copyright and etc, that just for testing purposes..
So, i want that when a pokemon spawns it add to list his name, id and game object, pokemon script:
void Start () {
GameController.instance.AddPokemonToList(GameController.instance.pokemons.Count + 1, this.gameObject.name, this.gameObject);
}
and then, on the GameController script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Pokemon {
public int id;
public string name;
public GameObject go;
}
public class GameController : MonoBehaviour {
public List<Pokemon> pokemons;
public static GameController instance;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void AddPokemonToList(int _id, string _name, GameObject _go) {
Pokemon _pokemon = new Pokemon {
id = _id,
name = _name,
go = _go
};
instance.pokemons.Add (_pokemon);
}
}
The console gives me an error on the pokemon script, null reference exeption. What's the problem ?
i see that you are trying to do singlton patern, but when do you actually load the variables with the objects ? i also dont see new List() anywhere
Answer by wibble82 · Apr 30, 2014 at 09:58 PM
You aren't creating the list, so it is null.
You'll need pokemons = new List();
Either put it in the start function, or just after the member variable declaration.
FYI that new List line will need point brackets with Pokemon in the middle, but my iPad won't let me enter that text for some reason!
Well that's definitely the problem I'm afraid. Did you out it after the member variable declaration like I said?
Oh I just noticed - the static game controller isn't being set either! You're trying to do a singleton pattern which is a bit more complex in unity. Check out this tutorial: http://clearcutgames.net/home/?p=437
Your answer
Follow this Question
Related Questions
Javascript Array to Generic List 1 Answer
Iterate through Variables in a Script and adding them to a Generic List 1 Answer
Null reference exception in Lists 1 Answer
A node in a childnode? 1 Answer
Remove and Add to List By Name aad 1 Answer