Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Serialized Generic with scriptable objects !

Discussion in '2020.1 Beta' started by DarylWinters, Jul 15, 2020.

  1. DarylWinters

    DarylWinters

    Joined:
    Jan 23, 2019
    Posts:
    5
    Hello,
    Since with Unity 2020.1 we're now able to serialize generic types, I was wondering if its possible to make the
    Code (CSharp):
    1. ScriptableObject.CreateInstance<GenericScriptableObject<...>()>
    works too in order to not to have to implement a non-generic class before.

    For exemple I have,
    Code (CSharp):
    1. public class Variable<T> : ScriptableObject
    2. {
    3.     private T _value = default;
    4.     public T Value
    5.     {
    6.         get => _value;
    7.         set => SetValue(value);
    8.     }
    9.  
    10.     public void SetValue(T value)
    11.     {
    12.         _value = value;
    13.     }
    14.  
    15. }
    and I want to be able to do
    Code (CSharp):
    1.  
    2.     public Variable<float> floatVariable;
    3.     void Start()
    4.     {
    5.         floatVariable = ScriptableObject.CreateInstance<Variable<float>>();
    6.     }
    (For now ScriptableObject.CreateInstance<Variable<float>>() just returns null)
    Thanks !
     
  2. MrPaparoz

    MrPaparoz

    Joined:
    Apr 14, 2018
    Posts:
    80
    As far as I know you can achieve that via an static method on Variable class.
    Code (CSharp):
    1.  
    2. public class Variable<T> :  ScriptableObject {
    3.     public static Variable<T> Create<U>(UArgs args) where U : Variable<T>{
    4.          var instance = ScriptableObject.CreateInstance<U>();
    5.          //modify and init instance
    6.          return instance;
    7.     }
    8. }
     
  3. DarylWinters

    DarylWinters

    Joined:
    Jan 23, 2019
    Posts:
    5
    Sadly no ... it doesn't work
     
  4. Lelepoop

    Lelepoop

    Joined:
    Nov 14, 2016
    Posts:
    126
    Try in 20.2
     
unityunity