无法使用 Godot 中的脚本更改精灵的纹理
Trouble changing texture of a sprite using script in Godot
我的游戏设置中有一个 Kinetic Body 2D,用于在需要时在我的字典中显示不同种类的精灵。为此,我使用了这段代码并且它有效:
get_node("Pineapple").get_node("Display").set_texture(global_const.pineapple)
变量 pineapple
在 global_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 抛出运行时错误 - 函数 'set_texture' 中的无效类型 'Sprite'。无法将参数 1 从字符串转换为对象。
我该如何解决这个问题?我哪里错了?
你的字典是 String
到 String
的映射。 reference.iname
和 reference.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))
我的游戏设置中有一个 Kinetic Body 2D,用于在需要时在我的字典中显示不同种类的精灵。为此,我使用了这段代码并且它有效:
get_node("Pineapple").get_node("Display").set_texture(global_const.pineapple)
变量 pineapple
在 global_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 抛出运行时错误 - 函数 'set_texture' 中的无效类型 'Sprite'。无法将参数 1 从字符串转换为对象。
我该如何解决这个问题?我哪里错了?
你的字典是 String
到 String
的映射。 reference.iname
和 reference.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))