You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot 4.1 C#中无法找到类相关函数的问题求助

问题

有Unity C#基础,刚学Godot 4.1(C#/.NET 8,Mac OSX 13.5.1),搭建3D角色rig时编写代码出现函数未找到的编译错误。

原代码:

using Godot;
using System;

public partial class world_control : Node
{
    SceneTree tree;
    Node3D camera;
    Node3D head;
    
    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        tree = GetTree();
        camera = tree.get_current_scene().find_child("camera", false, false);
        head = tree.get_current_scene().find_child("head", true, false);
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
    {
        camera.set_global_position(head.get_global_position());
        camera.set_global_rotation(head.get_global_rotation());
    }
}

报错信息:

/***/Godot/Hand_Cannon/world_control.cs(14,17): 'SceneTree' does not contain a definition for 'get_current_scene' and no accessible extension method 'get_current_scene' accepting a first argument of type 'SceneTree' could be found (are you missing a using directive or an assembly reference?)

/***/Godot/Hand_Cannon/world_control.cs(21,35): 'Node3D' does not contain a definition for 'get_global_position' and no accessible extension method 'get_global_position' accepting a first argument of type 'Node3D' could be found (are you missing a using directive or an assembly reference?)

其余错误均为类似的函数未找到问题。

解决方法

问题核心是Godot的C# API遵循PascalCase命名规范,你写的get_current_scene、find_child、set_global_position等是GDScript的snake_case命名,C#中不存在这些方法。修正后的代码如下:

using Godot;
using System;

public partial class WorldControl : Node
{
    SceneTree tree;
    Node3D camera;
    Node3D head;
    
    public override void _Ready()
    {
        tree = GetTree();
        // 替换get_current_scene为CurrentScene
        camera = tree.CurrentScene.FindChild("camera", false, false) as Node3D;
        head = tree.CurrentScene.FindChild("head", true, false) as Node3D;
    }

    public override void _Process(double delta)
    {
        // 替换set_global_position为GlobalPosition,set_global_rotation为GlobalRotation
        camera.GlobalPosition = head.GlobalPosition;
        camera.GlobalRotation = head.GlobalRotation;
    }
}

额外说明:

  • Godot C#中,属性(比如位置、旋转)直接通过大写开头的属性名访问/赋值,不需要get/set前缀方法,这和Unity的C#习惯一致,比如GlobalPosition对应GDScript的global_position。
  • FindChild方法返回的是Node类型,需要用as Node3D做类型转换,避免编译错误。
  • 建议类名也遵循PascalCase规范,比如把world_control改为WorldControl,符合C#编码习惯。

内容的提问来源于stack exchange,提问作者iWriteMehPrograms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:22:32