Godot Version
4.4.1
Question
I have a scenario where the root node has a C# script attached. After loading it from an external .pck file, I cannot instantiate it using PackedScene.Instantiate because the associated C# script class implementation does not exist in the external .pck package. Although I found a workaround to load this C# scene, since the code in this scene also loads other scenes, and those other scenes cannot be loaded either due to the C# code in the external .pck being empty implementations, this renders the entire scene unusable.
I instantiated the C# class by loading the assembly, but because it depends on child nodes, it also cannot be added to the tree as a standalone node.
var path = OS.GetExecutablePath().GetBaseDir();
var pckPath = path.PathJoin("mod.pck");
var dllPath = path.PathJoin("mod.dll");
var result = ProjectSettings.LoadResourcePack(pckPath);
GD.Print("res load: ", result);
var types = new List<Type>();
Assembly assembly = null;
try
{
assembly = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly())?.LoadFromAssemblyPath(dllPath);
}
catch (Exception e)
{
GD.Print(e);
return;
}
try
{
types = assembly.GetTypes().ToList();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types.Where(t => t != null).ToList();
foreach (var type in types)
{
GD.Print(type.FullName);
}
}
var modClass = (Node)Activator.CreateInstance(types.First(t => t.FullName == "MyNamespace.MyMod"));
var modScript = (CSharpScript)modClass.GetScript();
var node = ResourceLoader.Load<PackedScene>("res://MyMod/Mod.tscn").Instantiate();
var nodeID = node.GetInstanceId();
node.SetScript(modScript);
node = (Node)GodotObject.InstanceFromId(nodeID);
GetTree().Root.CallDeferred(Node.MethodName.AddChild, node);