Unity中如何根据资源名称自动设置ScriptableObject的pokemonName字段
自动同步ScriptableObject资源名与pokemonName字段
要实现创建PokemonBase类型资源时自动将pokemonName字段设为资源名称,只需利用Unity编辑器的OnValidate()方法——这个方法会在编辑器中创建、修改或加载该ScriptableObject时触发,刚好能用来同步文件名和字段值。
修改后的代码如下:
using UnityEngine; using System.IO; // 需要引入IO命名空间处理路径 [CreateAssetMenu(fileName = "NewPokemon", menuName = "Pokemon/Create a new Pokemon")] public class PokemonBase : ScriptableObject { [SerializeField] string pokemonName; public string PokemonName { get{return pokemonName;} set{pokemonName=value;} } // ... 其他字段 ... private void OnValidate() { // 仅在编辑器模式下执行 #if UNITY_EDITOR // 获取资源的完整路径 string assetPath = UnityEditor.AssetDatabase.GetAssetPath(this); // 提取不带扩展名的纯文件名 string fileName = Path.GetFileNameWithoutExtension(assetPath); // 将文件名赋值给pokemonName pokemonName = fileName; #endif } }
补充说明
- 引入
System.IO是为了用Path.GetFileNameWithoutExtension()去掉资源文件名的.asset后缀,得到纯名称。 - 用
#if UNITY_EDITOR包裹代码,避免编辑器相关逻辑被打包到游戏运行时。 - 后续修改资源文件名时,
OnValidate()会自动触发同步pokemonName;如果想保留手动修改pokemonName的优先级,可以在赋值前加判断(比如仅当pokemonName为空时才同步)。
内容的提问来源于stack exchange,提问作者Tiến Hưng
相关产品推荐
相关产品推荐

