using System.IO; using System.Collections; using System.Collections.Generic; using UnityEngine; using Puerts; namespace Game { public class JSLoader : ILoader, IModuleChecker { private string root; /// /// 构造方法 /// /// Js 脚本存放目录 public JSLoader(string root){ this.root = root; } /// /// * 接口要求实现 /// 判断文件是否存在 /// /// 文件路径 /// true/false public bool FileExists(string filePath){ // Puerts 需要调用到其目录下的一些 js 文件,这里通通判为存在 if (IsPuertsModule(filePath)) return true; #if UNITY_EDITOR return File.Exists(PathUnified(root, filePath)); #else return true; #endif } /// /// 定义哪些文件是 Esmodules /// /// 文件路径 /// true/false public bool IsESM(string filepath){ return filepath.Length < 4 || !filepath.EndsWith(".mjs") || !filepath.EndsWith(".js"); } /// /// * 接口要求实现 /// 文件内容读取 /// /// 模块路径 /// 文件完整路径 /// 文本内容 public string ReadFile(string filePath,out string debugPath){ bool isPuerts = IsPuertsModule(filePath); debugPath = isPuerts ? GetPuertsModulePath(filePath) : PathUnified(root, filePath); return File.ReadAllText(debugPath); } /// /// 获取 Puerts 自带模块路径 /// /// Puerts 自带模块名称 /// 模块完整路径 private string GetPuertsModulePath(string filePath) { return PathUnified(Application.dataPath,"Puerts/Runtime/Resources",filePath); } /// /// 判断模块是否为 Puerts自带模块 /// /// 模块名称 /// true/false private bool IsPuertsModule(string filePath){ return filePath.StartsWith("puerts/"); } /// /// 纠正路径(Windows下路径斜杠不正确的问题) /// /// /// 纠正之后的路径 private string PathUnified(params string[] args){ return Path.Combine(args).Replace("\\","/"); } } }