How do I load an Albedo Texture in GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 1-Tap

Im currently working on a project, which is a Strategygame in Space. For that I wanted to load the textures of each planet. This is the Code of each Planet (MeshInstance), render() is being called when the Solarsystem is opened.

extends MeshInstance

func render(planettype, textureytype):
	var texture_path
	var texture = String(textureytype)
	if planettype == 0:
		texture_path = "Sun" + texture + ".jpg"
	if planettype == 1:
		texture_path = "Waterplanet" + texture + ".jpg"
	if planettype == 2:
		texture_path = "Exoplanet" + texture + ".jpg"
	if planettype == 3:
		texture_path = "Rockplanet" + texture + ".jpg"
	if planettype == 4:
		texture_path = "Gasplanet" + texture + ".jpg"
	if planettype == 5:
		texture_path = "Poisoned" + texture + ".jpg"
	if planettype == 6:
		texture_path = "Waterplanet" + texture + ".jpg"
	
	var actual_path = "res://Designs/Planets/" + texture_path
	
	apply_texture(actual_path)
	
func apply_texture(actual_path):
	var texture = ImageTexture.new()
	var image = Image.new()
	image.load(actual_path)
	texture.create_from_image(image)
	self.material_override.albedo_texture = texture <-- here is probably the mistake

When I want to load it, it either doesn’t load the image at all, or says "Invalid set index ‘albedo_texture’ "

Im using Godot v3.1.1

:bust_in_silhouette: Reply From: Zylann

One reason why you might get this error is that your material_override property is null. i.e there is no material setup in there. To do this, try:

material_override = SpatialMaterial.new()
material_override.albedo_texture = texture

If it’s not null and you have a ShaderMaterial instead, try:

material_override.set_param("albedo_texture", texture)

Note: I see you create your texture manually. This might not work once the game is exported. Is that because you expect players to provide image files?
Otherwise, you could simply write this:

var texture = load(actual_path)

Thanks man, its working now!!

1-Tap | 2019-07-08 08:37