首页 > 解决方案 > 如何在游戏中导入图像文件并将其设置为纹理

问题描述

基本上我想在游戏运行时导入一个图像文件并将其设置为对象的精灵/纹理。

我刚开始编码,所以我的代码是一团糟,但我会告诉你我想出了什么。

我使用文件对话框来选择我想要的文件:

var selected = null

func _process(_delta):

if visible:

selected = get_current_path()

然后我尝试导入使用加载功能选择的文件并将其设置为纹理:

var tex = ImageTexture.new()
var img = Image

onready var imag = get_node("Sprite")
        
    if Input.is_action_just_pressed("ui_home"):
        img = load($FileDialog.selected)
        tex.create_from_image(img)
        imag.set_texture(tex)

但问题是这只适用于 res:// 文件夹中的文件。我无法从尚未在 godot 编辑器中导入为纹理的其他目录导入文件。帮助表示赞赏。谢谢!

标签: godotgdscript

解决方案


用于Image.load(path)从任意路径加载图像。确保检查返回的错误代码。

var image_path = "..."

var image = Image.new()
var error = image.load(image_path)
if error != OK:
    # handle the error

var texture = ImageTexture.new()
texture.create_from_image(image)

sprite.texture = texture

推荐阅读