Shimizoki
Shimizoki
CC#
Created by Shimizoki on 2/8/2023 in #help
❔ [Unity?] How to have a list of generic classes in inspector cast as derived class
I have some classes as follows:
c#
[System.Serializable]
public class TrackedMarkers<T, U>
where T : MarkerScriptable
where U : MarkerInterface
{
string tag;
public T t;
public U u;
}

public abstract class MarkerInterface : MonoBehaviour {
public virtual void myFunc() {}
}

public class Marker1 : MarkerInterface {
public int color;
public override void myFunc() {}

}


public class Marker2 : MarkerInterface {
public int count;
public override void myFunc() {}

}



public class MarkerScriptable : ScriptableObject {
public int[] ids = new int[0];
}


public class Scriptable1 : MarkerScriptable { /* unique stuff */ }

public class Scriptable2 : MarkerScriptable { /* unique stuff */ }
c#
[System.Serializable]
public class TrackedMarkers<T, U>
where T : MarkerScriptable
where U : MarkerInterface
{
string tag;
public T t;
public U u;
}

public abstract class MarkerInterface : MonoBehaviour {
public virtual void myFunc() {}
}

public class Marker1 : MarkerInterface {
public int color;
public override void myFunc() {}

}


public class Marker2 : MarkerInterface {
public int count;
public override void myFunc() {}

}



public class MarkerScriptable : ScriptableObject {
public int[] ids = new int[0];
}


public class Scriptable1 : MarkerScriptable { /* unique stuff */ }

public class Scriptable2 : MarkerScriptable { /* unique stuff */ }
In my main script I am attempting to have a list of Tracked Markers in the inspector, But if I initialize my list as 

c#
public List<TrackedMarkers<MarkerScriptable, MarkerInterface>> myList;

// In inspector I slot
// myList[0] = (Marker1, Scriptable1)
// myList[1] = (Marker2, Scriptable2)
c#
public List<TrackedMarkers<MarkerScriptable, MarkerInterface>> myList;

// In inspector I slot
// myList[0] = (Marker1, Scriptable1)
// myList[1] = (Marker2, Scriptable2)

 Then when I try and cast it later, I get the expected

c#
string t = myList[0].tag;
// Above line works
var tm = myList[0] as TrackedMarker<Scriptable1, Marker1>;

// error CS0039: Cannot convert type 'TrackedMarkers<MarkerScriptable, MarkerInterface>' to 'TrackedMarkers<Scriptable1, Marker1>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

c#
string t = myList[0].tag;
// Above line works
var tm = myList[0] as TrackedMarker<Scriptable1, Marker1>;

// error CS0039: Cannot convert type 'TrackedMarkers<MarkerScriptable, MarkerInterface>' to 'TrackedMarkers<Scriptable1, Marker1>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion



 I somewhat understand why… If it was stored in the baseClass list, it would not know which child it belongs to. However in unity the objects that I am slotting in are already the derived class… so it should be available.
78 replies