Getting a component of an instantiated object returns an error

Hi, I’m trying to get a component of an instantiated object in C# but it keeps returning errors whenever I try it. I have a prefab with a C# script component called MenuButton and I’m using this code to instantiate it and get the menu button component:

GameObject b = Instantiate(optionPrefab, transform.position, Quaternion.identity) as GameObject;
MenuButton b_btn = b.GetComponent<MenuButton>();

but I keep getting the same error:

NullReferenceException: Object reference not set to an instance of an object
CreateStartOptions.Start () (at Assets/CreateStartOptions.cs:16)

So to me it looks like the C# script or gameobject itself hasn’t yet been registered during the instantiate call and it doesn’t find the components of the object until the next frame. This same code always worked for me in UnityScript but since I’ve moved over to C# it’s given me the same error consistently.

How can I insure that I can get the component upon instantiation?

I do this quite often in my scripts using similar logic as you do, I just cast to a gameobject [(GameObject)] instead of using “as”, but I doubt that’s the issue.

Are you sure that optionPrefab is assigned to a GameObject variable in your script where you are trying to instantiate it? As in did you make the variable public and/or use [SerializeField] and then drag a copy of the Prefab into the variable spot in Unity Inspector?

[SerializeField] GameObject optionPrefab; 

The other option is are you sure of the spelling of your Script attached to your prefab? As in you are accessing a script “MenuButton”?

Have you tried with a standard component added to the prefab, such as a BoxCollider for example?

GameObject newObject = (GameObject)Instantiate(optionPrefab);
BoxCollider ourBox = newObject.GetComponent<BoxCollider>();