I have a base class BaseCollectionInspector
which has two derived classes: ReactionCollectionInspector
and ConditionCollectionInspector
.
The base class has this method:
protected override void AddItem(object obj) {
AssetInfo assetInfo = (AssetInfo) obj;
string assetName = Path.GetFileNameWithoutExtension(assetInfo.assetPath);
var assetType = Type.GetType(typeof(BaseReaction).Namespace + "." + assetName + ", Assembly-CSharp");
var newItem = (BaseReaction) collection.gameObject.AddComponent(assetType);
newItem.showItem = false; // Hide script in inspector
int index = collectionList.serializedProperty.arraySize++;
collectionList.serializedProperty.GetArrayElementAtIndex(index).objectReferenceValue = newItem;
serializedObject.ApplyModifiedProperties();
}
The difference between the two derived types is that one holds a list of BaseReaction
and the other BaseCondition
which both has a showItem
property.
They both would use the exact same AddItem
method, except the casting on assetType
and newItem
.
I'm trying to learn C# properly and want to use the DRY principle even if it's easy to just copy the code. I think I might be able to use an Interface, but I'm not sure how I would set that up, since I want the method to be just in the base class, adapting for the correct sub class.
I also tried putting something like this in each of the derived classes, but I can't find a way to use that for casting in the base class method:
private Type itemType = typeof(BaseReaction);
Thank you in advance!