GetComponent returning null inside script, but working well outside
Hi, hope someone can be of some help.
I have a list of GameObjects: public List slots = new List();
which I create as: slots.Add(Instantiate(inventorySlot));
, where inventorySlot is a prefab added through the inspector.
This prefab has an Image component and a ItemSlot script component.
In the ItemSlot Start() function I get the image component as:
Image img;
void Start()
{
img = GetComponent<Image>();
}
but when I check it later in a function it returns null.
public void Select()
{
Debug.Log(img); // returns null
}
But when in the script that contains the list I do this: Debug.Log(slots[selectedSlot].GetComponent<ItemSlot>().GetComponent<Image>());
no problem at all.
And when I was checking the Update function in ItemSlot script, turns out that there img is not null?
So, does someone know why inside the ItemSlot script and Select function img is null? Is it because I can only access it in Update?
Thanks in advance.
EDIT: I moved img = GetComponent<Image>();
to Awake and it works. Was it because it didn't have time to execute Start? But now I have inv = GetComponentInParent<Inventory>();
both in Awake and Start, and in my Select function return null the first time is executed but not the second time.
public void Select()
{
Debug.Log(inv); // returns null first time Select is executed, but not the second time
}
Is all just a matter that Awake/Start haven't had time to execute, even though they exist in the scene for some time (not active though) before being Select executed?
EDIT2: Now I tried having inv = GetComponentInParent<Inventory>();
only in Awake or only in Start, and it has the behavior described before only when the line is in Start. If it's only in Awake, returns null all the time. How can it be that in Awake is not executed but it is in Start? The obvious idea it would be because Inventory hasn't yet been created in Awake, but the Inventory exists since the previous scene, and it's not destroyed.