using UnityEngine;
using LitJson;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace ZXKFramework
{
public class UnityTools : MonoBehaviour
{
public static Sprite ToSprite(Texture2D self)
{
var rect = new Rect(0, 0, self.width, self.height);
var pivot = Vector2.one * 0.5f;
var newSprite = Sprite.Create(self, rect, pivot);
return newSprite;
}
public static string GetJson(object self)
{
string loRes = JsonMapper.ToJson(self);
return StringToUTF8(loRes);
}
public static string StringToUTF8(string self)
{
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
self = reg.Replace(self, delegate (Match m)
{
return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
});
return self;
}
///
/// 存入字典更新位置角度
///
/// 存入的字典
/// 实例化出来的模型名称
/// 位置
/// 角度
///
public static void AddPosAndRotation(Dictionary> DicPosAndRotation, string key, Vector3 vectorPos, Vector3 vectorRotation, GameObject gameObj)
{
List listVec = new List();
listVec.Add(vectorPos);
listVec.Add(vectorRotation);
if (!DicPosAndRotation.ContainsKey(key))
{
DicPosAndRotation.Add(key, listVec);
}
else
{
if (gameObj != null)
{
gameObj.transform.localPosition = DicPosAndRotation[key][0];
gameObj.transform.localEulerAngles = DicPosAndRotation[key][1];
}
}
}
//复制目录文件到指定目录
public static void CopyDirIntoDestDirectory(string sourceFileName, string destFileName, bool overwrite)
{
if (!Directory.Exists(destFileName))
Directory.CreateDirectory(destFileName);
foreach (var file in Directory.GetFiles(sourceFileName))
File.Copy(file, Path.Combine(destFileName, Path.GetFileName(file)), overwrite);
foreach (var d in Directory.GetDirectories(sourceFileName))
CopyDirIntoDestDirectory(d, Path.Combine(destFileName, Path.GetFileName(d)), overwrite);
}
//创建文件夹
public static void CreateDirectory(string destFileName)
{
if (!Directory.Exists(destFileName))
Directory.CreateDirectory(destFileName);
}
//获取所有文件名字
public static List GetFile(string path, List FileList)
{
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] fil = dir.GetFiles();
DirectoryInfo[] dii = dir.GetDirectories();
foreach (FileInfo f in fil)
{
long size = f.Length;
FileList.Add(Path.GetFileNameWithoutExtension(f.Name));
}
foreach (DirectoryInfo d in dii)
{
GetFile(d.Name, FileList);
}
return FileList;
}
//获取指定路径下面的所有资源文件 然后进行删除
public static bool DeleteAllFile(string fullPath)
{
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
for (int i = 0; i < files.Length; i++)
{
string FilePath = fullPath + "/" + files[i].Name;
File.Delete(FilePath);
}
return true;
}
return false;
}
//删除文件
public static void DeleteFile(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
//创建文件
public static void CreateFile(string path)
{
if (!File.Exists(path))
{
File.Create(path);
}
}
public static void OpenDirectory(string path)
{
if (string.IsNullOrEmpty(path)) return;
path = path.Replace("/", "\\");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// 新开线程防止锁死
Thread newThread = new Thread(new ParameterizedThreadStart(CmdOpenDirectory));
newThread.Start(path);
//可能360不信任
//System.Diagnostics.Process.Start("explorer.exe", path);
}
private static void CmdOpenDirectory(object obj)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c start " + obj.ToString();
Debug.Log(p.StartInfo.Arguments);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.WaitForExit();
p.Close();
}
public void FullSceneSet()
{
Screen.fullScreen = !Screen.fullScreen;
if (Screen.fullScreen) Screen.SetResolution(1920, 1080, false);
else Screen.SetResolution(1280, 720, false);
}
///
/// 获取一个随机打乱顺序的数组
///
/// 取出的数组里面要有多少个数
/// 随机数组的范围(最后的一个数)
/// 随机数组的范围(第一个数)
public static int[] GetRandomSequence(int rangNum, int endNum, int startNum = 0)
{
try
{
//随机总数组
int[] sequence = new int[endNum - startNum + 1];
//取到的不重复数字的数组长度
int[] output = new int[rangNum];
for (int i = startNum; i < endNum + 1; i++)
{
sequence[i - startNum] = i;
}
for (int i = 0; i < rangNum; i++)
{
//随机一个数,每随机一次,随机区间-1
int Num = UnityEngine.Random.Range(startNum, endNum + 1);
output[i] = sequence[Num - startNum];
//将区间最后一个数赋值到取到数上
sequence[Num - startNum] = sequence[endNum - startNum];
endNum--;
//执行一次效果如:1,2,3,4,5 取到2
//则下次随机区间变为1,5,3,4;
}
return output;
}
catch (Exception e)
{
Debug.LogError($"GetRandomSequence is Error:{e.ToString()}");
return null;
}
}
///
/// 获取时间戳13位
///
public static string GetTimeStamp()
{
return DateTimeOffset.Now.ToUnixTimeSeconds() + "000";
}
///
/// 两个时间戳相差多少秒
///
public static int TimeStampDiffSeconds(string t1, string t2)
{
return Mathf.Abs(Convert.ToInt32((ConvertToTime(t1) - ConvertToTime(t2)).TotalSeconds));
}
///
/// 时间戳转换成标准时间
///
public static DateTime ConvertToTime(string timeStamp)
{
string ID = TimeZoneInfo.Local.Id;
DateTime start = new DateTime(1970, 1, 1) + TimeZoneInfo.Local.GetUtcOffset(DateTime.Now);
DateTime dtStart = TimeZoneInfo.ConvertTime(start, TimeZoneInfo.FindSystemTimeZoneById(ID));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
DateTime time = dtStart.Add(toNow);
return time;
}
///
/// JSON字符串格式化
///
public static string JsonTree(string json)
{
int level = 0;
var jsonArr = json.ToArray(); // Using System.Linq;
string jsonTree = string.Empty;
for (int i = 0; i < json.Length; i++)
{
char c = jsonArr[i];
if (level > 0 && '\n' == jsonTree.ToArray()[jsonTree.Length - 1])
{
jsonTree += TreeLevel(level);
}
switch (c)
{
case '[':
jsonTree += c + "\n";
level++;
break;
case ',':
jsonTree += c + "\n";
break;
case ']':
jsonTree += "\n";
level--;
jsonTree += TreeLevel(level);
jsonTree += c;
break;
default:
jsonTree += c;
break;
}
}
return jsonTree;
}
///
/// 树等级
///
private static string TreeLevel(int level)
{
string leaf = string.Empty;
for (int t = 0; t < level; t++)
{
leaf += "\t";
}
return leaf;
}
///
/// 解析URL中的参数
///
public static string GetURLParameters(string url)
{
if (string.IsNullOrEmpty(url)) return null;
var paramStr = url.Split('?')[1];
var paramList = paramStr.Split('&');
if (paramList == null || paramList.Count() <= 0) return null;
return paramList.ToDictionary(e => Regex.Split(e, "=")[0], e => Regex.Split(e, "=")[1])["ticket"];
}
///
/// MD5 32位 大写加密
///
public static string MD5Encrypt32Big(string encryptContent)
{
string content = encryptContent;
//创建一个MD5CryptoServiceProvider对象的新实例。
MD5 md5 = MD5.Create();
//将输入的字符串转换为一个字节数组并计算哈希值。
byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(content));
//创建一个StringBuilder对象,用来收集字节数组中的每一个字节,然后创建一个字符串。
StringBuilder sb = new StringBuilder();
//遍历字节数组,将每一个字节转换为十六进制字符串后,追加到StringBuilder实例的结尾
for (int i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString("X2"));
}
//返回一个十六进制字符串
content = sb.ToString();
if (content.Length < 32)
Debug.LogError("32位 加密错误!!长度不对");
return content;
}
}
}