- Home /
Can't add GameObjects to a List
I am writing a dungeon generator. Its in very early stages. I got it to detect 1 exit node and spawn a hall tile and a room tile beyond that. An exit node is an empty GameObject. Now I want to make a list to store more then one exit node. I can then later iterate through all the nodes and spawn halls and rooms. I am stuck at this error:
NullReferenceException: Object reference not set to an instance of an object Dungeon.AddNodes (UnityEngine.Transform nodes) (at Assets/Dungeon.cs:47) Dungeon.FindNodes () (at Assets/Dungeon.cs:41) Dungeon.Start () (at Assets/Dungeon.cs:19)
Here is the code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Dungeon : MonoBehaviour {
public GameObject start; //holds the start tile
public GameObject player; //holds the player pawn
public GameObject halls; //holds the hall tiles, will be changed to an array later.
public GameObject rooms; //holds the room tiles, will be changed to an array later.
private List<Transform> exitNodes; //holds the current nodes, will be updated after each iteration of room generation.
// Use this for initialization
void Start () {
CreateStart();
FindNodes();
SpawnDungeon();
}
// Update is called once per frame
void Update () {
}
private void CreateStart()
{
//creates the starting tile and player pawn.
GameObject go = Instantiate(start, Vector3.zero, Quaternion.identity) as GameObject;
GameObject pc = Instantiate(player, Vector3.up, Quaternion.identity) as GameObject;
}
private void FindNodes()
{
//Finds all nodes tagged for the north side of the tile, indicating a positive x translation.
GameObject[] node = GameObject.FindGameObjectsWithTag("N_exit");
foreach(GameObject temp in node)
{
// adds the nodes to exitNode list, not working...
exitNodes.Add(temp.transform);
}
}
private void SpawnDungeon()
{
// Vector3.zero will become the location of the current node.
GameObject spawn = Instantiate(halls, Vector3.zero, Quaternion.identity) as GameObject;
//translate to the proper offset.
spawn.transform.Translate(2.5f,0,0);
//Vector3.zero will become the location of the current node.
spawn = Instantiate(rooms, Vector3.zero, Quaternion.identity) as GameObject;
//translate to the proper offset.
spawn.transform.Translate(10,0,0);
}
}
Answer by appearance · Feb 27, 2013 at 06:22 AM
You have only declared the list but not instantiated it.
You can instantiate the List in Start () method:
void Start () {
exitNodes = new List<Transform> ();
CreateStart();
FindNodes();
SpawnDungeon();
}
Answer by Mithrilshadow · Feb 28, 2013 at 03:01 AM
Doh! I knew it was going to be a n00b mistake! Thanks a bunch.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
NullReferenceException in follow function 0 Answers
Adding a prefab to gameObject at a certain position in runtime 0 Answers
How to use if statement properly 1 Answer
Find specific prefab in a list 2 Answers