Creating a custom script that extends other scripts in Editor

I have a base class called BaseObject.cs.

I’m trying to create a script for the Unity editor (Editor script) such that it will automatically create a new c# script called “TestScript.cs” of type TestScript that extends BaseObject.

Is this possible?

1 Answer

1

Sure but you need to actually create the .cs file:

    File.WriteAllText(filenameInAssets, yourScriptAsAString);
	AssetDatabase.Refresh();
	var scriptObject = AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath(filename, typeof(MonoScript)));

Though you have to wait for the script to import and compile before accessing it properly.

Thanks! It seems that File.WriteAllText(filenameInAssets, yourScriptAsAString); doesn't recognise Unity editor's localpath. Is there anyway to convert the editor's local asset path to a global one so that File.WriteAllText can know where to store the file?

Really? I just write to Assets/Whatever.cs

You have to have that Assets at the front for sure.

oh Thanks! yea, you are right. It works. I just need to have Assets at the front.

I just got a problem with this. So after creating the script in the assets folder, I added that to a gameobject. But I get this error: Script TestComponent has not finished compilation yet. Please wait until compilation of the script has finished and try again. UnityEngine.GameObject:AddComponent(String) Looks like I cannot add directly the newly created script to the gameobject because the AssetDatabase.Refresh() is asynchronous. Is there a way to keep looping and check that when the refresh is ready then I start adding the script as a component to a gameobject?