+1 vote
extends Node2D
var tree = preload("res://Objects/Tree.tscn")
var randomX = (randi() % 5561 + -2253)
var randomY = (randi() % 4395 + -1821)

func _spawn_tree():
    var Tree = tree.instance()
    Tree.global_position = ???

This is a Tree Spawner. I have 2 values, randomX and randomY
I want to set the position of "Tree" using these 2 values. How can I do this?

Godot version v3.4-stable_win64
in Engine by (15 points)

Note: Tree is already the name of a class in Godot, so your variable is conflicting with it (maybe not an error in your case tho).

Here are some suggestions to improve the code:

extends Node2D

# Use uppercase name suffixed with `Scene` so it is clear it is a scene,
# and `const` can be used because `preload` is run when the script is
# parsed, not when *instances of the script* are run.
# it also prevents it from being accidentally modified.
const TreeScene = preload("res://Objects/Tree.tscn")

var randomX = (randi() % 5561 + -2253)
var randomY = (randi() % 4395 + -1821)

func _spawn_tree():
    # Rename variable to match more standard naming convention
    # and avoid ambiguity with existing class name
    var tree = TreeScene.instance()
    tree.global_position = Vector2(randomX, randomY)

1 Answer

+2 votes
Tree.global_position = Vector2(randomX, randomY)
by (1,879 points)
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.