0 votes

Hello guys, I am migrating from Unity, I am looking for a equivalent of GetComponent() in Godot, I have two nodes from one of which I want to reach the other.

Soldier.cs

using Godot;
using System;
using Game;
public class Soldier : KinematicBody2D
{
    // Member variables here, example:
    // private int a = 2;
    // private string b = "textvar";
    public string name;
    public float speed;
    public Trench
    trench;
    public Team team = new Team(1);
    public override void _Ready()
    {
        // Called every time the node is added to the scene.
        // Initialization here

        SetProcess(true);

        this.AddToGroup("Team"+team.index);
    }

    public override void _Process(float delta)
    {
        base._Process(delta);
        trench = GetClosestTrench();
        GD.Print(trench);
        if (Position.x < trench.Position.x)
            MoveAndCollide(new Vector2(-1, 0));
        else
            MoveAndCollide(new Vector2(1, 0));

    }
        //this.MoveAndCollide(new Vector2(1,0));


    public Trench GetClosestTrench(){
        Trench r = new Trench();
        GD.Print("Team"+team.index);
        foreach(Node node in this.GetTree().GetNodesInGroup("Team"+team.index)){
            if (node.IsInGroup("Trench")){
                r = (Trench)node.GetScript() //here I want to get the trench class of the script that is attached to the node
            }
        }
        return r;
    }
}

Trench.cs

´╗┐using System;
using Godot;
using Game;
public class Trench : StaticBody2D
{
public Trench()
    {
    }
}
asked May 16 in Engine by Non (12 points)

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.