I have been trying to find all the variables of a script through reflection. If a script is attached to the game object or in the scene, then there is no problem getting information about that script, but when I take a script from the project, the below code cannot access any info. It could be something related to Serialization or having to call a constructor at runtime, but I cannot figure out how to do that.
public List<UnityEngine.Object> AllScripts;
[ContextMenu("Test")]
public void Test()
{
var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static ;
foreach (var aObj in AllScripts)
{
Type aType = aObj.GetType();
var aInstance = aType.GetConstructor(Type.EmptyTypes);
var aList = aObj.GetType().GetFields(bindingFlags);
string[] res = Directory.GetFiles(Application.dataPath, aObj.GetType().ToString().Replace("namespace.","") + ".cs", SearchOption.AllDirectories);
Debug.LogError( res[0]+" " + aList.Length + " " + aObj.GetType());
foreach (var aVal in aList)
{
Debug.LogError( aVal.Name+ "" +aVal.IsStatic);
}
}
}
Debug.LogErrorfor your output. In some circumstances this is treated as exception and no further code executed .. rather useDebug.LogorDebug.LogWarning. Are you talking about aMonoBehaviouror another class type?call a constructor at runtime: ForMonoBehaviouryou would have to add it to a GameObject like e.g.var instance = new GameObject("TEST").AddComponent<YOURTYPE>();.new GameObjectis valid instantiates an empty GameObject into the scene. For nonMonoBehaviourclass you could either simply usenewor e.g. theActivatorfor creating instances for dynamic types