Why can't I create a script that inherits from CollisionObject2D?

Godot Version

v4.2.1.stable.mono.official [b09f793f5]

Question

I’m trying to make a C# script that inherits from CollisionObject2D. Here is the code:

using Godot;

public partial class StateObject : CollisionObject2D
{

}

But I get the following error:

CS1729: 'CollisionObject2D' does not contain a constructor that takes 0 arguments

I’m uncertain why this is happening.

The reason I want this class to inherit from CollisionObject2D and not e.g. Area2D is that I want the node this script is placed on to have the option to be an Area2D or a StaticBody2D

It happens because CollisionObject2D constructor expects two arguments, a RID and a bool:

It’s not possible. CollisionObject2D and CollisionObject3D just communicate with the PhysicsServer2D and PhysicsServer3D respectively. Use those servers directly if you want to create a custom collision object.

I see. I don’t really need a custom collision object, I only need a script that can be added to either an Area2D or a StaticBody2D. Is there any possible way I could do this?

Weird, gdscript doesn’t complain if you extend CollisionObject2D. Have you tried adding a constructor with the expected arguments that just executes the constructor of the parent class? Or alternatively, will C# let you extend Node2D?

Oh, that’s interesting. I don’t believe there’s any way I can call a constructor for CollisionObject2D. I don’t believe it’s exposed through the C# API as there’s no constructor listed in the stubs in CollisionObject2D.cs

You can extend a Node2D in C#, yes.

Well based on this I was thinking something like:

public StateObject(RID rid, bool area) : base(rid, area)
    {
    }

But I don’t have C# set up so I can’t easily test if that actually works. (Also not sure if RID is a C# type, maybe that would have to change to int or something.)

But if you can extend Node2D maybe the simplest is to do that? Area2D and StaticBody2D are both subclasses so I think you should be able to attach a Node2D script to either.

Yeah doesn’t seem to work

Not the best solution, but as soundgnome said, inheriting from Node2D seems to work. Although if you need to get the CollisionObject2D to work on it, then that’s another problem altogether, for that maybe attach this script to a node with either a Area2D or a StaticBody2D as its child, and use GetNode() to grab the child and then convert the child to a CollisionObject2D from there. Here’s what I tested, and it seems to be able to be attached to either a StaticBody2D or Area2D and work:

using Godot;
using System;

public partial class StateObject : Node2D
{
	// Do whatever here
}