How to set position of each sprite when instancing several of them?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By LockManipulator

Right now I’m doing this:

onready var planet = preload("res://Planet.tscn")

func _ready():
    randomize()
    var s = planet.instance()
    for i in range(5):
	    add_child(s)
	    s.position.x = rand_range(0, 1920)
	    s.position.y = rand_range(0, 1080)

But every sprite is in the same position. Or it’s just loading in once because I only see one.

:bust_in_silhouette: Reply From: eons

Look at your function, you are only instancing one planet, the for is working over the same instance all the time (and there may be an error saying that the node is already in the tree after the first add_child).
Create, set position and add a new instance on every loop.

I’m not sure I follow along because it seems like I am doing what you suggested. Am I not creating a new instance on each loop?

LockManipulator | 2018-02-20 01:49

var s = planet.instance() is outside of the loop, so your code attempts to add one instance to the tree multiple times.

aozasori | 2018-02-20 03:06

Like this

for i in range(5):
    var s = planet.instance()
    add_child(s)
    s.position.x = rand_range(0, 1920)
    s.position.y = rand_range(0, 1080)

eons | 2018-02-26 10:49