- Home /
Accessing a prefab after instantiating results as null
I am instantiating a prefab from resources folder, after that when I try to access it through GetComponent, it returns as null and throws me the below error:
NullReferenceException: Object reference not set to an instance of an object dreamBathHomeScreen.AfterCategoryProcessingComplete () (at Assets/DreambathScripts/dreamBathHomeScreen.cs:188) dreamBathHomeScreen+c__Iterator1.MoveNext () (at Assets/DreambathScripts/dreamBathHomeScreen.cs:173) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
Here is my code:
void AfterCategoryProcessingComplete ()
{
productCategoryScreen.SetActive (true);
foreach (dreambathHomeCategories c in homeCategoriesList) {
GameObject button = Instantiate (Resources.Load ("dreamBath/horizontalCategories"), verticalScrollCategoryContent.transform) as GameObject;
button.transform.GetChild (0).gameObject.GetComponent<Text> ().text = c.CategoryName;
Debug.Log (c.CategoryName + "----------");
foreach (dreambathHomeCategories d in c.subcategory) {
GameObject parentS = button.GetComponent<horizonalCatPopulate> ().contentScroll;
GameObject buttonCh = Instantiate (Resources.Load ("dreamBath/subCategoryBtn"), parentS.transform) as GameObject;
Debug.Log (d.CategoryName + d.CategoryId + "----------");
buttonCh.GetComponent<subCatBtnPopulate> ().Instancename (d); //ERROR ON THIS LINE
}
}
foreach (dreambathHomeCategories c in homeCategoryImgUrl) {
Debug.Log (c.homecatImg + "----------");
ImageProcessing (c.homecatImg, imgHomeCategory);
}
}
Did you check buttonCh if its null? Also not sure what subCatBtnPopulate is. Is it really a component? (confused because it starts with lower case letter) Did you check if its null?
Answer by neosca · Nov 22, 2017 at 03:27 PM
buttonch is being instantiated in the previous line. It gets instantiated correctly in the heirerachy. subCatBtnPopulate is a script component added on that prefab. I am getting a null reference when I try to access buttonCh.
Your answer
Follow this Question
Related Questions
instantiate prefab object to existing object 1 Answer
Instantiating a prefab as a child of an instantiated prefab 0 Answers
NullReferenceException from a script after linking prefab with drag and drop in inspector. WTF? 1 Answer
Referencing gameObject from script after Instantiate 0 Answers
Object reference to set to instance on an instantiated object 1 Answer