How to i effect individual instances of newSquare

Godot Version

4.3

Question

im creating a grid of randomly colored squares and i want to effect individual instances of the var newSquare. For example if i wanted to change the color of a newSqaure instance on a key press.

extends Node

var amountx = 19
var amounty = 11
var ysqur = amounty * 60
var xsqur = amountx * 60
var SquareInstance = preload(“res://square_asset.tscn”)

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

func _ready() → void:

#for i in range(50, 200, 2):
	#print (i)



for x in range(26,xsqur, 50):
	for y in range(25,ysqur, 50):
		var random = randi() % 255 +50
		var newSquare = SquareInstance.instantiate()
		
		newSquare.position = Vector2(x, y)
		newSquare.set("modulate",Color8(2,random,random,255))
		
		add_child(newSquare)

pass # Replace with function body.

Your squares aren’t named so using get_node would be very difficult, you could re-iterate through this node’s children, remembering that you created your squares in a column-first you might be able to get it by index with some math.

func get_child_by_tile(tile_x: int, tile_y: int) -> void:
	var index := tile_y + tile_x * amounty
	return get_child(index)

Ah but you also step by 50, I don’t think calculating the index is particularly easy here either since you are using such strange units.


Make sure to format your code pastes

1 Like

Please use preformatted text ``` for code snippets.

I see you already have a scene “res://square_asset.tscn”, so you can just add this script to its root node. You can change “ui_accept” (Enter by default) action to something else. This way, each instance of the square will change its color when you press the action.

extends Control

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_accept"):
		modulate = Color(randf(), randf(), randf())
1 Like

im really dumb and this makes so much sence i tend to overcomplicate thing thank you

1 Like