Trying to make enemy color unique per enemy

Godot 4.4.1

Hi. I’m making a basic motorway for a scene in my game. The motorway consists of a Path3D that spawns mutiple instances of PathFollower3Ds with car meshes attached. The cars spawn, complete the path and despawn as required.

I want to make each car color unique per car instance. I tried doing this by overriding the material in the ready() function of the spawned cars. That did not work. Instead, it will change the color of EVERY spawned car at the same time.

I tried again by placing the code in the code that spawns the instance of the vehicle but I get the same issue.

extends Path3D

@export var newCar: PackedScene
var timeS = 0

Called when the node enters the scene tree for the first time.

func _ready() → void:
pass # Replace with function body.

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _process(delta: float) → void:

if timeS > 60:
	timeS = 0
	if randi_range(0, 2) == 1:
		spawn_car()
else:
	timeS += 1

func spawn_car():
var a = newCar.instantiate()
a.get_child(5).material_override.albedo_color = Color(randi_range(0,1),randi_range(0,1),randi_range(0,1),1)
add_child(a)

Here is the code so far.

Is there a simple fix to this? Perhaps a way of making each instance of a car have its own script?

Material is a Resource and Resources are shared by default. You’ll need to make them unique:

  • Right click over it in the inspector and click on Make Unique
  • Enable Local to Scene in the Resource. This will make unique the resource when instantiating the scene (if the resource is shared between nodes in the same scene the copies won’t be made unique)
  • Calling Resource.duplicate() in code. For example in the _ready() function of your car scene.

Of course. I didn’t consider that. It works fine now, thanks.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.