Texture Problem
Asked Answered
I

8

0

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.
Infuscate answered 3/12, 2023 at 15:51 Comment(0)
I
0

any ideas?

Infuscate Is there way to fix that?

Infuscate answered 3/12, 2023 at 19:0 Comment(0)
J
0

Infuscate Try loading the texture as a resource instead.

Jaquelynjaquenetta answered 3/12, 2023 at 19:7 Comment(0)
I
0

Jaquelynjaquenetta 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.

Infuscate answered 3/12, 2023 at 19:19 Comment(0)
J
0

Infuscate 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")

Jaquelynjaquenetta answered 3/12, 2023 at 19:25 Comment(0)
I
0

Jaquelynjaquenetta

Jaquelynjaquenetta 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

Infuscate answered 3/12, 2023 at 19:34 Comment(0)
J
0

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

Jaquelynjaquenetta answered 3/12, 2023 at 21:36 Comment(0)
I
0

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

Infuscate answered 4/12, 2023 at 7:20 Comment(0)
T
0

Infuscate 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.

Triplenerved answered 4/12, 2023 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.