环境及版本:windows,Godot 4.2.1
一、向Sprite2D导入并加载图片
func _ready():
var img = Image.new()
img.load("res://icon.svg")
var tex = ImageTexture.create_from_image(img)
self.texture = tex
产生如下警告:@ _ready(): Loaded resource as image file, this will not work on export: 'res://icon.svg'. Instead, import the image file as an Image resource and load it normally as a resource.
大意为:将资源加载为图像文件,这在导出时不起作用。相反,请将图像文件导入为图像资源,并将其作为资源正常加载。
查阅官方社区后,将代码改为:
func _ready():
self.texture = load("res://icon.svg")
警告即消失
原因应该是Image.load()可以从编辑器内部或外部导入图片,外部图片在项目打包导出后可能会产生路径所致。将图片导入项目成为内部资源,会生成后缀impot的文件,使用load()就不会有路径问题,Godot的Resource资源类可学习的地方还很多