How do i call a function for a script that is in a different scene

Godot Version

v4.2.2.stable.mono.official [15073afe3]

Question

Im trying to call the “Hurt” function that I made for my enemies but I get an error saying:

CS1061: ‘Node3D’ does not contain a definition for ‘Hurt’ and no accessible extension method ‘Hurt’ accepting a first argument of type ‘Node3D’ could be found (are you missing a using directive or an assembly reference?) C:\Users\Anan Mallick\OneDrive\Documents\Godot Projects\Speed Platformer\Player\player.cs(370,11)

I dont understand why its saying this, the only Node3D it could be colliding with is the Level Scene, but it doesnt have a Hurt method.

Code:

	private void Attack()
	{
		var enemies = GetNode<Area3D>("BasicAttackHitBox").GetOverlappingBodies();
		
		foreach(var enemy in enemies)
		{
			if (enemy.HasMethod("Hurt"))
			{
				enemy.Hurt();
				GD.Print(enemy);
			}
		}
	}

Here is the enemy code as well:

using Godot;
using System;

public partial class enemy : CharacterBody3D
{
	// The downward acceleration when in the air, in meters per second squared.
	[Export]
	public int FallAcceleration { get; set; } = 75;
	[Export]
	public int Health { get; set; } = 1;
	Vector3 direction = new Vector3(0, 0, 0);
	Vector3 _targetVelocity = Vector3.Zero;


	public override void _PhysicsProcess(double delta) //delta is the frames passed since last update. Keeps the game consistent accross devices
	{
		direction = Vector3.Zero;
		Gravity(direction.X, (float)delta);

		Velocity = _targetVelocity;
		MoveAndSlide();
	}

	private void Gravity(float direction, float delta)
	{
		_targetVelocity.Y -= FallAcceleration * (float)delta;
	}
	
	private void Hurt()
	{
		Health -= 1;
		GD.Print(Health);
	}
}

public partial class enemy : CharacterBody3D
enemy should start with capital letter
public partial class Enemy : CharacterBody3D

you needed casting and before casting you needed check if is possible to cast like this:

if (enemy is Enemy  _enemy)
_enemy.Hurt();

foreach(var enemy in enemies) you can reconsider your naming.
foreach(var body in bodies) more like it. if (body is Enemy _enemy)

1 Like
1 Like

Thank you for taking the time to look at my messy code, and im sorry for not replying earlier, things got in the way.

Your solution was very helpful, although im a bit confused where you would put the following in a Godot Scene. (I’m not sure how common knowledge this is but I am very new to godot.)

public interface IDamageable
{
    void TakeDamage(int damageTaken);
}

I would be very thankful for your help. : )

1 Like

any folder in any cs file, I can suggest Script/Interfaces/IDamageable.cs
after that any Class can inherit from interface.

public partial class MyClass : Character2d, IDamageable
{
// variables like Hitpoints
   public void TakeDamage(int damageTaken)
{
 // Logic
}
}

some YT tutorial

1 Like

Thank You!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.