+4 votes

Hi
How can i access to a variable from my gdscript inside of shading language?

I have found some information in docs about "uniforms" but i don't known how to use it.

For example in my gdscript "main_game.gd" i have variable "length = 10". How to use it inside od shader script?

in Engine by (227 points)

2 Answers

+11 votes
Best answer

You can pass variables from gdscript to shader script using the CanvasItemMaterial's set_shader_param method.

In your shader:

uniform float my_value;

In your gdscript:

var value = 2.5
var Mat

func _ready():
    Mat = self.get_material()
    Mat.set_shader_param("my_value",value)
by (1,308 points)
selected by
+4 votes

In 3.0

Shader

uniform float my_value;

GD Script

self.material.set_shader_param("my_value",Color(0.26, 1, .9, 1))

If you set a parent material, make sure the child has updated with the new material/shader. Otherwise will encounter null errors

by (673 points)

Could you please elaborate? I am trying to send my Player Position to my shader, and I am getting null errors.

My Particles2D shader is a child of my Player Kinematics2D.

self.material.setshaderparam("player_position", position)

I am getting error
"Attempt to call function 'setshaderparam' in base 'null instance' on a null instance

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.