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?
try an as MenuButton after the method invocation? MenuButton b_btn = b.GetComponent<MenuButton>() as MenuButton;
– AlwaysSunny@beeboks Which line is line 16? The code you've shown us wouldn't throw a NRE just because it can't find the MenuButton component (it would just set b_btn to null in that case). It looks to me more likely that b itself is null.
– Bonfire-Boy