Ggez游戏添加精灵表遇ResourceNotFound错误,如何解决?
问题描述
运行cargo run时出现资源找不到错误:
Error: ResourceNotFound("/sprites.png", [("/home/pablo/Dev/rust-game/target/debug/resources", IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" })), ("/home/pablo/.local/share/our_game", IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" })), ("/home/pablo/.config/our_game", IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" }))])
已将sprites.png放入项目根目录的resources文件夹:
❯ ls resources/ sprites.png
但程序会去target/debug/resources查找,该目录不存在:
❯ ls target/debug/resources ls: cannot access 'target/debug/resources': No such file or directory
尝试过cargo-resource-root选项(已被移除)和Cargo.toml的include字段,均无效。
解决方法
通过环境变量指定资源目录
启动游戏时直接通过环境变量告诉ggez资源路径,无需复制文件:RESOURCE_DIR=./resources cargo run用build脚本自动复制资源到target目录
- 新建项目根目录下的
build.rs文件,写入以下代码:
use std::fs; use std::path::Path; fn main() { let resources_src = Path::new("./resources"); let resources_dest = Path::new("./target/debug/resources"); if !resources_dest.exists() { fs::create_dir_all(resources_dest).unwrap(); } for entry in fs::read_dir(resources_src).unwrap() { let entry = entry.unwrap(); let target_path = resources_dest.join(entry.file_name()); fs::copy(entry.path(), target_path).unwrap(); } }- 在Cargo.toml中添加配置,确保编译时执行该脚本:
build = "build.rs"之后每次
cargo run,资源会自动复制到target目录,程序可正常读取。- 新建项目根目录下的
手动挂载资源目录到ggez上下文
在游戏初始化代码中,直接挂载项目根目录的resources文件夹:use ggez::{ContextBuilder, filesystem}; fn main() { let (ctx, event_loop) = ContextBuilder::new("our_game", "your_name") .add_resource_path("./resources") .build() .expect("Failed to initialize context"); // 后续游戏逻辑... }这样ggez会优先查找你指定的资源目录,无需依赖target目录的文件。
内容的提问来源于stack exchange,提问作者The Oddler
相关产品推荐
相关产品推荐

