At runtime I want to be able to switch an item between completely different behaviours, which I think is best done by swapping out a script (inherited from a master ‘ItemBase’ class, e.g. Item_Wood, Item_Stone, Item_Car). The items have custom methods, so they require their own scripts.
So to switch a gameobject from ‘stone’ to ‘wood’…
I can add a script:
InputItem.AddComponent<Item_Stone>();
(after using Destroy to remove the existing ‘Item_Wood’ script).
But how do I do this when I don’t know beforehand what the scripts specific types are?
I want to be able to dynamically copy an ItemBase script (of unknown type) from one gameobject to another, something like this (the following code doesn’t work):
ItemBase ibase = ObjectA.GetComponent<ItemBase>(); // ibase could be any class inherited from ItemBase
ObjectB.AddComponent<ibase.GetType>(); // want to add a class of the same type as ibase
The script will always be inherited from ItemBase, but I would not know beforehand what the actual script type is (it could be one of dozens of scripts, so hardcoding a switch statement is not something I want to do.
Or am I going about this completely the wrong way? The main result I’m after is to morph objects by interacting with each other, but in a very dynamic way (e.g. an item could change in hundreds of different ways based on different interactions). I want to keep my game objects intact, but change their behaviours completely by switching scripts.