[Question] I cannot add a MonoScript that is not in the file I am editing through another file that contains that MonoScript
Hi! I want to add a MonoScript to the file I'm editing but unfortunately its definition doesn't exist in this file, I've tried every other file containing that MonoScript to try to add it to the file I'm editing but it fails. error and not working. I tried adding like this:
public AssetContainer addMonoBehaviour(string mName, AssetPPtr assetPPtr, AssetTypeValueField newBaseField, long newPathId)
{
var monoBehaviourClassId = (int)AssetClassID.MonoBehaviour;
mainInst.file.Metadata.ScriptTypes.Add(assetPPtr);
var scriptIndex = mainInst.file.Metadata.ScriptTypes.Count - 1;
//
newBaseField["m_GameObject.m_FileID"].AsInt = 0;
newBaseField["m_GameObject.m_PathID"].AsLong = 0;
newBaseField["m_Enabled"].AsByte = 1;
newBaseField["m_Script.m_FileID"].AsInt = assetPPtr.FileId;
newBaseField["m_Script.m_PathID"].AsLong = assetPPtr.PathId;
newBaseField["m_Name"].AsString = mName;
//
var classDatabase = assetsManager.LoadClassDatabaseFromPackage(mainInst.file.Metadata.UnityVersion);
var afile = mainInst.file;
var newInfo = AssetFileInfo.Create(afile, newPathId, monoBehaviourClassId, (ushort)scriptIndex, classDatabase, false);
newInfo.SetNewData(newBaseField);
mainInst.file.Metadata.AddAssetInfo(newInfo);
return new AssetContainer(newInfo, mainInst, newBaseField);
}
The two parameters assetsPPtr and newBaseField were taken by me from another file containing the MonoScript I needed.
As a result, when I finished editing the file and tested it again with AssetStudio, I received the error as shown below:
newBaseField needs to have the rest of the MonoBehaviour fields. You don't show how it's created, but usually you add to ScriptTypes first, then call manager.CreateValueBaseField which will pick up the new script type in ScriptTypes and include the extra MonoBehaviour fields. Then you can fill out those extra fields as you need.
This is how I created the newBaseField, it was created through another file then I called the addMonoBehaviour function from the file I was editing and passed it in the newBaseField parameter, the newBaseField was created as I expected but it didn't work when I finish editing.
var scriptTypeInfos = AssetHelper.GetAssetsFileScriptInfos(assetsManager, mainInst);
var scriptIndex = scriptTypeInfos.Values.ToList().FindIndex(s => s.ClassName == monoType.ToString());
var ttType = mainInst.file.Metadata.FindTypeTreeTypeByScriptIndex((ushort)scriptIndex);
var tempField = new AssetTypeTemplateField();
tempField.FromTypeTree(ttType);
var newBaseField = ValueBuilder.DefaultValueFieldFromTemplate(tempField);
If I did anything wrong, please help me create a sample code about this problem. Thank you and have a happy new year.