Hey All,
I’ve been working on creating a dynamic UI. Here’s an image for a bit of an idea on my project:
As you can see, I’ll be able to select from a dropdown menu with a range of “Gun Types”. Each selection would have its own set of functions. The idea is for it to be polymorphed.
I’ve been working on this for several hours now. I’m very close, however, I haven’t completely solved it just yet.
Essentially, I have a base class with derived classes. This is for my item types (or gun types).
//Base class
public class item : MonoBehaviour
{
//Function has no purpose yet
public void performAction() {...}
}
public class auto : item
{
public float damage = 10f;
public float firerate = 5f;
public int clipSize = 1;
public int bulletCount = 1;
}
public class trajectory : item
{
public float damage = 5f;
public float firerate = 2f;
public int clipSize = 1;
public int bulletCount = 1;
}
[...]
I’ve been figuring out a method to do this to appear on the editor effectively. I’ve used an enum to select the class to use.
public enum Type
{
automatic,
semiAutomatic,
utility,
trajectory,
melee
}
public Type gunType = Type.automatic;
Then, to get these classes to show on the Editor UI (like in the image above)
public void OnBeforeSerialize()
{
if (!hasSelected) {
switch (gunType) {
case Type.automatic:
itemType = gameObject.AddComponent<auto>();
break;
case Type.semiAutomatic:
itemType = gameObject.AddComponent<semi>();
break;
[...]
}
hasSelected = true;
}
}
Then to remove the component, the usual response would be to
public void OnAfterDeserialize()
{
Destroy(itemType); //or DestroyImmediate(itemType);
hasSelected = false;
}
However, both options fail to destroy the component, as indicated in the error message:
I tried to do this with structs to get by attaching components (which would be preferable), however, I cannot use inheritance (unlike c++).