Hello guys i'm trying to write a game scenario which includes multiple levels.In the scenario the user will try to memorize the words on the screen then try to choose right ones by clicking buttons. I created multiple buttons as a GameObject (for specific reasons)
so here's how it goes
public GameObject[] buttons = new GameObject[7];
These are my buttons.I created them in my canvas as buttons but in script i treat them like a GameObject.
void wordsToButton()
{
for(int i = 0; i < wordsTxt.Length; i++)
{
buttons[i].GetComponentInChildren<Text>().text = wordsTxt[i].GetComponent<Text>().text;
buttons[i].transform.position = new Vector2(Random.Range(30, Screen.width - 20), Random.Range(30, Screen.height - 50));
}
for(int i=0; i <differentWords.Length; i++)
{
buttons[i+5].GetComponentInChildren<Text>().text = differentWords[i].GetComponent<Text>().text;
buttons[i+5].transform.position = new Vector2(Random.Range(30, Screen.width - 20), Random.Range(30, Screen.height - 50));
}
}
In here i am trying to edit button's text and give it a random position.Additionaly i also put some wrong words.It works fine.
public void buttonListeners()
{
for(int i=0; i < buttons.Length-1; i++)
{
buttons[i].GetComponent<Button>().onClick.AddListener(() =>
{
int n = i;
if(buttons[n].GetComponent<Text>().text == differentWords[0].GetComponent<Text>().text || buttons[n].GetComponent<Text>().text == differentWords[1].GetComponent<Text>().text)
{
correctAnswers--;
}
else
{
correctAnswers++;
}
});
}
}
In here i gave listeners to buttons.When user click on buttons it checks for correct answer.
public void level2()
{
if (levels[2].activeSelf == true)
{
differentWords[0].SetActive(false);
differentWords[1].SetActive(false);
levels[0].SetActive(false);
levels[1].SetActive(false);
levels[3].SetActive(false);
timer1 = 10;
InvokeRepeating("countDown1", 0.01f , 1);
}
wordsToButton();
buttonListeners();
}
This is the level which i talked about.So when i click a button on the screen it gives me this error:
NullReferenceException: Object reference not set to an instance of an object Word+c__AnonStorey0.<>m__0 () (at Assets/categories/Word.cs:184)
line 184 is :
if(buttons[n].GetComponent<Text>().text == differentWords[0].GetComponent<Text>().text || buttons[n].GetComponent<Text>().text == differentWords[1].GetComponent<Text>().text)
What should i do ? I know that I'm trying to reach null values.But it is not null actually, thus far my code works perfectly fine and i can see button's texts, all of them correct but when i click a button,it gives me this error.
Edit: I understood why it gives me errors.Writing this for helping some people. Because i try to get a Button's Text component. Which is null
. I fixed my code with
if(buttons[n].GetComponentInChildren<Text>().text == differentWords[0].GetComponent<Text>().text || buttons[n].GetComponentInChildren<Text>().text == differentWords[1].GetComponent<Text>().text)