GetComponent NullReferenceException

Hello.

I have GameObject which got Sprite renderer and function that assigns sprite that loaded from resoures:
using UnityEngine;
using System.Collections;

public class LetterButtonScript : MonoBehaviour {

	private int letterInt;

	private Sprite mySprite;

	private SpriteRenderer renderer;

	private bool dead;
	// Use this for initialization
	void Start () {
		renderer = GetComponent<SpriteRenderer>();
		letterInt = -1;
		dead = false;
	}
	
	// Update is called once per frame
	void Update () {
			
	}
	/// <summary>
	/// Sets the letter.
	/// </summary>
	/// <param name="letterNumber">Letter number.</param>
	public void setLetter(int letterNumber) {
		letterInt = letterNumber;
		mySprite = Resources.Load("letters/" + letterInt, typeof(Sprite)) as Sprite;
		renderer.sprite = mySprite;
	}

	public int getLetterNumber() {
		return letterInt;
	}

	
}

I have onther script with function that Instansiates it:

buttonsPositions.z = 0f;
		buttonsPositions.y = -2.7f;
		buttonsPositions.x = -4f;
		for (int i = 0; i < mysteryCharNumbers.Length; i++) {
			letterButtons *= Instantiate(letterButtonPrototype, buttonsPositions, this.transform.rotation) as GameObject;*
  •  	buttonsPositions.x += 0.65f;*
    
  •  }*
    

After that I try to set sprite to LetterButtons
for (int i = 0; i < letterButtons.Length; i++) {
_ LetterButtonScript script = letterButtons*.GetComponent();_
_ script.setLetter(mysteryCharNumbers);
}*_

However, it shows me NullReferenceException and shows me setLetter function
What I did wrong?

mySprite = Resources.Load(“letters/” + letterInt, typeof(Sprite)) as Sprite;

letterInt is an int. You cant put it as a name, because it would be like a string (if u get what i mean). Im not sure but perhaps try .ToString()… Honestly i dont think that will work. but null reference exception means it doesnt exist. Perhaps put an if statement to see if it does exist first. maybe you could isolate the issue.

I have found why my code does not work. I have MainScript that creates LetterButtons and else. I have written Instantiate functions to create LetterButtons in Start() function.

And another function that tries to make change SpriteRenderer of LetterButtonScript also written in Start() function. So I think It tries to do all things at the same time while some components are NULL.

I solved it by creating integer variable that checks the condition:

private int condition = -1;

In Update function it will look like that:

void Update () {
		if (condition == I_AM_INITIALIZING_QUESTION) {
			initializeQuestion();
		} else if (condition == I_AM_INITIALIZING_LETTERBUTTONS) {
			initializeEnteringButtonsAndMysteryString();
		} else if (condition == I_AM_GIVING_VALUES_FOR_LETTERBUTTONS) {
			initializeValuesForLetterButtons();
		} else if (condition == I_AM_INITIALIZING_PLACES_FOR_LETTERS) {
			initializeLetterPlaces();	
		} else if (condition == I_AM_CHECKING_ANSWER) {
			checkAnswer();	
		}
	}