PR

【Unityプラグイン】PlayerPrefsを編集するエディタを使おう!

PlayerPrefsを編集しよう! Unity

スクリプト内容(転載防止用)

using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEditor;
using UnityEngine;
using System.IO;

namespace TedLab.Editor
{
   public class PlayerPrefsEditor : EditorWindow
   {
      [Serializable]
      public class KeyInfo
      {
         public string name;

         public enum ValueType
         {
            Int,
            Float,
            String,
         }
         public ValueType type;

         public string Value
         {
            get => _value;
            set => _value = value;
         }
         private string _value = "";
      }
      public List<KeyInfo> keys = new(32);

      private const string EditorPrefix = "TedLab_PlayerPrefsEditor_";
      private const string KeysCountKey = EditorPrefix + "KeysCount";
      private const string KeysPrefixKey = EditorPrefix + "Keys";
      private const string KeyTypesPrefixKey = EditorPrefix + "KeyTypes";

      private SerializedObject _keysSerializedObj;
      private SerializedProperty _keysProp;
      private Vector2 _scrollPosition = Vector2.zero;

      private void OnEnable()
      {
         _keysSerializedObj = new SerializedObject(this);
         _keysProp = _keysSerializedObj.FindProperty("keys");
      
         keys.Clear();
         var count = EditorPrefs.GetInt( KeysCountKey, 0 );
         for( var i=0; i<count; ++i )
         {
            var indexStr = i.ToString("D2");
            var key = EditorPrefs.GetString( KeysPrefixKey + indexStr, "" );
            var keyType= EditorPrefs.GetString( KeyTypesPrefixKey + indexStr, "" );
            keys.Add(
               new KeyInfo(){ 
                  name = key, 
                  type = (KeyInfo.ValueType)Enum.Parse(typeof(KeyInfo.ValueType), keyType),
               });
         }
         UpdatePlayPrefs();
      }
      
      private void OnDisable()
      {
         var count = keys.Count;
         EditorPrefs.SetInt( KeysCountKey, count );
         for( var i=0; i<count; ++i )
         {
            var keyInfo = keys[i];
            var indexStr = i.ToString("D2");
            EditorPrefs.SetString( KeysPrefixKey + indexStr, keyInfo.name );
            EditorPrefs.SetString( KeyTypesPrefixKey + indexStr, keyInfo.type.ToString() );
         }
      }


      [MenuItem("TedLab/PlayerPrefs Editor")]
      private static void OpenWindow()
      {
         var window = GetWindow<PlayerPrefsEditor>();
         window.titleContent = new GUIContent("PlayerPrefs Editor");
         window.Show();
      }

      private void OnGUI()
      {
         using var scrollView = new EditorGUILayout.ScrollViewScope(_scrollPosition);
         _scrollPosition = scrollView.scrollPosition;
         
         GUILayout.Label("Settings", EditorStyles.boldLabel);
         _keysSerializedObj.Update();
         EditorGUILayout.PropertyField(_keysProp, true);
         if (_keysSerializedObj.ApplyModifiedProperties()) 
         {
            Refresh();
         }
         
         GUILayout.Space(10f);
         
         GUILayout.Label("PlayerPrefs", EditorStyles.boldLabel);
         Action buttonAction = null;
         using (new EditorGUILayout.HorizontalScope())
         {
            if (GUILayout.Button("Refresh", GUILayout.Width(60f))){
               buttonAction = Refresh;
            }
            if (GUILayout.Button("Export", GUILayout.Width(60f))){
               buttonAction = ExportFile;
            }
            if (GUILayout.Button("Import", GUILayout.Width(60f))){
               buttonAction = ImportFile;
            }
         }
         buttonAction?.Invoke();

         foreach (var key in keys)
         {
            using (new EditorGUILayout.HorizontalScope())
            {
               EditorGUILayout.LabelField(key.name);

               if (!PlayerPrefs.HasKey(key.name))
               {
                  key.Value = EditorGUILayout.TextField(key.Value);
                  if (GUILayout.Button("Create", GUILayout.Width(60f)))
                  {
                     SetPlayerPref(key.type, key.name, key.Value);
                     PlayerPrefs.Save();
                  }

                  GUILayout.FlexibleSpace();
               }
               else
               {
                  key.Value = EditorGUILayout.TextField(key.Value);
                  if (GUILayout.Button("Save", GUILayout.Width(50f)))
                  {
                     SetPlayerPref(key.type, key.name, key.Value);
                     PlayerPrefs.Save();
                  }

                  if (GUILayout.Button("Delete", GUILayout.Width(60f)))
                  {
                     PlayerPrefs.DeleteKey(key.name);
                     PlayerPrefs.Save();
                  }

                  if (GUILayout.Button("Copy", GUILayout.Width(50f)))
                  {
                     GUIUtility.systemCopyBuffer = key.Value;
                  }

                  GUILayout.FlexibleSpace();
               }
            }
         }
      }

      private void Refresh()
      {
         UpdatePlayPrefs();
         Repaint();
      }

      private const string SeparatorExport = "<TedLabSeparator>";
      private const string FileExtension = "tpp";

      private void ExportFile()
      {
         var path = EditorUtility.SaveFilePanel("PlayerPrefsファイルをエクスポート", Application.dataPath, "PlayerPrefs"+"."+FileExtension, FileExtension);
         if (string.IsNullOrEmpty(path))
            return;

         var exportText = CreateDataText(SeparatorExport);
         File.WriteAllText(path, exportText);
      }

      private string CreateDataText(string separator)
      {
         var outputText = "";
         foreach (var key in keys){
            outputText += key.name + separator + key.type + separator + key.Value + Environment.NewLine;
         }
         return outputText;
      }
      
      private void ImportFile()
      {
         var path = EditorUtility.OpenFilePanel("PlayerPrefsファイルをインポート", Application.dataPath, FileExtension);
         if (string.IsNullOrEmpty(path))
            return;
         
         var importText = File.ReadAllText(path);
         var lines = importText.Split(Environment.NewLine);
         
         keys.Clear();
         var valueType = typeof(KeyInfo.ValueType);
         foreach (var line in lines)
         {
            if (string.IsNullOrEmpty(line)){
               continue;
            }
            var dataList = line.Split(SeparatorExport);
            if (dataList.Length <= 0){
               continue;
            }
            var key = new KeyInfo();
            for (var i = 0; i < 3; ++i)
            {
               if (i >= dataList.Length){
                  break;
               }
               switch (i){
                  case 0: key.name = dataList[i]; break;
                  case 1: key.type = (KeyInfo.ValueType)Enum.Parse(valueType, dataList[i]); break;
                  case 2: key.Value = dataList[i]; break;
               }
            }
            keys.Add(key);
         }
         SaveAll();
      }

      private void SaveAll()
      {
         foreach (var key in keys)
         {
            SetPlayerPref(key.type, key.name, key.Value);
         }
         PlayerPrefs.Save();
      }


      private void UpdatePlayPrefs()
      {
         foreach (var key in keys)
         {
            var value = key.type switch
            {
               KeyInfo.ValueType.Int => PlayerPrefs.GetInt(key.name).ToString(),
               KeyInfo.ValueType.Float => PlayerPrefs.GetFloat(key.name).ToString(CultureInfo.InvariantCulture),
               KeyInfo.ValueType.String => PlayerPrefs.GetString(key.name),
               _ => throw new ArgumentOutOfRangeException()
            };
            key.Value = value;
         }
      }

      private void SetPlayerPref(KeyInfo.ValueType type, string keyName, string newValue)
      {
         switch (type)
         {
            case KeyInfo.ValueType.Int:
               PlayerPrefs.SetInt(keyName, int.Parse(newValue));
               break;
            case KeyInfo.ValueType.Float:
               PlayerPrefs.SetFloat(keyName, float.Parse(newValue));
               break;
            case KeyInfo.ValueType.String:
               PlayerPrefs.SetString(keyName, newValue);
               break;
            default:
               throw new ArgumentOutOfRangeException();
         }
      }
   }
}

コメント

スポンサーリンク
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

タイトルとURLをコピーしました