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

Unity中如何保存和加载TMP_Dropdown下拉菜单的选中值

TMP_Dropdown 选中项持久化保存/加载实现

你的思路完全正确,用int类型存储选中项索引是最简便的方案,直接用Unity内置的PlayerPrefs就能实现配置的本地持久化,重启游戏、跨场景都能保留用户选择。

实现逻辑

  • 存储时机:用户切换下拉选项时,将当前选中的索引值写入本地存储
  • 加载时机:初始化下拉菜单所有选项后,读取本地存储的索引值,赋值给下拉组件并刷新显示
  • 兜底逻辑:首次启动无本地存储数据时,指定默认选中项,避免空值报错

修改后完整代码

using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class TimeDropdownController : MonoBehaviour
{
    [SerializeField] private TMP_Dropdown timeDropdown;
    [SerializeField] private TMP_Text timeText;
    // 本地存储的键名,避免硬编码写错
    private const string TIME_DISPLAY_SAVE_KEY = "SelectedTimeFormatIndex";

    private void Start() {
        timeDropdown.options.Clear();
        List<string> items = new() {
            "",
            DateTime.Now.ToString(),
            DateTime.Now.ToLongDateString(),
            DateTime.Now.ToLongTimeString()
        };

        foreach(var item in items) {
            timeDropdown.options.Add(new TMP_Dropdown.OptionData() {
                text = item
            });
        }

        // 加载已保存的选中索引,第二个参数是首次启动的默认选中索引,这里设为1跳过第一个空字符串项
        int savedIndex = PlayerPrefs.GetInt(TIME_DISPLAY_SAVE_KEY, 1);
        // 赋值时不触发onValueChanged事件,避免重复调用回调
        timeDropdown.SetValueWithoutNotify(savedIndex);
        // 手动刷新时间显示
        DropdownItemSelected(timeDropdown);

        timeDropdown.onValueChanged.AddListener(delegate {
            DropdownItemSelected(timeDropdown);
        });
    }

    void DropdownItemSelected(TMP_Dropdown timeDropdown) {
        int index = timeDropdown.value;
        timeText.text = timeDropdown.options[index].text;
        // 将当前选中索引写入本地存储
        PlayerPrefs.SetInt(TIME_DISPLAY_SAVE_KEY, index);
        PlayerPrefs.Save();
    }
}

注意点

  • 代码里默认选中索引设为1,是因为你原有选项列表第一个是空字符串,如果需要默认选其他项,直接修改PlayerPrefs.GetInt的第二个参数即可
  • SetValueWithoutNotify赋值可以避免初始化加载时重复触发值变更事件,减少不必要的写入操作
  • PlayerPrefs.Save会立即将数据写入磁盘,如果不手动调用,游戏会在OnApplicationQuit时自动批量写入,手动调用更稳妥,避免游戏异常崩溃时配置丢失

内容的提问来源于stack exchange,提问作者user17646297

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 21:33:19