Generic UnityEngine.Objects
This package allows to create and use generic ScriptableObjects and MonoBehaviours in Unity3D. Although generic serializable classes are now supported by Unity 2020, generic ScriptableObject and MonoBehaviour are not yet, and this plugin allows to overcome this limitation.
What you can do with it:
Implement generic classes that inherit from ScriptableObject or MonoBehaviour (e.g. class GenericBehaviour : MonoBehaviour { }).
Create assets/components from a context menu and choose the generic argument type in the process.
Create object fields for generic UnityEngine.Objects and assigned created assets/components to those fields.
Instantiate generic UnityEngine.Objects from scripts (but see the limitations.)
Unity 2020.2 or higher
.NET 4.x :heavy_exclamation_mark: (when using Unity 2021.1 or lower)
:heavy_exclamation_mark: Before installing the package, please disable the Assembly Version Validation option in Player Settings.
Once you have the OpenUPM cli, run the following command:
openupm install com.solidalloy.generic-unity-objects
Or if you don't have it, add the scoped registry to manifest.json with the desired dependency semantic version:
"scopedRegistries": [
{
"name": "package.openupm.com",
"url": "https://package.openupm.com",
"scopes": [
"com.solidalloy",
"com.openupm",
"org.nuget"
]
}
],
"dependencies": {
"com.solidalloy.generic-unity-objects": "2.16.0"
},
Project supports Unity Package Manager. To install the project as a Git package do the following:
To create a generic ScriptableObject, you need to derive the class from GenericScriptableObject:
using System;
using GenericScriptableObjects;
[Serializable]
public class WarriorStats : GenericScriptableObject
where TClass : Class
{
public int Health;
public int Damage;
public TClass[] FindAllWarriorsWithTheseStats()
{
return FindObjectsOfType();
}
}(Actually, you can inherit from plain ScriptableObject but it's not recommended. Read more here.)
If you use Unity 2020, you need to specify the Serializable attribute explicitly. Otherwise, fields of type WarriorStats will not be serialized. If you use Unity 2021, this bug is fixed and Unity automatically marks generic UnityEngine.Objects as serializable.
In this example, there is only one generic argument, but you can use as many as you want.
Now, to be able to create assets from the context menu, you can add the [CreateGenericAssetMenu] attribute to the class. It has all the same optional properties as the [CreateAssetMenu] attribute: FileName, MenuName, Order.
using System;
using GenericScriptableObjects;
[Serializable]
[CreateGenericAssetMenu] // You can find "WarriorStats" at the top of Create menu.
public class WarriorStats : GenericScriptableObject
where TClass : Class
{
// ...
}Now you can create assets:
When you create an asset with certain generic arguments for the first time, a short compile dialog will show up. This is an expected behavior because the plugin needs to generate a non-generic class that derives from the generic class with the arguments you've chosen. Once the class is generated, a usual asset creation dialog will appear, where you will be prompted to enter the name of your new asset.
The type selection pop-up is powered by ClassTypeReference-for-Unity.
A generic ScriptableObject instance can be created at runtime. The CreateInstance method looks very similar, you just need pass a generic type instead:
var knightStats = GenericScriptableObject.CreateInstance>();
var knightStats2 = GenericScriptableObject.CreateInstance(typeof(WarriorStats));You can also use these methods inside the generic ScriptableObject without specifying the GenericScriptableObject class:
public class WarriorStats : GenericScriptableObject
where TClass : Class
{
public int Health;
public int Damage;
public WarriorStats Create()
{
// Use without "GenericScriptableObject."
var stats = CreateInstance>();
stats.Health = 100;
return stats;
}
}Warning! See the limitations of creating instances at runtime.
You can eliminate the need to choose generic type from a list by marking the field as [Creatable]. If such a field is empty, the :heavy_plus_sign: button will appear next to the object picker, and you will be able to create a scriptable object of the needed type in a few clicks. Declare the attribute like in the following example:
[CreateAssetMenu(menuName = "Classes/Archer")]
public class Archer : WarriorClass
{
[Creatable] public WarriorStats Stats;
public override bool HasMeleeAttack => false;
public override bool HasRangedAttack => true;
public override bool HasAOEAttack => false;
}Then you will be able to create a scriptable object without choosing its generic argument by pressing the button.
By the way, the attribute works with regular scriptable objects too, so you can use it everywhere.
If you want the :heavy_plus_sign: button for all your GenericScriptableObject fields without writing the [Creatable] attribute every time, you can enable it in Project Settings -> Packages -> Generic Unity Objects
Unlike generic ScriptableObjects, Generic MonoBehaviour can inherit directly from MonoBehaviour:
using System;
using UnityEngine;
[Serializable]
public class Unit : MonoBehaviour
where TWarrior : Warrior
{
public TWarrior[] Warriors;
}Note that the Serializable attribute is needed for a generic class to be serialized by Unity 2020. It is fixed in Unity 2021, and you don't need to put [Serializable] above generic UnityEngine.Objects.
Once the script is saved, you will be able to add a generic component through the Add Component button:
A generic MonoBehaviour component can be manipulated at runtime. The method names are the same, only "Component" part is replaced with "GenericComponent":
var archersSquad = gameObject.AddGenericComponent();
var knightsGroupComponent = gameObject.GetGenericComponent(typeof(Unit));Warning! See the limitations of creating instances at runtime.
You can create a serialized field for a generic ScriptableObject or MonoBehaviour just like for the usual one:
public class Knight : Class
{
[SerializeField] private WarriorStats _stats;
}In Unity 2020, remember to add the Serializable attribute to your class to be able to reference it in other classes.
You will get an object field in the inspector:
The file name of a generic UnityEngine.Object must contain the name of the type (e.g. "WarriorStats" in WarriorStats). Suffixes are up to you:
This way the plugin will be able to detect a class name change.
Sometimes you need to have an attribute on a generic class but it is not inherited, so when concrete children classes are generated, they don't have the attribute:
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class HideInMenuAttribute : Attribute { }
// won't work on child concrete types here because HideInMenu is not inherited
[HideInMenu]
public class TestScriptableObject : GenericScriptableObject { }In this case, you can use the ApplyToChildren attribute to specify which attributes to use when generating concrete child classes:
[ApplyToChildren(typeof(HideInMenuAttribute))]
public class TestScriptableObject : GenericScriptableObject { }Note that only attributes with parameter-less constructors can be used for this.
There are a few limitations that cannot be overcome, unfortunately.
Let's say you have a GenericScriptableObject class called GenericSO, and you created a GenericSO asset through the Assets/Create menu. Then, in a script, you call GenericScriptableObject.CreateInstance() and GenericScriptableObject.CreateInstance(). Both instances will be created just fine. However, AssetDatabase.CreateAsset() will be successful, but an asset created with AssetDatabase.CreateAsset>() will start showing "Missing Mono Script" after assemblies recompilation.
When you create a GenericScriptableObject asset with new sequence of generic arguments, a concrete class is generated to support this specific sequence. But if you create an instance with new sequence of generic arguments at runtime, the new concrete class cannot be generated without recompilation of the assembly, so it is emitted and will be destroyed after the program quits.
The principle is the same as with GenericScriptableObjects. Let's say you have a MonoBehaviour class called GenericBehaviour, and have already added a GenericBehaviour component through the Add Component button. In Play Mode, both calls will be fine: gameObject.AddGenericComponent() and gameObject.AddGenericComponent(). But in Edit Mode, gameObject.AddGenericComponent() will produce a component that will start showing "Missing Mono Script" after recompilation.
If you've created an asset of GenericSO through the Assets/Create menu once, a supporting concrete class has already been generated, so you can instantiate GenericSO in IL2CPP build. But GenericScriptableObject.CreateInstance() will throw NotSupportedException because an underlying concrete class was not generated in Editor, and IL2CPP doesn't support Reflection.Emit to generate classes dynamically.
GenericBehaviour>).In theory, it can be implemented, but it will add more complexity to the system and is used so rarely that I decided not to add such a feature.
Otherwise, when a concrete class is generated, it cannot access the constructor of the internal generic class. [IgnoreAcce
No open issues yet, or sync has not completed.