Topic was automatically imported from the old Question2Answer platform.
Asked By
Zylo_X
Hello godot community
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():
randomize()
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
Create a rng object and randomize it every rng object will have a different seed.
Example :
func _ready():
var rng = RandomNumberGenerator.new()
rng.randomize()
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
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()
add_child(temp)
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