You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:17:04