- Home /
Setting Letter Tile Objects to their Char or String Equivalent
Hi there. I have a letter tile for each letter in the alphabet. I am doing a hangman-type game and I am trying to take a work (in the example below the word is "books") and convert each letter to a gameobject tile. I convert the word to an array of characters. I tried doing the following and I am getting null returns in the Debug.Log. Any ideas? Thanks.
//we also want to know what the tile is by accessing the TileManager
public GameObject A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z;
//Object[] with all the tiles
private GameObject[] tilesAll;
//Object[] with only word tiles
private GameObject[] tilesWord;
string str = "Books";
char[] wordAsChars;
// Use this for initialization
void Start () {
//populating letter tiles into the tiles array
tilesAll = new GameObject[] {A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z};
//convert word string into an array of separate characters
wordAsChars = str.ToCharArray(0, str.Length);
//create space for the array
tilesWord = new GameObject[str.Length];
//populating only word's letter tiles into this array
for(int i=0; i<wordAsChars.Length; i++){
//each letter is converted to a string so it can be used in GameObject.Find
string letter = "" + wordAsChars[i];
//find the gameobject that is of the same letter
tilesWord[i] = GameObject.Find(letter);
}
}
Thank you in advance for any help. I am new to Unity...so I apologize if I did anything stupid. Be kind and don't tease me too much.
Thank you. Rachel
Answer by Olgo · Apr 14, 2015 at 11:24 PM
Not sure where you are putting your Debug.Log to get a null reference exception. However, I tested your variables with a Debug.Log and everything seems to work except for tilesWord[i]. The reason for this would be because these GameObjects dont exist yet.
Do you have prefabs created for each letter yet? Do you have them assigned to this script in the inspector?
You could load them each one by one with Resources.Load or you could drag and drop them in the inspector.
Answer by artistshc · Apr 15, 2015 at 06:33 AM
Thank you so much for taking the time to answer. It landed up the reason that it wasn't working was because I needed to capitalize all the letters in string str = "Books"; (to BOOKS) because all the object tiles were capitalized. Thank you for helping!
Rachel