How to manipulate shader parameters through a script?

Godot Version 4.3

I’ve made a shader to dynamically change the rgb values of two colors on a sprite. This functions as intended, but I want to be able to change those values during runtime with _ready(). I’ve seen several approaches accomplishing this online, none of which have seemed to work for me. Either producing an error or simply leaving the sprite unchanged. I am still a novice so any and all help is appreciated. :slight_smile:

-Shader Code-

shader_type canvas_item;

uniform vec4 original_0: source_color;
uniform vec4 original_1: source_color;

uniform vec4 replace_0: source_color;
uniform vec4 replace_1: source_color;

const float precision = 0.1;

vec4 swap_color(vec4 color){
vec4 original_colors[2] = vec4[2] (original_0, original_1);
vec4 replace_colors[2] = vec4[2] (replace_0, replace_1);
for (int i = 0; i < 2; i ++) {
if (distance(color, original_colors[i]) <= precision){
return replace_colors[i];
}
}
return color;
}

void fragment() {
COLOR = swap_color(texture(TEXTURE, UV));
}

-Current Unsuccessful Implementation-

extends StaticBody2D

func _ready():
$AnimatedSprite2D.material.set(“shader_paramater/original_0”, Vector4(0.00, 0.34, 0.97, 1.00))
$AnimatedSprite2D.material.set(“shader_paramater/original_1”, Vector4(0.00, 0.00, 0.73, 1.00))
$AnimatedSprite2D.material.set(“shader_paramater/replace_0”, Vector4(0.00, 0.34, 0.97, 1.00))
$AnimatedSprite2D.material.set(“shader_paramater/replace_1”, Vector4(0.00, 0.00, 0.73, 1.00))

The correct syntax would be something like this:

$AnimatedSprite2D.get_material().set_shader_parameter(“original_0”, Vector4(0.00, 0.34, 0.97, 1.00))

1 Like