I am working on unity, i want to find all classes that inherit fooparent class and list them all but i also want to display their version number which is static (class itself is not static). While I can list them and diplay version number when it is not static, when i change it to static i get null reference exception.
Base class (shoud i make it abstract? i posted non static version that works, you can alwasy add static and see it will not work)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FoosParent {
public string Version = "0.0";
public FoosParent()
{
}
public string GetVersion()
{
return Version;
}
}
Class that inherits base class (later there will be other classes that also inherit base class but does different things)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FoosChild : FoosParent {
public FoosChild()
{
Version = "0.1";
}
}
Find all classes
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public static class GetAllFoosParents {
public static IEnumerable Main()
{
return System.AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => type.IsSubclassOf(typeof(FoosParent)));
}
}
List them in unity window (for static I know both arguments for invoke should be null)
using UnityEngine;
using UnityEditor;
using System;
public class FoosParentListAll : EditorWindow
{
void OnGUI()
{
string list = "";
foreach(Type bp in GetAllFoosParents.Main())
{
object instance = Activator.CreateInstance(bp);
list += bp.ToString() + " " + bp.GetMethod("GetVersion", BindingFlags.Public | BindingFlags.Static).Invoke(instance, null);
list += "\n";
}
GUIStyle labelStyle = new GUIStyle(EditorStyles.label);
GUILayout.Label(list, labelStyle, GUILayout.ExpandWidth(true));
}
}
Also what i'd like is to have ability to override version number inside foochild without having to create copy of the GetVersion method but to override the variable itself. I tried to use public string new Version
but it didn't work since it will only change where it points inside not outside the child. Is there maybe better way to list all the classes then to use reflection? I hope what i try to do is clear enought, if not please ask.
Aucun commentaire:
Enregistrer un commentaire