Unity/Csharp/Cache
ナビゲーションに移動
検索に移動
サンプル
一定時間だけcacheするサンプルライブラリ。
- 取得
Debug.Log("key1=" + Cache.GetCache("key1"));
- 設定
Cache.SetCache("key1", "hoge", 60);
60秒だけ保存
ライブラリ
Cache.cs
using UnityEngine;
using System;
/**
* キャッシュクラス
* 取得:
* Debug.Log("key1=" + Cache.GetCache("key1"));
* 設定:
* Cache.SetCache("key1", "hoge", 60);
*/
public class Cache {
static string cacheKey = "cacheKey";
/// <summary>
/// 指定されたオブジェクトの情報を保存します
/// </summary>
private static void SetObject<T>(string key, T obj)
{
string json = JsonUtility.ToJson(obj);
Debug.Log("key=" + key);
Debug.Log("SetObject json=" + json);
PlayerPrefs.SetString(key, json);
}
/// <summary>
/// 指定されたオブジェクトの情報を読み込みます
/// </summary>
private static T GetObject<T>(string key)
{
string json = PlayerPrefs.GetString(key);
Debug.Log("key=" + key);
Debug.Log("GetObject json=" + json);
return JsonUtility.FromJson<T>(json);
}
private static void DelObject<T>(string key)
{
PlayerPrefs.SetString(key, null);
}
private static void SetObjectCache<T>(string key, T obj)
{
SetObject(cacheKey + "-" + key, obj);
}
private static T GetObjectCache<T>(string key)
{
return GetObject<T>(cacheKey + "-" + key);
}
private static void DelObjectCache<T>(string key)
{
DelObject<T>(cacheKey + "-" + key);
}
// keyと値と保持秒数
public static void SetCache(string key, string value, int lifetimeSec)
{
CacheRow cache = new CacheRow();
cache.data = value;
cache.limitUnixtime = Now() + lifetimeSec;
SetObjectCache(key, cache);
}
public static string GetCache(string key) {
CacheRow cache = GetObjectCache<CacheRow>(key);
if (cache != null) {
if (Now() < cache.limitUnixtime)
{
return cache.data;
}
else
{
DelCache(key); // 削除しておく。
}
}
return "";
}
public static void DelCache(string key)
{
DelObjectCache<string>(key);
}
private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long Now()
{
return (FromDateTime(DateTime.UtcNow));
}
public static long FromDateTime(DateTime dateTime)
{
double nowTicks = (dateTime.ToUniversalTime() - UNIX_EPOCH).TotalSeconds;
return (long)nowTicks;
}
}
CacheRow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class CacheRow
{
[SerializeField]
public String data = "";
[SerializeField]
public long limitUnixtime = 0;
}