I couldn't get the errors on the title

modules/mono/csharp_script.cpp:2327 - Exception thrown from constructor of temporary MonoObject:
 modules/mono/mono_gd/gd_mono_utils.cpp:369 - System.InvalidCastException: Specified cast is not valid.

I am trying to load an Area but can have a Kinematic body. I am trying to what I did 2 Questions ago with Godot 3 C#

Here is my code:

private Area FloorSegment = ResourceLoader.Load<Area>("res://MyMesh.tscn");
	public override void _Ready()
	{
		string aname;
		Area inst;
		Vector3 mabit = Vector3.Zero;
		mabit.y = -1;		
		inst = FloorSegment;
		inst.Translate(mabit);
		for (int i = 0; i < 10; i++)
		{			
			aname = string.Format("Wall {0}", i);
			inst.Name = aname;
			Vector3 mpos = Vector3.Zero;
			mpos.z = -2;
			inst.Translate(mpos);
			AddChild(inst);
		}
	}
  • xyz replied to this.

    AI_Messiah
    Firstly, You can't use a type argument for ResourceLoader::Load that does not derive from Resource. So if you're loading a *.tscn file (packed scene) it should be:

    private PackedScene s = ResourceLoader.Load<PackedScene>("res://MyMesh.tscn")

    Secondly, instead of working with a packed scene, you need to instantiate it to get the node(s) that can be added to the scene tree:

    private PackedScene s = ResourceLoader.Load<PackedScene>("res://MyMesh.tscn")
    public override void _Ready()
    {
    	Area FloorSegment = s.Instantiate<Area>();
    }

    You can do instantiating at initialization too:

    private Area FloorSegment = ResourceLoader.Load<PackedScene>("res://MyMesh.tscn").Instantiate<Area>();

    The thing is that this time I am using Godot 3 not 4 so I don't think that you are right.

    • xyz replied to this.

      AI_Messiah I am most definitely right 😉

      In version 3 the method is called Instance(). They changed it to Instantiate() in version 4.

      But regardless of the api details, the main point is that you need to instantiate the scene. Your code is trying to use a packed scene object (which is a resource) as if it was a node. That won't work.