How to precompile a shader material?

Godot Version



i have a single ShaderMaterial, local_to_scene enabled for both the ShaderMaterial itself, as well as the loaded .gdshader file located within my project, that is used by multiple nodes that are instantiated in the game at diferent times during execution. my problem is that the shader itself apparently gets recompiled every single time a node is instantiated with that material, which causes an awful lot of lag spikes in my game.

how do i make sure the shader is prepared and compiled only once for the rest of the runtime of the game (or at least for the remainder of the time where the current scene is fully loaded)?

try load in background Background loading — Godot Engine (stable) documentation in English and be careful in this demo code second click can make error, you needed check if resource is already has_cached

1 Like

cool! thank you :3

i tried it with an extra check for has_cached, like so:

class_name Character extends TextureRect

class Setup:
  static var _material: ShaderMaterial:
      if not ResourceLoader.has_cached("res://shaders/character_modulate.tres"):
        var err = ResourceLoader.load_threaded_request("res://shaders/character_modulate.tres")
        if err != Error.OK: print_debug("Problem loading: %s" % err)
      return ResourceLoader.load_threaded_get("res://shaders/character_modulate.tres")


func _init(character_name: StringName):
  name = character_name
  material = Character.Setup._material
  assert(material) #assertion fails here

but my problem is that, although the first instance loads fine when instantiated from elsewhere, any later instances fails the assertion from the _init function. why is that?

This why this document is wrong and confusing. not sure if is bug.
I use ResourceLoader.Load when is cashed.

1 Like

this solution seems to work out for now. thank you :3

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.