random value is always the same when instance the node more than once in the main scene

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

Hello godot community :slight_smile:

i want my NPC sprite to get a random color from shader material
every shader script is saved in a variable
i made a rand_value that contain the variables
everything is ok when i use only 1 NPC in the main scene
but when i use more than one they all get the same color

am i missing something??

extends Sprite2D

var red = preload("res://Scenes_Scripts/red.gdshader")
var blue = preload("res://Scenes_Scripts/blue.gdshader")
var yellow = preload("res://Scenes_Scripts/yellow.gdshader")

var color_list = [red,blue,yellow]
var rand_value = color_list[randi() % color_list.size()]
func _ready():
	self.material.shader = rand_value

note : * The parent node is {CharacterBody2D}
the sprite node is a child which i apply material shader on

*When i set the node as a local node in the main scene everything works fine

here is an image to make it clear

Image To Link — Image - mu8g1awqWw

:bust_in_silhouette: Reply From: Enfyna

Create a rng object and randomize it every rng object will have a different seed.

Example :

func  _ready():
    var rng = RandomNumberGenerator.new()
    var rand_value = color_list[rng.randi() % color_list.size()]
    self.material.shader = rand_value

Hi …
I tried this method and unfortunately it didn’t work :frowning:
I got the same result I don’t know why
all the nodes share the same random var

*When i set the node as a local node everything works fine

Zylo_X | 2023-03-26 00:11

Hmm. If you use a loop to create your nodes you have to use the duplicate() function.
For example :

func _ready():
    var node # your node

    for _i in range(10):
        var temp = node.duplicate()

If you don’t use the duplicate() function you will add the same node everytime.

Enfyna | 2023-03-26 02:37

Thanks again
But I’m not using a code to instance the NPC node
I’m putting the NPC nodes manually in the main scene
By instancing them as a child from the editor from the link icon at the top of the scene dock.

Zylo_X | 2023-03-26 07:33

Well I tried to recreate your scene now. I made a empty main scene with a empty script and created another scene that has a Node2D and a ColorRect node child. In the main scene I linked 6 objects. When I run it they get different colors.

I dont think your problem is with the random value you are probably making a mistake on assigning the shader. I would like to help but I dont know shaders.

Enfyna | 2023-03-26 09:15

Yes you’re Right i think the problem is in the shader
Properties or something like that
Also this is my first try with shaders
Again thank you so much

Zylo_X | 2023-03-26 09:32

:bust_in_silhouette: Reply From: Zylo_X

finally i found the solution :smiley:

i checked [ local to scene ] in material > Resource options