Random atlas for mesh

4.5

Hello, I have two codes

extends MeshInstance3D

func _ready():
	randomize()  

	var LABEL_SURFACE = 0  
	var mat = mesh.surface_get_material(LABEL_SURFACE)
	if mat == null:
		print("Материал поверхности не найден!")
		return

	mat = mat.duplicate()
	mesh.surface_set_material(LABEL_SURFACE, mat)

	var tile = randi() % 4
	var tile_x = tile % 2
	var tile_y = int(tile / 2)
	var uv_offset_x = tile_x * 0.5
	var uv_offset_y = 1.0 - (tile_y + 1) * 0.5

	mat.uv1_offset = Vector3(uv_offset_x, uv_offset_y, 0)```

extends Node3D

var min_count: int = 2
var max_count: int = 7
var spacing: float = 0.255
var gravity: float = 0.0

var cell = []
var food_cell = []

@onready var slots: Array = get_children()
@onready var food: Array = get_parent().get_node("eat").get_children()

func _ready():
	randomize()

	for f in food:
		f.visible = false
	for slot in slots:
		spawn_in_slot(slot)

func spawn_in_slot(slot: Marker3D) -> void:

	var count = randi_range(min_count, max_count)
	var template = food.pick_random()

	for j in range(count):
		var copy_food = template.duplicate()
		copy_food.visible = true
		add_child(copy_food)
		copy_food.position = slot.position - slot.transform.basis.z * spacing * j + template.position

		if food_cell.size() <= slots.find(slot):
			food_cell.append([])
		food_cell[slots.find(slot)].append(copy_food)

		print("Еда:", copy_food)
		
		copy_food.gravity_scale = gravity

When I ‘’'template.duplicate()“” it duplicates the texture from the first mesh. And they all turned out to be the same color. How to make the colors on the grids different?

What type is a template?

in “eat” (noda), but the first code is on the mesh. template = RigidBody3D
eat(noda)
-RigidBody3D
–mesh(code 1)
–CollisionShape3D

Try setting resource_local_to_scene to true for both mesh and its material in your MeshInstance3D.

1 Like