godot: Make preload invalid paths null instead of a compilation error
Operating system or device - Godot version: Windows 10 Godot 2.1 stable
Issue description:
The current behavior of preload with invalid paths is give an error in editor (Can’t preload resource at path) and crash at runtime.
A better approach could be instead of give an error in editor and crash at runtime, preload could return null and let the user check ingame if the preloaded var/const is null.
This could be useful for addons, for example I have an addon which has a timer created by script for delayed triggers and I wan’t the trigger addon to be independant from the project, but for this project the timer could be paused with a player ability, so I need a way to attach that script for the timer in the trigger. The easiest and optimal way to achieve this could be preload const and check if the script path is null. So with this I could use the addon without major modifications in another project or I could put another timer script at the path for custom behaviour in a new project.
NOTE: I’m aware of load and check/load the path in ready:
const _timer_script_path = "res://resources/scripts/timer.gd"
func _ready():
var timer = Timer.new()
var script = load(_timer_script_path)
if(script != null):
timer .set_script(script)
But that method should be less optimal because is 1 load for EACH ready vs a SINGLE preload in a CONST at start of the game
Steps to reproduce:
Create a script and try to preload an invalid resource with a const and run the game:
const _script = preload("res://resources/scripts/timer.gd")
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 1
- Comments: 17 (15 by maintainers)
Crash (parse error actually) is fine, this is meant to always work. It would be worse if you mess up the name, it doesn t work and you dont realize you made a mistake.
On Mon, Nov 14, 2016 at 5:49 PM, Marc notifications@github.com wrote:
Agree with Akien. Also I prefer a compile error than a successful compilation but a hidden bug.
That’s true, but if it really, really matters, you can make a global singleton holding those variables and doing whatever you want with the resources just once.
preloadexpects a const String. If that const String points to an invalid path, that’s a bug from whoever wrote the string, and it’s normal that the program gives an error.You can’t use
preloadto load resources dynamically, that’sload’s job, so it’s definitely what you want to use in your use case. It makes no sense to havepreloadreturn a null object if passed a bogus path. It should only return a null object if it was called on a valid path but an invalid resource (i.e. it couldn’t load the file because it’s not a resource Godot knows how to handle), not if the programmer made a typo.