- Home /
Assign a reference to a Monobehaviour
Hi, I'm not sure if this is possible, but basically I wanna do:
void SpawnItem(Item item){
GameObject newItem = Instantiate (itemIcon, transform.position, Quaternion.identity) as GameObject;
newItem.GetComponent<Item> () = item;
}
And lets just say I call that function after I figure out which item from my inventory to spawn. I have a List(Item), and Item is derived from Mono. I want to know if it's possible to: 1. Spawn a Gameobject with the component directly referring to the same instance from my List 2. When I pick up the Gameobject, I "take" the component, put it in my list, destroy the Gameobject
This is actually related to Unity UI drag/drop icon. When I drag and drop an icon, I want each icon to also bring the correct reference of the instance. Whenever I do that, the newly created icon in my inventory(that has a ), always have the default instance.
I tried putting a
ItemObject itemS = newItem.GetComponent<Item> ();
itemS = item;
But of course that just refers itemS to the (Item) component in the newly instantiated object, then refers it to item, thus not really changing what newItem.GetComponent refers to at all.
Answer by Kiwasi · Nov 22, 2014 at 10:46 PM
This can't be done as written. Components don't exist separate from GameObjects. You can change the properties of the component to match the old one.
So there is no way to make the component instance actually referring to 1 of the instance of the class type in my List somewhere?
I probably haven't properly understood the $$anonymous$$onoBehaviour.
If I have List of Item, and I add that list from an existing GameObject(add the component), then I delete the GameObject, the reference for the instance of the component would still exist in the List, right? Or would the Item instance "die" without it living as a component to a GameObject?
I hope my question makes sense. And I hope that question is actually relevant to my problem. And, can you suggest any further reading about this?
"You can change the properties of the component to match the old one."
But all in all I can't have it "point" to the old one, right? Unless maybe 1 of the member is a reference type and it's pointing to something else, that reference can be passed to the new one and the reference will be identical, right?
You hit it on the head there. Give the $$anonymous$$onobehaviour a reference to a non monobehaviour class. Then you can reference the identical instance as often as you like.