using System.Collections.Generic;
using NUnit.Framework;
using UnityEditor;
using UnityEditor.Search;
using UnityEngine;
static class Example_PropertyDatabase
{
// Where the property database will be written.
const string propertyDatabaseFilePath = "Temp/test_property_db";
static PropertyDatabase propertyDatabase;
static void InitializePropertyDatabase()
{
// Setup the property database. We configure it with automatic flushing so the file store
// will be updated automatically after an update.
propertyDatabase = new PropertyDatabase(propertyDatabaseFilePath, true);
}
static void ClearPropertyDatabase()
{
propertyDatabase.Clear();
// Since we are done with the property database, we should dispose it
// to clear all resources.
propertyDatabase.Dispose();
}
static PropertyDatabaseRecordKey GetPropertyKey(int id)
{
return PropertyDatabase.CreateRecordKey((ulong)id / 100, PropertyDatabase.CreatePropertyHash((id % 100).ToString()));
}
static object LoadPropertyValue(int id)
{
var recordKey = GetPropertyKey(id);
if (propertyDatabase.TryLoad(recordKey, out object value))
return value;
// Fetch the value with the time consuming operation and store it for future
// accesses.
value = id.ToString();
propertyDatabase.Store(recordKey, value);
return value;
}
[MenuItem("Examples/PropertyDatabase/Class")]
public static void RunExample()
{
InitializePropertyDatabase();
if (!propertyDatabase.valid)
{
Debug.LogFormat(LogType.Error, LogOption.NoStacktrace, null, $"PropertyDatabase \"{propertyDatabase.filePath}\" failed to open properly.");
return;
}
var allValues = new Dictionary<int, object>();
// Load the property values to do something with it.
for (var i = 0; i < 1000; ++i)
{
var value = LoadPropertyValue(i);
allValues.Add(i, value);
}
// Validate everything is in the database
for (var i = 0; i < 1000; ++i)
{
var key = GetPropertyKey(i);
if (!propertyDatabase.TryLoad(key, out object value))
Assert.Fail("Record should be in the database.");
Assert.AreEqual(i.ToString(), value);
}
ClearPropertyDatabase();
}
}