- Home /
Prefab: Printing single letters of a word in UI Panel (one public variable different values)
Hello.
I'm new to Unity and trying to make a basic Lingo game (a word missing 1 letter, so the user will have to select the right letter from the 2 options). So I've made a prefab for the yellow panel and its text.
Here's my problem: Suppose the word is "apple" and I want every yellow panel to hold 1 char. How can I achieve that with prefab? This is my code and what I get right now is A A A A A (first letter in "apple" which is "A" is dequeued and shown in every panel...). What should I do?
Thanks!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
using System.Collections.Generic;
public class WordStack : MonoBehaviour {
string word;
public Text letter;
void Start(){
word = "apple";
Queue<string> lettersQueue = new Queue<string>();
foreach (char element in word){
lettersQueue.Enqueue (element.ToString().ToUpper());
}
letter.text = lettersQueue.Dequeue();
}
void Update(){
}
}
Answer by ESchrauwen · Nov 14, 2016 at 12:30 PM
I can't really tell how this code relates to the rest of your project, but if this is the script that is attached to your prefab, it makes sense that it only ever gives you "A", because after Enqueueing all the letters, you only Dequeue once, which always returns the first item in your Queue.
Here's an idea; Create a script on your prefab which has a public variable called "letter". In the Start function, all you do is display that letter.
Generating the prefabs, each with its own letter, is not a job that should be done by each indivudual letter-prefab. Rather, you could make another object with a script on it that instantiates these prefabs.
Answer by sinameraji · Nov 14, 2016 at 04:40 PM
I can't really tell how this code relates to the rest of your project
Could you please elaborate a bit? Honestly I'm quite puzzled about the flow of a typical program in Unity.
I'd really appreciate it if you could help me get the bigger picture of how this should be done ideally. Thank you
If you attach a script to a prefab, that script will be running for every instance you create of this prefab. So in your case, you have 5 letter-prefabs, which means you have 5 WordStack scripts - one for each prefab.
I don't think that that is what you want. I think you want 1 object that takes care of creating prefabs (one for each letter in a given word). The prefabs themselves don't really have to do anything, other than display the letter they are assigned.
Thank you! One more question. How can the prefabInstantiator object create different prefabs? (different letter for each prefab) I can't find a way to pass variable to the prefab and make them different
The prefab would also has a script on it, and in that script you can add a public variable to hold the letter value.