+1 vote

Hello

I want to spawn enemies in random position, what I did in short was to instance my enemy scene into my main scene(that's where I code the spawning thing) and when I try to set the position of my enemy scene it says there is extension method for it

PackedScene foodsource;
public Node foodinstance;
      public override void _Ready()
        {
            foodsource = GD.Load<PackedScene>("res://Food.tscn");
            foodinstance = foodsource.Instance();
        }
     public override void _Process(float delta)
      {
        foodinstance.position // ***that's where there is error***
       }

I would happy for some help(in c# if it's possible)

in Engine by (38 points)

It will print the position of the root scene

PackedScene foodsource;
public Node foodinstance;
      public override void _Ready()
        {
            foodsource = GD.Load<PackedScene>("res://Food.tscn");
            foodinstance = foodsource.Instance();
        }
     public override void _Process(float delta)
      {
        //foodinstance.position // ***that's where there is error***
        foodinstance.Position;
       }

??
Its the same code

"P" uppercase
position <==> Position

Doesnt work bro

2 Answers

–1 vote

You need to set the Position to something. Ie.

foodinstance.Position = new Vector2(GD.RandRange(-100f, 100f), GD.RandRange(-100f, 100f));

Sorry if I got some detail wrong, I haven't done much C# on Godot.

by (1,100 points)

But according to the editor

Foodinstance.Position 

Doesnt exist
There is no position property for a node

+1 vote

Node doesn't have a Position property:
https://docs.godotengine.org/en/stable/classes/class_node.html#properties

You need a Node2D at least.

by (1,079 points)

But instance() returns Node and not Node2D
I also tried to cast it

foodinstance = (Node2D)foodsource.Instance();

Even though now there is position property I can't change it
the debugger says

cannot modify the return value Node2D.Position because it's not a variable.

That's right. You have to do it like this:

myNode2D.Position = new Vector2(100, 100);

That's because Position is a Property and not a public field.

public Vector2 Position { get; set; }

The property does the same like this:

private Vector2 _position;

public Vector2 GetPosition()
{
    return _position;
}

public void SetPosition(Vector2 position)
{
    _position = position;
}

GetPosition().x = 4711 gives me the same error.

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.