How do I change a colour with script?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Lapiz (Quarstudz)

Here is my code, I’m planning to make a rhythm game which the sprites actually change colour:

extends CanvasLayer
onready var colour = $"4LaneModeClrCtrl".modulate
onready var anim = $AnimationPlayer
export(String, "white", "red", "blue", "green", "yellow", "purple", "joke") var ColourMode

func _ready():
    colour = Color(255,0,0)

func set_colours():
    if ColourMode == "white":
	     colour = Color(0,0,0)
    elif ColourMode == "red":
	     colour = Color(255,0,0)
    elif ColourMode == "blue":
	     colour = Color(0,0,255)
    elif ColourMode == "green":
	     colour = Color(0,255,0)
    elif ColourMode == "yellow":
	     colour = Color(255,255,0)
    elif ColourMode == "purple":
	     colour = Color(255,0,255)
    elif ColourMode == "joke":
	    colour = Color(150,75,0)

func dev_mode_colour_cheat():
    if Input.is_action_just_pressed("cheat_code_white"):
	    ColourMode = "white"
    if Input.is_action_just_pressed("cheat_code_red"):
	    ColourMode = "red"
    if Input.is_action_just_pressed("cheat_code_blue"):
	    ColourMode = "blue"
    if Input.is_action_just_pressed("cheat_code_green"):
	    ColourMode = "green"
    if Input.is_action_just_pressed("cheat_code_yellow"):
	    ColourMode = "yellow"
    if Input.is_action_just_pressed("cheat_code_purple"):
	    ColourMode = "purple"
    if Input.is_action_just_pressed("cheat_code_joke"):
	    ColourMode = "joke"

Weirdly, it does not work. I tried the keys (1 - 7) which I mapped and it still won’t work.

:bust_in_silhouette: Reply From: kidscancode

There are a couple of problems here:

  1. You’re just setting your script’s colour variable, not changing anything about the Sprite itself. You need to set the Sprite’s modulate value directly:
if ColourMode == "white":
     $"4LaneModeClrCtrl".modulate = Color(0,0,0)

You can use a variable to store a node reference, but setting it to modulate in onready just gives it a value. It’s not some kind of link to the node’s property. For example:

onready var colour = $"4LaneModeClrCtrl"

and then:

if ColourMode == "white":
         colour.modulate = Color(0,0,0)
  1. Godot’s Color object takes floating point values between 0 and 1, not integers. Color(1, 0, 0) results in red, for example. If you want to use 8-bit values, use Color8().

and @GDScript — Godot Engine (3.1) documentation in English

Thank you for the help!

Might also ask another thing, how do I make it the colour fades into another colour?

Lapiz (Quarstudz) | 2019-11-04 08:45

Use a transition with the tween

zkmark | 2021-10-27 20:26

1 Like