Trying to access components of a prefab
I have a UI element that I want to dynamically add panels to. The panel is a prefab with two text fields inside it.
I created a class for the prefab, and the two text components are assigned to it in the inspector :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ListController : MonoBehaviour {
public Text TextName, TextDescription;
}
I then have a function which can instantiate the prefab, but im not able to access the components?
void myFunction()
{
GameObject newItemInList = Instantiate( myPrefab ) as GameObject;
ListController controller = newItemInList.GetComponent();
controller.TextName.text = "foo";
controller.TextDescription.text = "bar";
}
Apparently this is not an acceptable usage of GetComponent(); ? Ive written it this way cause I saw it used like this in a tutorial, only mine is saying GetComponent in this context "cannot be inferred from the usage"
Answer by TBruce · May 07, 2016 at 04:15 PM
This
ListController controller = newItemInList.GetComponent();
was incorrect. Also in the code below I added some debugging for you unstil you are satisfied with everyting
void myFunction()
{
GameObject newItemInList = Instantiate( myPrefab ) as GameObject;
ListController controller = newItemInList.GetComponent<ListController>();
if (controller != null)
{
if (controller.TextName != null)
{
controller.TextName.text = "foo";
}
else
{
Debug.LogWarning("controller.TextName is null");
}
if (controller.TextDescription != null)
{
controller.TextDescription.text = "bar";
}
else
{
Debug.LogWarning("controller.TextDescription is null");
}
}
else
{
Debug.LogWarning("controller is null");
}
}
Thank you so much. Its so obvious now it's pointed it out : )