百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
G

GenericUnityObjects

> 编程语言
开源

通用的 UnityEngine.Objects

178 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

通用的 UnityEngine.Objects

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.)

Requirements

  • Unity 2020.2 or higher

  • .NET 4.x :heavy_exclamation_mark: (when using Unity 2021.1 or lower)

How To Install

:heavy_exclamation_mark: Before installing the package, please disable the Assembly Version Validation option in Player Settings.

Install with OpenUPM

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:

json
  "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"
  },

Install via Package Manager

Project supports Unity Package Manager. To install the project as a Git package do the following:

  1. In Unity, open Project Settings -> Package Manager.
  2. Add a new scoped registry with the following details:
    • Name: package.openupm.com
    • URL: https://package.openupm.com
    • Scope(s):
      • com.openupm
      • com.solidalloy
      • org.nuget
  3. Hit Apply.
  4. Go to Window -> Package Manager.
  5. Press the + button, Add package from git URL.
  6. Enter com.solidalloy.generic-unity-objects, press Add.

Generic ScriptableObject Usage

Implementing a generic ScriptableObject

To create a generic ScriptableObject, you need to derive the class from GenericScriptableObject:

csharp
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.

CreateGenericAssetMenu attribute

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.

csharp
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.

Creating an instance at runtime

A generic ScriptableObject instance can be created at runtime. The CreateInstance method looks very similar, you just need pass a generic type instead:

csharp
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:

csharp
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.

Creatable attribute

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:

csharp
[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

Generic MonoBehaviour Usage

Implementing a generic MonoBehaviour

Unlike generic ScriptableObjects, Generic MonoBehaviour can inherit directly from MonoBehaviour:

csharp
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:

Creating an instance at runtime

A generic MonoBehaviour component can be manipulated at runtime. The method names are the same, only "Component" part is replaced with "GenericComponent":

csharp
var archersSquad = gameObject.AddGenericComponent();
var knightsGroupComponent = gameObject.GetGenericComponent(typeof(Unit));

Warning! See the limitations of creating instances at runtime.

Common

Referencing a generic UnityEngine.Object

You can create a serialized field for a generic ScriptableObject or MonoBehaviour just like for the usual one:

csharp
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:

File Naming

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:

  • WarriorStats`1.cs :heavy_check_mark:
  • WarriorStatsOfTClass.cs :heavy_check_mark:
  • WarriorStats.cs :heavy_check_mark:
  • Stats.cs :x:

This way the plugin will be able to detect a class name change.

ApplyToChildren Attribute

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:

csharp
[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:

csharp
[ApplyToChildren(typeof(HideInMenuAttribute))]
public class TestScriptableObject : GenericScriptableObject { }

Note that only attributes with parameter-less constructors can be used for this.

Limitations

There are a few limitations that cannot be overcome, unfortunately.

If a GenericScriptableObject with specific generic arguments has not been created through the Assets/Create menu yet, you can instantiate it at runtime, but cannot create an asset out of it.

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.

If a generic MonoBehaviour with specific generic arguments has not been added as component through the Add Component button yet, you can add it in play mode, but not in edit mode.

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 a generic UnityEngine.Object with specific generic arguments has not been created/added through Editor UI, it cannot be instantiated in IL2CPP builds.

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.

Using a generic class as a generic argument is prohibited (e.g. 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.

Generic UnityEngine.Object cannot be internal.

Otherwise, when a concrete class is generated, it cannot access the constructor of the internal generic class. [IgnoreAcce

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言