2021-04-25 13:51:21 +08:00

294 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Assets.Scripts.UI.Control;
using DG.Tweening;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
namespace Assets.Scripts
{
public static class Utils
{
/*获取ip*/
public enum ADDRESSFAM
{
IPv4, IPv6
}
/// <summary>
/// 获取本机IP
/// </summary>
/// <param name="Addfam">要获取的IP类型</param>
/// <returns></returns>
public static string GetIP(ADDRESSFAM Addfam)
{
if (Addfam == ADDRESSFAM.IPv6 && !Socket.OSSupportsIPv6)
{
return null;
}
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
#endif
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
//IPv4
if (Addfam == ADDRESSFAM.IPv4)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
//Debug.Log("IP:" + output);
}
}
//IPv6
else if (Addfam == ADDRESSFAM.IPv6)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
output = ip.Address.ToString();
}
}
}
}
}
return output;
}
/*获取ip*/
/*显示简略提示需要拖Toast的预制件且保证其他组件名字不是Toast,ToastContainer*/
private static Dictionary<int, string> _toastDict;
private static Dictionary<int, string> toastDict
{
get
{
if (_toastDict == null)
{
_toastDict = new Dictionary<int, string>
{
{0,"Images/home/wrong|#f93086" },{1,"Images/home/right|#41A6FE" }
};
}
return _toastDict;
}
set
{
_toastDict = value;
}
}
public static void showToast(GameObject game,string text,int duration = 1,int type = 0)
{
//type 0错误 1正确
var parent = Utils.FindUpParent(game.transform);
var toast = parent.Find("ToastContainer");
if (toast == null)
{
var newToast = MonoBehaviour.Instantiate(Resources.Load<GameObject>("UI/Prefab/ToastContainer"));
newToast.name = "ToastContainer";
newToast.GetComponent<RectTransform>().position = new Vector3(Screen.width / 2, Screen.height / 2, 0);
newToast.transform.parent = parent;
toast = newToast.transform;
}
var toastStyle = toastDict[type].Split('|');
toast.Find("Image").GetComponent<Image>().sprite = Resources.Load<Sprite>(toastStyle[0]);
toast.GetComponent<Image>().color = HexToColorHtml(toastStyle[1]);
toast.GetComponent<Toast>().showToast(JsonConvert.SerializeObject(new
{
text,
duration
}));
}
/*显示简略提示需要拖Toast的预制件且保证其他组件名字不是Toast,ToastContainer*/
/*删除父亲节点下的所有孩子*/
static public void DestroyChildren(this Transform t)
{
bool isPlaying = Application.isPlaying;
while (t.childCount != 0)
{
Transform child = t.GetChild(0);
if (isPlaying)
{
child.SetParent(null);
UnityEngine.Object.Destroy(child.gameObject);
}
else UnityEngine.Object.DestroyImmediate(child.gameObject);
}
}
/*删除父亲节点下的所有孩子*/
/*显示网络图片*/
public delegate Coroutine StartCoroutine(IEnumerator routine);
public static void DisplayImage(StartCoroutine startCoroutine,RawImage img, string url)
{
startCoroutine(DownloadImage(img, url));
}
public static void DisplayImageAysnc(StartCoroutine startCoroutine, RawImage img, string url,Action action)
{
startCoroutine(DownloadImageCallBack(img, url, action));
}
static IEnumerator DownloadImage(RawImage img,string MediaUrl)
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
Debug.Log(request.error);
else
img.texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
}
static IEnumerator DownloadImageToLocal(RawImage img, string MediaUrl)
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
Debug.Log(request.error);
else
img.texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
}
static IEnumerator DownloadImageCallBack(RawImage img, string MediaUrl,Action action)
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
Debug.Log(request.error);
else
{
img.texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
action.Invoke();
}
}
/*显示网络图片*/
/*获取最顶层对象*/
public static Transform FindUpParent(Transform zi)
{
if (zi.parent == null)
return zi;
else
return FindUpParent(zi.parent);
}
/*获取最顶层对象*/
public static Color HexToColor(string hex)
{
byte r = byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
byte g = byte.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
byte b = byte.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);
return new Color32(r, g, b, byte.MaxValue);
}
public static Color HexToColorHtml(string hex)
{
ColorUtility.TryParseHtmlString(hex, out Color c);
return c;
}
/// <summary>
/// Generate random digit code
/// </summary>
/// <param name="length">Length</param>
/// <returns>Result string</returns>
public static string GenerateRandomDigitCode(int length)
{
var random = new System.Random();
string str = string.Empty;
for (int i = 0; i < length; i++)
str = String.Concat(str, random.Next(10).ToString());
return str;
}
/*文件转精灵*/
public static Sprite PngToSprite(string fullPath, int x, int y)
{
using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read)) //自动双清
{
fs.Seek(0, SeekOrigin.Begin); //设定当前流的位置
byte[] bytes = new byte[fs.Length]; //创建文件长度缓冲区
fs.Read(bytes, 0, (int)fs.Length); //读取文件
Texture2D texture = new Texture2D(x, y); //创建Texture
texture.LoadImage(bytes);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one / 2);
}
}
/*文件转精灵*/
/*打开文件*/
public delegate void OpenFileCallBack(string path);
public static void OpenFile(OpenFileCallBack callBack,string filter = null)
{
OpenFileName ofn = new OpenFileName();
ofn.structSize = Marshal.SizeOf(ofn);
ofn.filter = "Image Files(*.jpg;*.jpeg;*.png;*.bmp)\0*.jpg;*.png;*.jpeg;*.bmp\0";
if (filter != null) ofn.filter = filter;
ofn.file = new string(new char[256]);
ofn.maxFile = ofn.file.Length;
ofn.fileTitle = new string(new char[64]);
ofn.maxFileTitle = ofn.fileTitle.Length;
ofn.initialDir = UnityEngine.Application.dataPath;//默认路径
ofn.title = "Open Project";
ofn.defExt = "JPG";//显示文件的类型
//注意 一下项目不一定要全选 但是0x00000008项不要缺少
ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR
if (Win32.GetOpenFileName(ofn))
{
callBack(ofn.file);
}
}
/*打开文件*/
/**/
public static void SetValidate(Dictionary<string, Selectable> dict, JArray errorList)
{
foreach (var error in errorList)
{
var className = dict[error.Value<string>("Field")].GetType().Name;
if (className == "InputField")
{
dict[error.Value<string>("Field")].GetComponent<PFUIInputField>()
.SetValidate(true);
}
else if (className == "Dropdown")
{
dict[error.Value<string>("Field")].GetComponent<PFUIDropdown>()
.SetValidate();
}
//formDict[error.Value<string>("Filed")].error.Value<string>("ErrMsg");
}
}
}
}