本文主要是介绍Unity3D:用泛型T实现数据的读写,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
通常我们单机游戏或者弱联网游戏,会有部分数据存储在本地。该数据本身为一个变量,需要有读写操作,但针对每个变量写一套函数就很麻烦。
于是可以使用泛型T做一个统一的操作处理:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ReadWrite
{public static readonly ReadWrite Inst = Singleton<ReadWrite>.Inst;public enum DateKey{name,//姓名coin,//钻石gold,//金币 }public SingletonDate<string> name = new SingletonDate<string>(DateKey.name);public SingletonDate<int> coin = new SingletonDate<int>(DateKey.coin);public SingletonDate<float> gold = new SingletonDate<float>(DateKey.gold);public void Start(){Debug.Log(coin.Read(true));coin.Write(213412);Debug.Log(coin.Read());Debug.Log(gold.Read(true));gold.Write(1342.342f);Debug.Log(gold.Read());Debug.Log(name.Read(true));name.Write("小明");Debug.Log(name.Read());}}/// <summary>
/// 唯一数据
/// </summary>
public class SingletonDate<T>
{public T date;public SingletonDate(ReadWrite.DateKey _name) { name = _name.ToString(); }public string name;public T Read(bool _isStart = false){if (!_isStart) return date;bool _isHas = PlayerPrefs.HasKey(name);Debug.LogError("type : " + typeof(T).Name);switch (typeof(T).Name){case "Int32": date = (T)Convert.ChangeType(_isHas ? PlayerPrefs.GetInt(name) : 0, typeof(T)); break;case "Single": date = (T)Convert.ChangeType(_isHas ? PlayerPrefs.GetFloat(name) : 0f, typeof(T)); break;case "String": date = (T)Convert.ChangeType(_isHas ? PlayerPrefs.GetString(name) : "", typeof(T)); break;}if (!_isHas) Write((T)Convert.ChangeType(0, typeof(T)));return date;}public void Write(T _t){date = _t;switch (typeof(T).Name){case "Int32":PlayerPrefs.SetInt(name, Convert.ToInt32(_t));break;case "Single": PlayerPrefs.SetFloat(name, Convert.ToSingle(_t)); break;case "String": PlayerPrefs.SetString(name, Convert.ToString(_t)); break;} }}
测试方法如下:
ReadWrite.Inst.Start();var _name = ReadWrite.Inst.name.Read();Debug.Log(_name);
测试结果:
这篇关于Unity3D:用泛型T实现数据的读写的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!