So i need to change the mesh texture in-game, while user playing.
when i used this code, my object texture becomes pink (texture issue color).
Is there way to fix that?

var texture = ImageTexture.new()
var image = Image.new()
var mesh = block_drop_item.get_child(0).get_child(0)
if block_drop_item.item_name == "block_grass":
	image.load("res://assets/blocks/grass.jpg")
if block_drop_item.item_name == "block_stone":
	image.load("res://assets/blocks/stone.jpg")
texture.create_from_image(image)
mesh.material_override.albedo_texture = texture

also tried this way:

apply_texture(mesh, "res://assets/blocks/grass.jpg")

func apply_texture(mesh, texture_path):
	var texture = ImageTexture.new()
	var image = Image.new()
	image.load(texture_path)
	texture.create_from_image(image)
	if mesh.material_override:
		mesh.material_override.albedo_texture = texture 
  • i have checked the texture loader, and it's successfully loads the file, but seems that can't apply it to mesh.

    darceyo Try loading the texture as a resource instead.

      xyz is there way to prepare some textures?
      I mean like when you make it manually (adding image as texture), and then just choose one from the code.

      • xyz replied to this.

        darceyo Yes but you don't need any of that in this case. Simply do mesh.material_override.albedo_texture = load("res://assets/blocks/grass.jpg")

          xyz

          xyz mesh.material_override.albedo_texture = load("res://assets/blocks/grass.jpg")

          actually it works, but for some reason it set the same texture to all my meshes on the scene

          • xyz replied to this.

            darceyo That's because they all have the same material. Texture is property of a material not of a mesh.

              xyz is there way to create a new material within code and then apply this texture to it?

                darceyo just clone it before making changes to it, you don't have to create a new one from scratch then. See Resource.duplicate()

                Something like this might work, I can't test it myself right now:

                mesh.material_override = mesh.material_override.duplicate()
                mesh.material_override.albedo_texture = load("res://assets/blocks/grass.jpg")

                Also keep in mind that this solution doesn't scale well. Usually you'd want to use as few unique materials as possible.