I’m currently learning Godot by following a tutorial but translating the GScript code into C#. The tutorial in question is here: https://www.youtube.com/watch?v=nAh_Kx5Zh5Q&t=17197s
I’m at the inheritance chapter where he creates a parent scene ItemContainer and two scenes that inherit from it: toilet and box.
My code for the 3 classes is as such:
using Godot;
using System;
public partial class ItemContainer : StaticBody2D
{
public virtual void Hit()
{
GD.Print("Ow");
}
}
using Godot;
using System;
public partial class toilet : ItemContainer
{
public override void Hit()
{
GD.Print("Toilet");
}
}
using Godot;
using System;
public partial class box : ItemContainer
{
public override void Hit()
{
GD.Print("Box");
}
}
From an earlier part of the tutorial I have a placeholder drone enemy which also has a Hit() method, all it currently does is print “drone hit” however this drone class doesn’t inherit from the item container class.
The hit method is called by the laser class which currently looks like this:
using Godot;
using System;
public partial class laser : Area2D
{
[Export] public float Speed = 750f;
public Vector2 direction;
public override void _Process(double delta)
{
this.Position += direction * (float)delta * Speed;
}
public void onCollision(Node2D body)
{
if (body.HasMethod("Hit")) ((drone)body).Hit();
QueueFree();
}
public void onTimeout()
{
QueueFree();
}
}
When calling the hit method I had to cast the body to a drone so VSCode can see the object does in fact have a hit method. This is quite annoying as I’m already checking if the object has the hit method but Godot straight up won’t build without the cast. The cast causes issues though as when shooting an item container it can’t cast to a drone and therefore doesn’t run.
I would like to know if there is a way in C# to simply run a method regardless of the object’s class or even an easy way to cast the object to the type of the object without knowing it in advance. I have found a solution which is by changing the laser’s code to:
public void onCollision(Node2D body)
{
if (body.HasMethod("Hit"))
{
if (body is drone drn) drn.Hit();
else if (body is ItemContainer itemC) itemC.Hit();
}
QueueFree();
}
While this works fine for now I would like to know if there is an easier way to run Hit because if there is even more types of classes that can be hit the if statement could get rather long and tedious. Anyway advice on how to simplify it is greatly appreciated!