I instantiate some objects, DisplayWord, which are essentially a button saved as a prefab. I’m able to access the button and it’s text and modify it. What I want to do is allow the player to make a new word based on the orignal word in the text. So I want to update the text in the button. I am able to set the text of the button after I instantiate it. However, when I reaccess my array of DisplayWords I use essentially the same code as when I instantiated it to update the button text. However, when I try to get their script components they are null. I’ve written a little test to show this. I hope someone can tell me what I am doing wrong.
public void Start() {
//SwitchDisplays(false);
letterRack.InitializeTiles();
CreateDisplayWord("MAN");
CreateDisplayWord("CAT");
UpdateDisplayWord("CAT", "CART");
print("DisplayWord.Start \n");
}
// private DisplayWord newDisplayWord;
public void CreateDisplayWord(string newWord) {
var newDisplayWord = Instantiate(displayWordPrefab, new Vector3(0, 0, 0), Quaternion.identity);
newDisplayWord.transform.SetParent(transform, false);
var displayButton = newDisplayWord.GetComponentInChildren<DisplayButton>();
displayButton.SetWord(newWord);
//newDisplayWord.GetComponentInChildren<Button>().onClick.AddListener(() => OnButtonClick(newWord));
print("DisplayBoard. CreateDisplayWord " + newWord + "\n");
}
public void UpdateDisplayWord(string originalWord, string newWord) {
displayWords = GetComponentsInChildren<DisplayWord>();
for (var i = 0; i < displayWords.Length; i++) {
var originalDisplayWord = displayWords[i];
// These return null ??
var displayButton = originalDisplayWord.GetComponentInChildren<DisplayButton>();
var displayButton2 = originalDisplayWord.gameObject.GetComponentInChildren<DisplayButton>();
if (originalWord.Equals(displayButton.GetWord())) {
displayButton.SetWord(newWord);
originalDisplayWord.GetComponentInChildren<Button>().onClick.AddListener(() => OnButtonClick(newWord));
print("DisplayBoard. UpdateDisplayWord " + newWord + "\n");
break;
}
print("DisplayBoard. UpdateDisplayWord " + newWord + "\n");
}
}