- Home /
Create script from template, then create .asset file from new script
I want to create a script from a template, then create a .asset of that file. It inherits from ScriptableObject.
using System.IO;
public class CreateScriptAndAsset : ScriptableObject
{
string NewFilePath = "Path/To/Template.cs.txt";
string[] TemplateLines = File.ReadAllLines(NewFilePath);
//Creates script file from the template at NewFilePath
File.WriteAllLines(NewFilePath, TemplateLines);
//I then want to create an instance of that type
var newObj = ScriptableObject.CreateInstance(NewFilesType);
AssetDatabase.CreateAsset(newObj);
}
I am having a few issues with this. First, the new File does not show up in the Editor till AFTER I leave the Editor and come back in. Second, the instance of the new script is not created soon enough for the call to AssetDatabase to use the object.
How do I go about getting these to work in-order? Visual Studio pops up an alert that the environment changed, and prompts for a re-load. This may be throwing off the instance timing.
Answer by benapprill · Jul 01, 2019 at 04:33 PM
AssemblyReloadEvents.afterAssemblyReloads delegate needed to be subscribed to with the code to generate the new object. This will run 'after' the added script-type has made its way into the Assembly.
using UnityEditor;
using UnityEngine;
public class HandleNewScriptAndSO : ScriptableObject
{
public StringRef ActiveDirectory_Ref;
public StringRef NewSOName;
public BoolRef TypeHasBeenAdded_Ref;
private string NewSOPath;
private void OnEnable()
{
AssemblyReloadEvents.afterAssemblyReload += GenerateNewSO;
}
public void GenerateNewSO()
{
if (TypeHasBeenAdded_Ref.Val)
{
ScriptableObject NewSO = CreateInstance(NewSOName.Val);
NewSOPath = ActiveDirectory_Ref.Val + '/' + NewSOName.Val + '/' + NewSOName.Val + ".asset";
AssetDatabase.CreateAsset(NewSO, NewSOPath);
TypeHasBeenAdded_Ref.Val = false;
}
}
}
Your answer
Follow this Question
Related Questions
Find Source of Prefab Instance in Editor? 1 Answer
How to get the asset file from the AssetDatabase.CreateAsset() 1 Answer
Custom assets give Missing (Mono Script) 0 Answers
Can I save a ScriptableObject holding data from a private database class without [SerializeField]? 1 Answer
Multiple Cars not working 1 Answer