ScriptableObject批量赋值脚本

这个脚本在Unity编辑器模式下用于自动填充HistoriesData文件中的pictures列表,从Gallery/Pictures路径下获取Sprite资源并更新到对应的历史数据中。通过设定autoAsign标志来触发自动赋值操作,确保数据文件被正确修改。
摘要由CSDN通过智能技术生成

在用到Scriptable的时候,赋值是个问题。可以参考下面的脚本进行自动赋值

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

/// <summary>
/// 编辑器模式下半自动填充HistoriesData文件中的pictures列表
/// </summary>
[ExecuteInEditMode]
public class AutoAsignHistoricalPictures : MonoBehaviour
{
    [SerializeField] private bool autoAsign;// 是否需要自动填充
    private void OnEnable()
    {
        if (autoAsign)
        {
            autoAsign = false;
            AutoAsign();
        }
    }

    private const string PATH_OF_HISTORIES = "Gallery/Histories";       // 历史数据所在的路径
    private const string PATH_OF_PICTURES = "Gallery/Pictures";         // 历史照片所在的路径
    private const string FORMAT_OF_PATH = "{0}/Unit{1}/Topic{2}";       // 资源路径格式
    private const string FORMAT_OF_PATH_AND_FILE_NAME = "{0}/{1}";      // 资源路径加文件名称格式
    private void AutoAsign()
    {
        HistoriesData[] historiesDatas = Resources.LoadAll<HistoriesData>(PATH_OF_HISTORIES);
        if (historiesDatas != null && historiesDatas.Length > 0)
        {
            foreach (HistoriesData historiesData in historiesDatas)
            {
                if (historiesData != null && historiesData.pictureNames != null && historiesData.pictureFilePaths != null)
                {
                    historiesData.pictureNames.Clear();
                    historiesData.pictureFilePaths.Clear();

                    string pathOfTopicPictures = string.Format(FORMAT_OF_PATH, PATH_OF_PICTURES, historiesData.unitId, historiesData.topicId);
                    Sprite[] pictures = Resources.LoadAll<Sprite>(pathOfTopicPictures);
                    if (pictures != null && pictures.Length > 0)
                    {
                        foreach (Sprite sprite in pictures)
                        {
                            historiesData.pictureNames.Add(sprite.name);
                            historiesData.pictureFilePaths.Add(string.Format(FORMAT_OF_PATH_AND_FILE_NAME, pathOfTopicPictures, sprite.name));
                        }
#if UNITY_EDITOR
                        EditorUtility.SetDirty(historiesData);// 修改数据文件之后,通知系统该文件已经被修改
#endif
                    }
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

染指流年丨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值