Dynamic casting?

Im not sure if this is even the right question or terms being used.

So i have a EditorGUILayout.Popup field that displays all the classes that inherit from a abstract class. Throw those classes names into a string array to feed into my EditorGUILayout.Popup field. All that works perfectly fine.

I have an EditorGUILayour.ObjectField() thats casted to the abstract class.

This is the problem.

    Type selectedType = Type.GetType(objectTypes[objectTypeIndex]); // objectTypes is an string[]
    EditorGUILayout.PrefixLabel(selectedType.Name + ":");

    data = (selectedType)EditorGUILayout.ObjectField(data, selectedType, true); /// ERROR LINE

I want to cast the return type of EditorGUILayout to the type of the variable selectedType.

Above is something i would like to try and do.

I thought about generics but, with this application, i would change the type during the application.

The reason i want to do this is to filter the options, the objectfield generated in the window you select an asset from.


But what i’m trying to do essentially is filter the results of the object picker panel based on the selectedType.

Instead of showing all of the ScriptableObjects that use those inherited scripts. Like “Archor Tower” and “Gun Tower” which are both of type TowerData, I just want to show “Gun Tower Skill” which is of type SkillData.

That is what it shows if i change the code to:

    data = (ObjectData)EditorGUILayout.ObjectField(data, typeof(ObjectData), true); 

At the time of this post i didnt know the window that pops up from a click on the object field was a object picker.

So how would i go about filtering the Object Picker to show the scriptableobjects of the type selected??

You cannot cast to a type like this. The compiler needs to know the type you want to cast to statically.

If I understand correctly, data has the type of the abstract class and all objects implement this class. So you would just want to cast to the abstract class.

If you really need to do anything type specific which cannot be handled via members of the abstract class you can do type checks like “if (data is FancyClass)” or “FancyClass fancyData = data as FancyClass” and check for fancyData != null.