Hi
I am trying to learn editor scripting, and I am experiencing stuff that I find weird, which probably because I don’t understand how Unity works.
I am trying to create a grid of GameObjects. I would like to store references to the created GameObjects in a Dictionary (or a two dimensional array), but it seems like I lose the references when going from editor mode to game mode/running the game.
I have tried to make a small code example to show my problem:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GridHandler : MonoBehaviour {
public GameObject gameObject;
public List<GameObject> list = new List<GameObject>();
public Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>();
void Start(){
//Using Start() to test in "game mode"
//I would like to use the references to the gameObjects that I generated in createGrid.
Debug.Log("Start");
Debug.Log(gameObject.transform.name);
Debug.Log(list[0].transform.name);
Debug.Log(dictionary["a"].transform.name); //This call gives error "KeyNotFoundException"
}
//This function is called from an editor script in "editor mode"
public void createGrid(){
//Clearing just for testing
list.Clear();
dictionary.Clear();
gameObject = new GameObject();
gameObject.transform.name = "1 - gameObject";
list.Add(new GameObject());
list[0].transform.name = "2 - list";
dictionary.Add("a", new GameObject());
dictionary["a"].transform.name = "3 - dictionary";
Debug.Log(gameObject.transform.name);
Debug.Log(list[0].transform.name);
Debug.Log(dictionary["a"].transform.name);
}
}
In the Console i get:
(createGrid called)
1 - gameObject
2 - list
3 - dictionary
(running program)
1 - gameObject
2 - list
Error (KeyNotFound)
I could store the grid in a list and let each gameObject know its position, it just doesn’t seem optimal, and I would like to understand why I can’t use a Dictionary.
It seems like I have the same problem when using dynamically generated two-dimensional arrays.
Please ask if I havn’t explained my problem precisely.
Best wishes
Hans Larsen