Hi,
I suppose its rather general C# scripting question then unity related but still.
I have two classes
public class Item
{
[INDENT]// Icon for inventory (drag'n'dropped in editor from prefab)[/INDENT]
[INDENT]public gameObject icon;[/INDENT]
[INDENT]// When Clicked[/INDENT]
[INDENT]OnInput[/INDENT]
[INDENT]{[/INDENT]
[INDENT][INDENT]inventory.AddItem(gameObject) // In this case everything's OK[/INDENT][/INDENT]
[INDENT][INDENT]Destroy(gameObject)[/INDENT][/INDENT]
[INDENT]}[/INDENT]
}
public class Inventory
{
[INDENT]public GameObject itemToInventory;[/INDENT]
[INDENT]private GameObject grabbedItem;[/INDENT]
[INDENT]OnInput ()[/INDENT]
[INDENT]{[/INDENT]
[INDENT][INDENT]AddItem(grabbedItem); // In this case I'll get an exception [/INDENT][/INDENT]
[INDENT][INDENT]Destroy(grabbedItem);[/INDENT][/INDENT]
[INDENT]}[/INDENT]
[INDENT]public void AddItem (GameObject item)[/INDENT]
[INDENT]{[/INDENT]
[INDENT][INDENT]if (item.GetComponent<Item>() != null)[/INDENT][/INDENT]
[INDENT][INDENT]{[/INDENT][/INDENT]
[INDENT][INDENT][INDENT]itemToInventory = item.GetComponent<Item>().icon; // In this case everything is FINE[/INDENT][/INDENT][/INDENT]
[INDENT][INDENT]} else[/INDENT][/INDENT]
[INDENT][INDENT]{[/INDENT][/INDENT]
[INDENT][INDENT][INDENT]itemToInventory = item; // In this case I'll get exception on instantiation[/INDENT][/INDENT][/INDENT]
[INDENT][INDENT]}[/INDENT][/INDENT]
[INDENT][INDENT]//StartDelay()// And call CallAfterAnimation() after its over[/INDENT][/INDENT]
[INDENT]}[/INDENT]
[INDENT]OnUpdate[/INDENT]
[INDENT]{[/INDENT]
[INDENT][INDENT]//When delay is over call CallAfterAnimation()[/INDENT][/INDENT]
[INDENT]}[/INDENT]
[INDENT]// Called with delay[/INDENT]
[INDENT]public void CallAfterAnimation[/INDENT]
[INDENT]{[/INDENT]
[INDENT][INDENT]Instantiate(itemToInventory)[/INDENT][/INDENT]
[INDENT]}[/INDENT]
}
So the thing is that when I’m saving temporary item from Item Class (through AddItem() in Inventory)
itemToInventory = item.GetComponent<Item>().icon;
and in the next moment destroying this gameObject Destroy(Item), itemToInventory stays valid (not null) and after delay Instantiate(itemToInventory)
works just fine. But when using Inventory’s class own method OnInput to save object like following (again through Inventory’s AddItem() )
itemToInventory = item;
then calling Destroy(item) makes itemToInventory == null and after delay there’s nothing to instantiate from so I’m getting exception at final method CallAfterAnimation().
The question is: how to save properly gameObject in itemToInventory variable to keep in not null even after destroying the object from which it got all the data?