0

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);
        }
    }
}
4
  • just a general note: Maybe you should not use Debug.LogError for your output. In some circumstances this is treated as exception and no further code executed .. rather use Debug.Log or Debug.LogWarning. Are you talking about a MonoBehaviour or another class type?
    – derHugo
    Mar 16, 2020 at 10:42
  • As to call a constructor at runtime: For MonoBehaviour you would have to add it to a GameObject like e.g. var instance = new GameObject("TEST").AddComponent<YOURTYPE>();. new GameObject is valid instantiates an empty GameObject into the scene. For non MonoBehaviour class you could either simply use new or e.g. the Activator for creating instances for dynamic types
    – derHugo
    Mar 16, 2020 at 10:46
  • I am using a framework where there are alot of unnecessary logs I cannot comment. That is why I decided to use logerror for readability. Anyway, I want this to work for all scripts, but yes this situation arises for monobehaviour specifically.
    – Apocaleone
    Mar 16, 2020 at 10:47
  • I tried using Activator but to no effect. It is not working for this case. I just tried other class types too...they aren't working either
    – Apocaleone
    Mar 16, 2020 at 10:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.