【问题标题】:Trouble changing texture of a sprite using script in Godot在 Godot 中使用脚本更改精灵的纹理时遇到问题
【发布时间】:2019-12-22 05:58:31
【问题描述】:

我的游戏设置中有一个 Kinetic Body 2D,用于在需要时在字典中显示不同类型的精灵。为此,我使用了这段代码并且成功了:

get_node("Pineapple").get_node("Display").set_texture(global_const.pineapple)

变量pineappleglobal_const.gd 单例脚本中以这种形式出现-

const pineapple = preload("res://Ingredients/Pineapple.png")

后来,我决定完全摆脱使用“global_const”变量,因为我为我想要显示的所有项目构建了一个字典。新字典现在看起来像这样 -

const ingredients = [{iname="Pineapple", icon="res://Ingredients/pineapple.png"},
{iname="Cherry", icon="res://Ingredients/cherry.png"},
{iname="Banana", icon="res://Ingredients/banana.png"}]

我想修改我使用set_texture 的代码,我这样做了 -

for item in on_scene_ingredients: #this loops through all the instances of my Kinetic Body 2D.
#they have different values in "iname" to differentiate between each other
    for reference in dictionary.ingredients: #this checks all the items in my library
        if item.iname==reference.iname: #checks for common name to assign the desired icon
                item.get_node("Display").set_texture(reference.icon)

我测试了所有变量是否正确以及逻辑是否存在任何缺陷,但没有。 导致问题的唯一行是 -

item.get_node("Display").set_texture(reference.icon)

Godot 引发运行时错误 - 基础“Sprite”中的“set_texture”函数中的类型无效。无法将参数 1 从 String 转换为 Object。

我该如何解决这个问题?我哪里错了?

【问题讨论】:

    标签: textures godot gdscript


    【解决方案1】:

    您的 dict 是 StringString 的映射。 reference.inamereference.icon 都是字符串,所以你的代码出来:

    item.get_node("Display").set_texture("res://Ingredients/pineapple.png")
    

    set_texture 需要 Texture,但您传递的是 String。您需要先加载纹理,然后再将其传递给set_texture

    item.get_node("Display").set_texture(load(reference.icon))
    

    【讨论】:

    • 你刚刚为我节省了几天的研究时间。谢谢你,你是一个绅士和一个学者。
    猜你喜欢
    • 2012-02-10
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多