How to make object not nullable when adding it to entity?

I made my own system of making Items as SOs for my game. Each Item has List of IComponentData and ISharedComponentData, so I can set them for this individual item. But when I want to spawn it in the world and add all components with

entityManager.AddComponentData(entity,item.GetComponent(0)); // 0 is index

I get error that item.GetComponent() must return not-nullable type. For now it returns object because I have several different components in the list. How I can make item.GetComponent() to return not-nullable type so I can use it in AddComponentData()?

Add struct to your method’s type constraint make it not nullable. Maybe yours is like :

public T GetComponent(int i) where T : IComponentData

Change it to :

public T GetComponent(int i) where T : struct, IComponentData

Since class can also implement an interface and IComponentData alone do not guarantee a struct.

But class itself is not generic class, it’s just scriptable object, therefore I can’t make method return T because it doesn’t know about T.

That’s the issue. You can use AddComponentObject to add a container for the ScriptableObject. These components can contain anything you want, they don’t have the normal ECS restrictions, since those are saved on the heap as far as I know

    public class ScriptableObjectContainerComponent: Component{
        public ScriptableObject myScriptableObject;
    }
em.AddComponentObject(new ScriptableObjectContainerComponent(){myScriptableObject=item.GetComponent(0)});