jeudi 14 novembre 2019

Unity3D: Reference .cs file in inspector, then get its type at runtime

I'm trying to let the user specify their own c# script that inherits from an abstract class I created. I have a working Unity Editor version, but because it is based on MonoScript class which is in the UnityEditor namespace, it gives an error when trying to compile into a built unity executable. I've tried several things but can't seem to get it to work.

If I know the assembly it will be in I can load an assembly and get the class from it by name. But I won't know which assembly the script may reside in, since the User can potentially place it anywhere.

working editor version

using UnityEditor; //This is the problem!!
using UnityEngine;

public class test : MonoBehaviour {
    public MonoScript testScript;

    void Start() {
        Type testType = testScript.GetType();
        Debug.Log(testType);
    }
}

This version is not dependent on UnityEditor, so it compiles, but it doesn't work.

using System;
using UnityEngine;

public class test : MonoBehaviour {

    public TextAsset testScript;

    void Start() {
        Type testType = GetType(testScript);
        Debug.Log(testType);
    }


    Type GetType(TextAsset textAsset) {
        string assetName = textAsset.name;
        Debug.Log(assetName);
        Type type = System.Type.GetType(assetName); //This is null
        Debug.Log(type);
        return type;
    }
}

I've also tried a bunch of solutions with getting assemblies and then loading the class by name, but haven't figured out a working solution.

I suspect the answer involves reflection, but I'm a reflection noob.





Aucun commentaire:

Enregistrer un commentaire