Skip to content

Instantly share code, notes, and snippets.

@drawcode
Created December 16, 2012 07:24
Show Gist options
  • Save drawcode/4304004 to your computer and use it in GitHub Desktop.
Save drawcode/4304004 to your computer and use it in GitHub Desktop.
Base file used in some Unity projects for loading items from different sources.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
#if !UNITY_WEBPLAYER
using System.Reflection;
using System.IO;
#endif
public enum DataObjectsStorage {
RESOURCES,
PERSISTENT,
PREFERENCES,
SERVER
}
public class DataObjects<T> {
public List<T> items;
public string pathKey = "";
public string path = "";
public List<string> packPaths;
public List<string> packPathsVersioned;
public DataObjectsStorage dataStorage = DataObjectsStorage.PERSISTENT;
public DataObjects() {
Reset();
}
public virtual void LoadData() {
switch (dataStorage) {
case DataObjectsStorage.SERVER:
Debug.Log("LoadDataFromServer:" + path + " " + pathKey);
LoadDataFromServer();
break;
case DataObjectsStorage.RESOURCES:
Debug.Log("LoadDataFromResources:" + path + " " + pathKey);
LoadDataFromResources();
break;
case DataObjectsStorage.PREFERENCES:
Debug.Log("LoadDataFromResources:" + path + " " + pathKey);
LoadDataFromPrefs();
break;
default:
Debug.Log("LoadDataFromPersistent:" + path + " " + pathKey);
LoadDataFromPersistent();
break;
}
}
public virtual void LoadDataFromPersistent() {
LoadDataFromPersistent(path);
}
public virtual void LoadDataFromResources() {
string data = LoadDataFromResources(path);
//LogUtil.Log("BaseGameAchievements:" + data);
LoadDataFromString(data);
}
public virtual void LoadDataFromPrefs() {
string data = LoadDataFromPrefs(pathKey);
LoadDataFromString(data);
}
public void LoadDataFromServer() {
// TODO
LoadDataFromServer(path);
}
public void LoadDataFromServer(string key) {
// TODO
}
public string LoadDataFromPrefs(string key) {
string data = "";
if (!SystemPrefUtil.HasLocalSetting(key)) {
data = SystemPrefUtil.GetLocalSettingString(key);
}
return data;
}
public string LoadDataFromPersistent(string path) {
return LoadDataFromPersistent(path, true);
}
public string LoadDataFromPersistent(string path, bool versioned) {
string fileData = "";
fileData = Contents.Instance.GetFileDataFromPersistentCache(path, versioned, false);
LoadDataFromString(fileData);
//if(!string.IsNullOrEmpty(fileData)) {
//string log = fileData;
//if(fileData.Length > 1000) {
// log = fileData.Substring(0, 990);
//}
////Debug.Log("LoadDataFromPersistent:fileData:" + log + " " + pathKey);
//}
////Debug.Log(">>>LoadDataFromPersistentPacks:" + path);
LoadDataFromPersistentPacks(path);
return fileData;
}
public bool SaveDataItemsToPersistent(string path) {
bool saved = false;
string fileData = "";
string pathPart = path;
path = Path.Combine(Contents.Instance.appCacheVersionPath, path);
string pathVersioned = Contents.Instance.GetFileVersioned(path);
Debug.Log("LoadDataFromPersistent:path:" + path);
Debug.Log("LoadDataFromPersistent:pathVersioned:" + pathVersioned + " " + pathKey);
bool prepared = PreparePersistentFile(pathPart, pathVersioned);
if (!prepared)
return false;
fileData = JsonMapper.ToJson(items);
FileSystemUtil.WriteString(pathVersioned, fileData);
Debug.Log("SaveDataItemsToPersistent:fileData:" + fileData + " " + pathKey);
saved = true;
return saved;
}
public bool SaveDataItemToPersistent(T obj, string path) {
bool saved = false;
string fileData = "";
string pathPart = path;
path = Path.Combine(Contents.Instance.appCacheVersionPath, path);
string pathVersioned = Contents.Instance.GetFileVersioned(path);
Debug.Log("LoadDataFromPersistent:path:" + path);
Debug.Log("LoadDataFromPersistent:pathVersioned:" + pathVersioned + " " + pathKey);
bool prepared = PreparePersistentFile(pathPart, pathVersioned);
if (!prepared)
return false;
fileData = JsonMapper.ToJson(obj);
FileSystemUtil.WriteString(pathVersioned, fileData);
Debug.Log("SaveDataItemsToPersistent:fileData:" + fileData + " " + pathKey);
saved = true;
return saved;
}
public bool PreparePersistentFile(string pathPart, string pathVersioned) {
bool prepared = true;
if (!File.Exists(pathVersioned)) {
prepared = false;
Debug.Log("LoadDataFromPersistent:pathVersioned not exist:" + pathVersioned + " " + pathKey);
// copy from streaming assets
string pathToCopy = Path.Combine(Contents.Instance.appCacheVersionPath, pathPart);
Debug.Log("LoadDataFromPersistent:pathToCopy:" + pathToCopy + " " + pathKey);
if (File.Exists(pathToCopy)) {
FileSystemUtil.MoveFile(pathToCopy, pathVersioned);
Debug.Log("LoadDataFromPersistent:file moved:" + pathToCopy + " " + pathKey);
prepared = true;
}
else {
Debug.Log("LoadDataFromPersistent:move not exist:" + pathToCopy + " " + pathKey);
prepared = false;
}
}
return prepared;
}
public void LoadDataFromPersistentPacks(string path) {
// Append data from additional pack data files
List<T> appendList = new List<T>();
List<T> appendItemList = new List<T>();
foreach (string packPath in Contents.Instance.GetPackPathsVersioned()) {
string data = "";
string pathData = Path.Combine(packPath, path);
string[] packDirs = packPath.TrimEnd(Path.DirectorySeparatorChar).Replace("data", "").TrimEnd(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
string packDirName = packDirs[packDirs.Length - 1];
string fileVersioned = Contents.Instance.GetFullPathVersioned(pathData);
if (File.Exists(fileVersioned)) {
data = Contents.Instance.GetFileDataFromPersistentCache(pathData, true, true);
}
if (!string.IsNullOrEmpty(data)) {
List<T> objs = new List<T>();
objs = LoadDataFromString(appendItemList, data);
int i = 0;
if (packDirName.Contains("app-viewer")) {
}
else {
i = 500;
}
for (int j = 0; j < objs.Count; j++) {
SetFieldValue(objs[j], "pack_code", packDirName);
SetFieldValue(objs[j], "pack_sort", i++);
}
if (objs != null && objs.Count > 0) {
appendList.AddRange(objs);
}
}
}
////Debug.Log("!!!!!! PackPathsVersionShared:" + Contents.Instance.GetPackPathsVersionedShared().Count);
foreach (string packPath in Contents.Instance.GetPackPathsVersionedShared()) {
string data = "";
string pathData = Path.Combine(packPath, path);
string[] packDirs = packPath.TrimEnd(Path.DirectorySeparatorChar).Replace("data", "").TrimEnd(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
string packDirName = packDirs[packDirs.Length - 1];
string fileVersioned = Contents.Instance.GetFullPathVersioned(pathData);
if (File.Exists(fileVersioned)) {
data = Contents.Instance.GetFileDataFromPersistentCache(pathData, true, true);
}
if (!string.IsNullOrEmpty(data)) {
List<T> objs = new List<T>();
objs = LoadDataFromString(appendItemList, data);
int i = 0;
if (packDirName.Contains("app-viewer")) {
}
else {
i = 500;
}
for (int j = 0; j < objs.Count; j++) {
SetFieldValue(objs[j], "pack_code", packDirName);
SetFieldValue(objs[j], "pack_sort", i++);
}
if (objs != null && objs.Count > 0) {
appendList.AddRange(objs);
}
}
}
foreach (string packPath in Contents.Instance.GetPackPathsNonVersioned()) {
string data = "";
string pathData = Path.Combine(packPath, path);
string[] packDirs = packPath.TrimEnd(Path.DirectorySeparatorChar).Replace("data", "").TrimEnd(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
string packDirName = packDirs[packDirs.Length - 1];
if (string.IsNullOrEmpty(packDirName)) {
packDirName = "";
}
string fileVersioned = Contents.Instance.GetFullPathVersioned(pathData);
if (File.Exists(fileVersioned)) {
////Debug.Log(">> PACK FILE EXISTS: " + pathData);
data = Contents.Instance.GetFileDataFromPersistentCache(pathData, true, true);
////Debug.Log(">> PACK FILE DATA: " + data);
}
if (!string.IsNullOrEmpty(data)) {
if (!string.IsNullOrEmpty(data)) {
List<T> objs = new List<T>();
objs = LoadDataFromString(appendItemList, data);
int i = 0;
if (packDirName.Contains("app-viewer")) {
}
else {
i = 500;
}
for (int j = 0; j < objs.Count; j++) {
SetFieldValue(objs[j], "pack_code", packDirName);
SetFieldValue(objs[j], "pack_sort", i++);
}
if (objs != null && objs.Count > 0) {
appendList.AddRange(objs);
}
}
}
}
items.AddRange(appendList);
}
public string LoadDataFromResources(string resourcesPath) {
string fileData = "";
////Debug.Log("LoadDataFromResources:resourcesPath:" + resourcesPath + " " + pathKey);
TextAsset textData = Resources.Load(resourcesPath, typeof(TextAsset)) as TextAsset;
if (textData != null) {
fileData = textData.text;
}
LoadDataFromString(fileData);
////Debug.Log("LoadDataFromResources:fileData:" + fileData + " " + pathKey);
return fileData;
}
public virtual void LoadDataFromString(string data) {
if (!string.IsNullOrEmpty(data)) {
items.Clear();
items = LoadDataFromString(items, data);
}
}
public virtual List<T> LoadDataFromString(List<T> objs, string data) {
if (!string.IsNullOrEmpty(data)) {
objs = JsonMapper.ToObject<List<T>>(data);
//LogUtil.Log("T loaded:" + objs.Count);
for (int j = 0; j < objs.Count; j++) {
SetFieldValue(objs[j], "pack_code", "default");
}
}
return objs;
}
public T GetById(string id) {
return GetByStringKey("code", id);
}
public T GetByPackCode(string packCode) {
return GetByStringKey("pack_code", packCode);
}
public bool CheckById(string id) {
return CheckByStringKey("code", id);
}
public T GetByUuid(string id) {
return GetByStringKey("uuid", id);
}
public bool CheckByUuid(string id) {
return CheckByStringKey("uuid", id);
}
public T GetByName(string id) {
return GetByStringKey("name", id);
}
public bool CheckByName(string id) {
return CheckByStringKey("name", id);
}
public T GetByStringKey(string key, string keyValue) {
foreach (T obj in GetAll()) {
try {
bool found = false;
foreach (System.Reflection.FieldInfo fieldInfo in obj.GetType().GetFields()) {
if (fieldInfo.Name == key) {
found = true;
break;
}
}
if (found) {
string codeValue = (string)obj.GetType().GetField(key).GetValue(obj);
if (codeValue.ToLower() == keyValue.ToLower()) {
return obj;
}
}
else {
foreach (System.Reflection.PropertyInfo propInfo in obj.GetType().GetProperties()) {
if (propInfo.Name == key) {
found = true;
break;
}
}
if (found) {
string codeValue = (string)obj.GetType().GetProperty(key).GetValue(obj, null);
if (codeValue.ToLower() == keyValue.ToLower()) {
return obj;
}
}
}
}
catch (Exception e) {
Debug.Log("GetByStringKey warning no key:" + e);
return default(T);
}
}
return default(T);
}
public object GetFieldValue(object obj, string fieldName) {
////Debug.Log("GetFieldValue:obj.GetType():" + obj.GetType());
bool hasGet = false;
foreach (var prop in fieldName.Split('.').Select(s => obj.GetType().GetField(s))) {
if (obj != null) {
obj = prop.GetValue(obj);
hasGet = true;
}
}
if (!hasGet) {
foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
if (prop.Name == fieldName) {
obj = prop.GetValue(obj, null);
}
}
}
return obj;
}
public void SetFieldValue(object obj, string fieldName, object fieldValue) {
////Debug.Log("SetFieldValue:obj.GetType():" + obj.GetType());
//bool hasSet = false;
foreach (FieldInfo field in fieldName.Split('.').Select(s => obj.GetType().GetField(s))) {
if (field != null) {
field.SetValue(obj, fieldValue);
//hasSet = true;
}
}
//if(!hasSet) {
foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
if (prop.Name == fieldName) {
prop.SetValue(obj, fieldValue, null);
}
}
//}
}
public bool CheckByStringKey(string key, string keyValue) {
foreach (T obj in GetAll()) {
try {
bool found = false;
foreach (System.Reflection.FieldInfo fieldInfo in obj.GetType().GetFields()) {
if (fieldInfo.Name == key) {
found = true;
break;
}
}
if (found) {
string codeValue = (string)obj.GetType().GetField(key).GetValue(obj);
if (codeValue.ToLower() == keyValue.ToLower()) {
return true;
}
}
}
catch (Exception e) {
Debug.Log("GetByStringKey warning no key:" + e);
return false;
}
}
return false;
}
public List<T> GetAll() {
if (!IsLoaded) {
LoadData();
items.Sort(
delegate(T c1, T c2) {
if (c1.GetType().GetField("sort_order") != null) {
int sort1 = (int)c1.GetType().GetField("sort_order").GetValue(c1);
int sort2 = (int)c2.GetType().GetField("sort_order").GetValue(c2);
return sort1.CompareTo(sort2);
}
else {
return -1;
}
}
);
}
return items;
}
public virtual bool IsLoaded {
get {
return items.Count > 0 ? true : false;
}
}
public virtual void Reset() {
items = new List<T>();
packPaths = new List<string>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment