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?

1 Answer

1

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.