I’ve got a scriptable object containing a list, where the elements will actually be derived classes of the list’s type.
class S : ScriptableObject {
public List<A> list;
public void Add(A a) {
list.Add(a)
}
}
abstract class A {} //standalone class, not monobehaviour or SO
class B : A {}
class C : A {}
I’ve created an instance of the scriptable object, and the list of that asset is extended from a separate script (as part of an Editor script, if that matters?):
class E {
//...
S so;
so.Add(new B());
so.Add(new C());
//...
}
Finally, there’s a monobehaviour which the asset is attached to, and I want to access the list of that asset.
class B : MonoBehaviour {
[SerializeField] S so;
void Start() {
foreach (var a in so.list) {
if (a as B) { print("B"); }
else if (a as C) { print("C"); }
else { print("A"); } // <-- this is all that gets printed
}
}
}
Essentially, by the time I am accessing the list in the monobehaviour, the derived information about the objects in the list seem to have been lost, and they can’t be cast to their actual types.
What am I doing wrong? Is there a way I can make sure the objects in the list stay as their actual types, rather than being converted to their base class?