0 votes

I'm trying to create instances of Sprite3D and randomize their texture.
I randomize what texture will be set however all instances end up with the same texture. As if all instances share the same configuration, the final texture for every Sprite3D will be the one from the last set_texture() call.

extends Spatial

var textures = [load("res://images/image1.png"), load("images/image2.png")]

func _ready():
    var objects = get_node("Objects")

    var w = 10;
    var h = 10;

    for i in range(10):
        var newSprite = Sprite3D.new()
        newSprite.translate( Vector3( w*rand_range(-1, 1), 0, h*rand_range(-1, 1)) )
        var r = randi() % 2

How do I assign different texture by code?

in Engine by (150 points)

I copy and pasted your code, used images of my own, and didn't experience the problem you're describing.

You may be experiencing a problem with your random number choice being the same. Try putting randomize() into the loop.

it's enough to call randomize() only once to get different random number.
it's better to put outside of loop.

With print() I could see that the result was random.
Not sure what happened, but I started using material and now it just works...

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 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.