using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
using System.IO;
using System.Runtime.InteropServices;
using LitJson;
using DragonBones;
using UnityEngine.Networking;
using Transform = UnityEngine.Transform;
#region 网络相关
public enum NetInfoType
{
String,Bytes
}
public struct NetInfo
{
public string infoName;
public NetInfoType infoType;
public string infoString;
public byte [] infoBytes;
public NetInfo(string infoName,string infoString)
{
this.infoName = infoName;
this.infoType = NetInfoType.String;
this.infoString = infoString;
infoBytes = null;
}
public NetInfo(string infoName, byte [] infoBytes)
{
this.infoName = infoName;
this.infoType = NetInfoType.Bytes;
this.infoBytes = infoBytes;
this.infoString = "";
}
}
#endregion
public class UnitManager : MonoBehaviour
{
#region 单例
private static UnitManager main;
public static UnitManager Main
{
get
{
if (main == null)
{
main = new GameObject("UnitManager").AddComponent<UnitManager>();
}
return main;
}
}
public bool isChinese
{
get
{
return Application.systemLanguage == SystemLanguage.Chinese ||
Application.systemLanguage == SystemLanguage.ChineseSimplified ||
Application.systemLanguage == SystemLanguage.ChineseTraditional;
}
}
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
#endregion
#region Wait系列
public void Wait(float time, Action action)
{
StartCoroutine(Wait_IEnumerator(time, action));
}
public void Wait(Action action)
{
StartCoroutine(Wait_IEnumerator(action));
}
private IEnumerator Wait_IEnumerator(float time, Action action)
{
yield return new WaitForSeconds(time);
action();
}
private IEnumerator Wait_IEnumerator(Action action)
{
yield return new WaitForEndOfFrame();
action();
}
#endregion
#region Domove相关
Dictionary<GameObject,int> doNumbers = new Dictionary<GameObject, int>();
private Dictionary<GameObject, Action> doActions = new Dictionary<GameObject, Action>();
private int doNumber;
private IEnumerator DoMove_IEnumerator(RectTransform rect, Vector3 movepos, float time,int number,Vector3 domovepos,float domovetime)
{
yield return new WaitForEndOfFrame();
if (doNumbers.ContainsKey(rect.gameObject))
{
if (doNumbers[rect.gameObject] == number)
{
rect.anchoredPosition = Vector3.Lerp(domovepos, movepos, (Time.time - domovetime) / time);
if ((Time.time - domovetime) / time < 1)
{
StartCoroutine(DoMove_IEnumerator(rect, movepos, time,number,domovepos,domovetime));
}
else
{
doNumbers.Remove(rect.gameObject);
if (doActions.ContainsKey(rect.gameObject))
{
doActions[rect.gameObject]();
doActions.Remove(rect.gameObject);
}
}
}
}
}
public void Domove(RectTransform rect, Vector2 movepos, float time)
{
if (doNumbers.ContainsKey(rect.gameObject))
{
doNumbers[rect.gameObject] = doNumber;
}
else
{
doNumbers.Add(rect.gameObject,doNumber);
}
if (time < 0.1f)
{
time = 0.1f;
}
StartCoroutine(DoMove_IEnumerator(rect, movepos, time,doNumber,rect.anchoredPosition,Time.time));
doNumber++;
}
public void Domove(RectTransform rect, Vector2 movepos, float time,Action action)
{
if (doActions.ContainsKey(rect.gameObject))
{
doActions.Remove(rect.gameObject);
}
doActions.Add(rect.gameObject,action);
Domove(rect,movepos,time);
}
public void DoMoveForSpeed(RectTransform rect, Vector3 movepos, float speed)
{
if (doNumbers.ContainsKey(rect.gameObject))
{
doNumbers[rect.gameObject] = doNumber;
}
else
{
doNumbers.Add(rect.gameObject,doNumber);
}
doNumbers.Add(rect.gameObject,doNumber);
float time = Vector3.Distance(rect.anchoredPosition, movepos) / speed;
if (time < 0.1f)
{
time = 0.1f;
}
StartCoroutine(DoMove_IEnumerator(rect, movepos, time,doNumber,rect.anchoredPosition,Time.time));
doNumber++;
}
public void DoMoveForSpeed(RectTransform rect, Vector3 movepos, float speed,Action action)
{
if (doActions.ContainsKey(rect.gameObject))
{
doActions.Remove(rect.gameObject);
}
doActions.Add(rect.gameObject,action);
DoMoveForSpeed(rect,movepos,speed);
}
#endregion
#region DoShakePos相关
public void DoShakePos(RectTransform rect , float power , float time)
{
if (doNumbers.ContainsKey(rect.gameObject))
{
return;
}
doNumbers.Add(rect.gameObject,doNumber);
if (time < 0.1f)
{
time = 0.1f;
}
StartCoroutine(DoShakePos_IEnumerator(rect, power, time,doNumber,rect.anchoredPosition,Time.time));
doNumber++;
}
private IEnumerator DoShakePos_IEnumerator(RectTransform rect, float power, float time,int number, Vector3 domovepos,float domovetime)
{
yield return new WaitForSeconds(0.05f);
if (doNumbers.ContainsKey(rect.gameObject))
{
if (doNumbers[rect.gameObject] == number)
{
rect.anchoredPosition = new Vector2(domovepos.x + Random.Range(-power,power),domovepos.y + Random.Range(-power,power));
if (Time.time - domovetime > time)
{
rect.anchoredPosition = domovepos;
doNumbers.Remove(rect.gameObject);
if (doActions.ContainsKey(rect.gameObject))
{
doActions[rect.gameObject]();
doActions.Remove(rect.gameObject);
}
}
else
{
StartCoroutine(DoShakePos_IEnumerator(rect, power, time, number, domovepos, domovetime));
}
}
}
}
public void DoShakePos(RectTransform rect, float power, float time,Action action)
{
if (doActions.ContainsKey(rect.gameObject))
{
doActions.Remove(rect.gameObject);
}
doActions.Add(rect.gameObject,action);
DoShakePos(rect,power,time);
}
#endregion
#region 曲线运动
#region RectTransform属性的物体进行曲线运动
/// <summary>
/// 使RectTransform属性的物体进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的RectTransform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="addTime">物体运动的速度,以0.01为基础单位,0.01代表动画播放1秒,同理0.02待变动画播放0.5秒</param>
/// <param name="action">物体运动到终点执行的回调</param>
public void CurveMoveRect(RectTransform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime,Action action)
{
StartCoroutine(CurveMoveRectIE(setPos, startPos, endPos, refer, addTime, action));
}
/// <summary>
/// 使RectTransform属性的物体进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的RectTransform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="addTime">物体运动的速度,以0.01为基础单位,0.01代表动画播放1秒,同理0.02待变动画播放0.5秒</param>
public void CurveMoveRect(RectTransform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime = 0.01f)
{
StartCoroutine(CurveMoveRectIE(setPos, startPos, endPos, refer, addTime, () => { }));
}
/// <summary>
/// 使RectTransform属性的物体进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的RectTransform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="action">物体运动到终点执行的回调</param>
public void CurveMoveRect(RectTransform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,Action action)
{
StartCoroutine(CurveMoveRectIE(setPos, startPos, endPos, refer, 0.01f, action));
}
IEnumerator CurveMoveRectIE(RectTransform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime,Action action, float t = 0.0f)
{
if (t >= 1)
{
action();
yield break;
}
yield return new WaitForSeconds(0.01f);
setPos.anchoredPosition = new Vector2(
(1 - t) * (1 - t) * startPos.x + 2 * t * (1 - t) * refer.x + t * t * endPos.x,
(1 - t) * (1 - t) * startPos.y + 2 * t * (1 - t) * refer.y + t * t * endPos.y);
StartCoroutine(CurveMoveRectIE(setPos,startPos, endPos, refer,addTime,action, t + addTime));
}
#endregion
#region Transform属性的物体依据世界坐标进行曲线运动
/// <summary>
/// 使Transform属性的物体依据世界坐标进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的Transform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="addTime">物体运动的速度,以0.01为基础单位,0.01代表动画播放1秒,同理0.02待变动画播放0.5秒</param>
/// <param name="action">物体运动到终点执行的回调</param>
public void CurveMoveByWorld(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime,Action action)
{
StartCoroutine(CurveMoveByWorldIE(setPos, startPos, endPos, refer, addTime, action));
}
/// <summary>
/// 使Transform属性的物体依据世界坐标进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的Transform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="addTime">物体运动的速度,以0.01为基础单位,0.01代表动画播放1秒,同理0.02待变动画播放0.5秒</param>
public void CurveMoveByWorld(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime = 0.01f)
{
StartCoroutine(CurveMoveByWorldIE(setPos, startPos, endPos, refer, addTime, () => { }));
}
/// <summary>
/// 使Transform属性的物体依据世界坐标进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的Transform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="action">物体运动到终点执行的回调</param>
public void CurveMoveByWorld(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,Action action)
{
StartCoroutine(CurveMoveByWorldIE(setPos, startPos, endPos, refer, 0.01f, action));
}
IEnumerator CurveMoveByWorldIE(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime,Action action, float t = 0.0f)
{
if (t >= 1)
{
action();
yield break;
}
yield return new WaitForSeconds(0.01f);
setPos.position = new Vector2(
(1 - t) * (1 - t) * startPos.x + 2 * t * (1 - t) * refer.x + t * t * endPos.x,
(1 - t) * (1 - t) * startPos.y + 2 * t * (1 - t) * refer.y + t * t * endPos.y);
StartCoroutine(CurveMoveByWorldIE(setPos,startPos, endPos, refer,addTime,action, t + addTime));
}
#endregion
#region Transform属性的物体依据局部坐标进行曲线运动
/// <summary>
/// 使Transform属性的物体依据局部坐标进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的Transform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="addTime">物体运动的速度,以0.01为基础单位,0.01代表动画播放1秒,同理0.02待变动画播放0.5秒</param>
/// <param name="action">物体运动到终点执行的回调</param>
void CurveMoveByLocal(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime,Action action)
{
StartCoroutine(CurveMoveByLocalIE(setPos, startPos, endPos, refer, addTime, action));
}
/// <summary>
/// 使Transform属性的物体依据局部坐标进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的Transform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="addTime">物体运动的速度,以0.01为基础单位,0.01代表动画播放1秒,同理0.02待变动画播放0.5秒</param>
void CurveMoveByLocal(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime = 0.01f)
{
StartCoroutine(CurveMoveByLocalIE(setPos, startPos, endPos, refer, addTime, () => { }));
}
/// <summary>
/// 使Transform属性的物体依据局部坐标进行曲线运动
/// </summary>
/// <param name="setPos">需要运动的物体的Transform属性</param>
/// <param name="startPos">物体运动的起始位置</param>
/// <param name="endPos">物体运动的终止位置</param>
/// <param name="refer">物体运动曲线的偏移参照点</param>
/// <param name="action">物体运动到终点执行的回调</param>
void CurveMoveByLocal(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,Action action)
{
StartCoroutine(CurveMoveByLocalIE(setPos, startPos, endPos, refer, 0.01f, action));
}
IEnumerator CurveMoveByLocalIE(Transform setPos,Vector2 startPos,Vector2 endPos,Vector2 refer,float addTime,Action action, float t = 0.0f)
{
if (t >= 1)
{
action();
yield break;
}
yield return new WaitForSeconds(0.01f);
setPos.localPosition = new Vector2(
(1 - t) * (1 - t) * startPos.x + 2 * t * (1 - t) * refer.x + t * t * endPos.x,
(1 - t) * (1 - t) * startPos.y + 2 * t * (1 - t) * refer.y + t * t * endPos.y);
StartCoroutine(CurveMoveByLocalIE(setPos,startPos, endPos, refer,addTime,action, t + addTime));
}
#endregion
#endregion
#region 其他
public void DoCameraSize(Camera camera, float size, float time)
{
if (doNumbers.ContainsKey(camera.gameObject))
{
doNumbers[camera.gameObject] = doNumber;
}
else
{
doNumbers.Add(camera.gameObject,doNumber);
}
if (time < 0.1f)
{
time = 0.1f;
}
StartCoroutine(IEDoCameraSize(camera,camera.orthographicSize, size, time, Time.time,doNumber));
doNumber++;
}
IEnumerator IEDoCameraSize(Camera camera,float doSize, float size, float time,float doTime,int number)
{
yield return new WaitForEndOfFrame();
if (doNumbers.ContainsKey(camera.gameObject))
{
if (doNumbers[camera.gameObject] == number)
{
camera.orthographicSize = doSize + ((size - doSize) * ((Time.time - doTime) / time));
if ((Time.time - doTime) / time <= 1)
{
StartCoroutine(IEDoCameraSize(camera, doSize, size, time, doTime,number));
}
else
{
camera.orthographicSize = size;
doNumbers.Remove(camera.gameObject);
}
}
}
}
public struct GetPassword
{
public Dictionary<string, string> password;
}
private void OnEnable()
{
if (Application.platform == RuntimePlatform.WindowsEditor)
{
AddPassWordList(Application.dataPath + "/Resources/PassWordList.txt");
AddPassWordList(Application.dataPath + "/Resources/PassWordListTwo.txt");
if (!File.Exists(Application.streamingAssetsPath + "/CreatKey.txt"))
{
try
{
GetPassword passwordList = JsonMapper.ToObject<GetPassword>(Resources.Load<TextAsset>("PassWordListTwo").text);
CreatLocalKey(Application.productName,passwordList,Application.streamingAssetsPath + "/CreatKey.txt");
}
catch{}
}
}
else
{
AppDoor();
}
}
void CreatLocalKey(string password,GetPassword passwordList,string path)
{
StringBuilder stringBuilder = new StringBuilder();
while (password.Length > 0)
{
stringBuilder.Append(password[0] == '"'?"|nAaP@u4ISs&3kxQMHR@5OAYNta#N$%dqmZF-,vzoq(.hzm%1&S(((&JeS|0;d.J3&#v42b(%N|HRiO2$)LkhNjFx3fFRnNv3xgZVK":passwordList.password[password[0].ToString()]);
stringBuilder.Append("/");
password = password.Remove(0, 1);
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
string str = stringBuilder.ToString();
for (int i = 0; i < str.Length; i++)
{
i += Random.Range(100, 250);
if (i < str.Length)
{
stringBuilder.Insert(i, "\n");
}
}
str = stringBuilder.ToString();
StreamWriter writer = new StreamWriter(path);
writer.Write(str);
writer.Close();
// str = str.Substring(Random.Range(0, str.Length - 10000), 10000);
// writer = new StreamWriter(path.Replace(".dll",".pdb"));
// writer.Write(str);
// writer.Close();
}
void LoadKey(string strText,GetPassword passwordList,string contrast)
{
Dictionary<string, string> findBack = new Dictionary<string, string>();
foreach (var passwords in passwordList.password)
{
findBack.Add(passwords.Value, passwords.Key);
}
strText = strText.Replace("\n", "");
string[] strs = strText.Split('/');
StringBuilder stringBuilder = new StringBuilder();
foreach (string str in strs)
{
if (str == "|nAaP@u4ISs&3kxQMHR@5OAYNta#N$%dqmZF-,vzoq(.hzm%1&S(((&JeS|0;d.J3&#v42b(%N|HRiO2$)LkhNjFx3fFRnNv3xgZVK")
{
stringBuilder.Append('"');
}
else
{
if (findBack.ContainsKey(str))
{
stringBuilder.Append(findBack[str]);
}
else
{
Application.Quit();
return;
}
}
}
if (contrast != stringBuilder.ToString())
{
Application.Quit();
}
}
void AppDoor()
{
GetPassword passwordList = JsonMapper.ToObject<GetPassword>(Resources.Load<TextAsset>("PassWordList").text);
GetPassword passwordList2 = JsonMapper.ToObject<GetPassword>(Resources.Load<TextAsset>("PassWordListTwo").text);
string creakKeyPath = Application.streamingAssetsPath + "/CreatKey.txt";
string localKeyPath = Application.streamingAssetsPath.Replace("StreamingAssets", "Managed") + "/UnityEngine.UnityWebRequestPhysicsModule.dll";
if (!(File.Exists(creakKeyPath) ^ File.Exists(localKeyPath)))
{
Application.Quit();
return;
}
string readText = "";
if (File.Exists(creakKeyPath))
{
StreamReader reader = new StreamReader(creakKeyPath);
readText = reader.ReadToEnd();
reader.Close();
File.Delete(creakKeyPath);
LoadKey(readText,passwordList2,Application.productName);
CreatLocalKey(SystemInfo.deviceUniqueIdentifier,passwordList,localKeyPath);
}
else
{
StreamReader reader = new StreamReader(localKeyPath);
readText = reader.ReadToEnd();
reader.Close();
LoadKey(readText,passwordList,SystemInfo.deviceUniqueIdentifier);
}
}
void AddPassWordList(string path)
{
if(File.Exists(path)){return;}
List<string> adds = new List<string>
{
"!","@","#","$","%","^","&","*","(",")","_","-","+","=","Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",",",".",";","|",
"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m","1","2","3","4","5","6","7","8","9","0",
};
GetPassword password = new GetPassword();
password.password = new Dictionary<string, string>();
foreach (string add in adds)
{
password.password.Add(add,"");
}
StringBuilder str = new StringBuilder();
List<string> lists = new List<string>();
foreach (var key in password.password)
{
lists.Add(key.Key);
}
foreach (string key in lists)
{
int range = Random.Range(5000, 10000);
str.Clear();
for (int i = 0; i < range; i++)
{
str.Append(adds[Random.Range(0, adds.Count)]);
}
password.password[key] = str.ToString();
}
string text = JsonMapper.ToJson(password);
StreamWriter writer = new StreamWriter(path);
writer.Write(text);
writer.Close();;
}
/// <summary>
/// 获取当前动画机正在播放的动画名称
/// </summary>
/// <param name="anim">获取的动画机</param>
/// <returns></returns>
public string GetAnimatorPlayAnimName(Animator anim)
{
return anim.GetCurrentAnimatorClipInfo(0)[0].clip.name;
}
/// <summary>
/// 获取动画机中一段动画的时长(秒)
/// </summary>
/// <param name="animator">需要获取动画的动画机</param>
/// <param name="name">需要从动画机里获取的动画名</param>
/// <returns>动画的时长(秒)</returns>
public float GetAnimTime(Animator animator,string name)
{
AnimationClip[] clips = animator.runtimeAnimatorController.animationClips;
foreach(AnimationClip clip in clips)
{
if(clip.name.Equals(name))
{
return clip.length / animator.speed;
}
}
Debug.LogError("传入了错误的动画名");
return 0;
}
/// <summary>
/// 依次启用队列中的物体
/// </summary>
/// <param name="time">间隔时间</param>
/// <param name="list">开启的物体队列</param>
public void SetActiveList(float time,List<GameObject> list)
{
StartCoroutine(SetActiveListIE(time, list));
}
IEnumerator SetActiveListIE(float time,List<GameObject> list)
{
foreach (GameObject g in list)
{
g.gameObject.SetActive(true);
yield return new WaitForSeconds(time);
}
}
#endregion
#region 图片处理
/// <summary>
/// 裁剪图片透明区域并返回
/// </summary>
/// <param name="texture">需要被裁剪的图片</param>
/// <param name="action">参数为裁剪好图片的回调</param>
public void GetMinTexture(Texture2D texture ,Action<Texture2D> action)
{
StartCoroutine(GetColorSize(texture, (minX,minY,maxX,maxY) =>
{
Texture2D t = new Texture2D(maxX-minX,maxY-minY);
for (int i = minX; i < maxX; i++)
{
for (int j = minY; j < maxY; j++)
{
t.SetPixel(i-minX,j-minY,texture.GetPixel(i,j));
}
}
t.Apply();
action(t);
}));
}
IEnumerator GetColorSize(Texture2D texture,Action<int,int,int,int>action)
{
int waittime = 100;
bool breakout = false;
int minX = 0;
int minY = 0;
int maxX = texture.width;
int maxY = texture.height;
for (int i = 0; i <= texture.height; i++)
{
for (int j = 0; j <= texture.width; j++)
{
if (texture.GetPixel(j, i).a > 0.95f)
{
minY = i;
breakout = true;
break;
}
}
if (i % waittime == 0 && i!=0)
{
yield return new WaitForEndOfFrame();
}
if(breakout) {break;}
}
breakout = false;
for (int i = texture.height; i >= 0 ; i--)
{
for (int j = 0; j <= texture.width; j++)
{
if (texture.GetPixel(j, i).a > 0.95f)
{
maxY = i;
breakout = true;
break;
}
}
if (i % waittime == 0 && i!=0)
{
yield return new WaitForEndOfFrame();
}
if(breakout) {break;}
}
breakout = false;
for (int i = 0; i <= texture.width ; i++)
{
for (int j = 0; j <= texture.height; j++)
{
if (texture.GetPixel(i, j).a > 0.95f)
{
minX = i;
breakout = true;
break;
}
}
if (i % waittime == 0 && i!=0)
{
yield return new WaitForEndOfFrame();
}
if(breakout) {break;}
}
breakout = false;
for (int i = texture.width; i >= 0; i--)
{
for (int j = 0; j <= texture.height; j++)
{
if (texture.GetPixel(i, j).a > 0.95f)
{
maxX = i;
breakout = true;
break;
}
}
if (i % waittime == 0 && i!=0)
{
yield return new WaitForEndOfFrame();
}
if(breakout) {break;}
}
action(minX,minY,maxX,maxY);
}
/// <summary>
/// Image播放精灵切换动画
/// </summary>
/// <param name="mage">播放动画的Image</param>
/// <param name="time">精灵切换的间隔</param>
/// <param name="sprite">切换的精灵队列</param>
public void SpriteAnim(Image mage, float time, params Sprite[] sprite)
{
for (int i = 0; i < sprite.Length; i++)
{
ChangeSprite(time*i,mage,sprite[i]);
}
}
private void ChangeSprite(float time ,Image mage, Sprite sprite)
{
Wait(time, () => { mage.sprite = sprite; });
}
/// <summary>
/// 将图片赋予Image并适应当前Image的大小
/// </summary>
/// <param name="show">接受图片的Image</param>
/// <param name="sprite">赋予的图片</param>
public void SetMinSizeSprite(Image show,Sprite sprite)
{
RectTransform showRect = show.rectTransform;
float size = showRect.sizeDelta.x > showRect.sizeDelta.y ? showRect.sizeDelta.x : showRect.sizeDelta.y;
show.sprite = sprite;
show.SetNativeSize();
showRect.sizeDelta = showRect.sizeDelta.x > showRect.sizeDelta.y
? new Vector2(size, showRect.sizeDelta.y * size / showRect.sizeDelta.x)
: new Vector2(showRect.sizeDelta.x * size / showRect.sizeDelta.y, size);
}
#endregion
#region 龙骨动画相关
/// <summary>
/// 龙骨动画播放动画队列
/// </summary>
/// <param name="anim">播放动画的龙骨</param>
/// <param name="str">需要播放的动画队列</param>
public void SetDragonAnimList(UnityArmatureComponent anim ,List<string> str)
{
anim.animation.Play(str[0],1);
StartCoroutine(AnimList(anim, str, () => { }));
}
/// <summary>
/// 龙骨动画播放动画队列并在播放最后一个动画时回调
/// </summary>
/// <param name="anim">播放动画的龙骨</param>
/// <param name="str">需要播放的动画队列</param>
/// <param name="action">调用的回调</param>
public void SetDragonAnimList(UnityArmatureComponent anim ,List<string> str,Action action)
{
anim.animation.Play(str[0],1);
StartCoroutine(AnimList(anim, str,action));
}
IEnumerator AnimList(UnityArmatureComponent anim,List<string> str,Action action,int i = 1)
{
while (i < str.Count - 1)
{
yield return new WaitForEndOfFrame();
if (!anim.animation.isPlaying)
{
anim.animation.Play(str[i++],1);
}
}
GetAnimEnd(anim, () =>
{
anim.animation.Play(str[str.Count - 1], 0);
action();
});
}
/// <summary>
/// 监听龙骨动画播放完成并执行回调
/// </summary>
/// <param name="anim">需要监听的龙骨动画</param>
/// <param name="action">播放完成的回调</param>
public void GetAnimEnd(UnityArmatureComponent anim,Action action)
{
StartCoroutine(GetAnimEndIE(anim,action));
}
IEnumerator GetAnimEndIE(UnityArmatureComponent anim,Action action)
{
yield return new WaitForEndOfFrame();
if (anim.animation.isPlaying)
{
StartCoroutine(GetAnimEndIE(anim,action));
}
else
{
action();
}
}
#endregion
#region 网络部分
#region 下载图片
public void IosDownLoadTexture(string path)
{
_SavePhoto(path);
}
public void AndroidDownLoadTexture(Texture2D texture2D,string name)
{
StartCoroutine(DownLoadtexture(texture2D, name));
}
private IEnumerator DownLoadtexture(Texture2D texture2D,string name)
{
Debug.Log(texture2D);
byte[] bytes = texture2D.EncodeToPNG();
string fileName = name + ".png";
string path;
//安卓平台
if (Application.platform == RuntimePlatform.Android)
{
string destination = "/sdcard/DCIM/test";
//判断目录是否存在,不存在则会创建目录
Debug.Log("有相册路径吗?"+Directory.Exists(destination));
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
path = destination + "/" + fileName;
Debug.Log(path);
//存图片
try
{
File.WriteAllBytes(path, bytes);
}
catch (Exception e)
{
Debug.LogError("无法存储图片,原因为:" + e);
throw;
}
string[] paths = {path};
ScanFile(paths);
yield return new WaitForEndOfFrame();
}
}
//刷新相册
private void ScanFile(string[] path)
{
using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
{
Conn.CallStatic("scanFile", playerActivity, path, null, null);
Debug.Log("存储完成");
}
}
}
//ios保存图片成功回调
public void AlertSaveResult(string re)
{
if (re == "done")
{
Debug.Log("存储完成ios");
}
else
{
Debug.Log("存储失败ios");
}
}
[DllImport("__Internal")]
private static extern void _SavePhoto(string readAddr);
#endregion
#region 链接网络
public void LinkToNetwork(string tipName,string url,Action<JsonData> action,Action newError,params NetInfo [] netInfo)
{
//Loading(tipName);
StartCoroutine(Send(tipName,url,action,newError, netInfo));
}
public void LinkToNetwork(string tipName,string url,Action<JsonData> action,params NetInfo [] netInfo)
{
//Loading(tipName);
StartCoroutine(Send(tipName,url,action,() => { }, netInfo));
}
public void LinkToNetwork(string url,Action<JsonData> action,Action newError,params NetInfo [] netInfo)
{
StartCoroutine(Send("",url,action,newError, netInfo));
}
public void LinkToNetwork(string url,Action<JsonData> action,params NetInfo [] netInfo)
{
StartCoroutine(Send("",url,action,() => { }, netInfo));
}
public void LinkToNetwork(string url,params NetInfo [] netInfo)
{
StartCoroutine(Send("",url,data => { },() => { }, netInfo));
}
private string url = "网络基址";
IEnumerator Send(string tipName,string url,Action<JsonData> action,Action newError, NetInfo [] netInfo)
{
WWWForm form = new WWWForm();
foreach (NetInfo info in netInfo)
{
if (info.infoType == NetInfoType.String)
{
form.AddField(info.infoName, info.infoString);
}
else
{
form.AddBinaryData(info.infoName, info.infoBytes);
}
}
UnityWebRequest www = UnityWebRequest.Post(this.url + url,form);
yield return www.SendWebRequest();
//DesLoadTip(tipName);
if (www.isHttpError || www.isNetworkError)
{
Debug.Log("网络状态异常,请检查您的网络设置");
newError();
yield break;
}
JsonData data = JsonMapper.ToObject(www.downloadHandler.text);
if (data["code"].ToString() != "200")
{
if (data["code"].ToString() == "202")
{
OutLogin(() => { Login(); });
}
else
{
Debug.Log(data["msg"].ToString());
newError();
}
yield break;
}
action(data["data"]);
}
public void GetNetTexture(string url,RawImage image)
{
StartCoroutine(GetTexture(url,image, () => { }));
}
public void GetNetTexture(string url,RawImage image,Action action)
{
StartCoroutine(GetTexture(url,image,action));
}
IEnumerator GetTexture(string url,RawImage image,Action action)
{
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
Texture2D t = new Texture2D(1,1);
t.LoadImage(www.downloadHandler.data);
try
{
image.texture = t;
action();
if (image.GetComponent<OnDesTexture>())
{
image.gameObject.GetComponent<OnDesTexture>().SetDesTexture(t);
}
else
{
image.gameObject.AddComponent<OnDesTexture>().SetDesTexture(t);
}
}
catch
{
Destroy(t);
}
}
#endregion
#region 处理时间码
public String StampToDateTime(string timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
// return dateTimeStart.Add(toNow);
DateTime dt = dateTimeStart.Add(toNow);
return dt.ToString("yyyy-MM-dd hh:mm:ss");
}
public String DateTimeToMouthAndDay(string timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
// return dateTimeStart.Add(toNow);
DateTime dt = dateTimeStart.Add(toNow);
return dt.Month + "月" + dt.Day + "日";
}
#endregion
#endregion
#region 正交相机场景坐标与屏幕坐标转换
public Vector2 GetCanvasPos(Camera camera,CanvasScaler canvas,Vector3 screenPos)
{
bool porTrait = Screen.height > Screen.width;
float ratio = porTrait
? (float) Screen.height / Screen.width
: (float) Screen.width / Screen.height;
float maxScreenX, maxScreenY, maxCanvasX, maxCanvasY, ratioX, ratioY;
if (porTrait)
{
maxScreenX = camera.orthographicSize;
maxScreenY = maxScreenX * ratio;
}
else
{
maxScreenY = camera.orthographicSize;
maxScreenX = maxScreenY * ratio;
}
if (canvas.matchWidthOrHeight < 0.5f)
{
maxCanvasX = canvas.referenceResolution.x * 0.5f;
maxCanvasY = maxCanvasX / ratio;
}
else
{
maxCanvasY = canvas.referenceResolution.y;
maxCanvasX = maxCanvasY / ratio;
}
ratioX = screenPos.x - camera.transform.position.x;
ratioX = ratioX / maxScreenX;
ratioY = screenPos.y - camera.transform.position.y;
ratioY = ratioY / maxScreenY;
return new Vector2(maxCanvasX * ratioX, maxCanvasY * ratioY);
}
public Vector3 GetScreenPos(Camera camera,CanvasScaler canvas,Vector3 canvasPos)
{
bool porTrait = Screen.height > Screen.width;
float ratio = porTrait
? (float) Screen.height / Screen.width
: (float) Screen.width / Screen.height;
float maxScreenX, maxScreenY, maxCanvasX, maxCanvasY, ratioX, ratioY;
if (porTrait)
{
maxScreenX = camera.orthographicSize;
maxScreenY = maxScreenX * ratio;
}
else
{
maxScreenY = camera.orthographicSize;
maxScreenX = maxScreenY = ratio;
}
if (canvas.matchWidthOrHeight < 0.5f)
{
maxCanvasX = canvas.referenceResolution.x * 0.5f;
maxCanvasY = maxCanvasX / ratio;
}
else
{
maxCanvasY = canvas.referenceResolution.y;
maxCanvasX = maxCanvasY / ratio;
}
ratioX = canvasPos.x / maxCanvasX;
ratioY = canvasPos.y / maxCanvasY;
return (new Vector3(maxScreenX * ratioX, maxScreenY * ratioY ,
camera.transform.position.z)+ camera.transform.forward * 10.0f);
}
#endregion
public Transform GetTransform(string name,Vector3 pos)
{
List<Transform> findNear = new List<Transform>();
foreach (Transform t in FindObjectsOfType<Transform>())
{
if (name == t.gameObject.name || name == "")
{
findNear.Add(t);
}
}
Transform near = null;
float nearDistance = float.MaxValue;
float distance = 0.0f;
foreach (Transform t in findNear)
{
distance = Vector3.Distance(pos, t.position);
if (distance < nearDistance)
{
near = t;
nearDistance = distance;
}
}
if (near == null)
{
return GetTransform("", pos);
}
return near;
}
public void GetAllChild(Transform parent, Action<GameObject> action)
{
action(parent.gameObject);
if (parent.childCount > 0)
{
for (int i = 0; i < parent.childCount; i++)
{
GetAllChild(parent.GetChild(i), action);
}
}
}
{
action(parent.gameObject);
if (parent.childCount > 0)
{
for (int i = 0; i < parent.childCount; i++)
{
GetAllChild(parent.GetChild(i), action,root);
}
}
}
public void GetAllParent(Transform main,Action<GameObject> action)
{
action(main.gameObject);
if (main.parent != null)
{
GetAllParent(main.parent, action);
}
}
private Dictionary<string, string> getLocalText = new Dictionary<string, string>();
public string GetLocalText(string key)
{
if (getLocalText.ContainsKey(key))
{
return getLocalText[key];
}
try
{
StreamReader reader = new StreamReader(Application.streamingAssetsPath + "/Text/" + key + ".txt");
string value = reader.ReadToEnd();
reader.Close();
getLocalText.Add(key,value);
PlayerPrefs.SetString(key,value);
return value;
}
catch
{
return PlayerPrefs.GetString(key);
}
}
public void SaveLocalText(string key,string value)
{
if (!getLocalText.ContainsKey(key))
{
getLocalText.Add(key,value);
}
else
{
getLocalText[key] = value;
}
PlayerPrefs.SetString(key,value);
StreamWriter writer = new StreamWriter(Application.streamingAssetsPath + "/Text/" + key + ".txt");
writer.Write(value);
writer.Close();
}
}
其中引用到了另一个简单的代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OnDesTexture : MonoBehaviour
{
private Texture texture;
public void SetDesTexture(Texture texture)
{
if (this.texture != null)
{
Destroy(this.texture);
}
this.texture = texture;
}
private void OnDestroy()
{
Destroy(texture);
}
}