How do I store a component Type field on a Scriptable Object

I want to store a Component in a Scriptable Object variable so that I can add it to the gameObject through script at Start

Example:

I put the Rigidbody2D component in a variable and it gets added. However I can put in the same variable other components like a custom script.

You can not store component references in a scriptable object. Well you could if those components actually live on prefabs. That’s because ScriptableObjects when stored as assets can only reference other assets. They can not reference something in the scene. However it makes little sense to store instances of certain classes just to use GetType on the instance to get the corresponding System.Type object.

You could use my SerializableMonoScript which allows you to drag and drop script files on a variable of that type and it would simply store the type name.

Note that this only works for your own scripts where you actually have a MonoScript asset in your project that you can drag and drop. So currently can not reference built-in component types that way.

Though I’m wondering what your usecase is. Usually you would create prefabs of objects and attach the objects they should have, configure them at edit time and at runtime you would simply instantiate the whole gameobject with all components.

Hello @noone492,

What I understand from what you are saying is this:

public class Thingy : MonoBehaviour {

    public SOMyComponentsToAdd datas;

    private void Start() {
        foreach (Component comp in this.datas.componentList) {
            this.gameObject.AddComponent(comp.GetType());
        }
    }

}

With componentList being a public List<Component> componentList in my ScriptableObject

If that’s not what you meant then can you explain in more details please?

I ment that i want to have a variable in a scriptable object that can store components of multiple type

using UnityEngine;

public class enemy : ScriptableObject
{
    //i can put in this variable any script I want or built in component
    //like RigidBody2D or BoxCollider2D and a custom script like gameManager
    public [WhatDoIPutHere] multipleTypeComponent; 
}