#Instantiate Object From Interface Reference

1 messages · Page 1 of 1 (latest)

glass dune
#
public interface IMyInterface { }

---

public class MyObject : MonoBehaviour, IMyInterface { }

---

IMyInterface mObj;
Instantiate(mObj);

I want to make something like this possible, however, understandably, this approach isn't possible as Unity can't be certain that mObj derives from MonoBehaviour.

Any knowledge on an alternative approach or how to make this one possible would be appreciated. Thanks.

#

I suppose I could have some middle class between IMyInterface and the objects that derive from it. However, I would prefer not too.

hollow swallow
#

Ive never tried doing something like this, so just throwing the idea out see if it may help - if mObj is not null, could you maybe setup a function to return the gameobject? Would something similar to this work?

public interface IMyInterface
{
public GameObject GetGO();
}

public class MyObject : MonoBehaviour, IMyInterface
{
public GameObject GetGO() => this.gameObject;
}

...
Instantiate(mObj.GetGo());
hardy tangle
#

This solution could also be expanded using generics, in case you need type-safety when instantiating: cs public interface IUnityObject<T> where T : UnityEngine.Object { T GetUnityObject(); }

A completely different way would be to check if (mObj is UnityEngine.Object obj) and then Instantiate(obj).
This would make sure that obj actually is the same as mObj (as opposed to GetGO() returning an arbitrary object).

glass dune
hardy tangle
#

Tbh, SerializeReference has never quite worked for me, in the rare cases I've used it.

glass dune
#

I feel like Unity serialization in it’s entirety is troublesome. Everything from generics to dictionaries and interfaces leads to problems.