+5 votes

Let's say i have a sprite and i want to load a texture with the path C:/test.png and assign it to the sprite.

Normally to assign a texture to a sprite via the editor you just load it and it's assigned to the sprite with a StreamTexture that has a .stex file.

I'm not sure how that all works, is there a simpler way to load a texture from a given file path into a sprite? StreamTexture seems like the only subclass of texture that's designed for handling loading textures from file, but i can't figure out how to make it work.

StreamTexture.LoadPath seems to reference the path of a .stex file, not sure how it works if you don't have a .stex file though.

in Engine by (29 points)

1 Answer

+12 votes
Best answer

To load a texture from a file located inside your project, this is the preferred way:

texture = load("res://path/to/your/texture.png")

To load a texture from a file located anywhere on the filesystem, provided your game has the access rights:

var image = Image.new()
var err = image.load("path/to/the/image.png")
if err != OK:
    # Failed
texture = ImageTexture.new()
texture.create_from_image(image, 0)

Note that this second way will not have gone through import, so any extra options need to be specified manually. It should be preferred for savegames or images provided by the player.

by (28,882 points)
selected by

Please how do I turn off the filter on this one? I wanna import pixel art images

On which one? Loading from game resources or loading from user's filesystem?

load() method returns "Resource" which is a base class of "ImageTexture". why both the methods are same ?

bob333: load written alone is a function, not a method (technically, it's a shorthand for ResourceLoader.load()). Image.load() on the other hand is a method of Image. They are not the same. One loads a resource, the other loads an image from a file.

@zylann: I should have been clearer. Why is the return type of "ResourceLoader.load()" considered as ImageTexture (ie. the first type in the post) ?

bob333: it will probably be a StreamTexture actually. That happens because ResourceLoader.load() returns the imported resource type from the path you provide. Images are imported by default as StreamTexture. If you want it to return an Image, you should configure that file to be imported as Image.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.