- Home /
Item Object Null When Spawned in as a Prefab Clone
This is kind of building on the earlier question I had with buying items and having them transfer into your inventory, but I've discovered the root of my issue, and It's a bit weird.
Each item (as a game object in the scene) has this script inside of it. ItemObjectEquippable is an abstract class that inherits MonoBehaviour. It also has an variable inside named Item.
public class ItemObjectGun : ItemObjectEquippable {
void Start () {
item = new ItemGun(); //Defines item type
}
// Update is called once per frame
void Update () {
item.Update ();
}
}
If you were to pick up the gun item, it would function normally (Can shoot etc), but what I found is that if you were to Spawn it by using Instantiate and then add it to the player inventory, it would claim that the item variable that is undefined.
If I run debug log on Item it would also print out undefined. Interestingly, If I spawn the Item prefab, then pick it up like any other item it would also work, but if I do this:
void AddToInventory(GameObject item) {
//Some code for if the inventory is empty to set this as the currently equipped inventory item
}
//Spawns item from ID and adds to inventory
void AddItemToInventory(int ID) {
ItemRegistry registry = ItemRegistry.instance;
GameObject toAdd = GameObject.Instantiate<GameObject>(registry.getItem(ID));
AddToInventory(toAdd);
}
Why does this happen and how can I fix it?
Items are ScriptableObjects by the way, I don't know if that is effecting something though.
Answer by DaUr3 · Jul 30, 2018 at 03:02 AM
Fixed. I didn't expect to this to be fixed that fast honestly, but the issue was start was too slow.
When getting picked up off the ground after spawning, the Start method of Monodevelop ran before my add to inventory method, so it worked, but if I were to instantiate it then add it immediately, the Start method doesn't have enough time to run.
TLDR; Use awake instead.