- Home /
This question was
closed Jul 11, 2020 at 03:30 PM by
benyyh for the following reason:
The question is answered, right answer was accepted
Question by
benyyh · Jul 11, 2020 at 02:56 PM ·
variableclassmonobehaviour
Monobehavior class variable become null after assigning value when instantiated
I instantiates a list of gameObject with forloop in my script, then assign values to one of their component. However the variabled I assigned becomes null after it Start. Can anyone help? Thanks a lot.
Script where instantiates a list of gameObjects
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ListController : MonoBehaviour
{
public ListHolder listHolder;
public GameObject itemGameObject;
public Transform anchor;
public float padding;
private IList list;
// Start is called before the first frame update
void Start()
{
list = listHolder.list;
float itemWidth = itemGameObject.GetComponent<RectTransform>().sizeDelta.x;
for(int i = 0; i < list.Count; i++) {
GameObject itemInstance = Instantiate(itemGameObject, anchor.position, Quaternion.identity, anchor);
itemInstance.transform.localPosition += new Vector3((padding + itemWidth) * i, 0f, 0f);
ItemController itemController = itemGameObject.GetComponent<ItemController>();
if(itemController != null) {
itemController.item = list[i];
Debug.Log(itemController.item); // Shows correct message
}
}
}
// Update is called once per frame
void Update()
{
}
}
Script attached to gameObject I instantiated
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemController : MonoBehaviour
{
public object item;
void Start() {
Debug.Log(item); // Show null
}
}
Comment
Best Answer
Answer by Elango · Jul 11, 2020 at 03:20 PM
You're assigning value for prefab instead of new instance.
ItemController itemController = itemGameObject.GetComponent<ItemController>();
should be
ItemController itemController = itemInstance.GetComponent<ItemController>();
O$$anonymous$$G thank so much lol.
It took me so much time looking at elsewhere, didn't realize I got it wrong here. No wonder some other parts are acting weird as well, but it somehow worked so I was not aware.
Again, thanks a lot.