public static class CCommon
{
public const string SAVE_NEWBEE_SCENE = "saveNewbeeScene";
public const string SAVE_NEWBEE_TAG = "%|%^%";
private static Vector3 m_tempVector;
public static RuntimePlatform platform = Application.platform;
public static string Extension;
public static string PersistentDataPath = Application.persistentDataPath;
public static string StreamingAssetsPath = Application.streamingAssetsPath;
#if UNITY_EDITOR
public static string PersistentDataURL = "file:///" + Application.persistentDataPath;
public static string StreamingAssetsURL = "file://" + Application.streamingAssetsPath;
#elif UNITY_ANDROID
public static string PersistentDataURL = "file://" + Application.persistentDataPath;
public static string StreamingAssetsURL = Application.streamingAssetsPath;
#elif UNITY_IPHONE
public static string PersistentDataURL = "file://" + Application.persistentDataPath;
public static string StreamingAssetsURL = System.Uri.EscapeUriString("file://" + Application.streamingAssetsPath);
#endif
private static Dictionary<string, Shader> m_shaderCollect = new Dictionary<string, Shader>();
private static List<string> m_TrieFilter = new List<string>();
public static void Init()
{
#if UNITY_ANDROID
Extension = CDEFINE.EXTENSION_POINT_ANDROID;
#else
Extension = CDEFINE.EXTENSION_POINT_IPHONE;
#endif
if (platform == RuntimePlatform.OSXEditor || platform == RuntimePlatform.WindowsEditor)
{
StreamingAssetsURL = "file://" + Application.streamingAssetsPath;
PersistentDataURL = "file:///" + Application.persistentDataPath;
}
if (platform == RuntimePlatform.Android)
{
if (Config.Instance.UseWWWLoadAsset)
{
StreamingAssetsPath = Application.dataPath + "!assets";
}
}
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY, CDEFINE.LAYER_DEFAULT, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_DEFAULT, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY, CDEFINE.LAYER_IGNORE_ENTITY, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY, CDEFINE.LAYER_ENTITY, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_ENTITY, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_TERRAIN, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_AIR_WALL, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_ENTITY, CDEFINE.LAYER_DROP_ITEM, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_DROP_ITEM, CDEFINE.LAYER_DROP_ITEM, true);
Shader.EnableKeyword("USE_CUSTOM_LIGHT");
Shader.DisableKeyword("USE_UNITY_LIGHT");
CDEFINE.SCREEN_W = Screen.width;
CDEFINE.SCREEN_H = Screen.height;
}
/// <summary>
/// 初始化敏感词汇
/// </summary>
public static void InitSensitiveWords()
{
ShieldContent retContent = HolderManager.m_ShieldHolder.GetStaticInfo(1);
if (null != retContent)
{
m_TrieFilter = retContent.content;
}
}
/// <summary>
/// destin 是否在以 source 为中心的矩形区域内
/// </summary>
/// <param name="source"></param>
/// <param name="destin"></param>
/// <param name="range">矩形的一半边长</param>
/// <returns></returns>
public static bool IsInRect(Vector3 source, Vector3 destin, float range)
{
m_tempVector = destin - source;
if (m_tempVector.x > -range && m_tempVector.x < range && m_tempVector.z > -range && m_tempVector.z < range)
return true;
else
return false;
}
/// <summary>
/// destin 是否在以 source 为中心的圆形区域内
/// </summary>
/// <param name="source"></param>
/// <param name="destin"></param>
/// <param name="range">矩形的一半边长</param>
/// <returns></returns>
public static bool IsInCircle(Vector3 source, Vector3 destin, float range)
{
m_tempVector = destin - source;
if (DistanceSqrXZ(source, destin) < range * range)
return true;
else
return false;
}
/// <summary>
/// 两点长度的平方,忽略Y方向
/// </summary>
/// <param name="source"></param>
/// <param name="destin"></param>
/// <returns></returns>
public static float DistanceSqrXZ(Vector3 source, Vector3 destin)
{
m_tempVector = destin - source;
return m_tempVector.x * m_tempVector.x + m_tempVector.z * m_tempVector.z;
}
/// <summary>
/// 忽略Y轴 小心使用,真的需要忽略Y轴吗
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static float DistanceXZ(Vector3 a, Vector3 b)
{
Vector3 v1 = a;
v1.y = 0;
Vector3 v2 = b;
v2.y = 0;
return Vector3.Distance(v1, v2);
}
public static float DistanceSqr(Vector3 a, Vector3 b)
{
a = b - a;
return a.x * a.x + a.y * a.y + a.z * a.z;
}
public static float Distance(Vector3 a, Vector3 b)
{
return Vector3.Distance(a, b);
}
public static float Distance(Vector2 a, Vector2 b)
{
return Vector2.Distance(a, b);
}
public static float AngelXZ(Vector3 a, Vector3 b)
{
Vector3 v1 = a;
v1.y = 0;
Vector3 v2 = b;
v2.y = 0;
return Vector3.Angle(v1, v2);
}
public static Vector3 GetVector3(proto.message.Point3D pt)
{
Vector3 pos = new Vector3(pt.x, pt.y, pt.z);
pos = CCommon.NavSamplePosition(pos);
return pos;
}
public static Vector3 ToVector3(this Point3D point)
{
Vector3 pos = new Vector3(point.x, point.y, point.z);
pos = CCommon.NavSamplePosition(pos);
return pos;
}
public static Point3D ToPoint3D(this Vector3 vector)
{
return new Point3D() { x = vector.x, y = vector.y, z = vector.z };
}
public static float ToRadian(this Vector3 eulerAngles)
{
return eulerAngles.y / Mathf.Rad2Deg;
}
/// <summary>
/// 取得相应骨骼名称的变换
/// </summary>
/// <param name="trans"></param>
/// <param name="boneName"></param>
/// <returns></returns>
public static Transform GetBone(Transform trans, string boneName)
{
if (string.IsNullOrEmpty(boneName) || boneName.Equals("0"))
{
return null;
}
if (null == trans)
{
return null;
}
Transform[] tran = trans.GetComponentsInChildren<Transform>(true);
foreach (Transform t in tran)
{
if (t.name == boneName)
{
return t;
}
}
return null;
}
public static void ReplaceShader(GameObject replaceObj, Shader shader = null)
{
#if UNITY_EDITOR
if (replaceObj == null)
return;
Renderer[] renders = replaceObj.GetComponentsInChildren<Renderer>(true);
Material[] materials;
for (int rIndex = 0, rCount = renders.Length; rIndex < rCount; rIndex++)
{
materials = renders[rIndex].sharedMaterials;
for (int mIndex = 0, mCount = materials.Length; mIndex < mCount; mIndex++)
{
ReplaceShader(materials[mIndex], shader);
}
}
PigeonCoopToolkit.Effects.Trails.TrailRenderer_Base[] trailRenderBases = replaceObj.GetComponentsInChildren<PigeonCoopToolkit.Effects.Trails.TrailRenderer_Base>(true);
for (int rIndex = 0, rCount = trailRenderBases.Length; rIndex < rCount; rIndex++)
{
if (trailRenderBases[rIndex] == null)
continue;
ReplaceShader(trailRenderBases[rIndex].TrailData.TrailMaterial, shader);
}
#endif
}
public static void ReplaceShader(Material mat, Shader shader = null)
{
#if UNITY_EDITOR
if (mat == null)
return;
string name = mat.shader.name;
int queue = 0;
if (shader == null)
{
if (m_shaderCollect.ContainsKey(name))
{
if (m_shaderCollect[name] == null)
{
m_shaderCollect[name] = Shader.Find(name);
if (m_shaderCollect[name] == null)
{
m_shaderCollect.Remove(name);
return;
}
}
}
else
{
Shader s = Shader.Find(name);
if (s == null)
{
return;
}
m_shaderCollect.Add(name, s);
}
if (CMain.Instance.ResetRenderQueue)
{
queue = mat.renderQueue;
}
mat.shader = m_shaderCollect[name];
if (CMain.Instance.ResetRenderQueue)
mat.renderQueue = queue;
}
else
{
if (CMain.Instance.ResetRenderQueue)
{
queue = mat.renderQueue;
}
mat.shader = shader;
if (CMain.Instance.ResetRenderQueue)
mat.renderQueue = queue;
}
#endif
}
public static Shader GetShader(string shaderName)
{
if (m_shaderCollect.ContainsKey(shaderName))
{
return m_shaderCollect[shaderName];
}
else
{
Shader shader = Shader.Find(shaderName);
if (shader != null)
m_shaderCollect.Add(shaderName, shader);
else
{
Debug.LogError("can't find shader:" + shaderName);
}
return shader;
}
}
public static void SetLayer(GameObject target, int layer, bool containsChild)
{
target.layer = layer;
if (containsChild)
{
Transform[] child = target.GetComponentsInChildren<Transform>(true);
for (int i = 0, count = child.Length; i < count; i++)
{
if (child[i] == target.transform)
continue;
child[i].gameObject.layer = layer;
}
}
}
/// <summary>
/// 根据界面名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetPanelPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/panel/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据界面名字获取Bundle路径(相对于配置文件)
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetPanelPathToMainfest(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/panel/");
build.Append(name);
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据Atlas名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetAtlasPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/atlas/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据Component名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetComponentPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/component/");
build.Append(name.ToLower().Trim());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据View名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetViewPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/view/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据UIEffect Prefab名字回去Bundle路径
/// </summary>
/// <returns>The user interface effect path.</returns>
/// <param name="name">Name.</param>
public static string GetUIEffectPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/effect/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 获取音效路径 TODO
/// </summary>
/// <returns>The audio path.</returns>
/// <param name="name">Name.</param>
public static string GetAudioPath(string name)
{
StringBuilder build = new StringBuilder("assets/audios/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
public static string GetFontPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/uifont/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 识别触控是否出现的UI上
/// </summary>
/// <returns></returns>
public static bool TouchOnUIGameObject()
{
return TouchOnUIGameObject(Input.mousePosition);
}
/// <summary>
/// 识别触控是否出现的UI上
/// </summary>
/// <returns></returns>
public static bool TouchOnUIGameObject(Vector2 point)
{
//return UICamera.hoveredObject != null;
RaycastHit hit = new RaycastHit();
bool bCollider = UICamera.Raycast(point, out hit);
//if (!bCollider && EasyTouch.instance != null)
//{
// bCollider = EasyTouch.instance.IsTouchHoverVirtualControll(point);// || BattleUiDialog.IsControl;
//}
return bCollider;
}
public static string GetEasyTouchTexturePath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/texture/easytouch/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
public static string GetPanelTexturePath(eTextureType type, string texName, string panelName = "")
{
if (string.IsNullOrEmpty(texName))
return "";
StringBuilder build = null;
switch (type)
{
case eTextureType.Public:
build = new StringBuilder("assets/uiresources/texture/public/");
break;
case eTextureType.Panel:
build = new StringBuilder("assets/uiresources/texture/" + panelName + "/");
break;
case eTextureType.SceneMap:
build = new StringBuilder("assets/uiresources/texture/scenemap_read_map/");
break;
case eTextureType.SkillOrMarkIcon:
build = new StringBuilder("assets/uiresources/texture/skill_stampicon/");
break;
case eTextureType.ItemIcon:
build = new StringBuilder("assets/uiresources/texture/itemicon/");
break;
case eTextureType.Other:
build = new StringBuilder("assets/uiresources/texture/other/");
break;
case eTextureType.HeadIcon:
build = new StringBuilder("assets/uiresources/texture/headicon/");
break;
case eTextureType.Buff:
build = new StringBuilder("assets/uiresources/texture/buff/");
break;
case eTextureType.ReadMap:
build = new StringBuilder("assets/uiresources/texture/read_map/");
break;
default:
build = new StringBuilder();
break;
}
build.Append(texName.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 创建路径
/// </summary>
/// <param name="path"></param>
public static void CreatePath(string path)
{
string NewPath = path.Replace("\\", "/");
string[] strs = NewPath.Split('/');
string p = "";
for (int i = 0; i < strs.Length; ++i)
{
p += strs[i];
if (i != strs.Length - 1)
{
p += "/";
}
if (!Path.HasExtension(p))
{
if (!Directory.Exists(p))
Directory.CreateDirectory(p);
}
}
}
/// <summary>
/// 替换静态label文字
/// </summary>
/// <param name="mPanel"></param>
/// <param name="mName"></param>
/// <param name="guiText"></param>
public static void SetStaticLabel(CPanel mPanel, string mName, int guiText, params object[] args)
{
if (null != mPanel && !string.IsNullOrEmpty(mName))
{
CLabel staticLabel = mPanel.GetElementBase(mName) as CLabel;
if (null == staticLabel)
{
return;
}
if (null != args && args.Length > 0)
staticLabel.Text = GetTextS(guiText, args);
else
staticLabel.Text = GetText(guiText);
}
}
public static void SetLabelContent(CPanel mPanel, string mName, string content)
{
if (null != mPanel && !string.IsNullOrEmpty(mName))
{
CLabel label = mPanel.GetElementBase(mName) as CLabel;
if (null != label)
{
label.Text = content;
}
}
}
public static int TextLength(string str)
{
if (string.IsNullOrEmpty(str))
return 0;
int len = str.Length;
bool pause = false;
int index = 0;
for (int i = 0; i < len; i++)
{
if (str[i].Equals('['))
{
pause = true;
continue;
}
else if (str[i].Equals(']'))
{
pause = false;
continue;
}
if (!pause)
index++;
}
return index;
}
public static string GetText(int uiID)
{
return GetText((uint)uiID);
}
/// <summary>
/// 绿色[6ec739],红色[ff1215]
/// </summary>
/// <param name="uiID"></param>
/// <param name="color"></param>
/// <returns></returns>
public static string GetText(int uiID, string color)
{
return color + GetText((uint)uiID) + "[-]";
}
public static string GetText(string str, string color)
{
return color + str + "[-]";
}
public static string GetText(int uiID, bool bNeedReplac)
{
return GetText((uint)uiID, bNeedReplac);
}
public static string GetText(uint uiID)
{
string s = GetLanguageText(uiID);
s = s.Replace("@", "\n");
return s;
}
public static string GetText(uint uiID, bool bNeedReplac)
{
string s = GetLanguageText(uiID);
if (bNeedReplac)
s = s.Replace("@", "\n");
else
s = s.Replace("@", " ");
return s;
}
public static string GetTextS(int uiID, params object[] args)
{
return GetTextS((uint)uiID, args);
}
/// <summary>
/// 值为空,返回默认的 无
/// </summary>
/// <param name="text"></param>
/// <param name="defaultId"></param>
/// <returns></returns>
public static string GetDefaultText(string text, int defaultId = 64000008)
{
if (!string.IsNullOrEmpty(text))
{
return text;
}
return CCommon.GetText(defaultId);
}
public static string GetTextS(uint uiID, params object[] args)
{
string rlt = GetLanguageText(uiID);
rlt = rlt.Replace("@", "\n");
string[] sp = new string[] { "%s" };
string[] str = rlt.Split(sp, StringSplitOptions.None);
if (str.Length <= 1 || args == null)
return rlt;
for (int i = 0; i < args.Length; i++)
{
string reStr = args[i].ToString();
if (i >= str.Length)
{
CDebug.LogError("Args lenght more than split string!");
continue;
}
str[i] += reStr;
}
rlt = string.Empty;
for (int i = 0; i < str.Length; i++)
{
rlt += str[i];
}
return rlt;
}
public static string GetTextS(string rlt, params object[] args)
{
rlt = rlt.Replace("@", "\n");
string[] sp = new string[] { "%s" };
string[] str = rlt.Split(sp, StringSplitOptions.None);
if (str.Length <= 1)
return rlt;
for (int i = 0; i < args.Length; i++)
{
string reStr = args[i].ToString();
if (i >= str.Length)
{
CDebug.LogError("Args lenght more than split string!");
continue;
}
str[i] += reStr;
}
rlt = string.Empty;
for (int i = 0; i < str.Length; i++)
{
rlt += str[i];
}
return rlt;
}
private static string GetLanguageText(uint uiID)
{
GUITextContent pInfo = HolderManager.m_GUITextHolder.GetStaticInfo(uiID);
if (null == pInfo)
{
return "$N/A";
}
return pInfo.SimpleChinese;
}
/// <summary>
/// 返回字符串的长度
/// 中文占2,英文占1
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static int GetMaxCharsLength(string text)
{
int len = 0;
if (!string.IsNullOrEmpty(text))
{
char[] tcs = text.ToCharArray();
int length = tcs.Length;
for (int i = 0; i < length; i++)
{
int c = (int)tcs[i];
if (c > 127)
{
len += 2;
}
else
{
len += 1;
}
}
}
return len;
}
/// <summary>
/// 限定字符串到达指定长度后换行。
/// </summary>
/// <param name="text"></param>
/// <param name="lineMaxCharLength"></param>
/// <returns></returns>
public static string GetAutoWrapChars(string text, int lineMaxCharLength)
{
int start = 0;
int end = 0;
string value = string.Empty;
if (!string.IsNullOrEmpty(text))
{
while (start < end)
{
start = end;
end = Mathf.Min(lineMaxCharLength, text.Length);
value += text.Substring(start, end);
if (end == lineMaxCharLength && lineMaxCharLength != text.Length)
{
value += "@";
}
}
}
return value;
}
/// <summary>
/// 限定字符串到达指定长度后换行。
/// </summary>
/// <param name="text"></param>
/// <param name="lineMaxCharLength"></param>
/// <returns></returns>
public static string GetAutoWrapChars(int gid, int lineMaxCharLength)
{
return GetAutoWrapChars(CCommon.GetText(gid), lineMaxCharLength);
}
public static void ShowErrorCode(int erroeCode)
{
int index = 80000000 + erroeCode;
ShowTextTip(CCommon.GetText(index), Color.red);
}
public static void SetErrorCodeParam(int errorCode, params object[] par)
{
int index = 80000000 + errorCode;
ShowTextTip(CCommon.GetTextS(index, par), Color.red);
}
public static void ShowTips(int textID, params object[] insert)
{
string msg = GetTextS(textID, insert);
#if UNITY_EDITOR
ShowTextTip("guitextID = " + textID.ToString() + ":" + msg);
#else
ShowTextTip(msg);
#endif
}
public static void ShowTextTip(string tipstr, Color color)
{
//SingleObject<HUDTextDialog>.Instance.ShowTextTip (tipstr, color);
ShowTextTip(tipstr);
}
public static void ShowTextTip(string tipstr)
{
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Warning, 0, 0, tipstr);
}
public static void ShowAwardsTips(List<proto.message.IDNum> item_list)
{
for (int i = 0; i < item_list.Count; i++)
{
BackpackItemData ba = new BackpackItemData(item_list[i].id);
//ShowOneAwardTips(ba, item_list[i].num);
}
}
public static void ShowOneAwardTips(BackpackItemData ba, int num)
{
//暂时不判断
//bool isBattle = CAvatar.Instance.WarnningType == WarnningType.Warnning ? true : false;
bool isBattle = false;
if (isBattle)
{
ItemContent itemCon = HolderManager.m_ItemHolder.GetStaticInfo(ba.id);
if (itemCon != null)
{
if ((eItemType)itemCon.Type == eItemType.Currency)
{
HUDAwardItem item = new HUDAwardItem();
item.id = ba.id;
item.number = num;
SingleObject<HUDAwardDialog>.Instance.ShowAward(item);
return;
}
}
}
if (ba.source == (int)eGetItem.eGetItem_Monster)
{
if ((CGameWorld.Instance.CurrentScene as CBattleScene != null) && (CGameWorld.Instance.CurrentScene as CBattleScene).IsDungeon())
{
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Award, ba.id, num, "");
}
}
else if (ba.source == (int)eGetItem.eGetItem_Offpvp)
{
}
else
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Award, ba.id, num, "");
}
public static void ShowLackTips(int id, string str)
{
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Lack, id, 0, str);
}
public static void ShowDebugTips(string text)
{
#if UNITY_EDITOR
ShowTextTip(text);
#else
CDebug.LogAssert(text);
#endif
}
/// <summary>
/// bytes转int
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static int BytesToInt(byte[] src, int offset)
{
int value = 0;
value = (int)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
return value;
}
public static long BytesToLong(byte[] src, int offset)
{
long value = 0;
value = (long)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24)
| ((src[offset + 4] & 0xFF) << 32)
| ((src[offset + 5] & 0xFF) << 40)
| ((src[offset + 6] & 0xFF) << 48)
| ((src[offset + 7] & 0xFF) << 56));
return value;
}
/// <summary>
/// bytes转ushort
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static ushort BytesToUshort(byte[] src, int offset)
{
ushort value = 0;
value = (ushort)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8));
return value;
}
/// <summary>
/// int 转 bytes
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static byte[] IntToBytes(int value)
{
byte[] src = new byte[4];
src[3] = (byte)((value >> 24) & 0xFF);
src[2] = (byte)((value >> 16) & 0xFF);
src[1] = (byte)((value >> 8) & 0xFF);
src[0] = (byte)(value & 0xFF);
return src;
}
public static byte[] LongToBytes(long value)
{
byte[] src = new byte[8];
src[7] = (byte)((value >> 56) & 0xFF);
src[6] = (byte)((value >> 48) & 0xFF);
src[5] = (byte)((value >> 40) & 0xFF);
src[4] = (byte)((value >> 32) & 0xFF);
src[3] = (byte)((value >> 24) & 0xFF);
src[2] = (byte)((value >> 16) & 0xFF);
src[1] = (byte)((value >> 8) & 0xFF);
src[0] = (byte)(value & 0xFF);
return src;
}
/// <summary>
/// PB消息体转byte数组
/// </summary>
/// <typeparam name="T">Protobuf消息体类型</typeparam>
/// <param name="msg">Protobuf消息体实例形参</param>
/// <returns></returns>
public static byte[] ProtobufMsgToBytes<T>(T msg) where T : class
{
using (MemoryStream memStream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(memStream, msg);
return memStream.ToArray();
}
return null;
}
/// <summary>
/// 字节数组转换成PB消息体
/// </summary>
/// <typeparam name="T">Protobuf消息体类型</typeparam>
/// <param name="bytes">服务端返回字节数组</param>
/// <returns></returns>
public static T BytesToProtobufMes<T>(object o) where T : class
{
//MemoryStream readStream = new MemoryStream(bytes);
//try
//{
// return ProtoBuf.Serializer.Deserialize<T>(readStream);
//}
//catch (Exception ex)
//{
// CDebug.LogException(ex);
//}
//finally
//{
// readStream.Close();
//}
//return null;
return o as T;
}
/// <summary>
/// 字节数组转换成PB消息体
/// </summary>
/// <typeparam name="T">Protobuf消息体类型</typeparam>
/// <param name="bytes">服务端返回字节数组</param>
/// <returns></returns>
public static object BytesToProtobufMes(Type type, byte[] bytes)
{
if (bytes == null || type == null)
return null;
MemoryStream readStream = new MemoryStream(bytes);
try
{
return ProtoBuf.Serializer.Deserialize(type, readStream);
}
catch (Exception ex)
{
CDebug.LogException(ex);
}
finally
{
readStream.Close();
}
return null;
}
#region Extension methods for: List<T>
/// <summary>
/// Sorted list
/// </summary>
/// <param name="theList"></param>
/// <returns></returns>
public static List<T> Sorted<T>(this List<T> theList)
{
List<T> aList = new List<T>(theList);
aList.Sort();
return aList;
}
/// <summary>
/// Sorted list
/// </summary>
/// <param name="theList"></param>
/// <returns></returns>
public static IEnumerable<T> Sorted<T>(this IEnumerable<T> theList, Comparison<T> theComparison)
{
List<T> aList = new List<T>(theList);
aList.Sort(theComparison);
foreach (T aT in aList)
yield return aT;
yield break;
}
#endregion
#region Extension methods for: IEnumerable
/// <summary>
/// Check if item is in collection
/// </summary>
/// <param name="theList"></param>
/// <param name="theNeedle"></param>
/// <returns></returns>
public static bool ContainsItem<T>(this IEnumerable<T> theList, T theNeedle) where T : class
{
foreach (T anElement in theList)
{
if (theNeedle.Equals(anElement))
{
return true;
}
}
return false;
}
/// <summary>
/// Join to string with separator
/// </summary>
/// <param name="theList"></param>
/// <param name="theSeparator"></param>
/// <returns></returns>
public static string JoinToString<T>(this IEnumerable<T> theList, string theSeparator)
{
if (theList == null)
return "";
List<string> aListStrings = new List<string>();
foreach (T anElement in theList)
{
aListStrings.Add(anElement.ToString());
}
return string.Join(theSeparator, aListStrings.ToArray());
}
/// <summary>
/// Insert item at position
/// </summary>
/// <param name="theList"></param>
/// <param name="theItem"></param>
/// <param name="thePosition"></param>
/// <returns></returns>
public static IEnumerable<T> InsertItem<T>(this IEnumerable<T> theList, T theItem, int thePosition)
{
int i = 0;
bool anInserted = false;
foreach (T anElement in theList)
{
if (i == thePosition)
{
yield return theItem;
anInserted = true;
}
yield return anElement;
i++;
}
if (!anInserted)
{
yield return theItem;
}
}
/// <summary>
/// Append a new item
/// </summary>
/// <param name="theList"></param>
/// <param name="theItem"></param>
/// <returns></returns>
public static IEnumerable<T> AppendItem<T>(this IEnumerable<T> theList, T theItem)
{
foreach (T anElement in theList)
{
yield return anElement;
}
yield return theItem;
}
/// <summary>
/// Remove doubles from IEnumerable
/// </summary>
/// <param name="theList"></param>
/// <returns></returns>
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> theList)
{
List<T> aDistinctList = new List<T>();
foreach (T anElement in theList)
{
if (!aDistinctList.Contains(anElement))
{
aDistinctList.Add(anElement);
yield return anElement;
}
}
yield break;
}
/// <summary>
/// Only return first list without elements of the second list
/// </summary>
/// <param name="theMainList"></param>
/// <param name="theListToRemove"></param>
/// <returns></returns>
public static IEnumerable<T> Remove<T>(this IEnumerable<T> theMainList, T[] theListToRemove)
{
List<T> aListToRemove = new List<T>(theListToRemove);
foreach (T anElement in theMainList)
{
if (!aListToRemove.Contains(anElement))
yield return anElement;
}
yield break;
}
public static IEnumerable<T> SortedAndReverse<T>(this IEnumerable<T> theList)
{
List<T> aList = new List<T>(theList);
aList.Sort();
aList.Reverse();
foreach (T aT in aList)
yield return aT;
yield break;
}
public static IEnumerable<T> Reversed<T>(this IEnumerable<T> theList)
{
List<T> aList = new List<T>(theList);
aList.Reverse();
foreach (T aT in aList)
yield return aT;
yield break;
}
/// <summary>
/// Convert to generic list
/// </summary>
/// <returns></returns>
public static List<T> ToDynList<T>(this IEnumerable<T> theList)
{
return new List<T>(theList);
}
#endregion
/// <summary>
/// 检测线段与球相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆点P</param>
/// <param name="radius">圆半径</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineSphere(Vector3 A, Vector3 B, Vector3 P, float range, float radius)
{
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.y - A.y) * (B.y - A.y) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
return DistanceSqr(A, P) < radius * radius;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.y - B.y) * (A.y - B.y) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
return DistanceSqr(B, P) < radius * radius;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
return DistanceSqr(P, m_tempVector) < radius * radius;
}
/// <summary>
/// 检测线段与圆相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆点P</param>
/// <param name="radius">圆半径</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineSegment(Vector3 A, Vector3 B, Vector3 P, float range, float radius)
{
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
return DistanceSqrXZ(A, P) < radius * radius;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
return DistanceSqrXZ(B, P) < radius * radius;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
return DistanceSqrXZ(P, m_tempVector) < radius * radius;
}
/// <summary>
/// 检测线段与圆柱相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆柱低圆点P</param>
/// <param name="radius">圆半径</param>
/// <param name="high">高度</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineCylinderStep(Vector3 A, Vector3 B, Vector3 P, float range, float radius, float high)
{
float dY;
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
dY = A.y - P.y;
return DistanceSqrXZ(A, P) < radius * radius && 0 < dY && dY < high;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
dY = B.y - P.y;
return DistanceSqrXZ(B, P) < radius * radius && 0 < dY && dY < high;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
dY = m_tempVector.y - P.y;
return DistanceSqrXZ(P, m_tempVector) < radius * radius && 0 < dY && dY < high;
}
/// <summary>
/// 检测线段与圆柱相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆柱圆点P</param>
/// <param name="radius">圆半径</param>
/// <param name="high">高度的一半</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineCylinder(Vector3 A, Vector3 B, Vector3 P, float range, float radius, float high)
{
float dY;
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
dY = A.y - P.y;
return DistanceSqrXZ(A, P) < radius * radius && -high < dY && dY < high;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
dY = B.y - P.y;
return DistanceSqrXZ(B, P) < radius * radius && -high < dY && dY < high;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
dY = m_tempVector.y - P.y;
return DistanceSqrXZ(P, m_tempVector) < radius * radius && -high < dY && dY < high;
}
/// <summary>
/// 插值计算,计算从范围A-B到范围a-b的插值计算,C为范围A-B中任意一点。注意C值可以超出A-B的范围,如超出之后相应的得到a-b的范围值也会超出
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="A"></param>
/// <param name="B"></param>
/// <param name="C"></param>
/// <returns></returns>
public static float Lerp(float a, float b, float A, float B, float C)
{
return a - (A - C) / (A - B) * (a - b);
}
public static float LerpClamp(float a, float b, float A, float B, float C)
{
if (A > B)
{
if (C > A)
C = A;
if (C < B)
C = B;
}
else
{
if (C < A)
C = A;
if (C > B)
C = B;
}
return a - (A - C) / (A - B) * (a - b);
}
public static int LerpClamp(int a, int b, float A, float B, float C)
{
if (A > B)
{
if (C > A)
C = A;
if (C < B)
C = B;
}
else
{
if (C < A)
C = A;
if (C > B)
C = B;
}
return (int)(a - (A - C) / (A - B) * (a - b));
}
public static long Clamp(long value, long min, long max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
public static GameObject CreateQuad(Material material, string name)
{
GameObject quad = new GameObject(name);
Mesh mesh = new Mesh();
Vector3[] vectors = new Vector3[4];
vectors[0] = new Vector3(-0.5f, -0.5f, 0);
vectors[1] = new Vector3(0.5f, -0.5f, 0);
vectors[2] = new Vector3(-0.5f, 0.5f, 0);
vectors[3] = new Vector3(0.5f, 0.5f, 0);
Vector2[] uvs = new Vector2[4];
uvs[0] = new Vector2(0, 0);
uvs[1] = new Vector2(1, 0);
uvs[2] = new Vector2(0, 1);
uvs[3] = new Vector2(1, 1);
int[] triangles = new int[6] { 0, 2, 1, 1, 2, 3 };
mesh.vertices = vectors;
mesh.uv = uvs;
mesh.triangles = triangles;
MeshFilter meshFilter = quad.AddComponent<MeshFilter>();
meshFilter.sharedMesh = mesh;
MeshRenderer meshRender = quad.AddComponent<MeshRenderer>();
meshRender.sharedMaterial = material;
return quad;
}
public static void MoveToShelterCamera(Camera camera, Transform trans, float distance)
{
if (camera == null || trans == null)
return;
float d = camera.nearClipPlane + distance;
float rad = (camera.fieldOfView / 2f) * Mathf.Deg2Rad;
float h = 2 * Mathf.Tan(rad) * d;
float l = camera.aspect * h;
Vector3 scale = new Vector3(l, h, trans.localScale.z);
trans.localScale = scale;
trans.parent = camera.transform;
trans.localPosition = new Vector3(0, 0, d);
trans.localRotation = Quaternion.identity;
}
/// <summary>
/// 将transform的绕Y轴偏转的弧度,转成一个Quaternion
/// </summary>
/// <param name="angel"></param>
/// <returns></returns>
public static Quaternion MakeYEulerToRotation(float rad)
{
Quaternion rot = Quaternion.Euler(Vector3.up * Mathf.Rad2Deg * rad);
return rot;
}
public static bool GetVector3OfStringList(List<string> strList, int index, ref Vector3 vector)
{
vector = Vector3.zero;
if (strList != null)
{
int idx = index * 3;
if (strList.Count >= 3 * (index + 1))
{
vector = new Vector3(Convert.ToSingle(strList[0 + idx]), Convert.ToSingle(strList[1 + idx]), Convert.ToSingle(strList[2 + idx]));
return true;
}
}
return false;
}
//获取某一技能升级level次的功能描述//
public static string GetPlayerSkillFunctionDes(PlayerSkillContent config, int level)
{
// 0级时读取1级的描述
if (level == 0)
{
level = 1;
}
while (level > config.MaxUpgradeNum)
{
level -= config.MaxUpgradeNum;
config = HolderManager.m_PlayerSkillHolder.GetStaticInfo(config.NextPhase);
}
List<object> desParams = new List<object>();
if (config.FunctionDescribeParams.Count != 0)
{
for (int i = 0; i < config.FunctionDescribeParams.Count; i++)
{
if (config.FunctionDescribeParams[i].list.Count == 1)
{
desParams.Add(config.FunctionDescribeParams[i].list[0].ToString());
}
else if (config.FunctionDescribeParams[i].list.Count == 2)
{
float baseValue = float.Parse(config.FunctionDescribeParams[i].list[0].Replace("%", ""));
float step = float.Parse(config.FunctionDescribeParams[i].list[1].Replace("%", ""));
string tmpStr = (baseValue + step * level).ToString();
if (config.FunctionDescribeParams[i].list[0].Contains("%"))
{
tmpStr += "%";
}
desParams.Add(tmpStr);
}
else
{
CDebug.LogError("TODO Leo");
}
}
}
if (desParams.Count != 0)
return CCommon.GetTextS(config.FunctionDescribe, desParams.ToArray());
else
return CCommon.GetText(config.FunctionDescribe);
}
//获取某一技能升级level次的功能描述//
public static string GetMarkFunctionDes(MarkContent config)
{
List<object> desParams = new List<object>();
if (config.FunctionDesParams.Count != 0)
{
for (int i = 0; i < config.FunctionDesParams.Count; i++)
{
if (config.FunctionDesParams[i].list.Count == 1)
{
desParams.Add(config.FunctionDesParams[i].list[0].ToString());
}
else if (config.FunctionDesParams[i].list.Count == 2)
{
float baseValue = float.Parse(config.FunctionDesParams[i].list[0].Replace("%", ""));
float step = float.Parse(config.FunctionDesParams[i].list[1].Replace("%", ""));
desParams.Add((baseValue + step).ToString());
}
else
{
CDebug.LogError("TODO Leo");
}
}
}
if (desParams.Count != 0)
return CCommon.GetTextS(config.FunctionDes, desParams.ToArray());
else
return CCommon.GetText(config.FunctionDes);
}
public static bool IsNumber(object obj)
{
if (obj != null)
{
string str = obj.ToString();
if (!string.IsNullOrEmpty(str))
{
char[] chars = str.ToCharArray();
int length = chars.Length;
for (int i = 0; i < length; i++)
{
if (chars[i] == '.')
{
continue;
}
if (!char.IsNumber(chars[i]))
{
return false;
}
}
return true;
}
}
return false;
}
public static Vector3 Vector3Mulity(Vector3 a, Vector3 b)
{
a.x *= b.x;
a.y *= b.y;
a.z *= b.z;
return a;
}
//找到navmesh上最近的点
public static Vector3 NavSamplePosition(Vector3 srcPosition)
{
Vector3 dstPosition = srcPosition;
UnityEngine.AI.NavMeshHit meshHit = new UnityEngine.AI.NavMeshHit();
int layer = 1 << UnityEngine.AI.NavMesh.GetAreaFromName("Walkable");
if (UnityEngine.AI.NavMesh.SamplePosition(srcPosition, out meshHit, 5f, layer))
{
dstPosition = meshHit.position;
}
return dstPosition;
}
//找出地面碰撞点
public static Vector3 GroundPosition(Vector3 srcPosition, int terrainLayer)
{
Ray ray = new Ray(srcPosition + Vector3.up * 5, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100, 1 << terrainLayer))
{
return hit.point;
}
return Vector3.zero;
}
/// <summary>
/// 获取玩家拥有物品的个数//
/// </summary>
public static long GetItemNum(int itemID)
{
return PlayerPropertyManager.Instance.PlayerInfo.GetSpecialItemCount(itemID);
}
/// <summary>
/// 获取物品对应的Icon名
/// </summary>
/// <param name="dataId"></param>
/// <returns></returns>
public static string GetItemIconById(int dataId)
{
string retValue = null;
eIDType type = GetTypeFormID(dataId);
switch (type)
{
case eIDType.Equip:
{
EquipContent equipContent = HolderManager.m_EquipHolder.GetStaticInfo(dataId);
if (null != equipContent)
{
EquipModelContent equipModelContent = HolderManager.m_EquipModelHolder.GetStaticInfo(equipContent.ModelID);
if (null != equipModelContent)
{
retValue = equipModelContent.Icon;
}
}
}
break;
case eIDType.Item:
{
ItemContent itemContent = HolderManager.m_ItemHolder.GetStaticInfo(dataId);
if (null != itemContent)
{
retValue = itemContent.IconPath;
}
}
break;
default:
break;
}
return retValue;
}
/// <summary>
/// 拆分数字
/// </summary>
/// <param name="num">数字</param>
/// <param name="startIndex">开始拆分索引值(从0开始,左往右递增)</param>
/// <returns></returns>
public static int Subint(this int num, int startIndex)
{
string number = num.ToString();
number = number.Substring(startIndex);
return int.Parse(number);
}
/// <summary>
/// 拆分数字
/// </summary>
/// <param name="num">数字</param>
/// <param name="startIndex">开始拆分索引值(从0开始,左往右递增)</param>
/// <param name="length">拆分长度</param>
/// <returns></returns>
public static int Subint(this int num, int startIndex, int length)
{
string number = num.ToString();
number = number.Substring(startIndex, length);
return int.Parse(number);
}
/// <summary>
/// 根据PlayerSkill或者Mark表的Key,识别唯一技能或者印记//
/// </summary>
/// <returns>The player skill or mark index.</returns>
/// <param name="key">Key.</param>
public static int GetPlayerSkillOrMarkIndex(int key)
{
return Mathf.FloorToInt(key / 100);
}
/// <summary>
/// 将曲线字符串,转换成曲线值数组
/// </summary>
/// <param name="curveList"></param>
/// <returns></returns>
public static Keyframe[] GetKeyframes(List<float> curveList)
{
int len = 0;
if (curveList != null)
{
len = curveList.Count;
}
Keyframe[] keyframes;
if (len < 4)
{
keyframes = new Keyframe[2];
keyframes[0] = new Keyframe(0, 0);
keyframes[1] = new Keyframe(1, 1);
}
else
{
keyframes = new Keyframe[(len / 4) + 2];
keyframes[0] = new Keyframe(0, 0);
int idx = 1;
for (int i = 0; i < len; i += 4)
{
Keyframe kf = new Keyframe(CConvert.ToSingle(curveList[i]), CConvert.ToSingle(curveList[i + 1]),
CConvert.ToSingle(curveList[i + 2]), CConvert.ToSingle(curveList[i + 3]));
keyframes[idx] = kf;
idx++;
}
keyframes[keyframes.Length - 1] = new Keyframe(1, 1);
}
return keyframes;
}
/// <summary>
/// 返回物品的种类
/// </summary>
/// <param name="itemId"></param>
/// <returns></returns>
public static eItemType GetItemType(int itemId)
{
ItemContent ic = HolderManager.m_ItemHolder.GetStaticInfo(itemId);
if (ic != null)
{
return (eItemType)ic.Type;
}
return eItemType.None;
}
/// <summary>
/// 通过ID得到是装备还是物品
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static eIDType GetTypeFormID(int id)
{
int t = id / 10000000;
if (t == 3)
{
return eIDType.Equip;
}
else if (t == 4)
return eIDType.Item;
else
return eIDType.Error;
}
private static List<int> ToggleGroups = new List<int>() { 6666 };
/// <summary>
/// 获取一个从未使用过的Group id//
/// </summary>
/// <returns>The un use group id.</returns>
public static int GetUnUseGroupID()
{
ToggleGroups.Add(ToggleGroups[ToggleGroups.Count - 1] + 2);
return ToggleGroups[ToggleGroups.Count - 1];
}
public static string GetQualityName(int quality)
{
if (quality > 0 && quality < 7)
return CCommon.GetText(28000031 + quality);
else if (quality == 0)
return CCommon.GetText(27100013);
return "";
}
public static string GetQualityName(eQuality quality)
{
return GetQualityName((int)quality);
}
public static string GetItemQualityBoard(int itemQuality)
{
switch (itemQuality)
{
case 1:
return "floor_quality_white";
case 2:
return "floor_quality_green";
case 3:
return "floor_quality_blue";
case 4:
return "floor_quality_purple";
case 5:
return "floor_quality_red";
case 6:
return "floor_quality_yellow";
default:
return "frame_forge_quality_dark";
}
}
public static string GetEquipQualityBoard(eQuality qua)
{
switch (qua)
{
case eQuality.None:
return "frame_forge_quality_dark";
case eQuality.White_Bronze:
return "floor_quality_white";
case eQuality.Green_Silver:
return "floor_quality_green";
case eQuality.Blue_Gold:
return "floor_quality_blue";
case eQuality.Purple_Epic:
return "floor_quality_purple";
case eQuality.Red_Legend:
return "floor_quality_red";
case eQuality.Orange_Artifact:
return "floor_quality_yellow";
}
return "floor_quality_white";
}
/// <summary>
/// 激活 / 不激活 显示对象
/// </summary>
/// <param name="goList"></param>
/// <param name="flg"></param>
public static void ActiveGameObjectList(List<GameObject> goList, bool flg)
{
if (goList != null)
{
int length = goList.Count;
for (int i = 0; i < length; i++)
{
goList[i].SetActive(flg);
}
}
}
#region 设置品质背景框
public static string[] QualitySpriteName = new string[]
{
//"frame_forge_quality_dark",
"floor_quality_white",
"floor_quality_green",
"floor_quality_blue",
"floor_quality_purple",
"floor_quality_red",
"floor_quality_yellow",
};
public static void SetQualityBgSprite(CPanel cpanel, string spriteName, eQuality quality, bool isNeedPerfect = false)
{
if (null == cpanel || string.IsNullOrEmpty(spriteName))
return;
CSprite sprite = cpanel.GetElementBase(spriteName) as CSprite;
if (null != sprite && quality != eQuality.None)
{
UIAtlas atlas = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_SYSTEM_FLOOR2);
sprite.SetSprite(atlas, GetEquipQualityBoard(quality), isNeedPerfect);
}
}
#endregion
#region 设置物品品质的背景图
public static string[] ItemQualitySpriteName = new string[]
{
"frame_forge_quality_dark",
"floor_quality_white",
"floor_quality_green",
"floor_quality_blue",
"floor_quality_purple",
"floor_quality_red",
"floor_quality_yellow",
};
/// <summary>
/// 设置物品的品质背景图
/// </summary>
/// <param name="cpanel"></param>
/// <param name="spriteName"></param>
/// <param name="quality">eEquipQuality</param>
/// <param name="isNeedPerfect">是否图片紧贴</param>
public static void SetItemQualitySprite(CPanel cpanel, string spriteName, eQuality quality, bool isNeedPerfect = false)
{
if (cpanel == null || string.IsNullOrEmpty(spriteName))
{
return;
}
CSprite sprite = cpanel.GetElementBase(spriteName) as CSprite;
if (sprite != null)
{
UIAtlas atlasname = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_SYSTEM_FLOOR2);
sprite.SetSprite(atlasname, GetEquipQualityBoard(quality), isNeedPerfect);
}
}
public static void SetItemQualitySprite(CSprite sprite, eQuality quality, bool isNeedPerfect = false)
{
if (sprite == null)
{
return;
}
UIAtlas atlasname = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_SYSTEM_FLOOR2);
sprite.SetSprite(atlasname, GetEquipQualityBoard(quality), isNeedPerfect);
}
public static void SetItemQualityButton(CButton button, eQuality quality, bool isNeedPerfect = false)
{
if (button == null)
{
return;
}
button.MySprite.spriteName = GetEquipQualityBoard(quality);
}
/// <summary>
/// 设置UI特效层级
/// uiEffectGo加载未完成,或刚才加载完时设置,有可能无效。用第二种方法
/// </summary>
/// <param name="panel"></param>
/// <param name="uiEffectGo"></param>
public static void SetUiEffectQuquq(UIWidget uiWidget, GameObject uiEffectGo, int adddDeath = 1)
{
if (uiEffectGo != null)
{
UIParticleRenderQuquq ququq = uiEffectGo.GetComponent<UIParticleRenderQuquq>();
if (ququq == null)
{
ququq = uiEffectGo.AddComponent<UIParticleRenderQuquq>();
}
if (uiWidget != null)
{
//ququq.Depth = uiWidget.depth - 1;
if (uiWidget.panel == null)
{
uiWidget.panel = uiWidget.CreatePanel();
}
if (uiWidget.panel != null)
{
BetterList<UIDrawCall> dcs = uiWidget.panel.drawCalls;
if (dcs != null)
{
int idx = dcs.size - 1;
if (idx > 0)
{
ququq.SetRenderQueue(dcs[idx].renderQueue + adddDeath);
}
return;
}
}
}
}
}
public static void SetUiEffectDepth(UIWidget uiWidget, GameObject uiEffectGo, int adddDeath = 1)
{
if (uiEffectGo != null)
{
UIParticleRenderQuquq ququq = uiEffectGo.GetComponent<UIParticleRenderQuquq>();
if (ququq == null)
{
ququq = uiEffectGo.AddComponent<UIParticleRenderQuquq>();
}
if (uiWidget != null)
{
ququq.Depth = uiWidget.depth + adddDeath;
}
}
}
public static void SetGameObjectDepth(GameObject uiEffectGo, int adddDeath = 1)
{
if (uiEffectGo != null)
{
UIParticleRenderQuquq ququq = uiEffectGo.GetComponent<UIParticleRenderQuquq>();
if (ququq == null)
{
ququq = uiEffectGo.AddComponent<UIParticleRenderQuquq>();
}
ququq.Depth = 3000 + adddDeath;
}
}
/// <summary>
/// 设置UI特效层级
/// </summary>
/// <param name="panel"></param>
/// <param name="uiEffectGo"></param>
public static void LoadUiEffectCallback(GameObject uiEffectGo, int setDepth = 10, UIWidget widget = null)
{
if (uiEffectGo != null)
{
uiEffectGo.transform.localPosition = new Vector3(0, 0, 0);
uiEffectGo.transform.localScale = Vector3.one;
uiEffectGo.gameObject.SetActive(false);
uiEffectGo.gameObject.SetActive(true);
if (!widget) widget = NGUITools.FindInParents<UIWidget>(uiEffectGo);
CCommon.SetUiEffectDepth(widget, uiEffectGo, 100);
}
}
#endregion
public static DateTime ConvertServerTime(int seconds)
{
return new DateTime(1970, 1, 1).AddSeconds((double)seconds);
}
/// <summary>
/// DateTime 转 时间 Unix时间戳格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static double DateTimeToStamp(DateTime dt)
{
DateTime startDt = new DateTime(1970, 1, 1, 0, 0, 0, dt.Kind);
return (dt - startDt).TotalSeconds;
}
/// <summary>
/// Unix时间戳 转 DateTime
/// </summary>
/// <param name="target"></param>
/// <param name="stampTime"></param>
/// <returns></returns>
public static DateTime StampToDateTime(DateTime target, double stampTime)
{
DateTime startDt = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
return startDt.AddSeconds(stampTime);
}
public static DateTime ConvertServerTime(double seconds)
{
return new DateTime(1970, 1, 1).AddSeconds(seconds);
}
public static eErrorType CheckErrorCode(int code, object[] args = null)
{
eErrorType et = (eErrorType)code;
if (et != eErrorType.eError_Success)
{
string errorStr = CCommon.GetTextS(80000000 + code, args);
if (errorStr != "$N/A")
{
#if UNITY_EDITOR
errorStr = "Error:" + code.ToString() + "," + errorStr;
#else
errorStr = errorStr;
#endif
ShowTextTip(errorStr);
}
else
{
#if UNITY_EDITOR
ShowTextTip("GUIText表缺少 [ff0000]" + (80000000 + code) + "[-] 的错误文本!");
#else
ShowTextTip("error [ff0000]"+code+"[-]");
#endif
}
}
return et;
}
/// <summary>
/// 从时间段列表中,对比当前时间取下一刷新时间的秒数
/// </summary>
/// <param name="timeStr"></param>
/// <returns></returns>
public static float GetRemainTimeByRefreshTimeList(string timeStr)
{
string[] timeList = timeStr.Split('~');
System.DateTime time = LoginManager.Instance.GetServerUtcDateTime();
int curSecond = (time.Hour + 8) % 24 * 3600 + time.Minute * 60 + time.Second;//utc时间+8小时=本地时间
int startSecond = 0;
int i = 0;
for (i = 0; i < timeList.Length; i++)
{
string[] childTime = timeList[i].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
if (startSecond > curSecond)//大于当前时间,则取该时间段作为刷新时间
{
startSecond -= curSecond;
break;
}
}
if (i >= timeList.Length)//已经过了今天最后一次刷新时间,则取第一次的
{
string[] childTime = timeList[0].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
startSecond = startSecond + (24 * 3600 - curSecond);
}
return startSecond;
}
/// <summary>
/// 从时间段列表中,对比当前时间取已刷新的开始时间
/// </summary>
/// <param name="timeStr"></param>
/// <returns>返回已开始多少秒</returns>
public static float GetRefreshTimeByRefreshTimeList(string timeStr)
{
string[] timeList = timeStr.Split('~');
System.DateTime time = LoginManager.Instance.GetServerUtcDateTime();
int curSecond = (time.Hour + 8) % 24 * 3600 + time.Minute * 60 + time.Second;//utc时间+8小时=本地时间
int startSecond = 0;
int i = 0;
bool isFind = false;
for (i = timeList.Length - 1; i >= 0; i--)
{
string[] childTime = timeList[i].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
if (startSecond <= curSecond)//小于当前时间,则取该时间段作为刷新时间
{
curSecond -= startSecond;
isFind = true;
break;
}
}
if (!isFind)//已经过了今天最后一次刷新时间,则取最后一次的
{
string[] childTime = timeList[timeList.Length - 1].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
curSecond += 24 * 3600;//加上一天的秒数
curSecond -= startSecond;
}
return curSecond;
}
/// <summary>
/// 获取离线时间
/// 离线时间<1小时,则显示已离线N分钟,不足1分钟的显示一分钟
/// 离线时间<24小时,则显示已离线N小时(隐藏分钟,满足60分钟,才会加1小时)
/// 离线时间>1天,则显示已离线N天N小时(隐藏分钟,满足60分钟,才会加1小时)
/// </summary>
/// <param name="timeBegin"></param>
/// <param name="timeEnd"></param>
/// <returns></returns>
public static string GetOutlineTimeStr(DateTime timeBegin, DateTime? timeEnd = null)
{
string result = string.Empty;
if (timeEnd == null)
timeEnd = LoginManager.Instance.GetServerUtcDateTime();
TimeSpan timeSpan = (DateTime)timeEnd - timeBegin;
long value = timeSpan.Ticks;
if (value > TimeSpan.TicksPerDay)
{
value /= TimeSpan.TicksPerDay;
long lefthour = timeSpan.Ticks - value * TimeSpan.TicksPerDay;
if (lefthour > TimeSpan.TicksPerHour)
{
lefthour /= TimeSpan.TicksPerHour;
return GetTextS(81100086, value) + GetText(81100089) + lefthour + GetText(81100088);
}
else
return GetTextS(81100086, value) + GetText(81100089);
}
else if (value > TimeSpan.TicksPerHour)
{
value /= TimeSpan.TicksPerHour;
return GetTextS(81100086, value) + GetText(81100088);
}
else if (value > TimeSpan.TicksPerMinute)
{
value /= TimeSpan.TicksPerMinute;
return GetTextS(81100086, value) + GetText(81100087);
}
else
{
return GetTextS(81100086, 1) + GetText(81100087);
}
}
public static int BaseKeyComtentSortByKey(BaseContent a, BaseContent b)
{
return a.Key.CompareTo(b.Key);
}
public static eMapType Key2MapType(int key)
{
if (key / 1000000 == (int)eMapType.Main)
{
return eMapType.MapLand;
}
return (eMapType)(key / 1000000);
}
public static string GetPlayerJobIcon(ePlayerJob job)
{
return GetPlayerJobIcon((int)job);
}
public static string GetPlayerJobIcon(int job)
{
PlayerConfigContent content = CData.Instance.GetPlayerConfigContent(job);
if (content != null)
return content.JobIcon;
else
return "";
}
public static string GetPlayerHeadIcon(ePlayerJob job)
{
return GetPlayerHeadIcon((int)job);
}
public static string GetPlayerHeadIcon(int job)
{
PlayerConfigContent content = CData.Instance.GetPlayerConfigContent(job);
if (content != null)
return content.HeadIcon;
else
return "";
}
/// <summary>
/// 通过职业获取职业名
/// </summary>
/// <param name="Career"></param>
/// <returns></returns>
public static string GetPlayerNameByCareer(int Career)
{
PlayerContent content = CData.Instance.GetPlayerContent((ePlayerJob)Career);
if (content != null)
return CCommon.GetText(content.NameID);
else
return "";
}
//获取优化后的数字显示,以后策划调整规则统一这里改//
public static string GetOptionNumString(ulong num)
{
if (num >= 1000000)
{//亿//
return Mathf.FloorToInt(num / 10000f).ToString() + "W";
}
return num.ToString();
}
/// <summary>
/// 获取通过条件各类型的描述
/// </summary>
/// <returns></returns>
public static string GetDungeonGradeTitle(eEvaluateType type, bool isMulMap = false)
{
string evaluateTitle = null;
switch (type)
{
case eEvaluateType.ClearanceTime:
evaluateTitle = GetText(50010003);
break;
case eEvaluateType.NumberOfAttacks:
{
if (isMulMap)
{
evaluateTitle = GetText(50010009);
}
else
{
evaluateTitle = GetText(50010004);
}
}
break;
case eEvaluateType.PlayerLeftoverHp:
if (isMulMap)
{
evaluateTitle = GetText(50010010);
}
else
{
evaluateTitle = GetText(50010005);
}
break;
case eEvaluateType.NpcLeftoverHp:
evaluateTitle = GetText(50010006);
break;
case eEvaluateType.NumOfAllPlayerDie:
evaluateTitle = GetText(50010007);
break;
case eEvaluateType.ParkourTimeScore:
evaluateTitle = GetText(76000014);
break;
case eEvaluateType.ParkourPropScore:
evaluateTitle = GetText(76000015);
break;
case eEvaluateType.ParkourPassScore:
evaluateTitle = GetText(76000016);
break;
case eEvaluateType.ParkourExtraPlus:
evaluateTitle = GetText(76000017);
break;
case eEvaluateType.FulfillTask:
evaluateTitle = GetText(50030043);
break;
default:
break;
}
return evaluateTitle;
}
public static string GetDungeonGradeDes(eEvaluateType type, int value)
{
string evaluateDes = null;
switch (type)
{
case eEvaluateType.ClearanceTime:
evaluateDes = "" + value + "s";
break;
case eEvaluateType.NumberOfAttacks:
evaluateDes = "" + value;
break;
case eEvaluateType.PlayerLeftoverHp:
evaluateDes = "" + value + "%";
break;
case eEvaluateType.NpcLeftoverHp:
evaluateDes = "" + value + "%";
break;
case eEvaluateType.NumOfAllPlayerDie:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourTimeScore:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourPropScore:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourPassScore:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourExtraPlus:
evaluateDes = "" + value;
break;
case eEvaluateType.FulfillTask:
evaluateDes = "" + value;
break;
default:
break;
}
return evaluateDes;
}
/// <summary>
/// 通过评分等级获取对应图片名
/// </summary>
/// <returns></returns>
public static string GetEvaluateScoreIcon(eEvaluateScoreType type)
{
string spriteName = null;
switch (type)
{
case eEvaluateScoreType.S:
spriteName = "icon_copy_s";
break;
case eEvaluateScoreType.A:
spriteName = "icon_copy_a";
break;
case eEvaluateScoreType.B:
spriteName = "icon_copy_b";
break;
case eEvaluateScoreType.C:
spriteName = "icon_copy_c";
break;
case eEvaluateScoreType.D:
spriteName = "icon_copy_d";
break;
default:
break;
}
return spriteName;
}
public static bool IsQuestHolder(int id)
{
return id / 10000000 == 6;
}
public static bool IsNpcHolder(int id)
{
return id < 100000000;
}
public static bool IsAvatarDead()
{
if (CGameWorld.Instance.CurrentState == EGameState.Battle)
{
if (CGameWorld.Instance.CurrentScene.IsSea)
{
return CShipAvatar.Instance.IsDead;
}
}
return CAvatar.Instance.IsDead;
}
/// <summary>
/// 获取周几字符串
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string GetDayOfWeekStringByDateTime(DateTime date)
{
DayOfWeek day = date.DayOfWeek;
string str = string.Empty;
switch (day)
{
case DayOfWeek.Monday:
str = GetText(64000022);
break;
case DayOfWeek.Tuesday:
str = GetText(64000023);
break;
case DayOfWeek.Wednesday:
str = GetText(64000024);
break;
case DayOfWeek.Thursday:
str = GetText(64000025);
break;
case DayOfWeek.Friday:
str = GetText(64000026);
break;
case DayOfWeek.Saturday:
str = GetText(64000027);
break;
case DayOfWeek.Sunday:
str = GetText(64000028);
break;
}
return str;
}
/// <summary>
/// 获取几月几日字符串
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string GetMonthDayStringByDateTime(DateTime date)
{
string str = date.Month + CCommon.GetText(73020022) + date.Day + CCommon.GetText(77000026);
return str;
}
/// <summary>
/// 格式化时间00:00:00
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public static string GetTimeBySecond(double seconds)
{
return DateTime.Parse(DateTime.Now.ToString("00:00:00")).AddSeconds(seconds).ToString("HH:mm:ss");
}
public static string GetDateStringByDateTime(DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd");
}
public static string GetMinuteBySecond(float seconds)
{
return DateTime.Parse(DateTime.Now.ToString("00:00")).AddSeconds(seconds).ToString("mm:ss");
}
public static string GetNowTimeByMinute()
{
return DateTime.Now.ToString("HH:mm");
}
public static string GetTimeStrByHours(double hours)
{
string date = "";
int daysTemp = (int)hours / 24;
int hoursTemp = (int)hours % 24;
if (daysTemp != 0)
date = daysTemp + GetText(70000033);
if (hoursTemp != 0)
date += hoursTemp + GetText(70000034);
return date;
}
public static string GetTimeStrByHoursMinuteSecond(float second, string tab = ":")
{
int h = Mathf.FloorToInt(second / 3600);
int m = Mathf.FloorToInt(second % 3600 / 60);
int s = Mathf.FloorToInt(second % 3600 % 60);
return h + tab + m + tab + s;
}
public static string GetTimeStrByMinuteSecond(float second, string tab = ":")
{
int m = Mathf.FloorToInt(second / 60);
int s = Mathf.FloorToInt(second % 60);
return m + tab + s;
}
public static void IgnoreCollision(UnityEngine.Collider collider1, UnityEngine.Collider collider2, bool state = true)
{
if (null == collider1 || null == collider2)
{
Debug.LogWarning(" Error ! collider para is null !");
return;
}
Transform trans1 = collider1.transform;
Transform trans2 = collider2.transform;
if (null == trans1 || null == trans2)
{
return;
}
if (!trans1.root.gameObject.activeInHierarchy || !trans2.root.gameObject.activeInHierarchy)
{
return;
}
if (!collider1.enabled || !collider2.enabled)
return;
//MyLog.Log(" IgonreCollision : " + collider1.name + " and " + collider2.name);
Physics.IgnoreCollision(collider1, collider2, state);
}
public static object[] StringListToObjectArray(List<string> stringList)
{
List<object> desParams = new List<object>();
for (int i = 0, count = stringList.Count; i < count; i++)
{
desParams.Add(stringList[i].ToString());
}
return desParams.ToArray();
}
public static bool AssetListIndex<T>(List<T> list, int index, bool debug = true)
{
if (list.Count > index)
{
return true;
}
else
{
if (debug)
Debug.LogError("index out of list count");
return false;
}
}
public static string TimeFormatDHMS(ulong time)
{
string str = "";
ulong residualVal = 0;
ulong days = time / (60 * 60 * 24); //天
residualVal = time % (60 * 60 * 24);
ulong hours = residualVal / (60 * 60); //时
residualVal = residualVal % (60 * 60);
ulong minutes = residualVal / 60; //分
residualVal = residualVal % 60; //秒
if (days > 0)
{
str = GetTextS(59003017, Convert.ToInt32(days), Convert.ToInt32(hours), Convert.ToInt32(minutes));
}
else
{
str = GetTextS(59003018, Convert.ToInt32(hours), Convert.ToInt32(minutes), Convert.ToInt32(residualVal));
}
return str;
}
public static string SecondToString(ulong seconds, eDateStringType dataType)
{
string retStr = "";
ulong residualVal = 0;
ulong days = seconds / (60 * 60 * 24); //天
residualVal = seconds % (60 * 60 * 24);
ulong hours = residualVal / (60 * 60); //时
residualVal = residualVal % (60 * 60);
ulong minutes = residualVal / 60; //分
residualVal = residualVal % 60; //秒
switch (dataType)
{
case eDateStringType.Seconds:
retStr = String.Format("{0:D2}", residualVal);
break;
case eDateStringType.Minutes:
retStr = String.Format("{0:D2}:{1:D2}", minutes, residualVal);
break;
case eDateStringType.Hours:
retStr = String.Format("{0:D2}:{1:D2}:{2:D2}", hours, minutes, residualVal);
break;
case eDateStringType.Days:
retStr = String.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}", days, hours, minutes, residualVal);
break;
default:
break;
}
return retStr;
}
/// <summary>
/// 当天是本月的第几周
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static int GetWeekNumInMonth(DateTime dt)
{
int dayInMonth = dt.Day;
DateTime firstDay = dt.AddDays(1 - dt.Day);
int weekDay = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;
int firstWeekEndDay = 7 - (weekDay - 1);
int diffDay = dayInMonth - firstWeekEndDay;
diffDay = diffDay > 0 ? diffDay : 1;
int weekNumInMonth = (diffDay % 7) == 0 ? (diffDay / 7 - 1) : (diffDay / 7) + 1 + ((dayInMonth > firstWeekEndDay) ? 1 : 0);
return weekNumInMonth;
}
/// <summary>
/// 获取本周起始时间,即本周一0点0分0秒
/// </summary>
/// <returns></returns>
public static DateTime GetWeekBeginTime()
{
DateTime today = LoginManager.Instance.GetServerUtcDateTime();
int weekDay = (int)today.DayOfWeek == 0 ? 7 : (int)today.DayOfWeek;
weekDay -= 1; //周一
var year = today.Year;
var month = today.Month;
var day = today.Day - weekDay;
var weekBeginTime = new DateTime(year, month, day, 0, 0, 0);
return weekBeginTime;
}
public static void ShowDebugPopDialog(string text)
{
ShowPopDialog(text, null, Color.red, null, null);
}
/// <summary>
///
/// </summary>
/// <param name="text">文本提示</param>
/// <param name="action">反馈回调</param>
/// <param name="args">反馈参数</param>
/// <param name="popKey">忽略键值,用于不再提示功能,一般取默认值</param>
public static void ShowPopDialog(string text, Action<bool, object> action, object args = null, object popKey = null,
eTipsModel mode = eTipsModel.Tips_TwoBtn, float limitTime = -1, string title = "",
bool showCancelCd = false, bool showConfirmCd = false)
{
ShowPopDialog(text, action, Color.white, args, popKey, mode, limitTime, title, showCancelCd, showConfirmCd);
}
public static void ShowCountDownPopDialog(string text, Action<bool, object> action, int countDownTime, string title = "")
{
SingleObject<YesOrNoDialoag>.Instance.Show(delegate()
{
SingleObject<YesOrNoDialoag>.Instance.InitDialog(text, action, countDownTime, title);
}, true);
}
private static void ShowPopDialog(string text, Action<bool, object> action, Color color, object args, object popKey, eTipsModel mode = eTipsModel.Tips_TwoBtn, float limitTime = -1, string title = "", bool showCancelCd = false, bool showConfirmCd = false)
{
SingleObject<YesOrNoDialoag>.Instance.Show(delegate()
{
SingleObject<YesOrNoDialoag>.Instance.InitDialog(text, action, color, args, popKey, mode, limitTime, title, showCancelCd, showConfirmCd);
}, true);
}
/// <summary>
/// 查询进入 活动 限制人数 Usual表
/// 0:通过,1:不在组队状态,2:在组队状态,3:在组队状态人数不足
/// </summary>
/// <param name="usualId"></param>
/// <returns></returns>
public static int CheckUsualLimitPeople(int usualId)
{
int canOpen = 0;
UsualContent usual = HolderManager.m_UsualHolder.GetStaticInfo(usualId);
if (usual == null)
{
return canOpen;
}
List<int> limit = usual.LimitPeople;
int teamerCount = CTeamManager.Instance.TeamerCount;
if (limit.Count == 2)
{
if (limit[0] == 1 && limit[1] == 1)
{
canOpen = teamerCount > 0 ? 2 : 0;
}
else
{
if (teamerCount <= 0)
{
canOpen = 1;
}
else if (teamerCount >= limit[0] && teamerCount <= limit[1])
{
canOpen = 0;
}
else
{
canOpen = 3;
}
}
}
return canOpen;
}
/// <summary>
/// 查询进入 活动 限制人数 Usual表
/// 0:通过,1:不在组队状态,2:在组队状态,3:在组队状态人数不足
/// </summary>
/// <param name="usualId"></param>
/// <returns></returns>
public static int CheckUsualLimitPeople(int min, int max)
{
int canOpen = 0;
int teamerCount = CTeamManager.Instance.TeamerCount;
int limitMin = min;
int limitMax = max;
if (limitMin == 1 && limitMax == 1)
{
canOpen = teamerCount > 0 ? 2 : 0;
}
else
{
if (teamerCount <= 0)
{
canOpen = 1;
}
else if (teamerCount >= limitMin && teamerCount <= limitMax)
{
canOpen = 0;
}
else
{
canOpen = 3;
}
}
return canOpen;
}
public static bool CheckIsOpen(int openContentID, ref int targetLevel)
{
OpenContent open = HolderManager.m_OpenHolder.GetStaticInfo(openContentID);
if (open != null)
{
OpenModuleCondition openCondition = (OpenModuleCondition)open.OpenCondition;
switch (openCondition)
{
case OpenModuleCondition.finishTask: break;
case OpenModuleCondition.level:
{
int level = SingleObject<PlayerPropertyManager>.Instance.PlayerProperty.GetIntProperty(eProtoAttData.ePlayerData_Level);
targetLevel = open.ConditionParam;
if (level < targetLevel)
{
return false;
}
}
break;
case OpenModuleCondition.receiveTask: break;
}
return true;
}
return false;
}
public static bool CheckIsOpen(int openContentID)
{
int level = 0;
return CheckIsOpen(openContentID, ref level);
}
/// <summary>
/// 查询进入 活动 条件是否成立(开启条件) Usual表
/// </summary>
/// <param name="usualId"></param>
/// <returns></returns>
public static bool CheckUsualOpenCondition(int usualId, bool needShopTips = true)
{
bool canOpen = false;
UsualContent usual = HolderManager.m_UsualHolder.GetStaticInfo(usualId);
if (usual == null)
{
return canOpen;
}
//开启条件判断
switch (usual.OpenCondition)
{
case 1:
canOpen = usual.OpenConditionParams <= PlayerPropertyManager.Instance.PlayerProperty.GetIntProperty(eProtoAttData.ePlayerData_Level);
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetTextS(19020001, usual.OpenConditionParams));//等级不足
}
}
break;
case 2://完成任务
break;
case 3://接到任务
break;
case 4:
int targetLevel = 0;
canOpen = CheckIsOpen(usual.OpenConditionParams, ref targetLevel);
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetTextS(19020001, targetLevel));//等级不足
}
}
break;
}
return canOpen;
}
/// <summary>
/// 查询进入 活动 条件是否成立(开启条件, 开启日期, 开启时段) Usual表
/// </summary>
/// <param name="usualId"></param>
/// <param name="ignoreOpenCondition">忽略开启条件</param>
/// <returns></returns>
public static bool CheckUsualOpenConditionAndTime(int usualId, bool ignoreOpenCondition = true, bool needShopTips = true)
{
bool canOpen = false;
UsualContent usual = HolderManager.m_UsualHolder.GetStaticInfo(usualId);
if (usual == null)
{
return canOpen;
}
//开启条件判断
if (ignoreOpenCondition)
{
canOpen = CheckUsualOpenCondition(usualId, needShopTips);
if (!canOpen)
{
return canOpen;
}
}
DateTime dt = LoginManager.Instance.GetServerCurGMTDataTime();
//开启日期判断
List<BaseStringContent> openDays = usual.OpenDay;
if (openDays != null)
{
int length = openDays.Count;
for (int i = 0; i < length; i++)
{
BaseStringContent bic = openDays[i];
switch (usual.OpenType)
{
case (int)eUsualOpenType.None:
canOpen = true;
break;
case (int)eUsualOpenType.DayOfWeek:
canOpen = (Convert.ToInt16(bic.list[0]) == (int)dt.DayOfWeek);
break;
case (int)eUsualOpenType.Day:
int startMonth, endMonth;
int startDay, endDay;
startMonth = endMonth = Convert.ToInt16(bic.list[1].Substring(0, 2));
startDay = endDay = Convert.ToInt16(bic.list[1].Substring(2, 2));
if (bic.list.Count > 2)
{
endMonth = Convert.ToInt16(bic.list[2].Substring(0, 2));
endDay = Convert.ToInt16(bic.list[2].Substring(2, 2));
}
if (dt.Month >= startMonth && dt.Month <= endMonth &&
dt.Day >= startDay && dt.Day <= endDay)
{
canOpen = true;
}
break;
case (int)eUsualOpenType.WeekLoop:
if (Convert.ToInt32(bic.list[0]) == PlayerPropertyManager.Instance.PlayerInfo.CurActivityWeek)
canOpen = true;
else
canOpen = false;
break;
}
if (canOpen) { break; }
}
}
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetText(32001016));//不是开放日
}
return canOpen;
}
//开启时段判断
List<BaseFloatContent> openTime = usual.OpenTime;
if (openTime[0].list.Count > 1)
{
int length = openTime.Count;
canOpen = false;
int onTime = dt.Hour * 100 + dt.Minute;
int endTime = 0;
for (int i = 0; i < length; i++)
{
int start = Mathf.FloorToInt(openTime[i].list[0] * 100);
int end = Mathf.FloorToInt(openTime[i].list[1] * 100);
if (start < onTime && onTime < end)
{
endTime = end;
canOpen = true;
}
}
}
else
{
canOpen = true;
}
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetText(32001017));//不是开放时段
}
return canOpen;
}
return canOpen;
}
public static string EnchantmentNameToColor(string name, SRandAttr mag, EquipEnchantContent eContent)
{
//改变颜色 0-10%显示白色、11-30%显示绿色、31-50%显示蓝色、51-70%显示紫色、71-90%显示橙色、91-100%显示红色
int _iValue1 = eContent.Range[1] - eContent.Range[0];
int _iValue2 = (int)mag.uiAttrVal - (int)eContent.Range[0];
eQuality _bValue = eQuality.None;
if (_iValue2 <= Math.Floor(_iValue1 * 0.1))
{
//10%
_bValue = eQuality.White_Bronze;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.3))
{
//11%-30%
_bValue = eQuality.Green_Silver;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.5))
{
//31%-50%
_bValue = eQuality.Blue_Gold;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.7))
{
//51%-70%
_bValue = eQuality.Purple_Epic;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.9))
{
//71%-90%
_bValue = eQuality.Orange_Artifact;
}
else
{
//91%-100%
_bValue = eQuality.Red_Legend;
}
return CCommon.NameToQualityColor(name, _bValue);
}
public static string NameToQualityColor(string name, eQuality qua)
{
string str = "";
str = GetEquipOrItemColor(qua);
str += name;
str += "[-]";
return str;
}
public static string NameToQualityColor(int nameID, eQuality qua)
{
string name = GetText(nameID);
return NameToQualityColor(name, qua);
}
public static string QualityToText(eQuality quality)
{
return GetText(80000900 + (int)quality);
}
public static string QualityToTextWithColor(eQuality quality)
{
return NameToQualityColor(QualityToText(quality), quality);
}
public static bool GetIsHaveSensitiveWords(string str)
{
if (string.IsNullOrEmpty(str))
return false;
return m_TrieFilter.Contains(str);
return m_TrieFilter.Contains(str);
}
//public static string StringSimplify(string str)
//{
// string preHandleStr = "";
// char[] c = str.ToCharArray();
// for (int i = 0; i < c.Length; i++)
// {
// //if (c[i] < '0')
// // continue;
// //if (c[i] > '9' && c[i] < 'A')
// // continue;
// //if (c[i] > 'Z' && c[i] < 'a')
// // continue;
// //if (c[i] > 'z' && c[i] < 128)
// // continue;
// if (c[i] > 0xFF00 && c[i] < 0xFF5F)
// {
// /*全角=>半角*/
// preHandleStr += (char)(c[i] - 0xFEE0);
// }
// else if (c[i] > 0x40 && c[i] < 0x5b)
// {
// /*大写=>小写*/
// preHandleStr += (char)(c[i] + 0x20);
// }
// else
// {
// preHandleStr += c[i];
// }
// }
// return preHandleStr;
//}
public static string StringDelUrl(string str)
{
int beginIndex = 0;
int endIndex = 0;
string preHandleStr = str;
while (true)
{
beginIndex = preHandleStr.IndexOf("[url");
endIndex = preHandleStr.IndexOf("[/url]");
if (beginIndex != -1 && endIndex != -1)
{
preHandleStr = preHandleStr.Remove(beginIndex, endIndex - beginIndex + 6);
}
else
{
break;
}
}
return preHandleStr;
}
/// <summary>
/// 判断是否包含标点符号,返回true即包含非法字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsHaveIllegalPunctuation(string str)
{
char[] c = str.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
//下划线是允许的
if (c[i] == 95)
break;
if (c[i] > 31 && c[i] < 48)
return true;
if (c[i] > 57 && c[i] < 65)
return true;
if (c[i] > 90 && c[i] < 97)
return true;
if (c[i] > 122 && c[i] < 255)
return true;
}
return false;
}
#region UI界面显示/隐藏引导用的红点标记
public static void SetUIGuideRedPointActive(GameObject targetGo, bool active, float offsetX = 0.0f, float offsetY = 0.0f)
{
if (active)
ShowUIGuideRedPoint(targetGo, 2, 20, offsetX, offsetY);
else
{
if (offsetX == 0 && offsetY == 0)
HideUIGuideRedPoint(targetGo);
else
RemoveUIGuideRedPoint(targetGo);
}
}
/// <summary>
/// 显示UI界面引导用的红点标记
/// </summary>
/// <param name="targetGo"></param>
/// <param name="pos">1:左上,2:右上,3:右下,4:左下</param>
/// <param name="depth">层深</param>
public static GameObject ShowUIGuideRedPoint(GameObject targetGo, int pos = 2, int depth = 20, float offsetX = 0.0f, float offsetY = 0.0f)
{
if (targetGo == null)
{
return null;
}
GameObject go = _GetUIGuideRedPointGo(targetGo);
if (go == null)
{
go = new GameObject("guidePointIcon");
UISprite icon = go.AddComponent<UISprite>();
icon.atlas = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_PUBLIC2);
icon.spriteName = "icon_new";
icon.type = UISprite.Type.Simple;
icon.MakePixelPerfect();
icon.depth = depth;
go.transform.SetParent(targetGo.transform);
go.transform.localPosition = new Vector3(0, 0, 0);
go.transform.localScale = Vector3.one;
}
go.transform.localPosition = new Vector3(0, 0, 0);
go.transform.localScale = Vector3.one;
if (!go.activeSelf)
{
go.SetActive(true);
}
Bounds bound = NGUIMath.CalculateRelativeWidgetBounds(targetGo.transform);
if (bound != null)
{
Vector3 max = bound.max;
Vector3 newPos = Vector3.zero;
switch (pos)
{
case 1:
newPos = new Vector3(bound.min.x + 13, bound.max.y - 13, 0);
break;
case 2:
newPos = new Vector3(bound.max.x - 13, bound.max.y - 13, 0);
break;
case 3:
newPos = new Vector3(bound.max.x - 13, bound.min.y + 13, 0);
break;
case 4:
newPos = new Vector3(bound.min.x + 13, bound.min.y + 13, 0);
break;
case 5:
newPos = new Vector3(offsetX, offsetY, 0);
break;
}
newPos.x += offsetX;
newPos.y += offsetY;
go.transform.localPosition = newPos;
}
return go;
}
/// <summary>
/// 隐藏UI界面引导用的红点标记
/// </summary>
/// <param name="targetGo"></param>
public static void HideUIGuideRedPoint(GameObject targetGo)
{
if (targetGo == null)
{
return;
}
GameObject go = _GetUIGuideRedPointGo(targetGo);
if (go != null && go.activeSelf)
{
go.SetActive(false);
}
}
/// <summary>
/// 删除UI界面引导用的红点标记
/// </summary>
/// <param name="targetGo"></param>
public static void RemoveUIGuideRedPoint(GameObject targetGo)
{
if (targetGo == null)
{
return;
}
GameObject go = _GetUIGuideRedPointGo(targetGo);
if (go != null)
{
GameObject.Destroy(go);
}
}
private static GameObject _GetUIGuideRedPointGo(GameObject targetGo)
{
Transform tf = targetGo.transform;
Transform pointTf = tf.Find("guidePointIcon");
return pointTf != null ? pointTf.gameObject : null;
}
#endregion
//展示语音录音图示
public static void SetActiveSpeechArea(bool isShow)
{
if (isShow)
{
SingleObject<InputExtensionDialog>.Instance.SetExtensionType(eInputExtensionType.None);
SingleObject<InputExtensionDialog>.Instance.Show(eCommunicationType.Chat);
}
else
{
SingleObject<InputExtensionDialog>.Instance.Close(null);
}
}
public static void RequestChangeScene(uint sceneID, bool needprogress = true, bool ignore = false)
{
if (UpdateManager.Instance.CheckAssetsNeedUpdate(eCheckLoadType.Map, CCommon.GetScenePath((int)sceneID), null, null, false))
{
return;
}
if (needprogress)
{
CChangeSceneProgressManager.Instance.ChangeScene(sceneID, needprogress, ignore);
return;
}
uint playerID = CAvatar.Instance.ID;
if (!CTeamManager.Instance.IsLeader(playerID) && CTeamManager.Instance.GetTeamerStatus(playerID) == eTeamStatus.Follow)
{
ShowTips(12020076);
return;
}
eMapType mapType = Key2MapType((int)sceneID);
if (mapType == eMapType.MapLand || mapType == eMapType.Main || mapType == eMapType.MapSea || mapType == eMapType.MapMovement)
{
BattleMessageHandle.Instance.RequestChangeScene(sceneID);
}
else if (mapType == eMapType.MapDungeon || mapType == eMapType.SeaDungeon)
{
CDialogManager.Instance.TriggerEvent(new CUIGlobalEvent(CUIGlobalEvent.CLICK_ENTER_DUNGEON) { Data = sceneID });
}
else if (mapType == eMapType.MapGuild)
{
if (PlayerPropertyManager.Instance.IsHasGuild())
{
GuildManager.Instance.RequestEnterScene(null);
}
else
{
ShowTextTip(GetText(80000191));
}
}
else if (mapType == eMapType.MapParkour)
{
}
else if (mapType == eMapType.MapPvp)
{
}
else if (mapType == eMapType.SeaPvp)
{
}
}
public static List<int> SpilStringToIntList(string str, string tag1 = "~")
{
string[] temptempStr = new string[0];
temptempStr = str.Split(tag1.ToCharArray(), StringSplitOptions.None);
List<int> tempList = new List<int>();
for (int j = 0; j < temptempStr.Length; j++)
{
tempList.Add(DataDecode.GetInt32(temptempStr[j]));
}
return tempList;
}
public static List<string> SpilStringToStringList(string str, string tag1 = "~")
{
string[] temptempStr = new string[0];
temptempStr = str.Split(tag1.ToCharArray(), StringSplitOptions.None);
return temptempStr.ToDynList<string>();
}
public static List<List<int>> SpilStringToIntListList(string str, string tag1 = "$", string tag2 = "~")
{
List<List<int>> list = new List<List<int>>();
string[] tempStr = new string[0];
if (!string.IsNullOrEmpty(str))
{
tempStr = str.Split(tag1.ToCharArray(), StringSplitOptions.None);
string[] temptempStr = new string[0];
for (int i = 0; i < tempStr.Length; i++)
{
temptempStr = tempStr[i].Split(tag2.ToCharArray(), StringSplitOptions.None);
List<int> tempList = new List<int>();
for (int j = 0; j < temptempStr.Length; j++)
{
tempList.Add(DataDecode.GetInt32(temptempStr[j]));
}
list.Add(tempList);
}
}
return list;
}
public static void GetStartDayAndEndDayFromWeekLoop(int year, int month, int weekNum, ref int startDay, ref int endDay)
{
DateTime date = new DateTime(year, month, 1);
for (int i = 0; i <= date.AddMonths(1).AddDays(-1).Day; i++)
{
if (new DateTime(date.Year, date.Month, i).DayOfWeek == DayOfWeek.Monday)
{
startDay = i;
endDay = i + 6;
}
}
}
public static int EquipID2EquipModelID(int equipID, out eEquipPartType type)
{
type = eEquipPartType.eEquipPart_Coat;
EquipContent content = HolderManager.m_EquipHolder.GetStaticInfo(equipID);
if (content == null)
return 0;
else
{
type = (eEquipPartType)content.EquipType;
return content.ModelID;
}
}
public static float easeInSine(float start, float end, float value)
{
end -= start;
return -end * Mathf.Cos(value / 1 * (Mathf.PI / 2)) + end + start;
}
public static float easeOutSine(float start, float end, float value)
{
end -= start;
return end * Mathf.Sin(value / 1 * (Mathf.PI / 2)) + start;
}
//通过品质取颜色值
public static string GetEquipOrItemColor(eQuality qua)
{
string str = "[ffffff]";
switch (qua)
{
case eQuality.None:
str = CDEFINE.NONE;
break;
case eQuality.White_Bronze:
str = CDEFINE.WHITE;
break;
case eQuality.Green_Silver:
str = CDEFINE.GREEN;
break;
case eQuality.Blue_Gold:
str = CDEFINE.BLUE;
break;
case eQuality.Purple_Epic:
str = CDEFINE.PUPLE;
break;
case eQuality.Red_Legend:
str = CDEFINE.RED;
break;
case eQuality.Orange_Artifact:
str = CDEFINE.ORANGE;
break;
}
return str;
}
/// <summary>
/// 获取品质spriteName
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static eQuality IndexToEquipQuality(int index)
{
switch (index)
{
case 0:
return eQuality.None;
case 1:
return eQuality.White_Bronze;
case 2:
return eQuality.Green_Silver;
case 3:
return eQuality.Blue_Gold;
case 4:
return eQuality.Purple_Epic;
case 5:
return eQuality.Orange_Artifact;
case 6:
return eQuality.Red_Legend;
}
return eQuality.None;
}
public static string TryGetValue(List<string> list, int index, string returnDefaultValue = "")
{
if (list != null)
{
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
CDebug.LogError("表数据错误,数组越界");
return returnDefaultValue;
}
public static int TryGetValue(List<int> list, int index, int returnDefaultValue = 0)
{
if (list != null)
{
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
CDebug.LogError("表数据错误,数组越界");
return returnDefaultValue;
}
public static byte TryGetValue(List<byte> list, int index, byte returnDefaultValue = 0)
{
if (list != null)
{
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
CDebug.LogError("表数据错误,数组越界");
return returnDefaultValue;
}
//用这个函数返回物品数据,不是自己拥有的物品
public static BackpackItemData GetItemData(int itemID)
{
BackpackItemData item = null;
switch (GetTypeFormID(itemID))
{
case eIDType.Equip:
{
EquipContent content = HolderManager.m_EquipHolder.GetStaticInfo(itemID);
if (content != null)
{
item = new BackpackItemData(itemID);
item.equipContent = content;
EquipModelContent equipModel = HolderManager.m_EquipModelHolder.GetStaticInfo(content.ModelID);
if (equipModel != null)
item.icon = equipModel.Icon;
item.location = eItemKeepLocation.None;
item.name = GetText(content.Name);
item.color = IndexToEquipQuality(content.Quality);
item.limitLv = content.LimitLevel;
item.type = eIDType.Equip;
BackpackEquipInfo equipInfo = new BackpackEquipInfo();
equipInfo.isEquiped = false;
equipInfo.bodyPart = (eEquipPartType)content.EquipType;
equipInfo.forgedLv = 0;
equipInfo.goodFixIncreasePercent = 0;
equipInfo.makerName = "";
equipInfo.fixTimes = 0;
item.equipInfo = equipInfo;
}
}
break;
case eIDType.Item:
{
ItemContent itemContent = HolderManager.m_ItemHolder.GetStaticInfo(itemID);
if (itemContent != null)
{
item = new BackpackItemData(itemID);
item.type = eIDType.Item;
item.itemContent = itemContent;
item.icon = itemContent.IconPath;
item.name = GetText(itemContent.NameID);
item.color = IndexToEquipQuality(itemContent.Quality);
BackpackItemInfo itemInfo = new BackpackItemInfo();
itemInfo.type = (eItemType)itemContent.Type;
itemInfo.subType = (eItemSubType)itemContent.SubType;
itemInfo.quality = itemContent.Quality;
item.itemInfo = itemInfo;
}
}
break;
}
return item;
}
public static void IsShowRedPoint(CElementBase target, bool isShow, int pos = 2, int depth = 20, float offsetX = 0.0f, float offsetY = 0.0f)
{
if (target != null)
{
if (COpenModule.CheckKeyIsOpen(target.Arg))
{
ShowUIGuideRedPoint(target.gameobject, pos, depth, offsetX, offsetY);
GameObject redPoint = _GetUIGuideRedPointGo(target.gameobject);
redPoint.SetActive(isShow);
}
}
}
public static void GetAttrString(BackpackItemData data, eEquipAttrType attrType, out List<string> attrName, out List<string> attrRange, out string attrTypeStr)
{
List<EquipAttr> attrTotalList = data.equipInfo.GetAttrListByType(attrType);
if (attrTotalList != null)
{
List<string> nameList = new List<string>();
List<string> rangeList = new List<string>();
for (int i = 0; i < attrTotalList.Count; i++)
{
float attrRangePercentMinimum = 0;
float attrRangePercentMaximum = 0;
if (data.equipContent != null)
{
//attrRangePercentMinimum = (float)data.equipContent.AttrValueRange[0] / 10000;
//attrRangePercentMaximum = (float)data.equipContent.AttrValueRange[1] / 10000;
}
string rangeStr = "";
List<int> info = BackpackEquipInfo.EquipAttrToIntList(attrTotalList[i]);
if (info != null)
{
float value1;
float value2;
int absoluteVal = info[2] - info[1];
switch (info[0])
{
case 1:
//属性值最小值计算公式: 最小值 + 差值*范围最小值
//属性值最大值计算公式: 最小值 + 差值*范围最大值
value1 = Mathf.CeilToInt(info[1] + absoluteVal * attrRangePercentMinimum);
value2 = Mathf.CeilToInt(info[1] + absoluteVal * attrRangePercentMaximum);
if (value1 == value2)
rangeStr = value1.ToString();
else
rangeStr = value1 + "-" + value2;
break;
case 2:
value1 = (info[1] + absoluteVal * attrRangePercentMinimum) / 100;
value2 = (info[1] + absoluteVal * attrRangePercentMaximum) / 100;
if (value1 == value2)
rangeStr = value1 + "%";
else
rangeStr = value1 + "%" + "-" + value2 + "%";
break;
default:
rangeStr = "";
break;
}
}
nameList.Add(attrTotalList[i].GetAttrName());
rangeList.Add(rangeStr);
}
attrName = nameList;
attrRange = rangeList;
attrTypeStr = attrTotalList[0].GetAttrType();
}
else
{
attrName = null;
attrRange = null;
attrTypeStr = null;
}
}
/// <summary>
/// 返回Tech表中的属性值 是否无值 0~0
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static bool GetTechValueIsNull(List<int> list)
{
if (list != null && list.Count > 0)
{
if (list[0] == 0)
{
return true;
}
}
return false;
}
/// <summary>
/// 属性表的单个数据
/// </summary>
public class TechSingleData
{
public eProtoAttData TechType; //属性类型
public int guitextId; //guitextID
public byte valueType; //0表示固定值1表示百分比
public int value; //属性值
public EquipAttr To()
{
EquipAttr attr = new EquipAttr();
attr.attrEnum = TechType;
attr.attrType = eEquipAttrType.MajorAttr;
attr.dataType = (eEquipAttrDataType)(valueType);
attr.value = value;
return attr;
}
public void From(EquipAttr attr)
{
if (attr != null)
{
TechType = attr.attrEnum;
valueType = (byte)((int)attr.dataType);
value = attr.value;
guitextId = CPlayerProperty.GetPropertyLanageID((int)TechType);
}
}
}
/// <summary>
/// 返回TechContent的值
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
static public List<TechSingleData> GetTechValue(int id)
{
TechContent tContent = HolderManager.m_TechHolder.GetStaticInfo(id);
return GetTechValue(tContent);
}
/// <summary>
/// 返回TechContent的值
/// </summary>
/// <param name="tContent"></param>
/// <returns></returns>
static public List<TechSingleData> GetTechValue(TechContent tContent)
{
List<TechSingleData> list = new List<TechSingleData>();
if (null == tContent)
return list;
for (int i = 0; i < GetTechProListMaxNum; i++)
{
List<int> value = GetTechProValue(i, tContent);
if (null != value && value.Count == 2 && value[0] > 0)
{
TechSingleData tvl = new TechSingleData();
tvl.guitextId = GetTechProGuiTextId(i);
tvl.valueType = (byte)value[0];
tvl.value = value[1];
tvl.TechType = (eProtoAttData)i;
list.Add(tvl);
}
}
return list;
}
/// <summary>
/// 返回Tech表中的属性值 所对应的GuiTextID
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static int GetTechProGuiTextId(int index)
{
int id = 0;
if (index >= 0 && index < GetTechProListMaxNum)
{
return 22100001 + index;
}
return id;
}
public const int GetTechProListMaxNum = 34;
/// <summary>
/// 返回Tech表中的属性值
/// </summary>
/// <param name="index">从0开始</param>
/// <returns></returns>
public static List<int> GetTechProValue(int index, TechContent tc)
{
List<int> list = null;
if (tc != null)
{
switch (index)
{
case 0: { list = tc.HpMax; } break;
case 1: { list = tc.Attack; } break;
case 2: { list = tc.Defense; } break;
case 3: { list = tc.Critical; } break;
case 4: { list = tc.ResistCritical; } break;
case 5: { list = tc.CriticalChance; } break;
case 6: { list = tc.ResistCriticalChance; } break;
case 7: { list = tc.CriticalDamage; } break;
case 8: { list = tc.ResistCriticalDamage; } break;
case 9: { list = tc.MeleeAttack; } break;
case 10: { list = tc.ResistMeleeAttack; } break;
case 11: { list = tc.RemoteAttack; } break;
case 12: { list = tc.ResistRemoteAttack; } break;
case 13: { list = tc.TrueDamage; } break;
case 14: { list = tc.ResistTrueDamage; } break;
case 15: { list = tc.AdditionalAtk; } break;
case 16: { list = tc.ResistAdditionalAtk; } break;
case 17: { list = tc.Refelect; } break;
case 18: { list = tc.HPRecoverRatio; } break;
case 19: { list = tc.VIT; } break;
case 20: { list = tc.VITRecoverRatio; } break;
case 21: { list = tc.VITLossRatio; } break;
case 22: { list = tc.ActVelocity; } break;
case 23: { list = tc.MoveVelocity; } break;
case 24: { list = tc.LeechLife; } break;
case 25: { list = tc.DerateCD; } break;
case 26: { list = tc.BOSSAtk; } break;
case 27: { list = tc.PKDamage; } break;
case 28: { list = tc.ResistPKDamage; } break;
case 29: { list = tc.DeadlyAttack; } break;
case 30: { list = tc.ResistDeadlyAttack; } break;
case 31: { list = tc.DeadlyAtkDamage; } break;
case 32: { list = tc.ResistDeadlyAtkDamage; } break;
case 33: { list = tc.ExpEx; } break;
case 34: { list = tc.MoneyEx; } break;
}
}
return list;
}
/// <summary>
/// 把数组里的TechContent属性值相加
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static List<TitleTechData> CalcPropTotal(List<int> param)
{
List<TitleTechData> list = new List<TitleTechData>();
int total = 0;
for (int i = 0; i < GetTechProListMaxNum; i++)
{
total = 0;
foreach (var item in param)
{
TechContent content = HolderManager.m_TechHolder.GetStaticInfo(item);
if (null == content) continue;
List<int> val = GetTechProValue(i, content);
total += val[1];
}
list.Add(new TitleTechData() { Index = i, Value = total });
}
return list;
}
/// <summary>
/// 把数组里的TechContent属性值相加
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static long CalcPowerTotal(List<int> param)
{
int total = 0;
long power = 0;
for (int i = 0; i < GetTechProListMaxNum; i++)
{
total = 0;
foreach (var item in param)
{
TechContent content = HolderManager.m_TechHolder.GetStaticInfo(item);
if (null == content) continue;
List<int> val = GetTechProValue(i, content);
total += val[1];
}
if (total > 0)
power += CCommon.GetPowerValue((eProtoAttData)i, total);
}
return power;
}
private static string[] _titleColor = new string[]
{
"ccf1d7", "ffffff",
"cceef1", "ffffff",
"f1ccf1", "ffffff",
"f1cccc", "ffffff",
"f1ebcc", "ffffff"
};
public static Color[] GetTitleColor(byte type)
{
Color[] cols = new Color[2];
switch (type)
{
case (byte)eTitleColorType.Bronze:
cols[0] = new Color32(204, 241, 215, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.Silver:
cols[0] = new Color32(204, 238, 241, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.Gold:
cols[0] = new Color32(241, 204, 241, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.BarkGold:
cols[0] = new Color32(241, 204, 204, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.Diamond:
cols[0] = new Color32(241, 235, 204, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
}
return cols;
}
public static int ComputeTechProValue(int index, TechContent tc)
{
List<int> list = GetTechProValue(index, tc);
if (GetTechValueIsNull(list))
return 0;
if (list[0] == 1)
{
return list[1];
}
else if (list[0] == 2)
{
return list[1] * GetAvatarAttributeWithTechIndex(index);
}
return 0;
}
static List<BaseIntContent> mDropItemList = new List<BaseIntContent>();
/// <summary>
/// 获取掉落物品数据
/// </summary>
/// <param name="key">dropitemID</param>
/// <returns></returns>
public static List<BaseIntContent> GetDropItemList(int key)
{
mDropItemList.Clear();
DropItemContent retContent = HolderManager.m_DropItemHolder.GetStaticInfo(key);
if (null != retContent)
{
BaseIntContent baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList1;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList2;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList3;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList4;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList5;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList6;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList7;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList8;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList9;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList10;
mDropItemList.Add(baseIntContent);
}
return mDropItemList;
}
/// <summary>
/// 获取掉落物品数据
/// </summary>
/// <param name="retContent">dropItemContent</param>
/// <returns></returns>
public static List<BaseIntContent> GetDropItemList(DropItemContent retContent)
{
mDropItemList.Clear();
if (null != retContent)
{
BaseIntContent baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList1;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList2;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList3;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList4;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList5;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList6;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList7;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList8;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList9;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList10;
mDropItemList.Add(baseIntContent);
}
return mDropItemList;
}
/// <summary>
/// 将格式为“2016~11~21~00~00~00” 转换成 DateTime
/// </summary>
/// <param name="timeList"></param>
/// <returns></returns>
public static DateTime GetDataTime(List<int> timeList)
{
DateTime dataTime = new DateTime();
if (timeList.Count >= 6)
{
dataTime.AddYears(timeList[0]);
dataTime.AddMonths(timeList[1]);
dataTime.AddDays(timeList[2]);
dataTime.AddHours(timeList[3]);
dataTime.AddMinutes(timeList[4]);
dataTime.AddSeconds(timeList[5]);
}
return dataTime;
}
/// <summary>
/// 将格式为“2016~11~21~00~00~00” 转换成时间戳
/// </summary>
/// <param name="timeList"></param>
/// <returns></returns>
public static double GetTimeStamp(List<int> timeList)
{
DateTime dataTime = GetDataTime(timeList);
double timeStamp = DateTimeToStamp(dataTime);
return timeStamp;
}
static Dictionary<int, List<int>> m_growthAwardDic = new Dictionary<int, List<int>>();
/// <summary>
/// 获取成长奖励表格数据信息
/// </summary>
/// <returns></returns>
public static Dictionary<int, List<int>> GetGrowthAwardInfo()
{
if (m_growthAwardDic.Count == 0)
{
foreach (KeyValuePair<int, TargetContent> kv in HolderManager.m_targetHolder.GetDict())
{
if (kv.Value.LevelClassify.Count != 2)
{
Debug.LogError("target excel “等级分类” 配置错误 with id : " + kv.Key);
break;
}
if (!m_growthAwardDic.ContainsKey(kv.Value.LevelClassify[0]))
{
List<int> targetList = new List<int>();
m_growthAwardDic.Add(kv.Value.LevelClassify[0], targetList);
}
m_growthAwardDic[kv.Value.LevelClassify[0]].Add(kv.Key);
}
}
return m_growthAwardDic;
}
/// <summary>
/// 等比缩放图片
/// </summary>
/// <param name="sprite"></param>
/// <param name="spriteName"></param>
/// <param name="scale"></param>
public static void SetUiScale(CSprite sprite, string spriteName, float scale)
{
if (sprite != null)
{
sprite.SetSprite(spriteName, true);
float wd = sprite.MySprite.width;
float ht = sprite.MySprite.height;
sprite.MySprite.width = Convert.ToInt32(wd * scale);
sprite.MySprite.height = Convert.ToInt32(ht * scale);
}
}
/// <summary>
/// 等比缩放图片
/// </summary>
/// <param name="texture"></param>
/// <param name="scale"></param>
public static void SetUiScale(CUITexture texture, float scale)
{
if (texture != null)
{
float wd = texture.MyTexture.width;
float ht = texture.MyTexture.height;
texture.MyTexture.width = Convert.ToInt32(wd * scale);
texture.MyTexture.height = Convert.ToInt32(ht * scale);
}
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="pointTf"></param>
/// <param name="dir">相对 pointTf 的 1上,2下,3左,4右</param>
public static void SetUiAnchors(CSprite target, Transform pointTf, float offset = 0, int dir = 1)
{
if (target != null && pointTf != null)
{
switch (dir)
{
case 1:
float posY = pointTf.localPosition.y + target.MySprite.height / 2 + offset;
target.localPosition = new Vector3(target.localPosition.x, posY, target.localPosition.z);
break;
}
}
}
/// <summary>
/// 打开界面
/// </summary>
/// <param name="dialogID"></param>
public static bool OpenDialogById(int dialogID, eOpenModule type = eOpenModule.None, CDialog fromDialog = null, bool checkOpen = false, params object[] args)
{
if (checkOpen)
{
if (!COpenModule.CheckKeyIsOpen(type))
{
ShowFunctionNotOpenTips();
return false;
}
}
CDialog dialog = CDialogManager.Instance.GetDialog(dialogID);
if (dialog is FunctionTabDialogBase && type != eOpenModule.None)//tab面板
(dialog as FunctionTabDialogBase).SetOpenToggle(type, args);
else
dialog.Refresh(args);
if (dialog != null)
{
if (dialog is ChatUiDialog)
{
SingleObject<BattleUiDialog>.Instance.ShowChatUiDialog();
}
//else if (dialogID == 21)//不知道是不是旧的,与配置对不上,先注释掉
//{
// SingleObject<BattleUiDialog>.Instance.ExecuteClickBtnEvent(eOpenModule.Activity_Welfare);
//}
else
{
//SingleObject<BattleUiDialog>.Instance.Close(null, true);
dialog.Show(null, fromDialog, true);
}
}
return true;
}
public static string GetGuildName(string str)
{
string guildName = string.Empty;
string[] arg = str.Split('*');
if (arg.Length >= 2)
guildName = arg[1];
else
guildName = arg[0];
return guildName;
}
public static HQuestAwardContent GetQuestAwardContentFromType(eQuestType type)
{
if (type >= eQuestType.DailyLoop && type < eQuestType.Max)
{
Dictionary<int, HQuestAwardContent> dict = HolderManager.m_HQuestAwardHolder.GetDict();
foreach (KeyValuePair<int, HQuestAwardContent> pair in dict)
{
if (pair.Value.Type == (byte)type)
return pair.Value;
}
}
return null;
}
//跳过打包流程,直接从txt读出表格数据
#if UNITY_EDITOR
public static UnityEngine.Object CreateStaticDataHolder(string holdClass, string path)
{
CSV.CsvStreamReader csv = new CSV.CsvStreamReader(path);
if (!csv.LoadCsvFile())
{
Debug.LogError(path + "无法读取,文件不存在或是被其它程序占用");
return null;
}
string FileName = Path.GetFileNameWithoutExtension(path);
ArrayList csvList = csv.GetRowList();
FileStreamHolder holder = ScriptableObject.CreateInstance<FileStreamHolder>();
holder.content = new List<FileStreamElement>();
XmlReader reader = null;
if (holdClass.Equals("TriggerHolder"))
{
reader = new XmlReader("Assets/xml/" + "trigger" + ".xml", holdClass);
}
else
{
reader = new XmlReader("Assets/xml/" + FileName + ".xml", holdClass);
}
int lineIndex = 0;
foreach (ArrayList array in csvList)
{
if (lineIndex == 0)
{
lineIndex++;//忽略第一行注解
continue;
}
int index = 0;
FileStreamElement fse = new FileStreamElement();
foreach (object tmp in array)
{
XmlData data = reader.GetData(index);
if (null == data)
{
//写入key值
if (index == 0)
{
if (fse.intList == null) fse.intList = new List<int>();
fse.intList.Add(DataDecode.GetInt32(tmp));
}
index++;
continue;
}
switch (data.type)
{
case "int":
{
if (fse.intList == null) fse.intList = new List<int>();
fse.intList.Add(DataDecode.GetInt32(tmp));
}
break;
case "string":
{
if (fse.stringList == null) fse.stringList = new List<string>();
fse.stringList.Add(DataDecode.GetString(tmp).Trim());
}
break;
case "byte":
{
if (fse.byteList == null) fse.byteList = new List<byte>();
fse.byteList.Add(DataDecode.GetByte(tmp));
}
break;
case "float":
{
if (fse.floatList == null) fse.floatList = new List<float>();
fse.floatList.Add(DataDecode.GetSingle(tmp));
}
break;
case "bool":
{
if (fse.boolList == null) fse.boolList = new List<bool>();
fse.boolList.Add(DataDecode.GetBoolean(tmp));
}
break;
case "intlist":
{
if (null == fse.intContentList) fse.intContentList = new List<BaseIntContent>();
BaseIntContent content = new BaseIntContent();
content.list = DataDecode.TransStrToIntList(tmp, data.split1);
fse.intContentList.Add(content);
}
break;
case "stringlist":
{
if (null == fse.stringContentList) fse.stringContentList = new List<BaseStringContent>();
BaseStringContent content = new BaseStringContent();
content.list = DataDecode.TransStrToStringList(tmp, data.split1);
fse.stringContentList.Add(content);
}
break;
case "floatlist":
{
if (null == fse.floatContentList) fse.floatContentList = new List<BaseFloatContent>();
BaseFloatContent content = new BaseFloatContent();
content.list = DataDecode.TransStrToFloatList(tmp, data.split1);
fse.floatContentList.Add(content);
}
break;
case "bytelist":
{
if (null == fse.byteContentList) fse.byteContentList = new List<BaseByteContent>();
BaseByteContent content = new BaseByteContent();
content.list = DataDecode.TransStrToByteList(tmp, data.split1);
fse.byteContentList.Add(content);
}
break;
case "stringlistlist":
{
if (null == fse.stringContentListList) fse.stringContentListList = new List<BaseStringListList>();
BaseStringListList content = new BaseStringListList();
content.list = DataDecode.TransStrToListStringClass(tmp, data.split1, data.split2);
fse.stringContentListList.Add(content);
}
break;
case "intlistlist":
{
if (null == fse.intContentListList) fse.intContentListList = new List<BaseIntListList>();
BaseIntListList content = new BaseIntListList();
content.list = DataDecode.TransStrToListIntClass(tmp, data.split1, data.split2);
fse.intContentListList.Add(content);
}
break;
case "floatlistlist":
{
if (null == fse.floatContentListList) fse.floatContentListList = new List<BaseFloatListList>();
BaseFloatListList content = new BaseFloatListList();
content.list = DataDecode.TransStrToListFloatClass(tmp, data.split1, data.split2);
fse.floatContentListList.Add(content);
}
break;
case "vector2":
{
if (null == fse.vector2List) fse.vector2List = new List<Vector2>();
fse.vector2List.Add(DataDecode.TransToVector2(tmp, data.split1));
}
break;
case "vector3":
{
if (null == fse.vector3List) fse.vector3List = new List<Vector3>();
fse.vector3List.Add(DataDecode.TransToVector3(tmp, data.split1));
}
break;
case "color":
{
if (null == fse.colorList) fse.colorList = new List<Color>();
fse.colorList.Add(DataDecode.TransStrToColor(tmp, data.split1));
}
break;
}
index++;
}
holder.content.Add(fse);
}
return holder as UnityEngine.Object;
}
#endif
//检测文件是否被其他软件占用
public static bool FileIsUsed(string fileFullName)
{
bool result = false;
if (!File.Exists(fileFullName))
{
result = false;
}
else
{
FileStream fileStream = null;
try
{
fileStream = File.Open(fileFullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
result = false;
}
catch (IOException ioEx)
{
result = true;
}
catch (Exception ex)
{
result = true;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
}
return result;
}
public static string GetGuildCareerName(eGuildPosition careerType)
{
string str = "";
switch (careerType)
{
case eGuildPosition.Ordinary:
str = GetText(73000109);
break;
case eGuildPosition.Elite:
str = GetText(73000110);
break;
case eGuildPosition.Elders:
str = GetText(73000111);
break;
case eGuildPosition.ViceChairman:
str = GetText(73000112);
break;
case eGuildPosition.Chairman:
str = GetText(73000113);
break;
default:
break;
}
return str;
}
public static string StringToEmotion(string text)
{
Dictionary<int, ExpressionContent> expressionDic = HolderManager.m_ExpressionHolder.GetDict();
List<int> expressionKeysList = new List<int>(expressionDic.Keys);
int count = expressionKeysList.Count;
for (int i = 0; i < count; i++)
{
text = text.Replace("[" + expressionKeysList[i] + "]", "[url=Emotion]" + "%patlas_ui_blackflag_expression_v1$" + expressionDic[expressionKeysList[i]].IconPath + "_01$[/url]");
}
return text;
}
public static Color ColorByteToColor(byte r, byte g, byte b, byte a = 1)
{
return new Color(r / 255f, g / 255f, b / 255f, a / 255f);
}
public static Color ColorStringToColor(string cStr)
{
if (cStr.Length == 8)
{
return NGUIText.ParseColor(cStr, 0);
}
return Color.black;
}
public static Color Color32ToColor(Color32 color32)
{
return ColorByteToColor(color32.r, color32.g, color32.b, color32.a);
}
/// <summary>
/// 获取玩家最大等级
/// </summary>
/// <returns></returns>
public static int GetMaxLevel()
{
Dictionary<int, LevelupContent> dict = HolderManager.m_LevelupHolder.GetDict();
return dict.Count;
}
/// <summary>
/// 根据 ringTarget 的高,调整background 的高和位置,使之适应 ringTarget 中的内容
/// </summary>
/// <param name="ringTarget"></param>
/// <param name="background"></param>
public static void CalculateBackgroundRingTransform(Transform ringTarget, CSprite background)
{
if (ringTarget == null || background == null) { return; }
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(ringTarget);
if (b != null)
{
background.MySprite.height = Mathf.FloorToInt(b.size.y);
background.localPosition = new Vector3(0, b.center.y, 0);
}
}
public static int ShopID2ItemID(eStorePanelType from, int shopID)
{
if (from == eStorePanelType.Chamber)
{
ShopContent content = HolderManager.m_ShopHolder.GetStaticInfo(shopID);
if (content != null)
return content.ItemID;
}
else if (from == eStorePanelType.Mall)
{
MallContent content = HolderManager.m_MallHolder.GetStaticInfo(shopID);
if (content != null)
return content.ItemID;
}
return shopID;
}
public static string GetChineseNumString(int num)
{
string numStr = string.Empty;
switch (num)
{
case 0:
break;
case 1:
numStr = GetText(77000020);
break;
case 2:
numStr = GetText(77000021);
break;
case 3:
numStr = GetText(77000022);
break;
case 4:
numStr = GetText(77000023);
break;
case 5:
numStr = GetText(77000024);
break;
case 6:
numStr = GetText(77000025);
break;
case 7:
numStr = GetText(77000026);
break;
}
return numStr;
}
public static int GetAvatarLevelupData(int type)
{
int avatarLevel = GetAvatarLevel();
LevelupContent lc = HolderManager.m_LevelupHolder.GetStaticInfo(avatarLevel);
if (lc == null)
return 0;
if (type == CDEFINE.ITEM_EXP)
{
return lc.BaseExp;
}
else if (type == CDEFINE.ITEM_SILVER)
{
return lc.BaseSilver;
}
else if (type == CDEFINE.ITEM_GOLD)
{
return lc.BaseGold;
}
else if (type == CDEFINE.ITEM_BIND_DIAMOND)
{
return lc.BaseIdentity;
}
else if (type == CDEFINE.ITEM_GUILD_CONTRIBUTION)
{
return lc.BaseGuildContribution;
}
else if (type == CDEFINE.ITEM_GUILD_MONEY)
{
return lc.BaseGuildMoney;
}
else if (type == CDEFINE.ITEM_M)
{
return lc.BaseItemM;
}
return 0;
}
public static int GetAvatarLevel()
{
return GetAvatarAttributeWithType(eProtoAttData.ePlayerData_Level);
}
public static float GetAvatarHPPregress()
{
return PlayerPropertyManager.Instance.PlayerProperty.GetHpProgress();
}
public static int GetAvatarAttributeWithType(eProtoAttData type)
{
return PlayerPropertyManager.Instance.PlayerProperty.GetIntProperty(type);
}
/// <summary>
///
/// </summary>
/// <param name="index">和GetTechProValue函数中的index意义相同</param>
/// <returns></returns>
public static int GetAvatarAttributeWithTechIndex(int index)
{
int val = 0;
switch (index)
{
case 0: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MaxHP); break;
case 1: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Attack); break;
case 2: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Defense); break;
case 3: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Critical); break;
case 4: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistCritical); break;
case 5: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_CriticalChance); break;
case 6: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistCriticalChance); break;
case 7: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_CriticalDamage); break;
case 8: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistCriticalDamage); break;
case 9: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MeleeAttack); break;
case 10: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistMeleeAttack); break;
case 11: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_RemoteAttack); break;
case 12: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistRemoteAttack); break;
case 13: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_TrueDamage); break;
case 14: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistTrueDamage); break;
case 16: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_AdditionalAtk); break;
case 18: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistAdditionalAtk); break;
case 20: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Refelect); break;
case 22: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_HPRecoverRatio); break;
case 23: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_VIT); break;
case 24: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_VITRecoverRatio); break;
case 25: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_VITLossRatio); break;
case 26: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ActVelocity); break;
case 27: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MoveVelocity); break;
case 28: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_LeechLife); break;
case 29: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_DerateCD); break;
case 30: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_BOSSAtk); break;
case 31: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_PKDamage); break;
case 32: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistPKDamage); break;
case 33: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_DeadlyAttack); break;
case 34: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistDeadlyAttack); break;
case 35: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_DeadlyAtkDamage); break;
case 36: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistDeadlyAtkDamage); break;
case 37: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ExpEx); break;
case 38: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MoneyEx); break;
}
return val;
}
public static bool EquipOutEquipMpdelID(int equipID, out int equipModelID, out eBodyParts part)
{
equipModelID = 0;
part = eBodyParts.Foot;
bool result = false;
EquipContent equipContent = HolderManager.m_EquipHolder.GetStaticInfo(equipID);
if (null != equipContent)
{
EquipModelContent equipModel = HolderManager.m_EquipModelHolder.GetStaticInfo(equipContent.ModelID);
if (null != equipModel)
{
equipModelID = equipModel.Key;
eEquipPartType bodyPart = (eEquipPartType)equipContent.EquipType;
switch (bodyPart)
{
case eEquipPartType.eEquipPart_Weapon:
{
part = eBodyParts.Weapon;
result = true;
}
break;
case eEquipPartType.eEquipPart_Helmet:
{
part = eBodyParts.Head;
result = true;
}
break;
case eEquipPartType.eEquipPart_Coat:
{
part = eBodyParts.UpperBody;
result = true;
}
break;
case eEquipPartType.eEquipPart_Trousers:
{
part = eBodyParts.LowerBody;
result = true;
}
break;
case eEquipPartType.eEquipPart_Belt:
{
part = eBodyParts.Waistband;
result = true;
}
break;
case eEquipPartType.eEquipPart_Shoe:
{
part = eBodyParts.Foot;
result = true;
}
break;
}
}
}
return result;
}
private static List<int> m_tempList = new List<int>();
public static List<int> ProtoEquipListToIDList(List<Equip> list)
{
m_tempList.Clear();
for (int i = 0; i < list.Count; i++)
{
m_tempList.Add(list[i].id);
}
return m_tempList;
}
//固定遮罩移动uipanel
static public void SetPanelClip(UIPanel panel, Vector3 value)
{
if (null == panel)
return;
Vector3 p = panel.transform.localPosition;
panel.transform.localPosition += value - p;
Vector2 cr = panel.clipOffset;
cr.x -= panel.transform.localPosition.x - p.x;
cr.y -= panel.transform.localPosition.y - p.y;
panel.clipOffset = cr;
}
static public void SetComponentPosition(Transform clickTransform, Transform panelTransform, UIPanel panel, SpringPanel.OnFinished OnFinished)
{
Bounds bound = NGUIMath.CalculateAbsoluteWidgetBounds(clickTransform);
Vector3 top = panelTransform.InverseTransformPoint(new Vector3(bound.max.x, bound.max.y, 0));
Vector3 bottom = panelTransform.InverseTransformPoint(new Vector3(bound.min.x, bound.min.y, 0));
float upMore = top.y - (panel.finalClipRegion.y + panel.finalClipRegion.w / 2);
float downLess = bottom.y - (panel.finalClipRegion.y - panel.finalClipRegion.w / 2);
if (upMore > 0)
{
SpringPanel.Begin(panelTransform.gameObject, new Vector3(panelTransform.localPosition.x, panelTransform.localPosition.y - upMore, 0), 10).onFinished = OnFinished;
}
else if (downLess < 0)
{
SpringPanel.Begin(panelTransform.gameObject, new Vector3(panelTransform.localPosition.x, panelTransform.localPosition.y - downLess, 0), 10).onFinished = OnFinished;
}
}
/// <summary>
/// 装备星级计算
/// 21~30 用太阳表示,11~20 用月亮表示,1~10 用星星表示
/// </summary>
/// <returns>The sprite name.</returns>
/// <param name="starLevel">Star level.</param>
/// <param name="id">Identifier.</param>
public static string GetEquipStarLevelSpriteName(int starLevel, int id, bool isShow = false)
{
if (starLevel > 20)
{
if (id < starLevel - 20)
return "state_forge_sun_gold";
else
return "state_forge_sun_dark";
}
else if (starLevel > 10)
{
if (id < starLevel - 10)
return "state_forge_moon_gold";
else
return "state_forge_moon_dark";
}
else
{
if (id < starLevel)
return "state_forge_star_gold";
else
return "state_forge_star_dark";
}
}
/// <summary>
/// 战斗力计算公式
/// </summary>
/// <param name="attrType"></param>
/// <param name="value"></param>
/// <returns></returns>
public static int GetPowerValue(eProtoAttData attrType, float value)
{
if (value == 0)
return 0;
int result = 0;
float factor = 1;
FightvalContent con = HolderManager.m_fightvalHolder.GetStaticInfo((int)attrType);
if (con != null)
factor = (float)con.Weight / (float)10000;
result += Mathf.FloorToInt(value * factor);
return result;
}
/// <summary>
/// 战斗力计算公式
/// </summary>
/// <param name="techId"></param>
/// <returns></returns>
public static int GetPowerValue(int techId)
{
TechContent tContent = HolderManager.m_TechHolder.GetStaticInfo(techId);
return GetPowerValue(tContent);
}
/// <summary>
/// 战斗力计算公式
/// </summary>
/// <param name="tContent"></param>
/// <returns></returns>
public static int GetPowerValue(TechContent tContent)
{
int value = 0;
if (null != tContent)
{
value = GetPowerValue(eProtoAttData.eAttData_MaxHP, tContent.HpMax[1]);
value += GetPowerValue(eProtoAttData.eAttData_Attack, tContent.Attack[1]);
value += GetPowerValue(eProtoAttData.eAttData_Defense, tContent.Defense[1]);
value += GetPowerValue(eProtoAttData.eAttData_Critical, tContent.Critical[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistCritical, tContent.ResistCritical[1]);
value += GetPowerValue(eProtoAttData.eAttData_CriticalChance, tContent.CriticalChance[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistCriticalChance, tContent.ResistCriticalChance[1]);
value += GetPowerValue(eProtoAttData.eAttData_CriticalDamage, tContent.CriticalDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistCriticalDamage, tContent.ResistCriticalDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_MeleeAttack, tContent.MeleeAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistMeleeAttack, tContent.ResistMeleeAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_RemoteAttack, tContent.RemoteAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistRemoteAttack, tContent.ResistRemoteAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_TrueDamage, tContent.TrueDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistTrueDamage, tContent.ResistTrueDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_AdditionalAtk, tContent.AdditionalAtk[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistAdditionalAtk, tContent.ResistAdditionalAtk[1]);
value += GetPowerValue(eProtoAttData.eAttData_Refelect, tContent.Refelect[1]);
value += GetPowerValue(eProtoAttData.eAttData_HPRecoverRatio, tContent.HPRecoverRatio[1]);
value += GetPowerValue(eProtoAttData.eAttData_VIT, tContent.VIT[1]);
value += GetPowerValue(eProtoAttData.eAttData_VITRecoverRatio, tContent.VITRecoverRatio[1]);
value += GetPowerValue(eProtoAttData.eAttData_VITLossRatio, tContent.VITLossRatio[1]);
value += GetPowerValue(eProtoAttData.eAttData_ActVelocity, tContent.ActVelocity[1]);
value += GetPowerValue(eProtoAttData.eAttData_MoveVelocity, tContent.MoveVelocity[1]);
value += GetPowerValue(eProtoAttData.eAttData_LeechLife, tContent.LeechLife[1]);
value += GetPowerValue(eProtoAttData.eAttData_DerateCD, tContent.DerateCD[1]);
value += GetPowerValue(eProtoAttData.eAttData_BOSSAtk, tContent.BOSSAtk[1]);
value += GetPowerValue(eProtoAttData.eAttData_PKDamage, tContent.PKDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistPKDamage, tContent.ResistPKDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_DeadlyAttack, tContent.DeadlyAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistDeadlyAttack, tContent.ResistDeadlyAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_DeadlyAtkDamage, tContent.DeadlyAtkDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistDeadlyAtkDamage, tContent.ResistDeadlyAtkDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ExpEx, tContent.ExpEx[1]);
value += GetPowerValue(eProtoAttData.eAttData_MoneyEx, tContent.MoneyEx[1]);
}
return value;
}
private static string[] equipPartIcon = new string[] {
"icon_forge_background_weapon",
"icon_forge_background_shoulder",
"icon_forge_background_necklace",
"icon_forge_background_bracer",
"icon_forge_background_ring",
"icon_forge_background_helmet",
"icon_forge_background_armour",
"icon_forge_background_belt",
"icon_forge_background_pants",
"icon_forge_background_boots",
};
/// <summary>
/// 装备部位没有装备的默认图标
/// </summary>
/// <param name="part"></param>
/// <returns></returns>
public static string GetEquipPartDefaultIcon(eEquipPartType part)
{
string partIcon = string.Empty;
switch (part)
{
case eEquipPartType.eEquipPart_Weapon:
partIcon = equipPartIcon[0];
break;
case eEquipPartType.eEquipPart_Shoulder:
partIcon = equipPartIcon[1];
break;
case eEquipPartType.eEquipPart_Necklace:
partIcon = equipPartIcon[2];
break;
case eEquipPartType.eEquipPart_Cuff:
partIcon = equipPartIcon[3];
break;
case eEquipPartType.eEquipPart_Ring:
partIcon = equipPartIcon[4];
break;
case eEquipPartType.eEquipPart_Helmet:
partIcon = equipPartIcon[5];
break;
case eEquipPartType.eEquipPart_Coat:
partIcon = equipPartIcon[6];
break;
case eEquipPartType.eEquipPart_Belt:
partIcon = equipPartIcon[7];
break;
case eEquipPartType.eEquipPart_Trousers:
partIcon = equipPartIcon[8];
break;
case eEquipPartType.eEquipPart_Shoe:
partIcon = equipPartIcon[9];
break;
case eEquipPartType.eEquipPart_Num:
break;
default:
break;
}
return partIcon;
}
/// <summary>
/// 获取装备部位名称
/// </summary>
/// <param name="part"></param>
/// <returns></returns>
public static string GetEquipPartName(eEquipPartType part)
{
switch (part)
{
case eEquipPartType.eEquipPart_Weapon:
return GetText(70070010);
case eEquipPartType.eEquipPart_Shoulder:
return GetText(70070001);
case eEquipPartType.eEquipPart_Necklace:
return GetText(70070002);
case eEquipPartType.eEquipPart_Cuff:
return GetText(70070003);
case eEquipPartType.eEquipPart_Ring:
return GetText(70070004);
case eEquipPartType.eEquipPart_Helmet:
return GetText(70070005);
case eEquipPartType.eEquipPart_Coat:
return GetText(70070006);
case eEquipPartType.eEquipPart_Belt:
return GetText(70070007);
case eEquipPartType.eEquipPart_Trousers:
return GetText(70070008);
case eEquipPartType.eEquipPart_Shoe:
return GetText(70070009);
default:
return string.Empty;
}
}
/// <summary>
/// 根据职业id获取名称
/// </summary>
/// <param name="jobId"></param>
/// <returns></returns>
public static string GetJobName(byte jobId, int type = 0)
{
switch (jobId)
{
case 0:
int s = 70060001;
switch ((eGEntityType)type)
{
case eGEntityType.Pet: s = 10003162; break;
case eGEntityType.Ride: s = 10003161; break;
case eGEntityType.Mercenary: s = 10003163; break;
}
return CCommon.GetText(s);
case 1:
return CCommon.GetText(70060002);
case 2:
return CCommon.GetText(70060003);
case 3:
return CCommon.GetText(70060004);
case 4:
return CCommon.GetText(70060005);
}
return null;
}
public static string GetLevelLimitString(int type, int level)
{
string s = "";
switch ((eGEntityType)type)
{
case eGEntityType.Role:
s = CCommon.GetTextS(70050011, level);
break;
case eGEntityType.Ride:
s = s + GetJobName(0, type) + CCommon.GetTextS(33304011, level);
break;
case eGEntityType.Pet:
s = s + GetJobName(0, type) + CCommon.GetTextS(70050011, level);
break;
case eGEntityType.Mercenary:
s = s + GetJobName(0, type) + CCommon.GetTextS(70050011, level);
break;
}
return s;
}
/// <summary>
/// 灰化
/// </summary>
/// <param name="gray"></param>
public static void SetGrayscale(GameObject go, bool gray)
{
Dictionary<string, Color> colors = new Dictionary<string, Color>();
if (null == colors) colors = new Dictionary<string, Color>();
GrayUtil.SetGrayscale(go, gray, colors);
}
public static void ShowFunctionNotOpenTips(int tipsID = 97000093)
{
CCommon.ShowTextTip(CCommon.GetText(tipsID));
}
public static bool CheckIsEnough(int id, long value, bool showTips = false, int tipsID = 0)
{
ItemContent itemContent = HolderManager.m_ItemHolder.GetStaticInfo(id);
if (itemContent != null)
{
if (PlayerPropertyManager.Instance.PlayerInfo.GetSpecialItemCount(id) < value)
{
if (showTips && tipsID >= 0)
{
CCommon.ShowTextTip(CCommon.GetTextS(tipsID == 0 ? 97100013 : tipsID, BackpackItemData.EquipQualityToName(CCommon.GetText(itemContent.NameID), (eQuality)itemContent.Quality)));
}
return false;
}
return true;
}
return false;
}
/// <summary>
/// 聊天非法字符过滤
/// </summary>
/// <param name="text"></param>
/// <param name="charIndex"></param>
/// <param name="addedChar"></param>
/// <returns></returns>
public static void ValidatorChatContent(CInput input, string text)
{
int index = input.Text.IndexOf("/gm");
if (index != -1)
{
return;
}
else
{
input.Text = input.Text.Replace(" ", "");
input.Text = input.Text.Replace("\n", "");
}
}
public static bool CompareValue(double v1, double v2, int type = 0)
{
switch (type)
{
case 0: return v1 < v2;
case 1: return v1 > v2;
}
return v1 == v2;
}
public static UnityEngine.GameObject FindObj(UnityEngine.GameObject g, string name)
{
if (g != null && !string.IsNullOrEmpty(name))
{
Transform tran = g.transform;
if (tran.name == name) return tran.gameObject;
Transform c = tran.Find(name);
if (c != null) return c.gameObject;
if (tran.childCount > 0)
{
foreach (Transform v in tran)
{
g = FindObj(v.gameObject, name);
if (g != null) return g;
}
}
}
return null;
}
//通过合成物ID 得到合成配方
public static ComposeContent GetComposeContent(int id)
{
Dictionary<int, ComposeContent> dic = HolderManager.m_ComposeHolder.GetDict();
foreach (KeyValuePair<int, ComposeContent> kv in dic)
{
if (kv.Value.ComposeId == id)
{
return kv.Value;
}
}
return null;
}
public static void ResetTweener(this UITweener tweener)
{
if (tweener != null)
{
tweener.ResetToBeginning();
tweener.Sample(0, false);
tweener.tweenFactor = 0f;
}
}
/// <summary>
/// 检测技能是否显示属性加成
/// </summary>
/// <returns></returns>
public static bool CheckPlayerSkillProp(PlayerSkillType type)
{
switch (type)
{
case PlayerSkillType.Passivity:
case PlayerSkillType.Guild:
case PlayerSkillType.Awaken:
case PlayerSkillType.Mount:
case PlayerSkillType.BoatPassite:
case PlayerSkillType.GodweaponPassite:
case PlayerSkillType.MercenaryPassite:
case PlayerSkillType.PetPassite:
case PlayerSkillType.MercenaryCommonPassite:
return true;
}
return false;
}
public static string GetOtherPlayerNameColor(CPlayer player)
{
string color = "";
if (player != null)
{
CMoveNpc self = (CGameWorld.Instance.CurrentScene as CBattleScene).Avatar;
if (self == player) color = "[2cc3ed]";
else
{
color = null;
CPlayerModel model = player.OriginalModel as CPlayerModel;
switch ((eModeType)PlayerPropertyManager.Instance.PlayerInfo.Mode)
{
case eModeType.Peace:
break;
case eModeType.Team:
if (CTeamManager.Instance.ContainPlayer(player.ID)) color = CDEFINE.BLUE;
else if (model != null && model.SyncPlayer != null && model.SyncPlayer.sPlyInfo != null && PlayerPropertyManager.Instance.PlayerInfo.GuildID > 0 && PlayerPropertyManager.Instance.PlayerInfo.GuildID == model.SyncPlayer.sPlyInfo.nguildid) color = CDEFINE.GREEN;
else color = CDEFINE.RED;
break;
case eModeType.Guild:
if (CTeamManager.Instance.ContainPlayer(player.ID)) color = CDEFINE.BLUE;
else if (model != null && model.SyncPlayer != null && model.SyncPlayer.sPlyInfo != null && PlayerPropertyManager.Instance.PlayerInfo.GuildID > 0 && PlayerPropertyManager.Instance.PlayerInfo.GuildID == model.SyncPlayer.sPlyInfo.nguildid) color = CDEFINE.GREEN;
else color = CDEFINE.RED;
break;
case eModeType.Whole:
color = CDEFINE.RED;
break;
case eModeType.Hatred:
if (model.SyncPlayer.sPlyInfo.pkval > 0) color = CDEFINE.RED;
break;
case eModeType.Server:
if (model.SyncPlayer.sPlyInfo.serverid != LoginManager.Instance.CurrentServerID) color = CDEFINE.RED;
break;
default: break;
}
/*if (color == null) {
switch ((eModeType)model.SyncPlayer.sPlyInfo.attackmode)
{
case eModeType.Peace:
case eModeType.Team:
case eModeType.Guild:
break;
case eModeType.Whole:
color = "[d71010]";
break;
case eModeType.Hatred:
if (model.SyncPlayer.sPlyInfo.pkval > 0) color = "[d71010]";
break;
case eModeType.Server:
if (model.SyncPlayer.sPlyInfo.serverid != LoginManager.Instance.CurrentServerID) color = "[d71010]";
break;
default: break;
}
}*/
if (color == null)
{
if (CTeamManager.Instance.ContainPlayer(player.ID)) color = CDEFINE.BLUE;
else if (model != null && model.SyncPlayer != null && model.SyncPlayer.sPlyInfo != null && PlayerPropertyManager.Instance.PlayerInfo.GuildID > 0 && PlayerPropertyManager.Instance.PlayerInfo.GuildID == model.SyncPlayer.sPlyInfo.nguildid) color = CDEFINE.GREEN;
else color = CDEFINE.WHITE;
}
}
}
return color;
}
/// <summary>
/// 是否可被攻击
/// </summary>
/// <param name="player"></param>
/// <param name="skillID"></param>
/// <returns></returns>
public static bool IsCanAttack(CBattlePlayer player, int skillID = 0)
{
if (player != null)
{
CMoveNpc self = (CGameWorld.Instance.CurrentScene as CBattleScene).Avatar;
if (player == self) return false;
CPlayerModel model = player.OriginalModel as CPlayerModel;
switch ((eModeType)PlayerPropertyManager.Instance.PlayerInfo.Mode)
{
case eModeType.Peace: return false;
case eModeType.Whole: return true;
case eModeType.Hatred:
if (model.SyncPlayer.sPlyInfo.pkval > 0) return true;
break;
case eModeType.Server:
if (model.SyncPlayer.sPlyInfo.serverid != LoginManager.Instance.CurrentServerID) return true;
break;
case eModeType.Team:
if (!CTeamManager.Instance.ContainPlayer(player.ID)) return true;
break;
case eModeType.Guild:
if (PlayerPropertyManager.Instance.PlayerInfo.GuildID != model.SyncPlayer.sPlyInfo.nguildid) return true;
break;
default: break;
}
}
return false;
}
public static void FilterAttackTargets(List<uint> targets, int skillID)
{
if (targets != null && targets.Count > 0)
{
for (int i = targets.Count - 1; i >= 0; i--)
{
CMoveNpc npc = CGameWorld.Instance.CurrentScene.IsSea ? CShipManager.Instance.GetShipByIndex(targets[i]) : CEntityManager.Instance.GetMoveNpcFormIndex(targets[i]);
if (npc != null && npc is CPlayer)
{
if (!CCommon.IsCanAttack(npc as CPlayer, skillID))
{
targets.RemoveAt(i);
}
}
else if (npc == null)
{
targets.RemoveAt(i);
}
}
}
}
public static bool IsCanAffect(CMoveNpc pAttker, CMoveNpc pTarget, eAffectType affectType = eAffectType.AffectAll)
{
CBattleScene btScene = (CGameWorld.Instance.CurrentScene as CBattleScene);
if (null == btScene)
{
return false;
}
bool state = true;
if (pAttker != null && pTarget != null)
{
//人打人或人打佣兵
if ((pAttker is CBattlePlayer || pAttker is CSoldier) && (pTarget is CBattlePlayer || pTarget is CSoldier))
{
CMoveNpc self = btScene.Avatar;
state = true;
if (pAttker == self || (pAttker is CSoldier && (pAttker as CSoldier).m_owner == self))
{
if (pTarget is CBattlePlayer)
state = IsCanAttack(pTarget as CBattlePlayer, 0);
else
state = IsCanAttack((pTarget as CSoldier).m_owner as CBattlePlayer, 0);
}
switch (affectType)
{
case eAffectType.AffectSelf: if (pAttker.ID != pTarget.ID) return false;
break;
case eAffectType.AffectFriendExceptSelf: if (state && pTarget == pAttker) return false;
break;
case eAffectType.ExceptSelf: if (state && pAttker == pTarget) return false;
break;
case eAffectType.AffectEnemy: if (!state) return false;
break;
case eAffectType.AffectFriends: if (state) return false;
break;
default:
break;
}
}
else
{
if (pTarget.NpcGroup == eNpcGroup.Neutral) return false;
switch (affectType)
{
case eAffectType.AffectAll:
break;
case eAffectType.AffectEnemy://敌方
{
if (pAttker.IsJust && pTarget.IsJust || pAttker.IsEvil && pTarget.IsEvil) return false;
}
break;
case eAffectType.AffectFriends://友方
{
if (pAttker.IsJust && pTarget.IsEvil || pAttker.IsEvil && pTarget.IsJust) return false;
}
break;
case eAffectType.AffectSelf:
{
if (pAttker.ID != pTarget.ID) return false;
}
break;
case eAffectType.AffectFriendExceptSelf:
{
if (pAttker == pTarget) return false;
if (pAttker.IsJust != pTarget.IsJust || pAttker.IsEvil != pTarget.IsEvil) return false;
}
break;
default:
break;
}
}
}
return state;
}
public static void ConfirmChangeAttackMode(string tips, eModeType mode = eModeType.Hatred, Action<bool> call = null)
{
if (CGameWorld.Instance.CurrentScene.SceneInfo.AllowAttackMode.Contains((int)mode))
{
CCommon.ShowPopDialog(tips, (b, arg) =>
{
PlayerPropertyManager.Instance.RequestChangeAttackMode((int)mode);
if (call != null) call(b);
});
}
}
//获取触发器的位置
public static Vector3 GetTriggerPos(Transform trans)
{
if (null == trans)
{
return Vector3.zero;
}
SceneTriggerData st = trans.GetComponent<SceneTriggerData>();
if (st == null || st.PointList.Length < 1)
return Vector3.zero;
return new Vector3(st.PointList[0].x, st.PointList[0].y, st.PointList[0].z);
}
//获取触发器的旋转
public static Vector3 GetTriggerRotation(Transform trans)
{
if (null == trans)
{
return Vector3.zero;
}
SceneTriggerData st = trans.GetComponent<SceneTriggerData>();
if (st == null || st.PointList.Length < 1)
return Vector3.zero;
return new Vector3(0, st.PointList[0].w, 0);
}
public static string GetCurrencyLocalString(int cid, int value)
{
ItemContent currency = HolderManager.m_ItemHolder.GetStaticInfo(cid);
string str = value.ToString();
if (currency != null)
{
int currencyCount = (int)PlayerPropertyManager.Instance.PlayerInfo.GetSpecialItemCount(cid);
if (value > currencyCount)
str = "[e51f1f]" + CCommon.GetOptionNumString((ulong)value) + "[-]";
else
str = "[44BD0A]" + CCommon.GetOptionNumString((ulong)value) + "[-]";
str += CCommon.GetText(currency.NameID);
}
return str;
}
public static List<EquipAttr> TechConvertAttr(int id)
{
List<CCommon.TechSingleData> techList = CCommon.GetTechValue(id);
List<EquipAttr> attrs = null;
if (techList != null && techList.Count > 0)
{
attrs = new List<EquipAttr>();
for (int i = 0; i < techList.Count; i++)
{
EquipAttr eq = techList[i].To();
eq.id = id;
attrs.Add(eq);
}
}
return attrs;
}
public static string LabFormatTwoColumnAttrString(UILabel label, List<EquipAttr> attrs, float padding = 0, string valueColor = "")
{
StringBuilder sb = new StringBuilder();
if (attrs.Count > 0)
{
NGUIText.rectWidth = label.width;
NGUIText.spacingX = label.spacingX;
NGUIText.spacingY = label.spacingY;
NGUIText.finalSize = Mathf.RoundToInt(label.fontSize / NGUIText.pixelDensity);
NGUIText.finalSpacingX = 0;
//maxWidth /= label.transform.localScale.x;
string info = "", v = "";
int cindex = 0;
float len = 0, temp = 0;
bool al = false;
float nl = NGUIText.CalculatePrintedSize(" ").x + NGUIText.spacingX;
string ce = string.IsNullOrEmpty(valueColor) ? "" : "[-]";
for (int i = 0; i < attrs.Count; i++)
{
info = "";
if (attrs[i].dataType == eEquipAttrDataType.Percent)
v = (100 * ((float)attrs[i].value / 10000)) + "%";
else
v = attrs[i].value.ToString();
info = attrs[i].GetAttrName() + " +" + v;
cindex++;
if (cindex == 2)
{
al = true;
if (len > 0)
{
temp = padding - len;
len = NGUIText.CalculatePrintedSize(info).x;
if (temp > 0)
{
cindex = 0;
int l = Mathf.CeilToInt(temp / nl);
for (int j = 0; j < l; j++) sb.Append(" ");
}
else
{
sb.AppendLine();
cindex--;
al = false;
}
}
info = attrs[i].GetAttrName() + valueColor + " +" + v + ce;
sb.Append(info);
if (al) sb.AppendLine();
}
else
{
if (padding > 0) len = NGUIText.CalculatePrintedSize(info).x;
info = attrs[i].GetAttrName() + valueColor + " +" + v + ce;
sb.Append(info);
}
}
}
return sb.ToString();
}
public static bool CheckDrugIsEnough(eItemSubType type = eItemSubType.RoleDrug, int tips = 0)
{
bool b = false;
int[] al = null;
switch (type)
{
case eItemSubType.RoleDrug: al = CDEFINE.DRUG_NORMAL_IDS; break;
case eItemSubType.ShipDrug: al = CDEFINE.DRUG_SHIP_IDS; break;
case eItemSubType.PkDrug: al = CDEFINE.DRUG_PK_IDS; break;
}
if (al.Length > 0)
{
for (int i = 0; i < al.Length; i++)
{
b = CheckIsEnough(al[i], 1, false);
if (b) break;
}
}
if (!b && tips > 0)
{
if (tips != 1) CCommon.ShowTips(tips);
else CCommon.ShowTextTip("背包内缺少回复药品!请购买!");
}
return b;
}
public static ItemContent GetBestDrug(eItemSubType type)
{
int[] al = null;
switch (type)
{
case eItemSubType.RoleDrug: al = CDEFINE.DRUG_NORMAL_IDS; break;
case eItemSubType.ShipDrug: al = CDEFINE.DRUG_SHIP_IDS; break;
case eItemSubType.PkDrug: al = CDEFINE.DRUG_PK_IDS; break;
}
if (al.Length > 0)
{
ItemContent item = null, temp = null;
for (int i = 0; i < al.Length; i++)
{
temp = HolderManager.m_ItemHolder.GetStaticInfo(al[i]);
if (temp != null)
{
if (item == null || (temp.Quality > item.Quality && ItemManager.Instance.CheckItemCanUse(al[i])))
item = temp;
}
}
return item;
}
return null;
}
public static List<BackpackItemData> GetDrugList(eItemSubType type = eItemSubType.RoleDrug, bool containNull = false)
{
List<BackpackItemData> list = new List<BackpackItemData>();
int[] al = null;
switch (type)
{
case eItemSubType.RoleDrug: al = CDEFINE.DRUG_NORMAL_IDS; break;
case eItemSubType.ShipDrug: al = CDEFINE.DRUG_SHIP_IDS; break;
case eItemSubType.PkDrug: al = CDEFINE.DRUG_PK_IDS; break;
}
if (al != null && al.Length > 0)
{
for (int i = 0; i < al.Length; i++)
{
var v = new BackpackItemData(al[i]) { count = 0 };
v.count = ItemManager.C<PackContainer>().GetItemNumById(al[i]);
list.Add(v);
}
}
return list;
}
public static void SetSptire(this UISprite sprite, string spName, string atlas = null, int w = 0, int h = 0, bool makePerfect = false)
{
if (sprite != null)
{
if (!string.IsNullOrEmpty(spName) && sprite.spriteName != spName)
{
if (!string.IsNullOrEmpty(atlas) && (sprite.atlas == null || sprite.atlas.name != atlas))
{
UIAtlas a = CResourceManager.Instance.GetAtlas(atlas);
if (a != null)
{
sprite.atlas = a;
sprite.spriteName = spName;
if (w > 0) sprite.width = w;
if (h > 0) sprite.height = h;
if (makePerfect) sprite.MakePixelPerfect();
return;
}
}
sprite.spriteName = spName;
if (w > 0) sprite.width = w;
if (h > 0) sprite.height = h;
if (makePerfect) sprite.MakePixelPerfect();
}
}
}
static public int MoveNpcSort(CMoveEntity a, CMoveEntity b)
{
return a.sortDis.CompareTo(b.sortDis);
}
public static void SetVipLever(char[] _char, string[] strArray, List<CSprite> _viplever, CSprite _spriteDi)
{
UIAtlas atlas = CResourceManager.Instance.GetAtlas(strArray[0]);
if (atlas != null)
{
_spriteDi.SetSprite(atlas, strArray[1]);
for (int i = 0; i < _char.Length; i++)
{
switch (_char[i])
{
case '1':
_viplever[i].SetSprite("icon_vip1");
break;
case '2':
_viplever[i].SetSprite("icon_vip2");
break;
case '3':
_viplever[i].SetSprite("icon_vip3");
break;
case '4':
_viplever[i].SetSprite("icon_vip4");
break;
case '5':
_viplever[i].SetSprite("icon_vip5");
break;
case '6':
_viplever[i].SetSprite("icon_vip6");
break;
case '7':
_viplever[i].SetSprite("icon_vip7");
break;
case '8':
_viplever[i].SetSprite("icon_vip8");
break;
case '9':
_viplever[i].SetSprite("icon_vip9");
break;
default:
break;
}
} // mSelfVipNum.SetSprite(list[PlayerPropertyManager.Instance.PlayerInfo.VipLevel].vipContent.VIPGradeMap);
//InitWidget(Convert.ToInt32((_char[0])));
}
//else
//{
// mSelfPlayerName.localPosition = new Vector3(153, 34, 0);
// // mOthersPlayerName.position
// mSelfVipDi.SetActive(false);
// mOthersVipDi.SetActive(false);
//}
}
/// <summary>
/// 显示获得新物品界面
/// </summary>
public static void ShowGetNewPartherDialog(BaseContent content, Action callback, eGetNewPartner getType)
{
SingleObject<GetNewPartnerDialog>.Instance.schemes_Content = content;
SingleObject<GetNewPartnerDialog>.Instance.CloseCallBack = callback;
SingleObject<GetNewPartnerDialog>.Instance.Show(null, false, getType);
}
public static Vector3 MousePositionToUIPosition(Camera uicamera)
{
Vector3 mousePosition = Input.mousePosition;
if (uicamera != null)
{
mousePosition.x = Mathf.Clamp01(mousePosition.x / ((float)Screen.width));
mousePosition.y = Mathf.Clamp01(mousePosition.y / ((float)Screen.height));
mousePosition = uicamera.ViewportToWorldPoint(mousePosition);
}
return mousePosition;
}
/// <summary>
/// 自动购买toogle
/// </summary>
/// <returns></returns>
public static PartnerAudoBuyComponent CreateAudoBuyComp(CPanel c, Vector3 pos, Action<bool, bool> callBack)
{
CPanel sonPanel;
CDynamicComponent cdy = c.GetElementBase("(DynamicComponent)AutoBuyNode") as CDynamicComponent;
if (cdy == null)
{
Debug.LogError("未找到挂节点 (DynamicComponent)AutoBuyNode");
return null;
}
sonPanel = cdy.AddItem("AutoBuyItem");
sonPanel.gameobject.transform.localPosition = pos;
PartnerAudoBuyComponent audobuyComp = new PartnerAudoBuyComponent(sonPanel, callBack);
return audobuyComp;
}
public static MallContent GetMallContent(int goodsID)
{
Dictionary<int, MallContent> dic = HolderManager.m_MallHolder.GetDict();
foreach (var item in dic)
{
if (item.Value.ItemID == goodsID)
{
return item.Value;
}
}
return null;
}
public static eMapGroup GetMapGroup(eMapType mapType)
{
eMapGroup group = eMapGroup.None;
if (mapType == eMapType.None) return group;
if (mapType == eMapType.MapDungeon ||
mapType == eMapType.SeaDungeon ||
mapType == eMapType.MapParkour ||
mapType == eMapType.LandMapTower ||
mapType == eMapType.MapNewbee ||
mapType == eMapType.SeaMapTower)
{
group = eMapGroup.Dungeon;
}
else if (mapType == eMapType.MapPvp
|| mapType == eMapType.SeaPvp
|| mapType == eMapType.OfflineBattle
)
{
group = eMapGroup.Ground;
}
else
{
group = eMapGroup.Scene;
}
return group;
}
/// <summary>
/// 获取场景配置
/// </summary>
/// <param name="mapID">场景ID</param>
/// <param name="scene">可能的场景配置</param>
/// <param name="dungeon">可能的副本配置</param>
/// <param name="ground">可能的战斗场景配置</param>
/// <param name="planesDungeon">是否位面副本</param>
/// <returns>如果存在配置</returns>
public static bool GetMapContent(int mapID, ref SceneContent scene, ref DungeonContent dungeon, ref BattleGroundContent ground, ref bool planesDungeon)
{
eMapType mapType = CCommon.Key2MapType(mapID);
eMapGroup g = GetMapGroup(mapType);
if (g != eMapGroup.None)
{
planesDungeon = false;
scene = null;
dungeon = null;
ground = null;
if (mapType == eMapType.None) return false;
if (g == eMapGroup.Dungeon)
{
dungeon = HolderManager.m_DungeonHolder.GetStaticInfo(mapID);
if (dungeon == null) return false;
}
else if (g == eMapGroup.Ground)
{
ground = HolderManager.m_BattleGroundHolder.GetStaticInfo(mapID);
if (ground == null) return false;
}
else
{
scene = HolderManager.m_SceneHolder.GetStaticInfo(mapID);
if (scene == null) return false;
}
if (mapType == eMapType.MapDungeon ||
mapType == eMapType.SeaDungeon ||
mapType == eMapType.MapParkour ||
mapType == eMapType.LandMapTower ||
mapType == eMapType.MapNewbee ||
mapType == eMapType.SeaMapTower)
{
planesDungeon = true;
}
}
return scene != null || dungeon != null || ground != null;
}
/// <summary>
/// 获得场景路径
/// </summary>
/// <returns></returns>
public static string GetScenePath(int mapID)
{
eMapType mapType = CCommon.Key2MapType(mapID);
SceneContent scene = null; DungeonContent dungeon = null; BattleGroundContent ground = null;
bool state = false;
if (GetMapContent(mapID, ref scene, ref dungeon, ref ground, ref state))
{
if (scene != null) return scene.ResourcePath;
if (dungeon != null) return dungeon.ScenePath;
if (ground != null) return ground.ScenePath;
}
return "";
}
/// <summary>
/// 从表中解析需要的称号字段
/// </summary>
/// <param name="_str"></param>
/// <param name="_csprite"></param>
/// <param name="_uiAtlas"></param>
public static void SetTieleSprite(string _str, CSprite _csprite, UIAtlas _uiAtlas)
{
if (_str.Contains("."))
_str = _str.Substring(0, _str.LastIndexOf('.'));
string[] str = _str.Split('/');
_csprite.SetSprite(_uiAtlas, str[4], false);
}
/// <summary>
/// 显示副本样式奖励窗口
/// <param name="dropItemId">掉落表ID</param>
/// <param name="textContent">描述内容</param>
/// <param name="textTitle">标题内容</param>
/// <param name="gridMaxPerLine">Guid并排放最大数量</param>
/// </summary>
public static void ShowCopySweepingDialog(int dropItemId, string textContent, string textTitle, int gridMaxPerLine, bool setGet = false)
{
SingleObject<CopySweepingDialog>.Instance.dropItemId = dropItemId;
SingleObject<CopySweepingDialog>.Instance.textContent = textContent;
SingleObject<CopySweepingDialog>.Instance.textTitle = textTitle;
SingleObject<CopySweepingDialog>.Instance.gridMaxPerLine = gridMaxPerLine;
SingleObject<CopySweepingDialog>.Instance.setGet = setGet;
SingleObject<CopySweepingDialog>.Instance.Show(null);
}
public static bool GetWayGoto(int getWay, bool go = true, params object[] args)
{
if (getWay > 0)
{
var way = HolderManager.m_getwayHolder.GetStaticInfo(getWay);
if (way != null)
{
if (go)
{
if (way.Key == 1002)//拍卖行,需要特殊处理
{
CDialogManager.Instance.HideAllDialog();
SingleObject<StoreDialog>.Instance.SetOpenPanel(eStorePanelType.Stall);
SingleObject<StoreDialog>.Instance.Show(delegate
{
if (args != null && args.Length > 0 && args[0] is int)
{
BusinessContent content = BourseManager.Instance.GetBusinessContentByItemID((int)args[0]);
if (content != null)
BourseManager.Instance.Request_Auction_CS_SearchItem(true, content.Key, 0, 0, 0, 0, 0, BourseStatus.Public, true, 0, BourseManager.PrePageNum);
}
});
}
else if (way.JumpType == 0)//不指引
{
CCommon.ShowTextTip(CCommon.GetText(77000041));
}
else if (way.JumpType == 1)//直接打开对应界面
{
CDialog c = CDialogManager.Instance.GetDialog(way.JumpArg[0]);
if (c != null)
{
if (way.JumpArg.Count >= 2)
{
eOpenModule type = (eOpenModule)way.JumpArg[1];
if (COpenModule.CheckKeyIsOpen(type))
{
if (c is FunctionTabDialogBase && type != eOpenModule.None)//tab面板
(c as FunctionTabDialogBase).SetOpenToggle(type, args);
}
else return false;
}
c.Show(() =>
{
CDialogManager.Instance.CloseAllDialog(true, (uint)c.PanelID, CDialogManager.D_BACKPACK_ITEM.id, SingleObject<ItemAccessMethodDialog>.Instance.PanelID);
}, false, args);
}
}
else if (way.JumpType == 2)//直接进入活动场景
{
CCommon.RequestChangeScene((uint)way.JumpArg[0]);
CDialogManager.Instance.CloseAllDialog(false);
SingleObject<BattleUiDialog>.Instance.Show(null);
}
else if (way.JumpType == 3)//跳转场景并寻路到npc
{
CDialogManager.Instance.CloseAllDialog(false);
CCommon.RequestChangeScene((uint)way.JumpArg[0]);
FindNpcManager.Instance.FindNpc(way.JumpArg[1]);
{
public const string SAVE_NEWBEE_SCENE = "saveNewbeeScene";
public const string SAVE_NEWBEE_TAG = "%|%^%";
private static Vector3 m_tempVector;
public static RuntimePlatform platform = Application.platform;
public static string Extension;
public static string PersistentDataPath = Application.persistentDataPath;
public static string StreamingAssetsPath = Application.streamingAssetsPath;
#if UNITY_EDITOR
public static string PersistentDataURL = "file:///" + Application.persistentDataPath;
public static string StreamingAssetsURL = "file://" + Application.streamingAssetsPath;
#elif UNITY_ANDROID
public static string PersistentDataURL = "file://" + Application.persistentDataPath;
public static string StreamingAssetsURL = Application.streamingAssetsPath;
#elif UNITY_IPHONE
public static string PersistentDataURL = "file://" + Application.persistentDataPath;
public static string StreamingAssetsURL = System.Uri.EscapeUriString("file://" + Application.streamingAssetsPath);
#endif
private static Dictionary<string, Shader> m_shaderCollect = new Dictionary<string, Shader>();
private static List<string> m_TrieFilter = new List<string>();
public static void Init()
{
#if UNITY_ANDROID
Extension = CDEFINE.EXTENSION_POINT_ANDROID;
#else
Extension = CDEFINE.EXTENSION_POINT_IPHONE;
#endif
if (platform == RuntimePlatform.OSXEditor || platform == RuntimePlatform.WindowsEditor)
{
StreamingAssetsURL = "file://" + Application.streamingAssetsPath;
PersistentDataURL = "file:///" + Application.persistentDataPath;
}
if (platform == RuntimePlatform.Android)
{
if (Config.Instance.UseWWWLoadAsset)
{
StreamingAssetsPath = Application.dataPath + "!assets";
}
}
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY, CDEFINE.LAYER_DEFAULT, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_DEFAULT, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY, CDEFINE.LAYER_IGNORE_ENTITY, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY, CDEFINE.LAYER_ENTITY, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_ENTITY, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_TERRAIN, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_IGNORE_ENTITY_TERRAIN_WALL, CDEFINE.LAYER_AIR_WALL, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_ENTITY, CDEFINE.LAYER_DROP_ITEM, true);
Physics.IgnoreLayerCollision(CDEFINE.LAYER_DROP_ITEM, CDEFINE.LAYER_DROP_ITEM, true);
Shader.EnableKeyword("USE_CUSTOM_LIGHT");
Shader.DisableKeyword("USE_UNITY_LIGHT");
CDEFINE.SCREEN_W = Screen.width;
CDEFINE.SCREEN_H = Screen.height;
}
/// <summary>
/// 初始化敏感词汇
/// </summary>
public static void InitSensitiveWords()
{
ShieldContent retContent = HolderManager.m_ShieldHolder.GetStaticInfo(1);
if (null != retContent)
{
m_TrieFilter = retContent.content;
}
}
/// <summary>
/// destin 是否在以 source 为中心的矩形区域内
/// </summary>
/// <param name="source"></param>
/// <param name="destin"></param>
/// <param name="range">矩形的一半边长</param>
/// <returns></returns>
public static bool IsInRect(Vector3 source, Vector3 destin, float range)
{
m_tempVector = destin - source;
if (m_tempVector.x > -range && m_tempVector.x < range && m_tempVector.z > -range && m_tempVector.z < range)
return true;
else
return false;
}
/// <summary>
/// destin 是否在以 source 为中心的圆形区域内
/// </summary>
/// <param name="source"></param>
/// <param name="destin"></param>
/// <param name="range">矩形的一半边长</param>
/// <returns></returns>
public static bool IsInCircle(Vector3 source, Vector3 destin, float range)
{
m_tempVector = destin - source;
if (DistanceSqrXZ(source, destin) < range * range)
return true;
else
return false;
}
/// <summary>
/// 两点长度的平方,忽略Y方向
/// </summary>
/// <param name="source"></param>
/// <param name="destin"></param>
/// <returns></returns>
public static float DistanceSqrXZ(Vector3 source, Vector3 destin)
{
m_tempVector = destin - source;
return m_tempVector.x * m_tempVector.x + m_tempVector.z * m_tempVector.z;
}
/// <summary>
/// 忽略Y轴 小心使用,真的需要忽略Y轴吗
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static float DistanceXZ(Vector3 a, Vector3 b)
{
Vector3 v1 = a;
v1.y = 0;
Vector3 v2 = b;
v2.y = 0;
return Vector3.Distance(v1, v2);
}
public static float DistanceSqr(Vector3 a, Vector3 b)
{
a = b - a;
return a.x * a.x + a.y * a.y + a.z * a.z;
}
public static float Distance(Vector3 a, Vector3 b)
{
return Vector3.Distance(a, b);
}
public static float Distance(Vector2 a, Vector2 b)
{
return Vector2.Distance(a, b);
}
public static float AngelXZ(Vector3 a, Vector3 b)
{
Vector3 v1 = a;
v1.y = 0;
Vector3 v2 = b;
v2.y = 0;
return Vector3.Angle(v1, v2);
}
public static Vector3 GetVector3(proto.message.Point3D pt)
{
Vector3 pos = new Vector3(pt.x, pt.y, pt.z);
pos = CCommon.NavSamplePosition(pos);
return pos;
}
public static Vector3 ToVector3(this Point3D point)
{
Vector3 pos = new Vector3(point.x, point.y, point.z);
pos = CCommon.NavSamplePosition(pos);
return pos;
}
public static Point3D ToPoint3D(this Vector3 vector)
{
return new Point3D() { x = vector.x, y = vector.y, z = vector.z };
}
public static float ToRadian(this Vector3 eulerAngles)
{
return eulerAngles.y / Mathf.Rad2Deg;
}
/// <summary>
/// 取得相应骨骼名称的变换
/// </summary>
/// <param name="trans"></param>
/// <param name="boneName"></param>
/// <returns></returns>
public static Transform GetBone(Transform trans, string boneName)
{
if (string.IsNullOrEmpty(boneName) || boneName.Equals("0"))
{
return null;
}
if (null == trans)
{
return null;
}
Transform[] tran = trans.GetComponentsInChildren<Transform>(true);
foreach (Transform t in tran)
{
if (t.name == boneName)
{
return t;
}
}
return null;
}
public static void ReplaceShader(GameObject replaceObj, Shader shader = null)
{
#if UNITY_EDITOR
if (replaceObj == null)
return;
Renderer[] renders = replaceObj.GetComponentsInChildren<Renderer>(true);
Material[] materials;
for (int rIndex = 0, rCount = renders.Length; rIndex < rCount; rIndex++)
{
materials = renders[rIndex].sharedMaterials;
for (int mIndex = 0, mCount = materials.Length; mIndex < mCount; mIndex++)
{
ReplaceShader(materials[mIndex], shader);
}
}
PigeonCoopToolkit.Effects.Trails.TrailRenderer_Base[] trailRenderBases = replaceObj.GetComponentsInChildren<PigeonCoopToolkit.Effects.Trails.TrailRenderer_Base>(true);
for (int rIndex = 0, rCount = trailRenderBases.Length; rIndex < rCount; rIndex++)
{
if (trailRenderBases[rIndex] == null)
continue;
ReplaceShader(trailRenderBases[rIndex].TrailData.TrailMaterial, shader);
}
#endif
}
public static void ReplaceShader(Material mat, Shader shader = null)
{
#if UNITY_EDITOR
if (mat == null)
return;
string name = mat.shader.name;
int queue = 0;
if (shader == null)
{
if (m_shaderCollect.ContainsKey(name))
{
if (m_shaderCollect[name] == null)
{
m_shaderCollect[name] = Shader.Find(name);
if (m_shaderCollect[name] == null)
{
m_shaderCollect.Remove(name);
return;
}
}
}
else
{
Shader s = Shader.Find(name);
if (s == null)
{
return;
}
m_shaderCollect.Add(name, s);
}
if (CMain.Instance.ResetRenderQueue)
{
queue = mat.renderQueue;
}
mat.shader = m_shaderCollect[name];
if (CMain.Instance.ResetRenderQueue)
mat.renderQueue = queue;
}
else
{
if (CMain.Instance.ResetRenderQueue)
{
queue = mat.renderQueue;
}
mat.shader = shader;
if (CMain.Instance.ResetRenderQueue)
mat.renderQueue = queue;
}
#endif
}
public static Shader GetShader(string shaderName)
{
if (m_shaderCollect.ContainsKey(shaderName))
{
return m_shaderCollect[shaderName];
}
else
{
Shader shader = Shader.Find(shaderName);
if (shader != null)
m_shaderCollect.Add(shaderName, shader);
else
{
Debug.LogError("can't find shader:" + shaderName);
}
return shader;
}
}
public static void SetLayer(GameObject target, int layer, bool containsChild)
{
target.layer = layer;
if (containsChild)
{
Transform[] child = target.GetComponentsInChildren<Transform>(true);
for (int i = 0, count = child.Length; i < count; i++)
{
if (child[i] == target.transform)
continue;
child[i].gameObject.layer = layer;
}
}
}
/// <summary>
/// 根据界面名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetPanelPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/panel/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据界面名字获取Bundle路径(相对于配置文件)
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetPanelPathToMainfest(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/panel/");
build.Append(name);
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据Atlas名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetAtlasPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/atlas/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据Component名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetComponentPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/component/");
build.Append(name.ToLower().Trim());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据View名字获取Bundle路径
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetViewPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/view/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 根据UIEffect Prefab名字回去Bundle路径
/// </summary>
/// <returns>The user interface effect path.</returns>
/// <param name="name">Name.</param>
public static string GetUIEffectPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/effect/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 获取音效路径 TODO
/// </summary>
/// <returns>The audio path.</returns>
/// <param name="name">Name.</param>
public static string GetAudioPath(string name)
{
StringBuilder build = new StringBuilder("assets/audios/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
public static string GetFontPath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/uifont/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 识别触控是否出现的UI上
/// </summary>
/// <returns></returns>
public static bool TouchOnUIGameObject()
{
return TouchOnUIGameObject(Input.mousePosition);
}
/// <summary>
/// 识别触控是否出现的UI上
/// </summary>
/// <returns></returns>
public static bool TouchOnUIGameObject(Vector2 point)
{
//return UICamera.hoveredObject != null;
RaycastHit hit = new RaycastHit();
bool bCollider = UICamera.Raycast(point, out hit);
//if (!bCollider && EasyTouch.instance != null)
//{
// bCollider = EasyTouch.instance.IsTouchHoverVirtualControll(point);// || BattleUiDialog.IsControl;
//}
return bCollider;
}
public static string GetEasyTouchTexturePath(string name)
{
StringBuilder build = new StringBuilder("assets/uiresources/texture/easytouch/");
build.Append(name.ToLower());
build.Append(".x");
return build.ToString();
}
public static string GetPanelTexturePath(eTextureType type, string texName, string panelName = "")
{
if (string.IsNullOrEmpty(texName))
return "";
StringBuilder build = null;
switch (type)
{
case eTextureType.Public:
build = new StringBuilder("assets/uiresources/texture/public/");
break;
case eTextureType.Panel:
build = new StringBuilder("assets/uiresources/texture/" + panelName + "/");
break;
case eTextureType.SceneMap:
build = new StringBuilder("assets/uiresources/texture/scenemap_read_map/");
break;
case eTextureType.SkillOrMarkIcon:
build = new StringBuilder("assets/uiresources/texture/skill_stampicon/");
break;
case eTextureType.ItemIcon:
build = new StringBuilder("assets/uiresources/texture/itemicon/");
break;
case eTextureType.Other:
build = new StringBuilder("assets/uiresources/texture/other/");
break;
case eTextureType.HeadIcon:
build = new StringBuilder("assets/uiresources/texture/headicon/");
break;
case eTextureType.Buff:
build = new StringBuilder("assets/uiresources/texture/buff/");
break;
case eTextureType.ReadMap:
build = new StringBuilder("assets/uiresources/texture/read_map/");
break;
default:
build = new StringBuilder();
break;
}
build.Append(texName.ToLower());
build.Append(".x");
return build.ToString();
}
/// <summary>
/// 创建路径
/// </summary>
/// <param name="path"></param>
public static void CreatePath(string path)
{
string NewPath = path.Replace("\\", "/");
string[] strs = NewPath.Split('/');
string p = "";
for (int i = 0; i < strs.Length; ++i)
{
p += strs[i];
if (i != strs.Length - 1)
{
p += "/";
}
if (!Path.HasExtension(p))
{
if (!Directory.Exists(p))
Directory.CreateDirectory(p);
}
}
}
/// <summary>
/// 替换静态label文字
/// </summary>
/// <param name="mPanel"></param>
/// <param name="mName"></param>
/// <param name="guiText"></param>
public static void SetStaticLabel(CPanel mPanel, string mName, int guiText, params object[] args)
{
if (null != mPanel && !string.IsNullOrEmpty(mName))
{
CLabel staticLabel = mPanel.GetElementBase(mName) as CLabel;
if (null == staticLabel)
{
return;
}
if (null != args && args.Length > 0)
staticLabel.Text = GetTextS(guiText, args);
else
staticLabel.Text = GetText(guiText);
}
}
public static void SetLabelContent(CPanel mPanel, string mName, string content)
{
if (null != mPanel && !string.IsNullOrEmpty(mName))
{
CLabel label = mPanel.GetElementBase(mName) as CLabel;
if (null != label)
{
label.Text = content;
}
}
}
public static int TextLength(string str)
{
if (string.IsNullOrEmpty(str))
return 0;
int len = str.Length;
bool pause = false;
int index = 0;
for (int i = 0; i < len; i++)
{
if (str[i].Equals('['))
{
pause = true;
continue;
}
else if (str[i].Equals(']'))
{
pause = false;
continue;
}
if (!pause)
index++;
}
return index;
}
public static string GetText(int uiID)
{
return GetText((uint)uiID);
}
/// <summary>
/// 绿色[6ec739],红色[ff1215]
/// </summary>
/// <param name="uiID"></param>
/// <param name="color"></param>
/// <returns></returns>
public static string GetText(int uiID, string color)
{
return color + GetText((uint)uiID) + "[-]";
}
public static string GetText(string str, string color)
{
return color + str + "[-]";
}
public static string GetText(int uiID, bool bNeedReplac)
{
return GetText((uint)uiID, bNeedReplac);
}
public static string GetText(uint uiID)
{
string s = GetLanguageText(uiID);
s = s.Replace("@", "\n");
return s;
}
public static string GetText(uint uiID, bool bNeedReplac)
{
string s = GetLanguageText(uiID);
if (bNeedReplac)
s = s.Replace("@", "\n");
else
s = s.Replace("@", " ");
return s;
}
public static string GetTextS(int uiID, params object[] args)
{
return GetTextS((uint)uiID, args);
}
/// <summary>
/// 值为空,返回默认的 无
/// </summary>
/// <param name="text"></param>
/// <param name="defaultId"></param>
/// <returns></returns>
public static string GetDefaultText(string text, int defaultId = 64000008)
{
if (!string.IsNullOrEmpty(text))
{
return text;
}
return CCommon.GetText(defaultId);
}
public static string GetTextS(uint uiID, params object[] args)
{
string rlt = GetLanguageText(uiID);
rlt = rlt.Replace("@", "\n");
string[] sp = new string[] { "%s" };
string[] str = rlt.Split(sp, StringSplitOptions.None);
if (str.Length <= 1 || args == null)
return rlt;
for (int i = 0; i < args.Length; i++)
{
string reStr = args[i].ToString();
if (i >= str.Length)
{
CDebug.LogError("Args lenght more than split string!");
continue;
}
str[i] += reStr;
}
rlt = string.Empty;
for (int i = 0; i < str.Length; i++)
{
rlt += str[i];
}
return rlt;
}
public static string GetTextS(string rlt, params object[] args)
{
rlt = rlt.Replace("@", "\n");
string[] sp = new string[] { "%s" };
string[] str = rlt.Split(sp, StringSplitOptions.None);
if (str.Length <= 1)
return rlt;
for (int i = 0; i < args.Length; i++)
{
string reStr = args[i].ToString();
if (i >= str.Length)
{
CDebug.LogError("Args lenght more than split string!");
continue;
}
str[i] += reStr;
}
rlt = string.Empty;
for (int i = 0; i < str.Length; i++)
{
rlt += str[i];
}
return rlt;
}
private static string GetLanguageText(uint uiID)
{
GUITextContent pInfo = HolderManager.m_GUITextHolder.GetStaticInfo(uiID);
if (null == pInfo)
{
return "$N/A";
}
return pInfo.SimpleChinese;
}
/// <summary>
/// 返回字符串的长度
/// 中文占2,英文占1
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static int GetMaxCharsLength(string text)
{
int len = 0;
if (!string.IsNullOrEmpty(text))
{
char[] tcs = text.ToCharArray();
int length = tcs.Length;
for (int i = 0; i < length; i++)
{
int c = (int)tcs[i];
if (c > 127)
{
len += 2;
}
else
{
len += 1;
}
}
}
return len;
}
/// <summary>
/// 限定字符串到达指定长度后换行。
/// </summary>
/// <param name="text"></param>
/// <param name="lineMaxCharLength"></param>
/// <returns></returns>
public static string GetAutoWrapChars(string text, int lineMaxCharLength)
{
int start = 0;
int end = 0;
string value = string.Empty;
if (!string.IsNullOrEmpty(text))
{
while (start < end)
{
start = end;
end = Mathf.Min(lineMaxCharLength, text.Length);
value += text.Substring(start, end);
if (end == lineMaxCharLength && lineMaxCharLength != text.Length)
{
value += "@";
}
}
}
return value;
}
/// <summary>
/// 限定字符串到达指定长度后换行。
/// </summary>
/// <param name="text"></param>
/// <param name="lineMaxCharLength"></param>
/// <returns></returns>
public static string GetAutoWrapChars(int gid, int lineMaxCharLength)
{
return GetAutoWrapChars(CCommon.GetText(gid), lineMaxCharLength);
}
public static void ShowErrorCode(int erroeCode)
{
int index = 80000000 + erroeCode;
ShowTextTip(CCommon.GetText(index), Color.red);
}
public static void SetErrorCodeParam(int errorCode, params object[] par)
{
int index = 80000000 + errorCode;
ShowTextTip(CCommon.GetTextS(index, par), Color.red);
}
public static void ShowTips(int textID, params object[] insert)
{
string msg = GetTextS(textID, insert);
#if UNITY_EDITOR
ShowTextTip("guitextID = " + textID.ToString() + ":" + msg);
#else
ShowTextTip(msg);
#endif
}
public static void ShowTextTip(string tipstr, Color color)
{
//SingleObject<HUDTextDialog>.Instance.ShowTextTip (tipstr, color);
ShowTextTip(tipstr);
}
public static void ShowTextTip(string tipstr)
{
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Warning, 0, 0, tipstr);
}
public static void ShowAwardsTips(List<proto.message.IDNum> item_list)
{
for (int i = 0; i < item_list.Count; i++)
{
BackpackItemData ba = new BackpackItemData(item_list[i].id);
//ShowOneAwardTips(ba, item_list[i].num);
}
}
public static void ShowOneAwardTips(BackpackItemData ba, int num)
{
//暂时不判断
//bool isBattle = CAvatar.Instance.WarnningType == WarnningType.Warnning ? true : false;
bool isBattle = false;
if (isBattle)
{
ItemContent itemCon = HolderManager.m_ItemHolder.GetStaticInfo(ba.id);
if (itemCon != null)
{
if ((eItemType)itemCon.Type == eItemType.Currency)
{
HUDAwardItem item = new HUDAwardItem();
item.id = ba.id;
item.number = num;
SingleObject<HUDAwardDialog>.Instance.ShowAward(item);
return;
}
}
}
if (ba.source == (int)eGetItem.eGetItem_Monster)
{
if ((CGameWorld.Instance.CurrentScene as CBattleScene != null) && (CGameWorld.Instance.CurrentScene as CBattleScene).IsDungeon())
{
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Award, ba.id, num, "");
}
}
else if (ba.source == (int)eGetItem.eGetItem_Offpvp)
{
}
else
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Award, ba.id, num, "");
}
public static void ShowLackTips(int id, string str)
{
SingleObject<NewTipsDialog>.Instance.ShowNewTips(eTipsType.Tips_Lack, id, 0, str);
}
public static void ShowDebugTips(string text)
{
#if UNITY_EDITOR
ShowTextTip(text);
#else
CDebug.LogAssert(text);
#endif
}
/// <summary>
/// bytes转int
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static int BytesToInt(byte[] src, int offset)
{
int value = 0;
value = (int)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
return value;
}
public static long BytesToLong(byte[] src, int offset)
{
long value = 0;
value = (long)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24)
| ((src[offset + 4] & 0xFF) << 32)
| ((src[offset + 5] & 0xFF) << 40)
| ((src[offset + 6] & 0xFF) << 48)
| ((src[offset + 7] & 0xFF) << 56));
return value;
}
/// <summary>
/// bytes转ushort
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static ushort BytesToUshort(byte[] src, int offset)
{
ushort value = 0;
value = (ushort)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8));
return value;
}
/// <summary>
/// int 转 bytes
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static byte[] IntToBytes(int value)
{
byte[] src = new byte[4];
src[3] = (byte)((value >> 24) & 0xFF);
src[2] = (byte)((value >> 16) & 0xFF);
src[1] = (byte)((value >> 8) & 0xFF);
src[0] = (byte)(value & 0xFF);
return src;
}
public static byte[] LongToBytes(long value)
{
byte[] src = new byte[8];
src[7] = (byte)((value >> 56) & 0xFF);
src[6] = (byte)((value >> 48) & 0xFF);
src[5] = (byte)((value >> 40) & 0xFF);
src[4] = (byte)((value >> 32) & 0xFF);
src[3] = (byte)((value >> 24) & 0xFF);
src[2] = (byte)((value >> 16) & 0xFF);
src[1] = (byte)((value >> 8) & 0xFF);
src[0] = (byte)(value & 0xFF);
return src;
}
/// <summary>
/// PB消息体转byte数组
/// </summary>
/// <typeparam name="T">Protobuf消息体类型</typeparam>
/// <param name="msg">Protobuf消息体实例形参</param>
/// <returns></returns>
public static byte[] ProtobufMsgToBytes<T>(T msg) where T : class
{
using (MemoryStream memStream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(memStream, msg);
return memStream.ToArray();
}
return null;
}
/// <summary>
/// 字节数组转换成PB消息体
/// </summary>
/// <typeparam name="T">Protobuf消息体类型</typeparam>
/// <param name="bytes">服务端返回字节数组</param>
/// <returns></returns>
public static T BytesToProtobufMes<T>(object o) where T : class
{
//MemoryStream readStream = new MemoryStream(bytes);
//try
//{
// return ProtoBuf.Serializer.Deserialize<T>(readStream);
//}
//catch (Exception ex)
//{
// CDebug.LogException(ex);
//}
//finally
//{
// readStream.Close();
//}
//return null;
return o as T;
}
/// <summary>
/// 字节数组转换成PB消息体
/// </summary>
/// <typeparam name="T">Protobuf消息体类型</typeparam>
/// <param name="bytes">服务端返回字节数组</param>
/// <returns></returns>
public static object BytesToProtobufMes(Type type, byte[] bytes)
{
if (bytes == null || type == null)
return null;
MemoryStream readStream = new MemoryStream(bytes);
try
{
return ProtoBuf.Serializer.Deserialize(type, readStream);
}
catch (Exception ex)
{
CDebug.LogException(ex);
}
finally
{
readStream.Close();
}
return null;
}
#region Extension methods for: List<T>
/// <summary>
/// Sorted list
/// </summary>
/// <param name="theList"></param>
/// <returns></returns>
public static List<T> Sorted<T>(this List<T> theList)
{
List<T> aList = new List<T>(theList);
aList.Sort();
return aList;
}
/// <summary>
/// Sorted list
/// </summary>
/// <param name="theList"></param>
/// <returns></returns>
public static IEnumerable<T> Sorted<T>(this IEnumerable<T> theList, Comparison<T> theComparison)
{
List<T> aList = new List<T>(theList);
aList.Sort(theComparison);
foreach (T aT in aList)
yield return aT;
yield break;
}
#endregion
#region Extension methods for: IEnumerable
/// <summary>
/// Check if item is in collection
/// </summary>
/// <param name="theList"></param>
/// <param name="theNeedle"></param>
/// <returns></returns>
public static bool ContainsItem<T>(this IEnumerable<T> theList, T theNeedle) where T : class
{
foreach (T anElement in theList)
{
if (theNeedle.Equals(anElement))
{
return true;
}
}
return false;
}
/// <summary>
/// Join to string with separator
/// </summary>
/// <param name="theList"></param>
/// <param name="theSeparator"></param>
/// <returns></returns>
public static string JoinToString<T>(this IEnumerable<T> theList, string theSeparator)
{
if (theList == null)
return "";
List<string> aListStrings = new List<string>();
foreach (T anElement in theList)
{
aListStrings.Add(anElement.ToString());
}
return string.Join(theSeparator, aListStrings.ToArray());
}
/// <summary>
/// Insert item at position
/// </summary>
/// <param name="theList"></param>
/// <param name="theItem"></param>
/// <param name="thePosition"></param>
/// <returns></returns>
public static IEnumerable<T> InsertItem<T>(this IEnumerable<T> theList, T theItem, int thePosition)
{
int i = 0;
bool anInserted = false;
foreach (T anElement in theList)
{
if (i == thePosition)
{
yield return theItem;
anInserted = true;
}
yield return anElement;
i++;
}
if (!anInserted)
{
yield return theItem;
}
}
/// <summary>
/// Append a new item
/// </summary>
/// <param name="theList"></param>
/// <param name="theItem"></param>
/// <returns></returns>
public static IEnumerable<T> AppendItem<T>(this IEnumerable<T> theList, T theItem)
{
foreach (T anElement in theList)
{
yield return anElement;
}
yield return theItem;
}
/// <summary>
/// Remove doubles from IEnumerable
/// </summary>
/// <param name="theList"></param>
/// <returns></returns>
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> theList)
{
List<T> aDistinctList = new List<T>();
foreach (T anElement in theList)
{
if (!aDistinctList.Contains(anElement))
{
aDistinctList.Add(anElement);
yield return anElement;
}
}
yield break;
}
/// <summary>
/// Only return first list without elements of the second list
/// </summary>
/// <param name="theMainList"></param>
/// <param name="theListToRemove"></param>
/// <returns></returns>
public static IEnumerable<T> Remove<T>(this IEnumerable<T> theMainList, T[] theListToRemove)
{
List<T> aListToRemove = new List<T>(theListToRemove);
foreach (T anElement in theMainList)
{
if (!aListToRemove.Contains(anElement))
yield return anElement;
}
yield break;
}
public static IEnumerable<T> SortedAndReverse<T>(this IEnumerable<T> theList)
{
List<T> aList = new List<T>(theList);
aList.Sort();
aList.Reverse();
foreach (T aT in aList)
yield return aT;
yield break;
}
public static IEnumerable<T> Reversed<T>(this IEnumerable<T> theList)
{
List<T> aList = new List<T>(theList);
aList.Reverse();
foreach (T aT in aList)
yield return aT;
yield break;
}
/// <summary>
/// Convert to generic list
/// </summary>
/// <returns></returns>
public static List<T> ToDynList<T>(this IEnumerable<T> theList)
{
return new List<T>(theList);
}
#endregion
/// <summary>
/// 检测线段与球相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆点P</param>
/// <param name="radius">圆半径</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineSphere(Vector3 A, Vector3 B, Vector3 P, float range, float radius)
{
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.y - A.y) * (B.y - A.y) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
return DistanceSqr(A, P) < radius * radius;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.y - B.y) * (A.y - B.y) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
return DistanceSqr(B, P) < radius * radius;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
return DistanceSqr(P, m_tempVector) < radius * radius;
}
/// <summary>
/// 检测线段与圆相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆点P</param>
/// <param name="radius">圆半径</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineSegment(Vector3 A, Vector3 B, Vector3 P, float range, float radius)
{
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
return DistanceSqrXZ(A, P) < radius * radius;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
return DistanceSqrXZ(B, P) < radius * radius;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
return DistanceSqrXZ(P, m_tempVector) < radius * radius;
}
/// <summary>
/// 检测线段与圆柱相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆柱低圆点P</param>
/// <param name="radius">圆半径</param>
/// <param name="high">高度</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineCylinderStep(Vector3 A, Vector3 B, Vector3 P, float range, float radius, float high)
{
float dY;
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
dY = A.y - P.y;
return DistanceSqrXZ(A, P) < radius * radius && 0 < dY && dY < high;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
dY = B.y - P.y;
return DistanceSqrXZ(B, P) < radius * radius && 0 < dY && dY < high;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
dY = m_tempVector.y - P.y;
return DistanceSqrXZ(P, m_tempVector) < radius * radius && 0 < dY && dY < high;
}
/// <summary>
/// 检测线段与圆柱相切
/// </summary>
/// <param name="A">线段端点A</param>
/// <param name="B">线段端点B</param>
/// <param name="P">圆柱圆点P</param>
/// <param name="radius">圆半径</param>
/// <param name="high">高度的一半</param>
/// <returns>true 相切 false 不相切</returns>
public static bool IsDistToLineCylinder(Vector3 A, Vector3 B, Vector3 P, float range, float radius, float high)
{
float dY;
radius += range;
float dotA = (P.x - A.x) * (B.x - A.x) + (P.z - A.z) * (B.z - A.z);
if (dotA < 0)
{
dY = A.y - P.y;
return DistanceSqrXZ(A, P) < radius * radius && -high < dY && dY < high;
}
float dotB = (P.x - B.x) * (A.x - B.x) + (P.z - B.z) * (A.z - B.z);
if (dotB < 0)
{
dY = B.y - P.y;
return DistanceSqrXZ(B, P) < radius * radius && -high < dY && dY < high;
}
m_tempVector = A + ((B - A) * dotA) / (dotA + dotB);
dY = m_tempVector.y - P.y;
return DistanceSqrXZ(P, m_tempVector) < radius * radius && -high < dY && dY < high;
}
/// <summary>
/// 插值计算,计算从范围A-B到范围a-b的插值计算,C为范围A-B中任意一点。注意C值可以超出A-B的范围,如超出之后相应的得到a-b的范围值也会超出
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="A"></param>
/// <param name="B"></param>
/// <param name="C"></param>
/// <returns></returns>
public static float Lerp(float a, float b, float A, float B, float C)
{
return a - (A - C) / (A - B) * (a - b);
}
public static float LerpClamp(float a, float b, float A, float B, float C)
{
if (A > B)
{
if (C > A)
C = A;
if (C < B)
C = B;
}
else
{
if (C < A)
C = A;
if (C > B)
C = B;
}
return a - (A - C) / (A - B) * (a - b);
}
public static int LerpClamp(int a, int b, float A, float B, float C)
{
if (A > B)
{
if (C > A)
C = A;
if (C < B)
C = B;
}
else
{
if (C < A)
C = A;
if (C > B)
C = B;
}
return (int)(a - (A - C) / (A - B) * (a - b));
}
public static long Clamp(long value, long min, long max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
public static GameObject CreateQuad(Material material, string name)
{
GameObject quad = new GameObject(name);
Mesh mesh = new Mesh();
Vector3[] vectors = new Vector3[4];
vectors[0] = new Vector3(-0.5f, -0.5f, 0);
vectors[1] = new Vector3(0.5f, -0.5f, 0);
vectors[2] = new Vector3(-0.5f, 0.5f, 0);
vectors[3] = new Vector3(0.5f, 0.5f, 0);
Vector2[] uvs = new Vector2[4];
uvs[0] = new Vector2(0, 0);
uvs[1] = new Vector2(1, 0);
uvs[2] = new Vector2(0, 1);
uvs[3] = new Vector2(1, 1);
int[] triangles = new int[6] { 0, 2, 1, 1, 2, 3 };
mesh.vertices = vectors;
mesh.uv = uvs;
mesh.triangles = triangles;
MeshFilter meshFilter = quad.AddComponent<MeshFilter>();
meshFilter.sharedMesh = mesh;
MeshRenderer meshRender = quad.AddComponent<MeshRenderer>();
meshRender.sharedMaterial = material;
return quad;
}
public static void MoveToShelterCamera(Camera camera, Transform trans, float distance)
{
if (camera == null || trans == null)
return;
float d = camera.nearClipPlane + distance;
float rad = (camera.fieldOfView / 2f) * Mathf.Deg2Rad;
float h = 2 * Mathf.Tan(rad) * d;
float l = camera.aspect * h;
Vector3 scale = new Vector3(l, h, trans.localScale.z);
trans.localScale = scale;
trans.parent = camera.transform;
trans.localPosition = new Vector3(0, 0, d);
trans.localRotation = Quaternion.identity;
}
/// <summary>
/// 将transform的绕Y轴偏转的弧度,转成一个Quaternion
/// </summary>
/// <param name="angel"></param>
/// <returns></returns>
public static Quaternion MakeYEulerToRotation(float rad)
{
Quaternion rot = Quaternion.Euler(Vector3.up * Mathf.Rad2Deg * rad);
return rot;
}
public static bool GetVector3OfStringList(List<string> strList, int index, ref Vector3 vector)
{
vector = Vector3.zero;
if (strList != null)
{
int idx = index * 3;
if (strList.Count >= 3 * (index + 1))
{
vector = new Vector3(Convert.ToSingle(strList[0 + idx]), Convert.ToSingle(strList[1 + idx]), Convert.ToSingle(strList[2 + idx]));
return true;
}
}
return false;
}
//获取某一技能升级level次的功能描述//
public static string GetPlayerSkillFunctionDes(PlayerSkillContent config, int level)
{
// 0级时读取1级的描述
if (level == 0)
{
level = 1;
}
while (level > config.MaxUpgradeNum)
{
level -= config.MaxUpgradeNum;
config = HolderManager.m_PlayerSkillHolder.GetStaticInfo(config.NextPhase);
}
List<object> desParams = new List<object>();
if (config.FunctionDescribeParams.Count != 0)
{
for (int i = 0; i < config.FunctionDescribeParams.Count; i++)
{
if (config.FunctionDescribeParams[i].list.Count == 1)
{
desParams.Add(config.FunctionDescribeParams[i].list[0].ToString());
}
else if (config.FunctionDescribeParams[i].list.Count == 2)
{
float baseValue = float.Parse(config.FunctionDescribeParams[i].list[0].Replace("%", ""));
float step = float.Parse(config.FunctionDescribeParams[i].list[1].Replace("%", ""));
string tmpStr = (baseValue + step * level).ToString();
if (config.FunctionDescribeParams[i].list[0].Contains("%"))
{
tmpStr += "%";
}
desParams.Add(tmpStr);
}
else
{
CDebug.LogError("TODO Leo");
}
}
}
if (desParams.Count != 0)
return CCommon.GetTextS(config.FunctionDescribe, desParams.ToArray());
else
return CCommon.GetText(config.FunctionDescribe);
}
//获取某一技能升级level次的功能描述//
public static string GetMarkFunctionDes(MarkContent config)
{
List<object> desParams = new List<object>();
if (config.FunctionDesParams.Count != 0)
{
for (int i = 0; i < config.FunctionDesParams.Count; i++)
{
if (config.FunctionDesParams[i].list.Count == 1)
{
desParams.Add(config.FunctionDesParams[i].list[0].ToString());
}
else if (config.FunctionDesParams[i].list.Count == 2)
{
float baseValue = float.Parse(config.FunctionDesParams[i].list[0].Replace("%", ""));
float step = float.Parse(config.FunctionDesParams[i].list[1].Replace("%", ""));
desParams.Add((baseValue + step).ToString());
}
else
{
CDebug.LogError("TODO Leo");
}
}
}
if (desParams.Count != 0)
return CCommon.GetTextS(config.FunctionDes, desParams.ToArray());
else
return CCommon.GetText(config.FunctionDes);
}
public static bool IsNumber(object obj)
{
if (obj != null)
{
string str = obj.ToString();
if (!string.IsNullOrEmpty(str))
{
char[] chars = str.ToCharArray();
int length = chars.Length;
for (int i = 0; i < length; i++)
{
if (chars[i] == '.')
{
continue;
}
if (!char.IsNumber(chars[i]))
{
return false;
}
}
return true;
}
}
return false;
}
public static Vector3 Vector3Mulity(Vector3 a, Vector3 b)
{
a.x *= b.x;
a.y *= b.y;
a.z *= b.z;
return a;
}
//找到navmesh上最近的点
public static Vector3 NavSamplePosition(Vector3 srcPosition)
{
Vector3 dstPosition = srcPosition;
UnityEngine.AI.NavMeshHit meshHit = new UnityEngine.AI.NavMeshHit();
int layer = 1 << UnityEngine.AI.NavMesh.GetAreaFromName("Walkable");
if (UnityEngine.AI.NavMesh.SamplePosition(srcPosition, out meshHit, 5f, layer))
{
dstPosition = meshHit.position;
}
return dstPosition;
}
//找出地面碰撞点
public static Vector3 GroundPosition(Vector3 srcPosition, int terrainLayer)
{
Ray ray = new Ray(srcPosition + Vector3.up * 5, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100, 1 << terrainLayer))
{
return hit.point;
}
return Vector3.zero;
}
/// <summary>
/// 获取玩家拥有物品的个数//
/// </summary>
public static long GetItemNum(int itemID)
{
return PlayerPropertyManager.Instance.PlayerInfo.GetSpecialItemCount(itemID);
}
/// <summary>
/// 获取物品对应的Icon名
/// </summary>
/// <param name="dataId"></param>
/// <returns></returns>
public static string GetItemIconById(int dataId)
{
string retValue = null;
eIDType type = GetTypeFormID(dataId);
switch (type)
{
case eIDType.Equip:
{
EquipContent equipContent = HolderManager.m_EquipHolder.GetStaticInfo(dataId);
if (null != equipContent)
{
EquipModelContent equipModelContent = HolderManager.m_EquipModelHolder.GetStaticInfo(equipContent.ModelID);
if (null != equipModelContent)
{
retValue = equipModelContent.Icon;
}
}
}
break;
case eIDType.Item:
{
ItemContent itemContent = HolderManager.m_ItemHolder.GetStaticInfo(dataId);
if (null != itemContent)
{
retValue = itemContent.IconPath;
}
}
break;
default:
break;
}
return retValue;
}
/// <summary>
/// 拆分数字
/// </summary>
/// <param name="num">数字</param>
/// <param name="startIndex">开始拆分索引值(从0开始,左往右递增)</param>
/// <returns></returns>
public static int Subint(this int num, int startIndex)
{
string number = num.ToString();
number = number.Substring(startIndex);
return int.Parse(number);
}
/// <summary>
/// 拆分数字
/// </summary>
/// <param name="num">数字</param>
/// <param name="startIndex">开始拆分索引值(从0开始,左往右递增)</param>
/// <param name="length">拆分长度</param>
/// <returns></returns>
public static int Subint(this int num, int startIndex, int length)
{
string number = num.ToString();
number = number.Substring(startIndex, length);
return int.Parse(number);
}
/// <summary>
/// 根据PlayerSkill或者Mark表的Key,识别唯一技能或者印记//
/// </summary>
/// <returns>The player skill or mark index.</returns>
/// <param name="key">Key.</param>
public static int GetPlayerSkillOrMarkIndex(int key)
{
return Mathf.FloorToInt(key / 100);
}
/// <summary>
/// 将曲线字符串,转换成曲线值数组
/// </summary>
/// <param name="curveList"></param>
/// <returns></returns>
public static Keyframe[] GetKeyframes(List<float> curveList)
{
int len = 0;
if (curveList != null)
{
len = curveList.Count;
}
Keyframe[] keyframes;
if (len < 4)
{
keyframes = new Keyframe[2];
keyframes[0] = new Keyframe(0, 0);
keyframes[1] = new Keyframe(1, 1);
}
else
{
keyframes = new Keyframe[(len / 4) + 2];
keyframes[0] = new Keyframe(0, 0);
int idx = 1;
for (int i = 0; i < len; i += 4)
{
Keyframe kf = new Keyframe(CConvert.ToSingle(curveList[i]), CConvert.ToSingle(curveList[i + 1]),
CConvert.ToSingle(curveList[i + 2]), CConvert.ToSingle(curveList[i + 3]));
keyframes[idx] = kf;
idx++;
}
keyframes[keyframes.Length - 1] = new Keyframe(1, 1);
}
return keyframes;
}
/// <summary>
/// 返回物品的种类
/// </summary>
/// <param name="itemId"></param>
/// <returns></returns>
public static eItemType GetItemType(int itemId)
{
ItemContent ic = HolderManager.m_ItemHolder.GetStaticInfo(itemId);
if (ic != null)
{
return (eItemType)ic.Type;
}
return eItemType.None;
}
/// <summary>
/// 通过ID得到是装备还是物品
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static eIDType GetTypeFormID(int id)
{
int t = id / 10000000;
if (t == 3)
{
return eIDType.Equip;
}
else if (t == 4)
return eIDType.Item;
else
return eIDType.Error;
}
private static List<int> ToggleGroups = new List<int>() { 6666 };
/// <summary>
/// 获取一个从未使用过的Group id//
/// </summary>
/// <returns>The un use group id.</returns>
public static int GetUnUseGroupID()
{
ToggleGroups.Add(ToggleGroups[ToggleGroups.Count - 1] + 2);
return ToggleGroups[ToggleGroups.Count - 1];
}
public static string GetQualityName(int quality)
{
if (quality > 0 && quality < 7)
return CCommon.GetText(28000031 + quality);
else if (quality == 0)
return CCommon.GetText(27100013);
return "";
}
public static string GetQualityName(eQuality quality)
{
return GetQualityName((int)quality);
}
public static string GetItemQualityBoard(int itemQuality)
{
switch (itemQuality)
{
case 1:
return "floor_quality_white";
case 2:
return "floor_quality_green";
case 3:
return "floor_quality_blue";
case 4:
return "floor_quality_purple";
case 5:
return "floor_quality_red";
case 6:
return "floor_quality_yellow";
default:
return "frame_forge_quality_dark";
}
}
public static string GetEquipQualityBoard(eQuality qua)
{
switch (qua)
{
case eQuality.None:
return "frame_forge_quality_dark";
case eQuality.White_Bronze:
return "floor_quality_white";
case eQuality.Green_Silver:
return "floor_quality_green";
case eQuality.Blue_Gold:
return "floor_quality_blue";
case eQuality.Purple_Epic:
return "floor_quality_purple";
case eQuality.Red_Legend:
return "floor_quality_red";
case eQuality.Orange_Artifact:
return "floor_quality_yellow";
}
return "floor_quality_white";
}
/// <summary>
/// 激活 / 不激活 显示对象
/// </summary>
/// <param name="goList"></param>
/// <param name="flg"></param>
public static void ActiveGameObjectList(List<GameObject> goList, bool flg)
{
if (goList != null)
{
int length = goList.Count;
for (int i = 0; i < length; i++)
{
goList[i].SetActive(flg);
}
}
}
#region 设置品质背景框
public static string[] QualitySpriteName = new string[]
{
//"frame_forge_quality_dark",
"floor_quality_white",
"floor_quality_green",
"floor_quality_blue",
"floor_quality_purple",
"floor_quality_red",
"floor_quality_yellow",
};
public static void SetQualityBgSprite(CPanel cpanel, string spriteName, eQuality quality, bool isNeedPerfect = false)
{
if (null == cpanel || string.IsNullOrEmpty(spriteName))
return;
CSprite sprite = cpanel.GetElementBase(spriteName) as CSprite;
if (null != sprite && quality != eQuality.None)
{
UIAtlas atlas = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_SYSTEM_FLOOR2);
sprite.SetSprite(atlas, GetEquipQualityBoard(quality), isNeedPerfect);
}
}
#endregion
#region 设置物品品质的背景图
public static string[] ItemQualitySpriteName = new string[]
{
"frame_forge_quality_dark",
"floor_quality_white",
"floor_quality_green",
"floor_quality_blue",
"floor_quality_purple",
"floor_quality_red",
"floor_quality_yellow",
};
/// <summary>
/// 设置物品的品质背景图
/// </summary>
/// <param name="cpanel"></param>
/// <param name="spriteName"></param>
/// <param name="quality">eEquipQuality</param>
/// <param name="isNeedPerfect">是否图片紧贴</param>
public static void SetItemQualitySprite(CPanel cpanel, string spriteName, eQuality quality, bool isNeedPerfect = false)
{
if (cpanel == null || string.IsNullOrEmpty(spriteName))
{
return;
}
CSprite sprite = cpanel.GetElementBase(spriteName) as CSprite;
if (sprite != null)
{
UIAtlas atlasname = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_SYSTEM_FLOOR2);
sprite.SetSprite(atlasname, GetEquipQualityBoard(quality), isNeedPerfect);
}
}
public static void SetItemQualitySprite(CSprite sprite, eQuality quality, bool isNeedPerfect = false)
{
if (sprite == null)
{
return;
}
UIAtlas atlasname = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_SYSTEM_FLOOR2);
sprite.SetSprite(atlasname, GetEquipQualityBoard(quality), isNeedPerfect);
}
public static void SetItemQualityButton(CButton button, eQuality quality, bool isNeedPerfect = false)
{
if (button == null)
{
return;
}
button.MySprite.spriteName = GetEquipQualityBoard(quality);
}
/// <summary>
/// 设置UI特效层级
/// uiEffectGo加载未完成,或刚才加载完时设置,有可能无效。用第二种方法
/// </summary>
/// <param name="panel"></param>
/// <param name="uiEffectGo"></param>
public static void SetUiEffectQuquq(UIWidget uiWidget, GameObject uiEffectGo, int adddDeath = 1)
{
if (uiEffectGo != null)
{
UIParticleRenderQuquq ququq = uiEffectGo.GetComponent<UIParticleRenderQuquq>();
if (ququq == null)
{
ququq = uiEffectGo.AddComponent<UIParticleRenderQuquq>();
}
if (uiWidget != null)
{
//ququq.Depth = uiWidget.depth - 1;
if (uiWidget.panel == null)
{
uiWidget.panel = uiWidget.CreatePanel();
}
if (uiWidget.panel != null)
{
BetterList<UIDrawCall> dcs = uiWidget.panel.drawCalls;
if (dcs != null)
{
int idx = dcs.size - 1;
if (idx > 0)
{
ququq.SetRenderQueue(dcs[idx].renderQueue + adddDeath);
}
return;
}
}
}
}
}
public static void SetUiEffectDepth(UIWidget uiWidget, GameObject uiEffectGo, int adddDeath = 1)
{
if (uiEffectGo != null)
{
UIParticleRenderQuquq ququq = uiEffectGo.GetComponent<UIParticleRenderQuquq>();
if (ququq == null)
{
ququq = uiEffectGo.AddComponent<UIParticleRenderQuquq>();
}
if (uiWidget != null)
{
ququq.Depth = uiWidget.depth + adddDeath;
}
}
}
public static void SetGameObjectDepth(GameObject uiEffectGo, int adddDeath = 1)
{
if (uiEffectGo != null)
{
UIParticleRenderQuquq ququq = uiEffectGo.GetComponent<UIParticleRenderQuquq>();
if (ququq == null)
{
ququq = uiEffectGo.AddComponent<UIParticleRenderQuquq>();
}
ququq.Depth = 3000 + adddDeath;
}
}
/// <summary>
/// 设置UI特效层级
/// </summary>
/// <param name="panel"></param>
/// <param name="uiEffectGo"></param>
public static void LoadUiEffectCallback(GameObject uiEffectGo, int setDepth = 10, UIWidget widget = null)
{
if (uiEffectGo != null)
{
uiEffectGo.transform.localPosition = new Vector3(0, 0, 0);
uiEffectGo.transform.localScale = Vector3.one;
uiEffectGo.gameObject.SetActive(false);
uiEffectGo.gameObject.SetActive(true);
if (!widget) widget = NGUITools.FindInParents<UIWidget>(uiEffectGo);
CCommon.SetUiEffectDepth(widget, uiEffectGo, 100);
}
}
#endregion
public static DateTime ConvertServerTime(int seconds)
{
return new DateTime(1970, 1, 1).AddSeconds((double)seconds);
}
/// <summary>
/// DateTime 转 时间 Unix时间戳格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static double DateTimeToStamp(DateTime dt)
{
DateTime startDt = new DateTime(1970, 1, 1, 0, 0, 0, dt.Kind);
return (dt - startDt).TotalSeconds;
}
/// <summary>
/// Unix时间戳 转 DateTime
/// </summary>
/// <param name="target"></param>
/// <param name="stampTime"></param>
/// <returns></returns>
public static DateTime StampToDateTime(DateTime target, double stampTime)
{
DateTime startDt = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
return startDt.AddSeconds(stampTime);
}
public static DateTime ConvertServerTime(double seconds)
{
return new DateTime(1970, 1, 1).AddSeconds(seconds);
}
public static eErrorType CheckErrorCode(int code, object[] args = null)
{
eErrorType et = (eErrorType)code;
if (et != eErrorType.eError_Success)
{
string errorStr = CCommon.GetTextS(80000000 + code, args);
if (errorStr != "$N/A")
{
#if UNITY_EDITOR
errorStr = "Error:" + code.ToString() + "," + errorStr;
#else
errorStr = errorStr;
#endif
ShowTextTip(errorStr);
}
else
{
#if UNITY_EDITOR
ShowTextTip("GUIText表缺少 [ff0000]" + (80000000 + code) + "[-] 的错误文本!");
#else
ShowTextTip("error [ff0000]"+code+"[-]");
#endif
}
}
return et;
}
/// <summary>
/// 从时间段列表中,对比当前时间取下一刷新时间的秒数
/// </summary>
/// <param name="timeStr"></param>
/// <returns></returns>
public static float GetRemainTimeByRefreshTimeList(string timeStr)
{
string[] timeList = timeStr.Split('~');
System.DateTime time = LoginManager.Instance.GetServerUtcDateTime();
int curSecond = (time.Hour + 8) % 24 * 3600 + time.Minute * 60 + time.Second;//utc时间+8小时=本地时间
int startSecond = 0;
int i = 0;
for (i = 0; i < timeList.Length; i++)
{
string[] childTime = timeList[i].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
if (startSecond > curSecond)//大于当前时间,则取该时间段作为刷新时间
{
startSecond -= curSecond;
break;
}
}
if (i >= timeList.Length)//已经过了今天最后一次刷新时间,则取第一次的
{
string[] childTime = timeList[0].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
startSecond = startSecond + (24 * 3600 - curSecond);
}
return startSecond;
}
/// <summary>
/// 从时间段列表中,对比当前时间取已刷新的开始时间
/// </summary>
/// <param name="timeStr"></param>
/// <returns>返回已开始多少秒</returns>
public static float GetRefreshTimeByRefreshTimeList(string timeStr)
{
string[] timeList = timeStr.Split('~');
System.DateTime time = LoginManager.Instance.GetServerUtcDateTime();
int curSecond = (time.Hour + 8) % 24 * 3600 + time.Minute * 60 + time.Second;//utc时间+8小时=本地时间
int startSecond = 0;
int i = 0;
bool isFind = false;
for (i = timeList.Length - 1; i >= 0; i--)
{
string[] childTime = timeList[i].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
if (startSecond <= curSecond)//小于当前时间,则取该时间段作为刷新时间
{
curSecond -= startSecond;
isFind = true;
break;
}
}
if (!isFind)//已经过了今天最后一次刷新时间,则取最后一次的
{
string[] childTime = timeList[timeList.Length - 1].Split(':');
int hour = int.Parse(childTime[0]);
int minute = int.Parse(childTime[1]);
startSecond = hour * 3600 + minute * 60;
curSecond += 24 * 3600;//加上一天的秒数
curSecond -= startSecond;
}
return curSecond;
}
/// <summary>
/// 获取离线时间
/// 离线时间<1小时,则显示已离线N分钟,不足1分钟的显示一分钟
/// 离线时间<24小时,则显示已离线N小时(隐藏分钟,满足60分钟,才会加1小时)
/// 离线时间>1天,则显示已离线N天N小时(隐藏分钟,满足60分钟,才会加1小时)
/// </summary>
/// <param name="timeBegin"></param>
/// <param name="timeEnd"></param>
/// <returns></returns>
public static string GetOutlineTimeStr(DateTime timeBegin, DateTime? timeEnd = null)
{
string result = string.Empty;
if (timeEnd == null)
timeEnd = LoginManager.Instance.GetServerUtcDateTime();
TimeSpan timeSpan = (DateTime)timeEnd - timeBegin;
long value = timeSpan.Ticks;
if (value > TimeSpan.TicksPerDay)
{
value /= TimeSpan.TicksPerDay;
long lefthour = timeSpan.Ticks - value * TimeSpan.TicksPerDay;
if (lefthour > TimeSpan.TicksPerHour)
{
lefthour /= TimeSpan.TicksPerHour;
return GetTextS(81100086, value) + GetText(81100089) + lefthour + GetText(81100088);
}
else
return GetTextS(81100086, value) + GetText(81100089);
}
else if (value > TimeSpan.TicksPerHour)
{
value /= TimeSpan.TicksPerHour;
return GetTextS(81100086, value) + GetText(81100088);
}
else if (value > TimeSpan.TicksPerMinute)
{
value /= TimeSpan.TicksPerMinute;
return GetTextS(81100086, value) + GetText(81100087);
}
else
{
return GetTextS(81100086, 1) + GetText(81100087);
}
}
public static int BaseKeyComtentSortByKey(BaseContent a, BaseContent b)
{
return a.Key.CompareTo(b.Key);
}
public static eMapType Key2MapType(int key)
{
if (key / 1000000 == (int)eMapType.Main)
{
return eMapType.MapLand;
}
return (eMapType)(key / 1000000);
}
public static string GetPlayerJobIcon(ePlayerJob job)
{
return GetPlayerJobIcon((int)job);
}
public static string GetPlayerJobIcon(int job)
{
PlayerConfigContent content = CData.Instance.GetPlayerConfigContent(job);
if (content != null)
return content.JobIcon;
else
return "";
}
public static string GetPlayerHeadIcon(ePlayerJob job)
{
return GetPlayerHeadIcon((int)job);
}
public static string GetPlayerHeadIcon(int job)
{
PlayerConfigContent content = CData.Instance.GetPlayerConfigContent(job);
if (content != null)
return content.HeadIcon;
else
return "";
}
/// <summary>
/// 通过职业获取职业名
/// </summary>
/// <param name="Career"></param>
/// <returns></returns>
public static string GetPlayerNameByCareer(int Career)
{
PlayerContent content = CData.Instance.GetPlayerContent((ePlayerJob)Career);
if (content != null)
return CCommon.GetText(content.NameID);
else
return "";
}
//获取优化后的数字显示,以后策划调整规则统一这里改//
public static string GetOptionNumString(ulong num)
{
if (num >= 1000000)
{//亿//
return Mathf.FloorToInt(num / 10000f).ToString() + "W";
}
return num.ToString();
}
/// <summary>
/// 获取通过条件各类型的描述
/// </summary>
/// <returns></returns>
public static string GetDungeonGradeTitle(eEvaluateType type, bool isMulMap = false)
{
string evaluateTitle = null;
switch (type)
{
case eEvaluateType.ClearanceTime:
evaluateTitle = GetText(50010003);
break;
case eEvaluateType.NumberOfAttacks:
{
if (isMulMap)
{
evaluateTitle = GetText(50010009);
}
else
{
evaluateTitle = GetText(50010004);
}
}
break;
case eEvaluateType.PlayerLeftoverHp:
if (isMulMap)
{
evaluateTitle = GetText(50010010);
}
else
{
evaluateTitle = GetText(50010005);
}
break;
case eEvaluateType.NpcLeftoverHp:
evaluateTitle = GetText(50010006);
break;
case eEvaluateType.NumOfAllPlayerDie:
evaluateTitle = GetText(50010007);
break;
case eEvaluateType.ParkourTimeScore:
evaluateTitle = GetText(76000014);
break;
case eEvaluateType.ParkourPropScore:
evaluateTitle = GetText(76000015);
break;
case eEvaluateType.ParkourPassScore:
evaluateTitle = GetText(76000016);
break;
case eEvaluateType.ParkourExtraPlus:
evaluateTitle = GetText(76000017);
break;
case eEvaluateType.FulfillTask:
evaluateTitle = GetText(50030043);
break;
default:
break;
}
return evaluateTitle;
}
public static string GetDungeonGradeDes(eEvaluateType type, int value)
{
string evaluateDes = null;
switch (type)
{
case eEvaluateType.ClearanceTime:
evaluateDes = "" + value + "s";
break;
case eEvaluateType.NumberOfAttacks:
evaluateDes = "" + value;
break;
case eEvaluateType.PlayerLeftoverHp:
evaluateDes = "" + value + "%";
break;
case eEvaluateType.NpcLeftoverHp:
evaluateDes = "" + value + "%";
break;
case eEvaluateType.NumOfAllPlayerDie:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourTimeScore:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourPropScore:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourPassScore:
evaluateDes = "" + value;
break;
case eEvaluateType.ParkourExtraPlus:
evaluateDes = "" + value;
break;
case eEvaluateType.FulfillTask:
evaluateDes = "" + value;
break;
default:
break;
}
return evaluateDes;
}
/// <summary>
/// 通过评分等级获取对应图片名
/// </summary>
/// <returns></returns>
public static string GetEvaluateScoreIcon(eEvaluateScoreType type)
{
string spriteName = null;
switch (type)
{
case eEvaluateScoreType.S:
spriteName = "icon_copy_s";
break;
case eEvaluateScoreType.A:
spriteName = "icon_copy_a";
break;
case eEvaluateScoreType.B:
spriteName = "icon_copy_b";
break;
case eEvaluateScoreType.C:
spriteName = "icon_copy_c";
break;
case eEvaluateScoreType.D:
spriteName = "icon_copy_d";
break;
default:
break;
}
return spriteName;
}
public static bool IsQuestHolder(int id)
{
return id / 10000000 == 6;
}
public static bool IsNpcHolder(int id)
{
return id < 100000000;
}
public static bool IsAvatarDead()
{
if (CGameWorld.Instance.CurrentState == EGameState.Battle)
{
if (CGameWorld.Instance.CurrentScene.IsSea)
{
return CShipAvatar.Instance.IsDead;
}
}
return CAvatar.Instance.IsDead;
}
/// <summary>
/// 获取周几字符串
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string GetDayOfWeekStringByDateTime(DateTime date)
{
DayOfWeek day = date.DayOfWeek;
string str = string.Empty;
switch (day)
{
case DayOfWeek.Monday:
str = GetText(64000022);
break;
case DayOfWeek.Tuesday:
str = GetText(64000023);
break;
case DayOfWeek.Wednesday:
str = GetText(64000024);
break;
case DayOfWeek.Thursday:
str = GetText(64000025);
break;
case DayOfWeek.Friday:
str = GetText(64000026);
break;
case DayOfWeek.Saturday:
str = GetText(64000027);
break;
case DayOfWeek.Sunday:
str = GetText(64000028);
break;
}
return str;
}
/// <summary>
/// 获取几月几日字符串
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string GetMonthDayStringByDateTime(DateTime date)
{
string str = date.Month + CCommon.GetText(73020022) + date.Day + CCommon.GetText(77000026);
return str;
}
/// <summary>
/// 格式化时间00:00:00
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public static string GetTimeBySecond(double seconds)
{
return DateTime.Parse(DateTime.Now.ToString("00:00:00")).AddSeconds(seconds).ToString("HH:mm:ss");
}
public static string GetDateStringByDateTime(DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd");
}
public static string GetMinuteBySecond(float seconds)
{
return DateTime.Parse(DateTime.Now.ToString("00:00")).AddSeconds(seconds).ToString("mm:ss");
}
public static string GetNowTimeByMinute()
{
return DateTime.Now.ToString("HH:mm");
}
public static string GetTimeStrByHours(double hours)
{
string date = "";
int daysTemp = (int)hours / 24;
int hoursTemp = (int)hours % 24;
if (daysTemp != 0)
date = daysTemp + GetText(70000033);
if (hoursTemp != 0)
date += hoursTemp + GetText(70000034);
return date;
}
public static string GetTimeStrByHoursMinuteSecond(float second, string tab = ":")
{
int h = Mathf.FloorToInt(second / 3600);
int m = Mathf.FloorToInt(second % 3600 / 60);
int s = Mathf.FloorToInt(second % 3600 % 60);
return h + tab + m + tab + s;
}
public static string GetTimeStrByMinuteSecond(float second, string tab = ":")
{
int m = Mathf.FloorToInt(second / 60);
int s = Mathf.FloorToInt(second % 60);
return m + tab + s;
}
public static void IgnoreCollision(UnityEngine.Collider collider1, UnityEngine.Collider collider2, bool state = true)
{
if (null == collider1 || null == collider2)
{
Debug.LogWarning(" Error ! collider para is null !");
return;
}
Transform trans1 = collider1.transform;
Transform trans2 = collider2.transform;
if (null == trans1 || null == trans2)
{
return;
}
if (!trans1.root.gameObject.activeInHierarchy || !trans2.root.gameObject.activeInHierarchy)
{
return;
}
if (!collider1.enabled || !collider2.enabled)
return;
//MyLog.Log(" IgonreCollision : " + collider1.name + " and " + collider2.name);
Physics.IgnoreCollision(collider1, collider2, state);
}
public static object[] StringListToObjectArray(List<string> stringList)
{
List<object> desParams = new List<object>();
for (int i = 0, count = stringList.Count; i < count; i++)
{
desParams.Add(stringList[i].ToString());
}
return desParams.ToArray();
}
public static bool AssetListIndex<T>(List<T> list, int index, bool debug = true)
{
if (list.Count > index)
{
return true;
}
else
{
if (debug)
Debug.LogError("index out of list count");
return false;
}
}
public static string TimeFormatDHMS(ulong time)
{
string str = "";
ulong residualVal = 0;
ulong days = time / (60 * 60 * 24); //天
residualVal = time % (60 * 60 * 24);
ulong hours = residualVal / (60 * 60); //时
residualVal = residualVal % (60 * 60);
ulong minutes = residualVal / 60; //分
residualVal = residualVal % 60; //秒
if (days > 0)
{
str = GetTextS(59003017, Convert.ToInt32(days), Convert.ToInt32(hours), Convert.ToInt32(minutes));
}
else
{
str = GetTextS(59003018, Convert.ToInt32(hours), Convert.ToInt32(minutes), Convert.ToInt32(residualVal));
}
return str;
}
public static string SecondToString(ulong seconds, eDateStringType dataType)
{
string retStr = "";
ulong residualVal = 0;
ulong days = seconds / (60 * 60 * 24); //天
residualVal = seconds % (60 * 60 * 24);
ulong hours = residualVal / (60 * 60); //时
residualVal = residualVal % (60 * 60);
ulong minutes = residualVal / 60; //分
residualVal = residualVal % 60; //秒
switch (dataType)
{
case eDateStringType.Seconds:
retStr = String.Format("{0:D2}", residualVal);
break;
case eDateStringType.Minutes:
retStr = String.Format("{0:D2}:{1:D2}", minutes, residualVal);
break;
case eDateStringType.Hours:
retStr = String.Format("{0:D2}:{1:D2}:{2:D2}", hours, minutes, residualVal);
break;
case eDateStringType.Days:
retStr = String.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}", days, hours, minutes, residualVal);
break;
default:
break;
}
return retStr;
}
/// <summary>
/// 当天是本月的第几周
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static int GetWeekNumInMonth(DateTime dt)
{
int dayInMonth = dt.Day;
DateTime firstDay = dt.AddDays(1 - dt.Day);
int weekDay = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;
int firstWeekEndDay = 7 - (weekDay - 1);
int diffDay = dayInMonth - firstWeekEndDay;
diffDay = diffDay > 0 ? diffDay : 1;
int weekNumInMonth = (diffDay % 7) == 0 ? (diffDay / 7 - 1) : (diffDay / 7) + 1 + ((dayInMonth > firstWeekEndDay) ? 1 : 0);
return weekNumInMonth;
}
/// <summary>
/// 获取本周起始时间,即本周一0点0分0秒
/// </summary>
/// <returns></returns>
public static DateTime GetWeekBeginTime()
{
DateTime today = LoginManager.Instance.GetServerUtcDateTime();
int weekDay = (int)today.DayOfWeek == 0 ? 7 : (int)today.DayOfWeek;
weekDay -= 1; //周一
var year = today.Year;
var month = today.Month;
var day = today.Day - weekDay;
var weekBeginTime = new DateTime(year, month, day, 0, 0, 0);
return weekBeginTime;
}
public static void ShowDebugPopDialog(string text)
{
ShowPopDialog(text, null, Color.red, null, null);
}
/// <summary>
///
/// </summary>
/// <param name="text">文本提示</param>
/// <param name="action">反馈回调</param>
/// <param name="args">反馈参数</param>
/// <param name="popKey">忽略键值,用于不再提示功能,一般取默认值</param>
public static void ShowPopDialog(string text, Action<bool, object> action, object args = null, object popKey = null,
eTipsModel mode = eTipsModel.Tips_TwoBtn, float limitTime = -1, string title = "",
bool showCancelCd = false, bool showConfirmCd = false)
{
ShowPopDialog(text, action, Color.white, args, popKey, mode, limitTime, title, showCancelCd, showConfirmCd);
}
public static void ShowCountDownPopDialog(string text, Action<bool, object> action, int countDownTime, string title = "")
{
SingleObject<YesOrNoDialoag>.Instance.Show(delegate()
{
SingleObject<YesOrNoDialoag>.Instance.InitDialog(text, action, countDownTime, title);
}, true);
}
private static void ShowPopDialog(string text, Action<bool, object> action, Color color, object args, object popKey, eTipsModel mode = eTipsModel.Tips_TwoBtn, float limitTime = -1, string title = "", bool showCancelCd = false, bool showConfirmCd = false)
{
SingleObject<YesOrNoDialoag>.Instance.Show(delegate()
{
SingleObject<YesOrNoDialoag>.Instance.InitDialog(text, action, color, args, popKey, mode, limitTime, title, showCancelCd, showConfirmCd);
}, true);
}
/// <summary>
/// 查询进入 活动 限制人数 Usual表
/// 0:通过,1:不在组队状态,2:在组队状态,3:在组队状态人数不足
/// </summary>
/// <param name="usualId"></param>
/// <returns></returns>
public static int CheckUsualLimitPeople(int usualId)
{
int canOpen = 0;
UsualContent usual = HolderManager.m_UsualHolder.GetStaticInfo(usualId);
if (usual == null)
{
return canOpen;
}
List<int> limit = usual.LimitPeople;
int teamerCount = CTeamManager.Instance.TeamerCount;
if (limit.Count == 2)
{
if (limit[0] == 1 && limit[1] == 1)
{
canOpen = teamerCount > 0 ? 2 : 0;
}
else
{
if (teamerCount <= 0)
{
canOpen = 1;
}
else if (teamerCount >= limit[0] && teamerCount <= limit[1])
{
canOpen = 0;
}
else
{
canOpen = 3;
}
}
}
return canOpen;
}
/// <summary>
/// 查询进入 活动 限制人数 Usual表
/// 0:通过,1:不在组队状态,2:在组队状态,3:在组队状态人数不足
/// </summary>
/// <param name="usualId"></param>
/// <returns></returns>
public static int CheckUsualLimitPeople(int min, int max)
{
int canOpen = 0;
int teamerCount = CTeamManager.Instance.TeamerCount;
int limitMin = min;
int limitMax = max;
if (limitMin == 1 && limitMax == 1)
{
canOpen = teamerCount > 0 ? 2 : 0;
}
else
{
if (teamerCount <= 0)
{
canOpen = 1;
}
else if (teamerCount >= limitMin && teamerCount <= limitMax)
{
canOpen = 0;
}
else
{
canOpen = 3;
}
}
return canOpen;
}
public static bool CheckIsOpen(int openContentID, ref int targetLevel)
{
OpenContent open = HolderManager.m_OpenHolder.GetStaticInfo(openContentID);
if (open != null)
{
OpenModuleCondition openCondition = (OpenModuleCondition)open.OpenCondition;
switch (openCondition)
{
case OpenModuleCondition.finishTask: break;
case OpenModuleCondition.level:
{
int level = SingleObject<PlayerPropertyManager>.Instance.PlayerProperty.GetIntProperty(eProtoAttData.ePlayerData_Level);
targetLevel = open.ConditionParam;
if (level < targetLevel)
{
return false;
}
}
break;
case OpenModuleCondition.receiveTask: break;
}
return true;
}
return false;
}
public static bool CheckIsOpen(int openContentID)
{
int level = 0;
return CheckIsOpen(openContentID, ref level);
}
/// <summary>
/// 查询进入 活动 条件是否成立(开启条件) Usual表
/// </summary>
/// <param name="usualId"></param>
/// <returns></returns>
public static bool CheckUsualOpenCondition(int usualId, bool needShopTips = true)
{
bool canOpen = false;
UsualContent usual = HolderManager.m_UsualHolder.GetStaticInfo(usualId);
if (usual == null)
{
return canOpen;
}
//开启条件判断
switch (usual.OpenCondition)
{
case 1:
canOpen = usual.OpenConditionParams <= PlayerPropertyManager.Instance.PlayerProperty.GetIntProperty(eProtoAttData.ePlayerData_Level);
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetTextS(19020001, usual.OpenConditionParams));//等级不足
}
}
break;
case 2://完成任务
break;
case 3://接到任务
break;
case 4:
int targetLevel = 0;
canOpen = CheckIsOpen(usual.OpenConditionParams, ref targetLevel);
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetTextS(19020001, targetLevel));//等级不足
}
}
break;
}
return canOpen;
}
/// <summary>
/// 查询进入 活动 条件是否成立(开启条件, 开启日期, 开启时段) Usual表
/// </summary>
/// <param name="usualId"></param>
/// <param name="ignoreOpenCondition">忽略开启条件</param>
/// <returns></returns>
public static bool CheckUsualOpenConditionAndTime(int usualId, bool ignoreOpenCondition = true, bool needShopTips = true)
{
bool canOpen = false;
UsualContent usual = HolderManager.m_UsualHolder.GetStaticInfo(usualId);
if (usual == null)
{
return canOpen;
}
//开启条件判断
if (ignoreOpenCondition)
{
canOpen = CheckUsualOpenCondition(usualId, needShopTips);
if (!canOpen)
{
return canOpen;
}
}
DateTime dt = LoginManager.Instance.GetServerCurGMTDataTime();
//开启日期判断
List<BaseStringContent> openDays = usual.OpenDay;
if (openDays != null)
{
int length = openDays.Count;
for (int i = 0; i < length; i++)
{
BaseStringContent bic = openDays[i];
switch (usual.OpenType)
{
case (int)eUsualOpenType.None:
canOpen = true;
break;
case (int)eUsualOpenType.DayOfWeek:
canOpen = (Convert.ToInt16(bic.list[0]) == (int)dt.DayOfWeek);
break;
case (int)eUsualOpenType.Day:
int startMonth, endMonth;
int startDay, endDay;
startMonth = endMonth = Convert.ToInt16(bic.list[1].Substring(0, 2));
startDay = endDay = Convert.ToInt16(bic.list[1].Substring(2, 2));
if (bic.list.Count > 2)
{
endMonth = Convert.ToInt16(bic.list[2].Substring(0, 2));
endDay = Convert.ToInt16(bic.list[2].Substring(2, 2));
}
if (dt.Month >= startMonth && dt.Month <= endMonth &&
dt.Day >= startDay && dt.Day <= endDay)
{
canOpen = true;
}
break;
case (int)eUsualOpenType.WeekLoop:
if (Convert.ToInt32(bic.list[0]) == PlayerPropertyManager.Instance.PlayerInfo.CurActivityWeek)
canOpen = true;
else
canOpen = false;
break;
}
if (canOpen) { break; }
}
}
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetText(32001016));//不是开放日
}
return canOpen;
}
//开启时段判断
List<BaseFloatContent> openTime = usual.OpenTime;
if (openTime[0].list.Count > 1)
{
int length = openTime.Count;
canOpen = false;
int onTime = dt.Hour * 100 + dt.Minute;
int endTime = 0;
for (int i = 0; i < length; i++)
{
int start = Mathf.FloorToInt(openTime[i].list[0] * 100);
int end = Mathf.FloorToInt(openTime[i].list[1] * 100);
if (start < onTime && onTime < end)
{
endTime = end;
canOpen = true;
}
}
}
else
{
canOpen = true;
}
if (!canOpen)
{
if (needShopTips)
{
CCommon.ShowTextTip(CCommon.GetText(32001017));//不是开放时段
}
return canOpen;
}
return canOpen;
}
public static string EnchantmentNameToColor(string name, SRandAttr mag, EquipEnchantContent eContent)
{
//改变颜色 0-10%显示白色、11-30%显示绿色、31-50%显示蓝色、51-70%显示紫色、71-90%显示橙色、91-100%显示红色
int _iValue1 = eContent.Range[1] - eContent.Range[0];
int _iValue2 = (int)mag.uiAttrVal - (int)eContent.Range[0];
eQuality _bValue = eQuality.None;
if (_iValue2 <= Math.Floor(_iValue1 * 0.1))
{
//10%
_bValue = eQuality.White_Bronze;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.3))
{
//11%-30%
_bValue = eQuality.Green_Silver;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.5))
{
//31%-50%
_bValue = eQuality.Blue_Gold;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.7))
{
//51%-70%
_bValue = eQuality.Purple_Epic;
}
else if (_iValue2 <= Math.Floor(_iValue1 * 0.9))
{
//71%-90%
_bValue = eQuality.Orange_Artifact;
}
else
{
//91%-100%
_bValue = eQuality.Red_Legend;
}
return CCommon.NameToQualityColor(name, _bValue);
}
public static string NameToQualityColor(string name, eQuality qua)
{
string str = "";
str = GetEquipOrItemColor(qua);
str += name;
str += "[-]";
return str;
}
public static string NameToQualityColor(int nameID, eQuality qua)
{
string name = GetText(nameID);
return NameToQualityColor(name, qua);
}
public static string QualityToText(eQuality quality)
{
return GetText(80000900 + (int)quality);
}
public static string QualityToTextWithColor(eQuality quality)
{
return NameToQualityColor(QualityToText(quality), quality);
}
public static bool GetIsHaveSensitiveWords(string str)
{
if (string.IsNullOrEmpty(str))
return false;
return m_TrieFilter.Contains(str);
return m_TrieFilter.Contains(str);
}
//public static string StringSimplify(string str)
//{
// string preHandleStr = "";
// char[] c = str.ToCharArray();
// for (int i = 0; i < c.Length; i++)
// {
// //if (c[i] < '0')
// // continue;
// //if (c[i] > '9' && c[i] < 'A')
// // continue;
// //if (c[i] > 'Z' && c[i] < 'a')
// // continue;
// //if (c[i] > 'z' && c[i] < 128)
// // continue;
// if (c[i] > 0xFF00 && c[i] < 0xFF5F)
// {
// /*全角=>半角*/
// preHandleStr += (char)(c[i] - 0xFEE0);
// }
// else if (c[i] > 0x40 && c[i] < 0x5b)
// {
// /*大写=>小写*/
// preHandleStr += (char)(c[i] + 0x20);
// }
// else
// {
// preHandleStr += c[i];
// }
// }
// return preHandleStr;
//}
public static string StringDelUrl(string str)
{
int beginIndex = 0;
int endIndex = 0;
string preHandleStr = str;
while (true)
{
beginIndex = preHandleStr.IndexOf("[url");
endIndex = preHandleStr.IndexOf("[/url]");
if (beginIndex != -1 && endIndex != -1)
{
preHandleStr = preHandleStr.Remove(beginIndex, endIndex - beginIndex + 6);
}
else
{
break;
}
}
return preHandleStr;
}
/// <summary>
/// 判断是否包含标点符号,返回true即包含非法字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsHaveIllegalPunctuation(string str)
{
char[] c = str.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
//下划线是允许的
if (c[i] == 95)
break;
if (c[i] > 31 && c[i] < 48)
return true;
if (c[i] > 57 && c[i] < 65)
return true;
if (c[i] > 90 && c[i] < 97)
return true;
if (c[i] > 122 && c[i] < 255)
return true;
}
return false;
}
#region UI界面显示/隐藏引导用的红点标记
public static void SetUIGuideRedPointActive(GameObject targetGo, bool active, float offsetX = 0.0f, float offsetY = 0.0f)
{
if (active)
ShowUIGuideRedPoint(targetGo, 2, 20, offsetX, offsetY);
else
{
if (offsetX == 0 && offsetY == 0)
HideUIGuideRedPoint(targetGo);
else
RemoveUIGuideRedPoint(targetGo);
}
}
/// <summary>
/// 显示UI界面引导用的红点标记
/// </summary>
/// <param name="targetGo"></param>
/// <param name="pos">1:左上,2:右上,3:右下,4:左下</param>
/// <param name="depth">层深</param>
public static GameObject ShowUIGuideRedPoint(GameObject targetGo, int pos = 2, int depth = 20, float offsetX = 0.0f, float offsetY = 0.0f)
{
if (targetGo == null)
{
return null;
}
GameObject go = _GetUIGuideRedPointGo(targetGo);
if (go == null)
{
go = new GameObject("guidePointIcon");
UISprite icon = go.AddComponent<UISprite>();
icon.atlas = CResourceManager.Instance.GetAtlas(CDEFINE.ATLAS_PUBLIC2);
icon.spriteName = "icon_new";
icon.type = UISprite.Type.Simple;
icon.MakePixelPerfect();
icon.depth = depth;
go.transform.SetParent(targetGo.transform);
go.transform.localPosition = new Vector3(0, 0, 0);
go.transform.localScale = Vector3.one;
}
go.transform.localPosition = new Vector3(0, 0, 0);
go.transform.localScale = Vector3.one;
if (!go.activeSelf)
{
go.SetActive(true);
}
Bounds bound = NGUIMath.CalculateRelativeWidgetBounds(targetGo.transform);
if (bound != null)
{
Vector3 max = bound.max;
Vector3 newPos = Vector3.zero;
switch (pos)
{
case 1:
newPos = new Vector3(bound.min.x + 13, bound.max.y - 13, 0);
break;
case 2:
newPos = new Vector3(bound.max.x - 13, bound.max.y - 13, 0);
break;
case 3:
newPos = new Vector3(bound.max.x - 13, bound.min.y + 13, 0);
break;
case 4:
newPos = new Vector3(bound.min.x + 13, bound.min.y + 13, 0);
break;
case 5:
newPos = new Vector3(offsetX, offsetY, 0);
break;
}
newPos.x += offsetX;
newPos.y += offsetY;
go.transform.localPosition = newPos;
}
return go;
}
/// <summary>
/// 隐藏UI界面引导用的红点标记
/// </summary>
/// <param name="targetGo"></param>
public static void HideUIGuideRedPoint(GameObject targetGo)
{
if (targetGo == null)
{
return;
}
GameObject go = _GetUIGuideRedPointGo(targetGo);
if (go != null && go.activeSelf)
{
go.SetActive(false);
}
}
/// <summary>
/// 删除UI界面引导用的红点标记
/// </summary>
/// <param name="targetGo"></param>
public static void RemoveUIGuideRedPoint(GameObject targetGo)
{
if (targetGo == null)
{
return;
}
GameObject go = _GetUIGuideRedPointGo(targetGo);
if (go != null)
{
GameObject.Destroy(go);
}
}
private static GameObject _GetUIGuideRedPointGo(GameObject targetGo)
{
Transform tf = targetGo.transform;
Transform pointTf = tf.Find("guidePointIcon");
return pointTf != null ? pointTf.gameObject : null;
}
#endregion
//展示语音录音图示
public static void SetActiveSpeechArea(bool isShow)
{
if (isShow)
{
SingleObject<InputExtensionDialog>.Instance.SetExtensionType(eInputExtensionType.None);
SingleObject<InputExtensionDialog>.Instance.Show(eCommunicationType.Chat);
}
else
{
SingleObject<InputExtensionDialog>.Instance.Close(null);
}
}
public static void RequestChangeScene(uint sceneID, bool needprogress = true, bool ignore = false)
{
if (UpdateManager.Instance.CheckAssetsNeedUpdate(eCheckLoadType.Map, CCommon.GetScenePath((int)sceneID), null, null, false))
{
return;
}
if (needprogress)
{
CChangeSceneProgressManager.Instance.ChangeScene(sceneID, needprogress, ignore);
return;
}
uint playerID = CAvatar.Instance.ID;
if (!CTeamManager.Instance.IsLeader(playerID) && CTeamManager.Instance.GetTeamerStatus(playerID) == eTeamStatus.Follow)
{
ShowTips(12020076);
return;
}
eMapType mapType = Key2MapType((int)sceneID);
if (mapType == eMapType.MapLand || mapType == eMapType.Main || mapType == eMapType.MapSea || mapType == eMapType.MapMovement)
{
BattleMessageHandle.Instance.RequestChangeScene(sceneID);
}
else if (mapType == eMapType.MapDungeon || mapType == eMapType.SeaDungeon)
{
CDialogManager.Instance.TriggerEvent(new CUIGlobalEvent(CUIGlobalEvent.CLICK_ENTER_DUNGEON) { Data = sceneID });
}
else if (mapType == eMapType.MapGuild)
{
if (PlayerPropertyManager.Instance.IsHasGuild())
{
GuildManager.Instance.RequestEnterScene(null);
}
else
{
ShowTextTip(GetText(80000191));
}
}
else if (mapType == eMapType.MapParkour)
{
}
else if (mapType == eMapType.MapPvp)
{
}
else if (mapType == eMapType.SeaPvp)
{
}
}
public static List<int> SpilStringToIntList(string str, string tag1 = "~")
{
string[] temptempStr = new string[0];
temptempStr = str.Split(tag1.ToCharArray(), StringSplitOptions.None);
List<int> tempList = new List<int>();
for (int j = 0; j < temptempStr.Length; j++)
{
tempList.Add(DataDecode.GetInt32(temptempStr[j]));
}
return tempList;
}
public static List<string> SpilStringToStringList(string str, string tag1 = "~")
{
string[] temptempStr = new string[0];
temptempStr = str.Split(tag1.ToCharArray(), StringSplitOptions.None);
return temptempStr.ToDynList<string>();
}
public static List<List<int>> SpilStringToIntListList(string str, string tag1 = "$", string tag2 = "~")
{
List<List<int>> list = new List<List<int>>();
string[] tempStr = new string[0];
if (!string.IsNullOrEmpty(str))
{
tempStr = str.Split(tag1.ToCharArray(), StringSplitOptions.None);
string[] temptempStr = new string[0];
for (int i = 0; i < tempStr.Length; i++)
{
temptempStr = tempStr[i].Split(tag2.ToCharArray(), StringSplitOptions.None);
List<int> tempList = new List<int>();
for (int j = 0; j < temptempStr.Length; j++)
{
tempList.Add(DataDecode.GetInt32(temptempStr[j]));
}
list.Add(tempList);
}
}
return list;
}
public static void GetStartDayAndEndDayFromWeekLoop(int year, int month, int weekNum, ref int startDay, ref int endDay)
{
DateTime date = new DateTime(year, month, 1);
for (int i = 0; i <= date.AddMonths(1).AddDays(-1).Day; i++)
{
if (new DateTime(date.Year, date.Month, i).DayOfWeek == DayOfWeek.Monday)
{
startDay = i;
endDay = i + 6;
}
}
}
public static int EquipID2EquipModelID(int equipID, out eEquipPartType type)
{
type = eEquipPartType.eEquipPart_Coat;
EquipContent content = HolderManager.m_EquipHolder.GetStaticInfo(equipID);
if (content == null)
return 0;
else
{
type = (eEquipPartType)content.EquipType;
return content.ModelID;
}
}
public static float easeInSine(float start, float end, float value)
{
end -= start;
return -end * Mathf.Cos(value / 1 * (Mathf.PI / 2)) + end + start;
}
public static float easeOutSine(float start, float end, float value)
{
end -= start;
return end * Mathf.Sin(value / 1 * (Mathf.PI / 2)) + start;
}
//通过品质取颜色值
public static string GetEquipOrItemColor(eQuality qua)
{
string str = "[ffffff]";
switch (qua)
{
case eQuality.None:
str = CDEFINE.NONE;
break;
case eQuality.White_Bronze:
str = CDEFINE.WHITE;
break;
case eQuality.Green_Silver:
str = CDEFINE.GREEN;
break;
case eQuality.Blue_Gold:
str = CDEFINE.BLUE;
break;
case eQuality.Purple_Epic:
str = CDEFINE.PUPLE;
break;
case eQuality.Red_Legend:
str = CDEFINE.RED;
break;
case eQuality.Orange_Artifact:
str = CDEFINE.ORANGE;
break;
}
return str;
}
/// <summary>
/// 获取品质spriteName
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static eQuality IndexToEquipQuality(int index)
{
switch (index)
{
case 0:
return eQuality.None;
case 1:
return eQuality.White_Bronze;
case 2:
return eQuality.Green_Silver;
case 3:
return eQuality.Blue_Gold;
case 4:
return eQuality.Purple_Epic;
case 5:
return eQuality.Orange_Artifact;
case 6:
return eQuality.Red_Legend;
}
return eQuality.None;
}
public static string TryGetValue(List<string> list, int index, string returnDefaultValue = "")
{
if (list != null)
{
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
CDebug.LogError("表数据错误,数组越界");
return returnDefaultValue;
}
public static int TryGetValue(List<int> list, int index, int returnDefaultValue = 0)
{
if (list != null)
{
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
CDebug.LogError("表数据错误,数组越界");
return returnDefaultValue;
}
public static byte TryGetValue(List<byte> list, int index, byte returnDefaultValue = 0)
{
if (list != null)
{
if (index >= 0 && index < list.Count)
{
return list[index];
}
}
CDebug.LogError("表数据错误,数组越界");
return returnDefaultValue;
}
//用这个函数返回物品数据,不是自己拥有的物品
public static BackpackItemData GetItemData(int itemID)
{
BackpackItemData item = null;
switch (GetTypeFormID(itemID))
{
case eIDType.Equip:
{
EquipContent content = HolderManager.m_EquipHolder.GetStaticInfo(itemID);
if (content != null)
{
item = new BackpackItemData(itemID);
item.equipContent = content;
EquipModelContent equipModel = HolderManager.m_EquipModelHolder.GetStaticInfo(content.ModelID);
if (equipModel != null)
item.icon = equipModel.Icon;
item.location = eItemKeepLocation.None;
item.name = GetText(content.Name);
item.color = IndexToEquipQuality(content.Quality);
item.limitLv = content.LimitLevel;
item.type = eIDType.Equip;
BackpackEquipInfo equipInfo = new BackpackEquipInfo();
equipInfo.isEquiped = false;
equipInfo.bodyPart = (eEquipPartType)content.EquipType;
equipInfo.forgedLv = 0;
equipInfo.goodFixIncreasePercent = 0;
equipInfo.makerName = "";
equipInfo.fixTimes = 0;
item.equipInfo = equipInfo;
}
}
break;
case eIDType.Item:
{
ItemContent itemContent = HolderManager.m_ItemHolder.GetStaticInfo(itemID);
if (itemContent != null)
{
item = new BackpackItemData(itemID);
item.type = eIDType.Item;
item.itemContent = itemContent;
item.icon = itemContent.IconPath;
item.name = GetText(itemContent.NameID);
item.color = IndexToEquipQuality(itemContent.Quality);
BackpackItemInfo itemInfo = new BackpackItemInfo();
itemInfo.type = (eItemType)itemContent.Type;
itemInfo.subType = (eItemSubType)itemContent.SubType;
itemInfo.quality = itemContent.Quality;
item.itemInfo = itemInfo;
}
}
break;
}
return item;
}
public static void IsShowRedPoint(CElementBase target, bool isShow, int pos = 2, int depth = 20, float offsetX = 0.0f, float offsetY = 0.0f)
{
if (target != null)
{
if (COpenModule.CheckKeyIsOpen(target.Arg))
{
ShowUIGuideRedPoint(target.gameobject, pos, depth, offsetX, offsetY);
GameObject redPoint = _GetUIGuideRedPointGo(target.gameobject);
redPoint.SetActive(isShow);
}
}
}
public static void GetAttrString(BackpackItemData data, eEquipAttrType attrType, out List<string> attrName, out List<string> attrRange, out string attrTypeStr)
{
List<EquipAttr> attrTotalList = data.equipInfo.GetAttrListByType(attrType);
if (attrTotalList != null)
{
List<string> nameList = new List<string>();
List<string> rangeList = new List<string>();
for (int i = 0; i < attrTotalList.Count; i++)
{
float attrRangePercentMinimum = 0;
float attrRangePercentMaximum = 0;
if (data.equipContent != null)
{
//attrRangePercentMinimum = (float)data.equipContent.AttrValueRange[0] / 10000;
//attrRangePercentMaximum = (float)data.equipContent.AttrValueRange[1] / 10000;
}
string rangeStr = "";
List<int> info = BackpackEquipInfo.EquipAttrToIntList(attrTotalList[i]);
if (info != null)
{
float value1;
float value2;
int absoluteVal = info[2] - info[1];
switch (info[0])
{
case 1:
//属性值最小值计算公式: 最小值 + 差值*范围最小值
//属性值最大值计算公式: 最小值 + 差值*范围最大值
value1 = Mathf.CeilToInt(info[1] + absoluteVal * attrRangePercentMinimum);
value2 = Mathf.CeilToInt(info[1] + absoluteVal * attrRangePercentMaximum);
if (value1 == value2)
rangeStr = value1.ToString();
else
rangeStr = value1 + "-" + value2;
break;
case 2:
value1 = (info[1] + absoluteVal * attrRangePercentMinimum) / 100;
value2 = (info[1] + absoluteVal * attrRangePercentMaximum) / 100;
if (value1 == value2)
rangeStr = value1 + "%";
else
rangeStr = value1 + "%" + "-" + value2 + "%";
break;
default:
rangeStr = "";
break;
}
}
nameList.Add(attrTotalList[i].GetAttrName());
rangeList.Add(rangeStr);
}
attrName = nameList;
attrRange = rangeList;
attrTypeStr = attrTotalList[0].GetAttrType();
}
else
{
attrName = null;
attrRange = null;
attrTypeStr = null;
}
}
/// <summary>
/// 返回Tech表中的属性值 是否无值 0~0
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static bool GetTechValueIsNull(List<int> list)
{
if (list != null && list.Count > 0)
{
if (list[0] == 0)
{
return true;
}
}
return false;
}
/// <summary>
/// 属性表的单个数据
/// </summary>
public class TechSingleData
{
public eProtoAttData TechType; //属性类型
public int guitextId; //guitextID
public byte valueType; //0表示固定值1表示百分比
public int value; //属性值
public EquipAttr To()
{
EquipAttr attr = new EquipAttr();
attr.attrEnum = TechType;
attr.attrType = eEquipAttrType.MajorAttr;
attr.dataType = (eEquipAttrDataType)(valueType);
attr.value = value;
return attr;
}
public void From(EquipAttr attr)
{
if (attr != null)
{
TechType = attr.attrEnum;
valueType = (byte)((int)attr.dataType);
value = attr.value;
guitextId = CPlayerProperty.GetPropertyLanageID((int)TechType);
}
}
}
/// <summary>
/// 返回TechContent的值
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
static public List<TechSingleData> GetTechValue(int id)
{
TechContent tContent = HolderManager.m_TechHolder.GetStaticInfo(id);
return GetTechValue(tContent);
}
/// <summary>
/// 返回TechContent的值
/// </summary>
/// <param name="tContent"></param>
/// <returns></returns>
static public List<TechSingleData> GetTechValue(TechContent tContent)
{
List<TechSingleData> list = new List<TechSingleData>();
if (null == tContent)
return list;
for (int i = 0; i < GetTechProListMaxNum; i++)
{
List<int> value = GetTechProValue(i, tContent);
if (null != value && value.Count == 2 && value[0] > 0)
{
TechSingleData tvl = new TechSingleData();
tvl.guitextId = GetTechProGuiTextId(i);
tvl.valueType = (byte)value[0];
tvl.value = value[1];
tvl.TechType = (eProtoAttData)i;
list.Add(tvl);
}
}
return list;
}
/// <summary>
/// 返回Tech表中的属性值 所对应的GuiTextID
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static int GetTechProGuiTextId(int index)
{
int id = 0;
if (index >= 0 && index < GetTechProListMaxNum)
{
return 22100001 + index;
}
return id;
}
public const int GetTechProListMaxNum = 34;
/// <summary>
/// 返回Tech表中的属性值
/// </summary>
/// <param name="index">从0开始</param>
/// <returns></returns>
public static List<int> GetTechProValue(int index, TechContent tc)
{
List<int> list = null;
if (tc != null)
{
switch (index)
{
case 0: { list = tc.HpMax; } break;
case 1: { list = tc.Attack; } break;
case 2: { list = tc.Defense; } break;
case 3: { list = tc.Critical; } break;
case 4: { list = tc.ResistCritical; } break;
case 5: { list = tc.CriticalChance; } break;
case 6: { list = tc.ResistCriticalChance; } break;
case 7: { list = tc.CriticalDamage; } break;
case 8: { list = tc.ResistCriticalDamage; } break;
case 9: { list = tc.MeleeAttack; } break;
case 10: { list = tc.ResistMeleeAttack; } break;
case 11: { list = tc.RemoteAttack; } break;
case 12: { list = tc.ResistRemoteAttack; } break;
case 13: { list = tc.TrueDamage; } break;
case 14: { list = tc.ResistTrueDamage; } break;
case 15: { list = tc.AdditionalAtk; } break;
case 16: { list = tc.ResistAdditionalAtk; } break;
case 17: { list = tc.Refelect; } break;
case 18: { list = tc.HPRecoverRatio; } break;
case 19: { list = tc.VIT; } break;
case 20: { list = tc.VITRecoverRatio; } break;
case 21: { list = tc.VITLossRatio; } break;
case 22: { list = tc.ActVelocity; } break;
case 23: { list = tc.MoveVelocity; } break;
case 24: { list = tc.LeechLife; } break;
case 25: { list = tc.DerateCD; } break;
case 26: { list = tc.BOSSAtk; } break;
case 27: { list = tc.PKDamage; } break;
case 28: { list = tc.ResistPKDamage; } break;
case 29: { list = tc.DeadlyAttack; } break;
case 30: { list = tc.ResistDeadlyAttack; } break;
case 31: { list = tc.DeadlyAtkDamage; } break;
case 32: { list = tc.ResistDeadlyAtkDamage; } break;
case 33: { list = tc.ExpEx; } break;
case 34: { list = tc.MoneyEx; } break;
}
}
return list;
}
/// <summary>
/// 把数组里的TechContent属性值相加
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static List<TitleTechData> CalcPropTotal(List<int> param)
{
List<TitleTechData> list = new List<TitleTechData>();
int total = 0;
for (int i = 0; i < GetTechProListMaxNum; i++)
{
total = 0;
foreach (var item in param)
{
TechContent content = HolderManager.m_TechHolder.GetStaticInfo(item);
if (null == content) continue;
List<int> val = GetTechProValue(i, content);
total += val[1];
}
list.Add(new TitleTechData() { Index = i, Value = total });
}
return list;
}
/// <summary>
/// 把数组里的TechContent属性值相加
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static long CalcPowerTotal(List<int> param)
{
int total = 0;
long power = 0;
for (int i = 0; i < GetTechProListMaxNum; i++)
{
total = 0;
foreach (var item in param)
{
TechContent content = HolderManager.m_TechHolder.GetStaticInfo(item);
if (null == content) continue;
List<int> val = GetTechProValue(i, content);
total += val[1];
}
if (total > 0)
power += CCommon.GetPowerValue((eProtoAttData)i, total);
}
return power;
}
private static string[] _titleColor = new string[]
{
"ccf1d7", "ffffff",
"cceef1", "ffffff",
"f1ccf1", "ffffff",
"f1cccc", "ffffff",
"f1ebcc", "ffffff"
};
public static Color[] GetTitleColor(byte type)
{
Color[] cols = new Color[2];
switch (type)
{
case (byte)eTitleColorType.Bronze:
cols[0] = new Color32(204, 241, 215, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.Silver:
cols[0] = new Color32(204, 238, 241, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.Gold:
cols[0] = new Color32(241, 204, 241, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.BarkGold:
cols[0] = new Color32(241, 204, 204, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
case (byte)eTitleColorType.Diamond:
cols[0] = new Color32(241, 235, 204, 255);
cols[1] = new Color32(255, 255, 255, 255);
break;
}
return cols;
}
public static int ComputeTechProValue(int index, TechContent tc)
{
List<int> list = GetTechProValue(index, tc);
if (GetTechValueIsNull(list))
return 0;
if (list[0] == 1)
{
return list[1];
}
else if (list[0] == 2)
{
return list[1] * GetAvatarAttributeWithTechIndex(index);
}
return 0;
}
static List<BaseIntContent> mDropItemList = new List<BaseIntContent>();
/// <summary>
/// 获取掉落物品数据
/// </summary>
/// <param name="key">dropitemID</param>
/// <returns></returns>
public static List<BaseIntContent> GetDropItemList(int key)
{
mDropItemList.Clear();
DropItemContent retContent = HolderManager.m_DropItemHolder.GetStaticInfo(key);
if (null != retContent)
{
BaseIntContent baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList1;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList2;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList3;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList4;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList5;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList6;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList7;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList8;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList9;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList10;
mDropItemList.Add(baseIntContent);
}
return mDropItemList;
}
/// <summary>
/// 获取掉落物品数据
/// </summary>
/// <param name="retContent">dropItemContent</param>
/// <returns></returns>
public static List<BaseIntContent> GetDropItemList(DropItemContent retContent)
{
mDropItemList.Clear();
if (null != retContent)
{
BaseIntContent baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList1;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList2;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList3;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList4;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList5;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList6;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList7;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList8;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList9;
mDropItemList.Add(baseIntContent);
baseIntContent = new BaseIntContent();
baseIntContent.list = retContent.DropList10;
mDropItemList.Add(baseIntContent);
}
return mDropItemList;
}
/// <summary>
/// 将格式为“2016~11~21~00~00~00” 转换成 DateTime
/// </summary>
/// <param name="timeList"></param>
/// <returns></returns>
public static DateTime GetDataTime(List<int> timeList)
{
DateTime dataTime = new DateTime();
if (timeList.Count >= 6)
{
dataTime.AddYears(timeList[0]);
dataTime.AddMonths(timeList[1]);
dataTime.AddDays(timeList[2]);
dataTime.AddHours(timeList[3]);
dataTime.AddMinutes(timeList[4]);
dataTime.AddSeconds(timeList[5]);
}
return dataTime;
}
/// <summary>
/// 将格式为“2016~11~21~00~00~00” 转换成时间戳
/// </summary>
/// <param name="timeList"></param>
/// <returns></returns>
public static double GetTimeStamp(List<int> timeList)
{
DateTime dataTime = GetDataTime(timeList);
double timeStamp = DateTimeToStamp(dataTime);
return timeStamp;
}
static Dictionary<int, List<int>> m_growthAwardDic = new Dictionary<int, List<int>>();
/// <summary>
/// 获取成长奖励表格数据信息
/// </summary>
/// <returns></returns>
public static Dictionary<int, List<int>> GetGrowthAwardInfo()
{
if (m_growthAwardDic.Count == 0)
{
foreach (KeyValuePair<int, TargetContent> kv in HolderManager.m_targetHolder.GetDict())
{
if (kv.Value.LevelClassify.Count != 2)
{
Debug.LogError("target excel “等级分类” 配置错误 with id : " + kv.Key);
break;
}
if (!m_growthAwardDic.ContainsKey(kv.Value.LevelClassify[0]))
{
List<int> targetList = new List<int>();
m_growthAwardDic.Add(kv.Value.LevelClassify[0], targetList);
}
m_growthAwardDic[kv.Value.LevelClassify[0]].Add(kv.Key);
}
}
return m_growthAwardDic;
}
/// <summary>
/// 等比缩放图片
/// </summary>
/// <param name="sprite"></param>
/// <param name="spriteName"></param>
/// <param name="scale"></param>
public static void SetUiScale(CSprite sprite, string spriteName, float scale)
{
if (sprite != null)
{
sprite.SetSprite(spriteName, true);
float wd = sprite.MySprite.width;
float ht = sprite.MySprite.height;
sprite.MySprite.width = Convert.ToInt32(wd * scale);
sprite.MySprite.height = Convert.ToInt32(ht * scale);
}
}
/// <summary>
/// 等比缩放图片
/// </summary>
/// <param name="texture"></param>
/// <param name="scale"></param>
public static void SetUiScale(CUITexture texture, float scale)
{
if (texture != null)
{
float wd = texture.MyTexture.width;
float ht = texture.MyTexture.height;
texture.MyTexture.width = Convert.ToInt32(wd * scale);
texture.MyTexture.height = Convert.ToInt32(ht * scale);
}
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="pointTf"></param>
/// <param name="dir">相对 pointTf 的 1上,2下,3左,4右</param>
public static void SetUiAnchors(CSprite target, Transform pointTf, float offset = 0, int dir = 1)
{
if (target != null && pointTf != null)
{
switch (dir)
{
case 1:
float posY = pointTf.localPosition.y + target.MySprite.height / 2 + offset;
target.localPosition = new Vector3(target.localPosition.x, posY, target.localPosition.z);
break;
}
}
}
/// <summary>
/// 打开界面
/// </summary>
/// <param name="dialogID"></param>
public static bool OpenDialogById(int dialogID, eOpenModule type = eOpenModule.None, CDialog fromDialog = null, bool checkOpen = false, params object[] args)
{
if (checkOpen)
{
if (!COpenModule.CheckKeyIsOpen(type))
{
ShowFunctionNotOpenTips();
return false;
}
}
CDialog dialog = CDialogManager.Instance.GetDialog(dialogID);
if (dialog is FunctionTabDialogBase && type != eOpenModule.None)//tab面板
(dialog as FunctionTabDialogBase).SetOpenToggle(type, args);
else
dialog.Refresh(args);
if (dialog != null)
{
if (dialog is ChatUiDialog)
{
SingleObject<BattleUiDialog>.Instance.ShowChatUiDialog();
}
//else if (dialogID == 21)//不知道是不是旧的,与配置对不上,先注释掉
//{
// SingleObject<BattleUiDialog>.Instance.ExecuteClickBtnEvent(eOpenModule.Activity_Welfare);
//}
else
{
//SingleObject<BattleUiDialog>.Instance.Close(null, true);
dialog.Show(null, fromDialog, true);
}
}
return true;
}
public static string GetGuildName(string str)
{
string guildName = string.Empty;
string[] arg = str.Split('*');
if (arg.Length >= 2)
guildName = arg[1];
else
guildName = arg[0];
return guildName;
}
public static HQuestAwardContent GetQuestAwardContentFromType(eQuestType type)
{
if (type >= eQuestType.DailyLoop && type < eQuestType.Max)
{
Dictionary<int, HQuestAwardContent> dict = HolderManager.m_HQuestAwardHolder.GetDict();
foreach (KeyValuePair<int, HQuestAwardContent> pair in dict)
{
if (pair.Value.Type == (byte)type)
return pair.Value;
}
}
return null;
}
//跳过打包流程,直接从txt读出表格数据
#if UNITY_EDITOR
public static UnityEngine.Object CreateStaticDataHolder(string holdClass, string path)
{
CSV.CsvStreamReader csv = new CSV.CsvStreamReader(path);
if (!csv.LoadCsvFile())
{
Debug.LogError(path + "无法读取,文件不存在或是被其它程序占用");
return null;
}
string FileName = Path.GetFileNameWithoutExtension(path);
ArrayList csvList = csv.GetRowList();
FileStreamHolder holder = ScriptableObject.CreateInstance<FileStreamHolder>();
holder.content = new List<FileStreamElement>();
XmlReader reader = null;
if (holdClass.Equals("TriggerHolder"))
{
reader = new XmlReader("Assets/xml/" + "trigger" + ".xml", holdClass);
}
else
{
reader = new XmlReader("Assets/xml/" + FileName + ".xml", holdClass);
}
int lineIndex = 0;
foreach (ArrayList array in csvList)
{
if (lineIndex == 0)
{
lineIndex++;//忽略第一行注解
continue;
}
int index = 0;
FileStreamElement fse = new FileStreamElement();
foreach (object tmp in array)
{
XmlData data = reader.GetData(index);
if (null == data)
{
//写入key值
if (index == 0)
{
if (fse.intList == null) fse.intList = new List<int>();
fse.intList.Add(DataDecode.GetInt32(tmp));
}
index++;
continue;
}
switch (data.type)
{
case "int":
{
if (fse.intList == null) fse.intList = new List<int>();
fse.intList.Add(DataDecode.GetInt32(tmp));
}
break;
case "string":
{
if (fse.stringList == null) fse.stringList = new List<string>();
fse.stringList.Add(DataDecode.GetString(tmp).Trim());
}
break;
case "byte":
{
if (fse.byteList == null) fse.byteList = new List<byte>();
fse.byteList.Add(DataDecode.GetByte(tmp));
}
break;
case "float":
{
if (fse.floatList == null) fse.floatList = new List<float>();
fse.floatList.Add(DataDecode.GetSingle(tmp));
}
break;
case "bool":
{
if (fse.boolList == null) fse.boolList = new List<bool>();
fse.boolList.Add(DataDecode.GetBoolean(tmp));
}
break;
case "intlist":
{
if (null == fse.intContentList) fse.intContentList = new List<BaseIntContent>();
BaseIntContent content = new BaseIntContent();
content.list = DataDecode.TransStrToIntList(tmp, data.split1);
fse.intContentList.Add(content);
}
break;
case "stringlist":
{
if (null == fse.stringContentList) fse.stringContentList = new List<BaseStringContent>();
BaseStringContent content = new BaseStringContent();
content.list = DataDecode.TransStrToStringList(tmp, data.split1);
fse.stringContentList.Add(content);
}
break;
case "floatlist":
{
if (null == fse.floatContentList) fse.floatContentList = new List<BaseFloatContent>();
BaseFloatContent content = new BaseFloatContent();
content.list = DataDecode.TransStrToFloatList(tmp, data.split1);
fse.floatContentList.Add(content);
}
break;
case "bytelist":
{
if (null == fse.byteContentList) fse.byteContentList = new List<BaseByteContent>();
BaseByteContent content = new BaseByteContent();
content.list = DataDecode.TransStrToByteList(tmp, data.split1);
fse.byteContentList.Add(content);
}
break;
case "stringlistlist":
{
if (null == fse.stringContentListList) fse.stringContentListList = new List<BaseStringListList>();
BaseStringListList content = new BaseStringListList();
content.list = DataDecode.TransStrToListStringClass(tmp, data.split1, data.split2);
fse.stringContentListList.Add(content);
}
break;
case "intlistlist":
{
if (null == fse.intContentListList) fse.intContentListList = new List<BaseIntListList>();
BaseIntListList content = new BaseIntListList();
content.list = DataDecode.TransStrToListIntClass(tmp, data.split1, data.split2);
fse.intContentListList.Add(content);
}
break;
case "floatlistlist":
{
if (null == fse.floatContentListList) fse.floatContentListList = new List<BaseFloatListList>();
BaseFloatListList content = new BaseFloatListList();
content.list = DataDecode.TransStrToListFloatClass(tmp, data.split1, data.split2);
fse.floatContentListList.Add(content);
}
break;
case "vector2":
{
if (null == fse.vector2List) fse.vector2List = new List<Vector2>();
fse.vector2List.Add(DataDecode.TransToVector2(tmp, data.split1));
}
break;
case "vector3":
{
if (null == fse.vector3List) fse.vector3List = new List<Vector3>();
fse.vector3List.Add(DataDecode.TransToVector3(tmp, data.split1));
}
break;
case "color":
{
if (null == fse.colorList) fse.colorList = new List<Color>();
fse.colorList.Add(DataDecode.TransStrToColor(tmp, data.split1));
}
break;
}
index++;
}
holder.content.Add(fse);
}
return holder as UnityEngine.Object;
}
#endif
//检测文件是否被其他软件占用
public static bool FileIsUsed(string fileFullName)
{
bool result = false;
if (!File.Exists(fileFullName))
{
result = false;
}
else
{
FileStream fileStream = null;
try
{
fileStream = File.Open(fileFullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
result = false;
}
catch (IOException ioEx)
{
result = true;
}
catch (Exception ex)
{
result = true;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
}
return result;
}
public static string GetGuildCareerName(eGuildPosition careerType)
{
string str = "";
switch (careerType)
{
case eGuildPosition.Ordinary:
str = GetText(73000109);
break;
case eGuildPosition.Elite:
str = GetText(73000110);
break;
case eGuildPosition.Elders:
str = GetText(73000111);
break;
case eGuildPosition.ViceChairman:
str = GetText(73000112);
break;
case eGuildPosition.Chairman:
str = GetText(73000113);
break;
default:
break;
}
return str;
}
public static string StringToEmotion(string text)
{
Dictionary<int, ExpressionContent> expressionDic = HolderManager.m_ExpressionHolder.GetDict();
List<int> expressionKeysList = new List<int>(expressionDic.Keys);
int count = expressionKeysList.Count;
for (int i = 0; i < count; i++)
{
text = text.Replace("[" + expressionKeysList[i] + "]", "[url=Emotion]" + "%patlas_ui_blackflag_expression_v1$" + expressionDic[expressionKeysList[i]].IconPath + "_01$[/url]");
}
return text;
}
public static Color ColorByteToColor(byte r, byte g, byte b, byte a = 1)
{
return new Color(r / 255f, g / 255f, b / 255f, a / 255f);
}
public static Color ColorStringToColor(string cStr)
{
if (cStr.Length == 8)
{
return NGUIText.ParseColor(cStr, 0);
}
return Color.black;
}
public static Color Color32ToColor(Color32 color32)
{
return ColorByteToColor(color32.r, color32.g, color32.b, color32.a);
}
/// <summary>
/// 获取玩家最大等级
/// </summary>
/// <returns></returns>
public static int GetMaxLevel()
{
Dictionary<int, LevelupContent> dict = HolderManager.m_LevelupHolder.GetDict();
return dict.Count;
}
/// <summary>
/// 根据 ringTarget 的高,调整background 的高和位置,使之适应 ringTarget 中的内容
/// </summary>
/// <param name="ringTarget"></param>
/// <param name="background"></param>
public static void CalculateBackgroundRingTransform(Transform ringTarget, CSprite background)
{
if (ringTarget == null || background == null) { return; }
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(ringTarget);
if (b != null)
{
background.MySprite.height = Mathf.FloorToInt(b.size.y);
background.localPosition = new Vector3(0, b.center.y, 0);
}
}
public static int ShopID2ItemID(eStorePanelType from, int shopID)
{
if (from == eStorePanelType.Chamber)
{
ShopContent content = HolderManager.m_ShopHolder.GetStaticInfo(shopID);
if (content != null)
return content.ItemID;
}
else if (from == eStorePanelType.Mall)
{
MallContent content = HolderManager.m_MallHolder.GetStaticInfo(shopID);
if (content != null)
return content.ItemID;
}
return shopID;
}
public static string GetChineseNumString(int num)
{
string numStr = string.Empty;
switch (num)
{
case 0:
break;
case 1:
numStr = GetText(77000020);
break;
case 2:
numStr = GetText(77000021);
break;
case 3:
numStr = GetText(77000022);
break;
case 4:
numStr = GetText(77000023);
break;
case 5:
numStr = GetText(77000024);
break;
case 6:
numStr = GetText(77000025);
break;
case 7:
numStr = GetText(77000026);
break;
}
return numStr;
}
public static int GetAvatarLevelupData(int type)
{
int avatarLevel = GetAvatarLevel();
LevelupContent lc = HolderManager.m_LevelupHolder.GetStaticInfo(avatarLevel);
if (lc == null)
return 0;
if (type == CDEFINE.ITEM_EXP)
{
return lc.BaseExp;
}
else if (type == CDEFINE.ITEM_SILVER)
{
return lc.BaseSilver;
}
else if (type == CDEFINE.ITEM_GOLD)
{
return lc.BaseGold;
}
else if (type == CDEFINE.ITEM_BIND_DIAMOND)
{
return lc.BaseIdentity;
}
else if (type == CDEFINE.ITEM_GUILD_CONTRIBUTION)
{
return lc.BaseGuildContribution;
}
else if (type == CDEFINE.ITEM_GUILD_MONEY)
{
return lc.BaseGuildMoney;
}
else if (type == CDEFINE.ITEM_M)
{
return lc.BaseItemM;
}
return 0;
}
public static int GetAvatarLevel()
{
return GetAvatarAttributeWithType(eProtoAttData.ePlayerData_Level);
}
public static float GetAvatarHPPregress()
{
return PlayerPropertyManager.Instance.PlayerProperty.GetHpProgress();
}
public static int GetAvatarAttributeWithType(eProtoAttData type)
{
return PlayerPropertyManager.Instance.PlayerProperty.GetIntProperty(type);
}
/// <summary>
///
/// </summary>
/// <param name="index">和GetTechProValue函数中的index意义相同</param>
/// <returns></returns>
public static int GetAvatarAttributeWithTechIndex(int index)
{
int val = 0;
switch (index)
{
case 0: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MaxHP); break;
case 1: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Attack); break;
case 2: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Defense); break;
case 3: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Critical); break;
case 4: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistCritical); break;
case 5: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_CriticalChance); break;
case 6: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistCriticalChance); break;
case 7: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_CriticalDamage); break;
case 8: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistCriticalDamage); break;
case 9: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MeleeAttack); break;
case 10: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistMeleeAttack); break;
case 11: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_RemoteAttack); break;
case 12: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistRemoteAttack); break;
case 13: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_TrueDamage); break;
case 14: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistTrueDamage); break;
case 16: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_AdditionalAtk); break;
case 18: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistAdditionalAtk); break;
case 20: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_Refelect); break;
case 22: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_HPRecoverRatio); break;
case 23: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_VIT); break;
case 24: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_VITRecoverRatio); break;
case 25: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_VITLossRatio); break;
case 26: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ActVelocity); break;
case 27: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MoveVelocity); break;
case 28: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_LeechLife); break;
case 29: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_DerateCD); break;
case 30: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_BOSSAtk); break;
case 31: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_PKDamage); break;
case 32: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistPKDamage); break;
case 33: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_DeadlyAttack); break;
case 34: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistDeadlyAttack); break;
case 35: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_DeadlyAtkDamage); break;
case 36: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ResistDeadlyAtkDamage); break;
case 37: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_ExpEx); break;
case 38: val = GetAvatarAttributeWithType(eProtoAttData.eAttData_MoneyEx); break;
}
return val;
}
public static bool EquipOutEquipMpdelID(int equipID, out int equipModelID, out eBodyParts part)
{
equipModelID = 0;
part = eBodyParts.Foot;
bool result = false;
EquipContent equipContent = HolderManager.m_EquipHolder.GetStaticInfo(equipID);
if (null != equipContent)
{
EquipModelContent equipModel = HolderManager.m_EquipModelHolder.GetStaticInfo(equipContent.ModelID);
if (null != equipModel)
{
equipModelID = equipModel.Key;
eEquipPartType bodyPart = (eEquipPartType)equipContent.EquipType;
switch (bodyPart)
{
case eEquipPartType.eEquipPart_Weapon:
{
part = eBodyParts.Weapon;
result = true;
}
break;
case eEquipPartType.eEquipPart_Helmet:
{
part = eBodyParts.Head;
result = true;
}
break;
case eEquipPartType.eEquipPart_Coat:
{
part = eBodyParts.UpperBody;
result = true;
}
break;
case eEquipPartType.eEquipPart_Trousers:
{
part = eBodyParts.LowerBody;
result = true;
}
break;
case eEquipPartType.eEquipPart_Belt:
{
part = eBodyParts.Waistband;
result = true;
}
break;
case eEquipPartType.eEquipPart_Shoe:
{
part = eBodyParts.Foot;
result = true;
}
break;
}
}
}
return result;
}
private static List<int> m_tempList = new List<int>();
public static List<int> ProtoEquipListToIDList(List<Equip> list)
{
m_tempList.Clear();
for (int i = 0; i < list.Count; i++)
{
m_tempList.Add(list[i].id);
}
return m_tempList;
}
//固定遮罩移动uipanel
static public void SetPanelClip(UIPanel panel, Vector3 value)
{
if (null == panel)
return;
Vector3 p = panel.transform.localPosition;
panel.transform.localPosition += value - p;
Vector2 cr = panel.clipOffset;
cr.x -= panel.transform.localPosition.x - p.x;
cr.y -= panel.transform.localPosition.y - p.y;
panel.clipOffset = cr;
}
static public void SetComponentPosition(Transform clickTransform, Transform panelTransform, UIPanel panel, SpringPanel.OnFinished OnFinished)
{
Bounds bound = NGUIMath.CalculateAbsoluteWidgetBounds(clickTransform);
Vector3 top = panelTransform.InverseTransformPoint(new Vector3(bound.max.x, bound.max.y, 0));
Vector3 bottom = panelTransform.InverseTransformPoint(new Vector3(bound.min.x, bound.min.y, 0));
float upMore = top.y - (panel.finalClipRegion.y + panel.finalClipRegion.w / 2);
float downLess = bottom.y - (panel.finalClipRegion.y - panel.finalClipRegion.w / 2);
if (upMore > 0)
{
SpringPanel.Begin(panelTransform.gameObject, new Vector3(panelTransform.localPosition.x, panelTransform.localPosition.y - upMore, 0), 10).onFinished = OnFinished;
}
else if (downLess < 0)
{
SpringPanel.Begin(panelTransform.gameObject, new Vector3(panelTransform.localPosition.x, panelTransform.localPosition.y - downLess, 0), 10).onFinished = OnFinished;
}
}
/// <summary>
/// 装备星级计算
/// 21~30 用太阳表示,11~20 用月亮表示,1~10 用星星表示
/// </summary>
/// <returns>The sprite name.</returns>
/// <param name="starLevel">Star level.</param>
/// <param name="id">Identifier.</param>
public static string GetEquipStarLevelSpriteName(int starLevel, int id, bool isShow = false)
{
if (starLevel > 20)
{
if (id < starLevel - 20)
return "state_forge_sun_gold";
else
return "state_forge_sun_dark";
}
else if (starLevel > 10)
{
if (id < starLevel - 10)
return "state_forge_moon_gold";
else
return "state_forge_moon_dark";
}
else
{
if (id < starLevel)
return "state_forge_star_gold";
else
return "state_forge_star_dark";
}
}
/// <summary>
/// 战斗力计算公式
/// </summary>
/// <param name="attrType"></param>
/// <param name="value"></param>
/// <returns></returns>
public static int GetPowerValue(eProtoAttData attrType, float value)
{
if (value == 0)
return 0;
int result = 0;
float factor = 1;
FightvalContent con = HolderManager.m_fightvalHolder.GetStaticInfo((int)attrType);
if (con != null)
factor = (float)con.Weight / (float)10000;
result += Mathf.FloorToInt(value * factor);
return result;
}
/// <summary>
/// 战斗力计算公式
/// </summary>
/// <param name="techId"></param>
/// <returns></returns>
public static int GetPowerValue(int techId)
{
TechContent tContent = HolderManager.m_TechHolder.GetStaticInfo(techId);
return GetPowerValue(tContent);
}
/// <summary>
/// 战斗力计算公式
/// </summary>
/// <param name="tContent"></param>
/// <returns></returns>
public static int GetPowerValue(TechContent tContent)
{
int value = 0;
if (null != tContent)
{
value = GetPowerValue(eProtoAttData.eAttData_MaxHP, tContent.HpMax[1]);
value += GetPowerValue(eProtoAttData.eAttData_Attack, tContent.Attack[1]);
value += GetPowerValue(eProtoAttData.eAttData_Defense, tContent.Defense[1]);
value += GetPowerValue(eProtoAttData.eAttData_Critical, tContent.Critical[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistCritical, tContent.ResistCritical[1]);
value += GetPowerValue(eProtoAttData.eAttData_CriticalChance, tContent.CriticalChance[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistCriticalChance, tContent.ResistCriticalChance[1]);
value += GetPowerValue(eProtoAttData.eAttData_CriticalDamage, tContent.CriticalDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistCriticalDamage, tContent.ResistCriticalDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_MeleeAttack, tContent.MeleeAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistMeleeAttack, tContent.ResistMeleeAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_RemoteAttack, tContent.RemoteAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistRemoteAttack, tContent.ResistRemoteAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_TrueDamage, tContent.TrueDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistTrueDamage, tContent.ResistTrueDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_AdditionalAtk, tContent.AdditionalAtk[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistAdditionalAtk, tContent.ResistAdditionalAtk[1]);
value += GetPowerValue(eProtoAttData.eAttData_Refelect, tContent.Refelect[1]);
value += GetPowerValue(eProtoAttData.eAttData_HPRecoverRatio, tContent.HPRecoverRatio[1]);
value += GetPowerValue(eProtoAttData.eAttData_VIT, tContent.VIT[1]);
value += GetPowerValue(eProtoAttData.eAttData_VITRecoverRatio, tContent.VITRecoverRatio[1]);
value += GetPowerValue(eProtoAttData.eAttData_VITLossRatio, tContent.VITLossRatio[1]);
value += GetPowerValue(eProtoAttData.eAttData_ActVelocity, tContent.ActVelocity[1]);
value += GetPowerValue(eProtoAttData.eAttData_MoveVelocity, tContent.MoveVelocity[1]);
value += GetPowerValue(eProtoAttData.eAttData_LeechLife, tContent.LeechLife[1]);
value += GetPowerValue(eProtoAttData.eAttData_DerateCD, tContent.DerateCD[1]);
value += GetPowerValue(eProtoAttData.eAttData_BOSSAtk, tContent.BOSSAtk[1]);
value += GetPowerValue(eProtoAttData.eAttData_PKDamage, tContent.PKDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistPKDamage, tContent.ResistPKDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_DeadlyAttack, tContent.DeadlyAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistDeadlyAttack, tContent.ResistDeadlyAttack[1]);
value += GetPowerValue(eProtoAttData.eAttData_DeadlyAtkDamage, tContent.DeadlyAtkDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ResistDeadlyAtkDamage, tContent.ResistDeadlyAtkDamage[1]);
value += GetPowerValue(eProtoAttData.eAttData_ExpEx, tContent.ExpEx[1]);
value += GetPowerValue(eProtoAttData.eAttData_MoneyEx, tContent.MoneyEx[1]);
}
return value;
}
private static string[] equipPartIcon = new string[] {
"icon_forge_background_weapon",
"icon_forge_background_shoulder",
"icon_forge_background_necklace",
"icon_forge_background_bracer",
"icon_forge_background_ring",
"icon_forge_background_helmet",
"icon_forge_background_armour",
"icon_forge_background_belt",
"icon_forge_background_pants",
"icon_forge_background_boots",
};
/// <summary>
/// 装备部位没有装备的默认图标
/// </summary>
/// <param name="part"></param>
/// <returns></returns>
public static string GetEquipPartDefaultIcon(eEquipPartType part)
{
string partIcon = string.Empty;
switch (part)
{
case eEquipPartType.eEquipPart_Weapon:
partIcon = equipPartIcon[0];
break;
case eEquipPartType.eEquipPart_Shoulder:
partIcon = equipPartIcon[1];
break;
case eEquipPartType.eEquipPart_Necklace:
partIcon = equipPartIcon[2];
break;
case eEquipPartType.eEquipPart_Cuff:
partIcon = equipPartIcon[3];
break;
case eEquipPartType.eEquipPart_Ring:
partIcon = equipPartIcon[4];
break;
case eEquipPartType.eEquipPart_Helmet:
partIcon = equipPartIcon[5];
break;
case eEquipPartType.eEquipPart_Coat:
partIcon = equipPartIcon[6];
break;
case eEquipPartType.eEquipPart_Belt:
partIcon = equipPartIcon[7];
break;
case eEquipPartType.eEquipPart_Trousers:
partIcon = equipPartIcon[8];
break;
case eEquipPartType.eEquipPart_Shoe:
partIcon = equipPartIcon[9];
break;
case eEquipPartType.eEquipPart_Num:
break;
default:
break;
}
return partIcon;
}
/// <summary>
/// 获取装备部位名称
/// </summary>
/// <param name="part"></param>
/// <returns></returns>
public static string GetEquipPartName(eEquipPartType part)
{
switch (part)
{
case eEquipPartType.eEquipPart_Weapon:
return GetText(70070010);
case eEquipPartType.eEquipPart_Shoulder:
return GetText(70070001);
case eEquipPartType.eEquipPart_Necklace:
return GetText(70070002);
case eEquipPartType.eEquipPart_Cuff:
return GetText(70070003);
case eEquipPartType.eEquipPart_Ring:
return GetText(70070004);
case eEquipPartType.eEquipPart_Helmet:
return GetText(70070005);
case eEquipPartType.eEquipPart_Coat:
return GetText(70070006);
case eEquipPartType.eEquipPart_Belt:
return GetText(70070007);
case eEquipPartType.eEquipPart_Trousers:
return GetText(70070008);
case eEquipPartType.eEquipPart_Shoe:
return GetText(70070009);
default:
return string.Empty;
}
}
/// <summary>
/// 根据职业id获取名称
/// </summary>
/// <param name="jobId"></param>
/// <returns></returns>
public static string GetJobName(byte jobId, int type = 0)
{
switch (jobId)
{
case 0:
int s = 70060001;
switch ((eGEntityType)type)
{
case eGEntityType.Pet: s = 10003162; break;
case eGEntityType.Ride: s = 10003161; break;
case eGEntityType.Mercenary: s = 10003163; break;
}
return CCommon.GetText(s);
case 1:
return CCommon.GetText(70060002);
case 2:
return CCommon.GetText(70060003);
case 3:
return CCommon.GetText(70060004);
case 4:
return CCommon.GetText(70060005);
}
return null;
}
public static string GetLevelLimitString(int type, int level)
{
string s = "";
switch ((eGEntityType)type)
{
case eGEntityType.Role:
s = CCommon.GetTextS(70050011, level);
break;
case eGEntityType.Ride:
s = s + GetJobName(0, type) + CCommon.GetTextS(33304011, level);
break;
case eGEntityType.Pet:
s = s + GetJobName(0, type) + CCommon.GetTextS(70050011, level);
break;
case eGEntityType.Mercenary:
s = s + GetJobName(0, type) + CCommon.GetTextS(70050011, level);
break;
}
return s;
}
/// <summary>
/// 灰化
/// </summary>
/// <param name="gray"></param>
public static void SetGrayscale(GameObject go, bool gray)
{
Dictionary<string, Color> colors = new Dictionary<string, Color>();
if (null == colors) colors = new Dictionary<string, Color>();
GrayUtil.SetGrayscale(go, gray, colors);
}
public static void ShowFunctionNotOpenTips(int tipsID = 97000093)
{
CCommon.ShowTextTip(CCommon.GetText(tipsID));
}
public static bool CheckIsEnough(int id, long value, bool showTips = false, int tipsID = 0)
{
ItemContent itemContent = HolderManager.m_ItemHolder.GetStaticInfo(id);
if (itemContent != null)
{
if (PlayerPropertyManager.Instance.PlayerInfo.GetSpecialItemCount(id) < value)
{
if (showTips && tipsID >= 0)
{
CCommon.ShowTextTip(CCommon.GetTextS(tipsID == 0 ? 97100013 : tipsID, BackpackItemData.EquipQualityToName(CCommon.GetText(itemContent.NameID), (eQuality)itemContent.Quality)));
}
return false;
}
return true;
}
return false;
}
/// <summary>
/// 聊天非法字符过滤
/// </summary>
/// <param name="text"></param>
/// <param name="charIndex"></param>
/// <param name="addedChar"></param>
/// <returns></returns>
public static void ValidatorChatContent(CInput input, string text)
{
int index = input.Text.IndexOf("/gm");
if (index != -1)
{
return;
}
else
{
input.Text = input.Text.Replace(" ", "");
input.Text = input.Text.Replace("\n", "");
}
}
public static bool CompareValue(double v1, double v2, int type = 0)
{
switch (type)
{
case 0: return v1 < v2;
case 1: return v1 > v2;
}
return v1 == v2;
}
public static UnityEngine.GameObject FindObj(UnityEngine.GameObject g, string name)
{
if (g != null && !string.IsNullOrEmpty(name))
{
Transform tran = g.transform;
if (tran.name == name) return tran.gameObject;
Transform c = tran.Find(name);
if (c != null) return c.gameObject;
if (tran.childCount > 0)
{
foreach (Transform v in tran)
{
g = FindObj(v.gameObject, name);
if (g != null) return g;
}
}
}
return null;
}
//通过合成物ID 得到合成配方
public static ComposeContent GetComposeContent(int id)
{
Dictionary<int, ComposeContent> dic = HolderManager.m_ComposeHolder.GetDict();
foreach (KeyValuePair<int, ComposeContent> kv in dic)
{
if (kv.Value.ComposeId == id)
{
return kv.Value;
}
}
return null;
}
public static void ResetTweener(this UITweener tweener)
{
if (tweener != null)
{
tweener.ResetToBeginning();
tweener.Sample(0, false);
tweener.tweenFactor = 0f;
}
}
/// <summary>
/// 检测技能是否显示属性加成
/// </summary>
/// <returns></returns>
public static bool CheckPlayerSkillProp(PlayerSkillType type)
{
switch (type)
{
case PlayerSkillType.Passivity:
case PlayerSkillType.Guild:
case PlayerSkillType.Awaken:
case PlayerSkillType.Mount:
case PlayerSkillType.BoatPassite:
case PlayerSkillType.GodweaponPassite:
case PlayerSkillType.MercenaryPassite:
case PlayerSkillType.PetPassite:
case PlayerSkillType.MercenaryCommonPassite:
return true;
}
return false;
}
public static string GetOtherPlayerNameColor(CPlayer player)
{
string color = "";
if (player != null)
{
CMoveNpc self = (CGameWorld.Instance.CurrentScene as CBattleScene).Avatar;
if (self == player) color = "[2cc3ed]";
else
{
color = null;
CPlayerModel model = player.OriginalModel as CPlayerModel;
switch ((eModeType)PlayerPropertyManager.Instance.PlayerInfo.Mode)
{
case eModeType.Peace:
break;
case eModeType.Team:
if (CTeamManager.Instance.ContainPlayer(player.ID)) color = CDEFINE.BLUE;
else if (model != null && model.SyncPlayer != null && model.SyncPlayer.sPlyInfo != null && PlayerPropertyManager.Instance.PlayerInfo.GuildID > 0 && PlayerPropertyManager.Instance.PlayerInfo.GuildID == model.SyncPlayer.sPlyInfo.nguildid) color = CDEFINE.GREEN;
else color = CDEFINE.RED;
break;
case eModeType.Guild:
if (CTeamManager.Instance.ContainPlayer(player.ID)) color = CDEFINE.BLUE;
else if (model != null && model.SyncPlayer != null && model.SyncPlayer.sPlyInfo != null && PlayerPropertyManager.Instance.PlayerInfo.GuildID > 0 && PlayerPropertyManager.Instance.PlayerInfo.GuildID == model.SyncPlayer.sPlyInfo.nguildid) color = CDEFINE.GREEN;
else color = CDEFINE.RED;
break;
case eModeType.Whole:
color = CDEFINE.RED;
break;
case eModeType.Hatred:
if (model.SyncPlayer.sPlyInfo.pkval > 0) color = CDEFINE.RED;
break;
case eModeType.Server:
if (model.SyncPlayer.sPlyInfo.serverid != LoginManager.Instance.CurrentServerID) color = CDEFINE.RED;
break;
default: break;
}
/*if (color == null) {
switch ((eModeType)model.SyncPlayer.sPlyInfo.attackmode)
{
case eModeType.Peace:
case eModeType.Team:
case eModeType.Guild:
break;
case eModeType.Whole:
color = "[d71010]";
break;
case eModeType.Hatred:
if (model.SyncPlayer.sPlyInfo.pkval > 0) color = "[d71010]";
break;
case eModeType.Server:
if (model.SyncPlayer.sPlyInfo.serverid != LoginManager.Instance.CurrentServerID) color = "[d71010]";
break;
default: break;
}
}*/
if (color == null)
{
if (CTeamManager.Instance.ContainPlayer(player.ID)) color = CDEFINE.BLUE;
else if (model != null && model.SyncPlayer != null && model.SyncPlayer.sPlyInfo != null && PlayerPropertyManager.Instance.PlayerInfo.GuildID > 0 && PlayerPropertyManager.Instance.PlayerInfo.GuildID == model.SyncPlayer.sPlyInfo.nguildid) color = CDEFINE.GREEN;
else color = CDEFINE.WHITE;
}
}
}
return color;
}
/// <summary>
/// 是否可被攻击
/// </summary>
/// <param name="player"></param>
/// <param name="skillID"></param>
/// <returns></returns>
public static bool IsCanAttack(CBattlePlayer player, int skillID = 0)
{
if (player != null)
{
CMoveNpc self = (CGameWorld.Instance.CurrentScene as CBattleScene).Avatar;
if (player == self) return false;
CPlayerModel model = player.OriginalModel as CPlayerModel;
switch ((eModeType)PlayerPropertyManager.Instance.PlayerInfo.Mode)
{
case eModeType.Peace: return false;
case eModeType.Whole: return true;
case eModeType.Hatred:
if (model.SyncPlayer.sPlyInfo.pkval > 0) return true;
break;
case eModeType.Server:
if (model.SyncPlayer.sPlyInfo.serverid != LoginManager.Instance.CurrentServerID) return true;
break;
case eModeType.Team:
if (!CTeamManager.Instance.ContainPlayer(player.ID)) return true;
break;
case eModeType.Guild:
if (PlayerPropertyManager.Instance.PlayerInfo.GuildID != model.SyncPlayer.sPlyInfo.nguildid) return true;
break;
default: break;
}
}
return false;
}
public static void FilterAttackTargets(List<uint> targets, int skillID)
{
if (targets != null && targets.Count > 0)
{
for (int i = targets.Count - 1; i >= 0; i--)
{
CMoveNpc npc = CGameWorld.Instance.CurrentScene.IsSea ? CShipManager.Instance.GetShipByIndex(targets[i]) : CEntityManager.Instance.GetMoveNpcFormIndex(targets[i]);
if (npc != null && npc is CPlayer)
{
if (!CCommon.IsCanAttack(npc as CPlayer, skillID))
{
targets.RemoveAt(i);
}
}
else if (npc == null)
{
targets.RemoveAt(i);
}
}
}
}
public static bool IsCanAffect(CMoveNpc pAttker, CMoveNpc pTarget, eAffectType affectType = eAffectType.AffectAll)
{
CBattleScene btScene = (CGameWorld.Instance.CurrentScene as CBattleScene);
if (null == btScene)
{
return false;
}
bool state = true;
if (pAttker != null && pTarget != null)
{
//人打人或人打佣兵
if ((pAttker is CBattlePlayer || pAttker is CSoldier) && (pTarget is CBattlePlayer || pTarget is CSoldier))
{
CMoveNpc self = btScene.Avatar;
state = true;
if (pAttker == self || (pAttker is CSoldier && (pAttker as CSoldier).m_owner == self))
{
if (pTarget is CBattlePlayer)
state = IsCanAttack(pTarget as CBattlePlayer, 0);
else
state = IsCanAttack((pTarget as CSoldier).m_owner as CBattlePlayer, 0);
}
switch (affectType)
{
case eAffectType.AffectSelf: if (pAttker.ID != pTarget.ID) return false;
break;
case eAffectType.AffectFriendExceptSelf: if (state && pTarget == pAttker) return false;
break;
case eAffectType.ExceptSelf: if (state && pAttker == pTarget) return false;
break;
case eAffectType.AffectEnemy: if (!state) return false;
break;
case eAffectType.AffectFriends: if (state) return false;
break;
default:
break;
}
}
else
{
if (pTarget.NpcGroup == eNpcGroup.Neutral) return false;
switch (affectType)
{
case eAffectType.AffectAll:
break;
case eAffectType.AffectEnemy://敌方
{
if (pAttker.IsJust && pTarget.IsJust || pAttker.IsEvil && pTarget.IsEvil) return false;
}
break;
case eAffectType.AffectFriends://友方
{
if (pAttker.IsJust && pTarget.IsEvil || pAttker.IsEvil && pTarget.IsJust) return false;
}
break;
case eAffectType.AffectSelf:
{
if (pAttker.ID != pTarget.ID) return false;
}
break;
case eAffectType.AffectFriendExceptSelf:
{
if (pAttker == pTarget) return false;
if (pAttker.IsJust != pTarget.IsJust || pAttker.IsEvil != pTarget.IsEvil) return false;
}
break;
default:
break;
}
}
}
return state;
}
public static void ConfirmChangeAttackMode(string tips, eModeType mode = eModeType.Hatred, Action<bool> call = null)
{
if (CGameWorld.Instance.CurrentScene.SceneInfo.AllowAttackMode.Contains((int)mode))
{
CCommon.ShowPopDialog(tips, (b, arg) =>
{
PlayerPropertyManager.Instance.RequestChangeAttackMode((int)mode);
if (call != null) call(b);
});
}
}
//获取触发器的位置
public static Vector3 GetTriggerPos(Transform trans)
{
if (null == trans)
{
return Vector3.zero;
}
SceneTriggerData st = trans.GetComponent<SceneTriggerData>();
if (st == null || st.PointList.Length < 1)
return Vector3.zero;
return new Vector3(st.PointList[0].x, st.PointList[0].y, st.PointList[0].z);
}
//获取触发器的旋转
public static Vector3 GetTriggerRotation(Transform trans)
{
if (null == trans)
{
return Vector3.zero;
}
SceneTriggerData st = trans.GetComponent<SceneTriggerData>();
if (st == null || st.PointList.Length < 1)
return Vector3.zero;
return new Vector3(0, st.PointList[0].w, 0);
}
public static string GetCurrencyLocalString(int cid, int value)
{
ItemContent currency = HolderManager.m_ItemHolder.GetStaticInfo(cid);
string str = value.ToString();
if (currency != null)
{
int currencyCount = (int)PlayerPropertyManager.Instance.PlayerInfo.GetSpecialItemCount(cid);
if (value > currencyCount)
str = "[e51f1f]" + CCommon.GetOptionNumString((ulong)value) + "[-]";
else
str = "[44BD0A]" + CCommon.GetOptionNumString((ulong)value) + "[-]";
str += CCommon.GetText(currency.NameID);
}
return str;
}
public static List<EquipAttr> TechConvertAttr(int id)
{
List<CCommon.TechSingleData> techList = CCommon.GetTechValue(id);
List<EquipAttr> attrs = null;
if (techList != null && techList.Count > 0)
{
attrs = new List<EquipAttr>();
for (int i = 0; i < techList.Count; i++)
{
EquipAttr eq = techList[i].To();
eq.id = id;
attrs.Add(eq);
}
}
return attrs;
}
public static string LabFormatTwoColumnAttrString(UILabel label, List<EquipAttr> attrs, float padding = 0, string valueColor = "")
{
StringBuilder sb = new StringBuilder();
if (attrs.Count > 0)
{
NGUIText.rectWidth = label.width;
NGUIText.spacingX = label.spacingX;
NGUIText.spacingY = label.spacingY;
NGUIText.finalSize = Mathf.RoundToInt(label.fontSize / NGUIText.pixelDensity);
NGUIText.finalSpacingX = 0;
//maxWidth /= label.transform.localScale.x;
string info = "", v = "";
int cindex = 0;
float len = 0, temp = 0;
bool al = false;
float nl = NGUIText.CalculatePrintedSize(" ").x + NGUIText.spacingX;
string ce = string.IsNullOrEmpty(valueColor) ? "" : "[-]";
for (int i = 0; i < attrs.Count; i++)
{
info = "";
if (attrs[i].dataType == eEquipAttrDataType.Percent)
v = (100 * ((float)attrs[i].value / 10000)) + "%";
else
v = attrs[i].value.ToString();
info = attrs[i].GetAttrName() + " +" + v;
cindex++;
if (cindex == 2)
{
al = true;
if (len > 0)
{
temp = padding - len;
len = NGUIText.CalculatePrintedSize(info).x;
if (temp > 0)
{
cindex = 0;
int l = Mathf.CeilToInt(temp / nl);
for (int j = 0; j < l; j++) sb.Append(" ");
}
else
{
sb.AppendLine();
cindex--;
al = false;
}
}
info = attrs[i].GetAttrName() + valueColor + " +" + v + ce;
sb.Append(info);
if (al) sb.AppendLine();
}
else
{
if (padding > 0) len = NGUIText.CalculatePrintedSize(info).x;
info = attrs[i].GetAttrName() + valueColor + " +" + v + ce;
sb.Append(info);
}
}
}
return sb.ToString();
}
public static bool CheckDrugIsEnough(eItemSubType type = eItemSubType.RoleDrug, int tips = 0)
{
bool b = false;
int[] al = null;
switch (type)
{
case eItemSubType.RoleDrug: al = CDEFINE.DRUG_NORMAL_IDS; break;
case eItemSubType.ShipDrug: al = CDEFINE.DRUG_SHIP_IDS; break;
case eItemSubType.PkDrug: al = CDEFINE.DRUG_PK_IDS; break;
}
if (al.Length > 0)
{
for (int i = 0; i < al.Length; i++)
{
b = CheckIsEnough(al[i], 1, false);
if (b) break;
}
}
if (!b && tips > 0)
{
if (tips != 1) CCommon.ShowTips(tips);
else CCommon.ShowTextTip("背包内缺少回复药品!请购买!");
}
return b;
}
public static ItemContent GetBestDrug(eItemSubType type)
{
int[] al = null;
switch (type)
{
case eItemSubType.RoleDrug: al = CDEFINE.DRUG_NORMAL_IDS; break;
case eItemSubType.ShipDrug: al = CDEFINE.DRUG_SHIP_IDS; break;
case eItemSubType.PkDrug: al = CDEFINE.DRUG_PK_IDS; break;
}
if (al.Length > 0)
{
ItemContent item = null, temp = null;
for (int i = 0; i < al.Length; i++)
{
temp = HolderManager.m_ItemHolder.GetStaticInfo(al[i]);
if (temp != null)
{
if (item == null || (temp.Quality > item.Quality && ItemManager.Instance.CheckItemCanUse(al[i])))
item = temp;
}
}
return item;
}
return null;
}
public static List<BackpackItemData> GetDrugList(eItemSubType type = eItemSubType.RoleDrug, bool containNull = false)
{
List<BackpackItemData> list = new List<BackpackItemData>();
int[] al = null;
switch (type)
{
case eItemSubType.RoleDrug: al = CDEFINE.DRUG_NORMAL_IDS; break;
case eItemSubType.ShipDrug: al = CDEFINE.DRUG_SHIP_IDS; break;
case eItemSubType.PkDrug: al = CDEFINE.DRUG_PK_IDS; break;
}
if (al != null && al.Length > 0)
{
for (int i = 0; i < al.Length; i++)
{
var v = new BackpackItemData(al[i]) { count = 0 };
v.count = ItemManager.C<PackContainer>().GetItemNumById(al[i]);
list.Add(v);
}
}
return list;
}
public static void SetSptire(this UISprite sprite, string spName, string atlas = null, int w = 0, int h = 0, bool makePerfect = false)
{
if (sprite != null)
{
if (!string.IsNullOrEmpty(spName) && sprite.spriteName != spName)
{
if (!string.IsNullOrEmpty(atlas) && (sprite.atlas == null || sprite.atlas.name != atlas))
{
UIAtlas a = CResourceManager.Instance.GetAtlas(atlas);
if (a != null)
{
sprite.atlas = a;
sprite.spriteName = spName;
if (w > 0) sprite.width = w;
if (h > 0) sprite.height = h;
if (makePerfect) sprite.MakePixelPerfect();
return;
}
}
sprite.spriteName = spName;
if (w > 0) sprite.width = w;
if (h > 0) sprite.height = h;
if (makePerfect) sprite.MakePixelPerfect();
}
}
}
static public int MoveNpcSort(CMoveEntity a, CMoveEntity b)
{
return a.sortDis.CompareTo(b.sortDis);
}
public static void SetVipLever(char[] _char, string[] strArray, List<CSprite> _viplever, CSprite _spriteDi)
{
UIAtlas atlas = CResourceManager.Instance.GetAtlas(strArray[0]);
if (atlas != null)
{
_spriteDi.SetSprite(atlas, strArray[1]);
for (int i = 0; i < _char.Length; i++)
{
switch (_char[i])
{
case '1':
_viplever[i].SetSprite("icon_vip1");
break;
case '2':
_viplever[i].SetSprite("icon_vip2");
break;
case '3':
_viplever[i].SetSprite("icon_vip3");
break;
case '4':
_viplever[i].SetSprite("icon_vip4");
break;
case '5':
_viplever[i].SetSprite("icon_vip5");
break;
case '6':
_viplever[i].SetSprite("icon_vip6");
break;
case '7':
_viplever[i].SetSprite("icon_vip7");
break;
case '8':
_viplever[i].SetSprite("icon_vip8");
break;
case '9':
_viplever[i].SetSprite("icon_vip9");
break;
default:
break;
}
} // mSelfVipNum.SetSprite(list[PlayerPropertyManager.Instance.PlayerInfo.VipLevel].vipContent.VIPGradeMap);
//InitWidget(Convert.ToInt32((_char[0])));
}
//else
//{
// mSelfPlayerName.localPosition = new Vector3(153, 34, 0);
// // mOthersPlayerName.position
// mSelfVipDi.SetActive(false);
// mOthersVipDi.SetActive(false);
//}
}
/// <summary>
/// 显示获得新物品界面
/// </summary>
public static void ShowGetNewPartherDialog(BaseContent content, Action callback, eGetNewPartner getType)
{
SingleObject<GetNewPartnerDialog>.Instance.schemes_Content = content;
SingleObject<GetNewPartnerDialog>.Instance.CloseCallBack = callback;
SingleObject<GetNewPartnerDialog>.Instance.Show(null, false, getType);
}
public static Vector3 MousePositionToUIPosition(Camera uicamera)
{
Vector3 mousePosition = Input.mousePosition;
if (uicamera != null)
{
mousePosition.x = Mathf.Clamp01(mousePosition.x / ((float)Screen.width));
mousePosition.y = Mathf.Clamp01(mousePosition.y / ((float)Screen.height));
mousePosition = uicamera.ViewportToWorldPoint(mousePosition);
}
return mousePosition;
}
/// <summary>
/// 自动购买toogle
/// </summary>
/// <returns></returns>
public static PartnerAudoBuyComponent CreateAudoBuyComp(CPanel c, Vector3 pos, Action<bool, bool> callBack)
{
CPanel sonPanel;
CDynamicComponent cdy = c.GetElementBase("(DynamicComponent)AutoBuyNode") as CDynamicComponent;
if (cdy == null)
{
Debug.LogError("未找到挂节点 (DynamicComponent)AutoBuyNode");
return null;
}
sonPanel = cdy.AddItem("AutoBuyItem");
sonPanel.gameobject.transform.localPosition = pos;
PartnerAudoBuyComponent audobuyComp = new PartnerAudoBuyComponent(sonPanel, callBack);
return audobuyComp;
}
public static MallContent GetMallContent(int goodsID)
{
Dictionary<int, MallContent> dic = HolderManager.m_MallHolder.GetDict();
foreach (var item in dic)
{
if (item.Value.ItemID == goodsID)
{
return item.Value;
}
}
return null;
}
public static eMapGroup GetMapGroup(eMapType mapType)
{
eMapGroup group = eMapGroup.None;
if (mapType == eMapType.None) return group;
if (mapType == eMapType.MapDungeon ||
mapType == eMapType.SeaDungeon ||
mapType == eMapType.MapParkour ||
mapType == eMapType.LandMapTower ||
mapType == eMapType.MapNewbee ||
mapType == eMapType.SeaMapTower)
{
group = eMapGroup.Dungeon;
}
else if (mapType == eMapType.MapPvp
|| mapType == eMapType.SeaPvp
|| mapType == eMapType.OfflineBattle
)
{
group = eMapGroup.Ground;
}
else
{
group = eMapGroup.Scene;
}
return group;
}
/// <summary>
/// 获取场景配置
/// </summary>
/// <param name="mapID">场景ID</param>
/// <param name="scene">可能的场景配置</param>
/// <param name="dungeon">可能的副本配置</param>
/// <param name="ground">可能的战斗场景配置</param>
/// <param name="planesDungeon">是否位面副本</param>
/// <returns>如果存在配置</returns>
public static bool GetMapContent(int mapID, ref SceneContent scene, ref DungeonContent dungeon, ref BattleGroundContent ground, ref bool planesDungeon)
{
eMapType mapType = CCommon.Key2MapType(mapID);
eMapGroup g = GetMapGroup(mapType);
if (g != eMapGroup.None)
{
planesDungeon = false;
scene = null;
dungeon = null;
ground = null;
if (mapType == eMapType.None) return false;
if (g == eMapGroup.Dungeon)
{
dungeon = HolderManager.m_DungeonHolder.GetStaticInfo(mapID);
if (dungeon == null) return false;
}
else if (g == eMapGroup.Ground)
{
ground = HolderManager.m_BattleGroundHolder.GetStaticInfo(mapID);
if (ground == null) return false;
}
else
{
scene = HolderManager.m_SceneHolder.GetStaticInfo(mapID);
if (scene == null) return false;
}
if (mapType == eMapType.MapDungeon ||
mapType == eMapType.SeaDungeon ||
mapType == eMapType.MapParkour ||
mapType == eMapType.LandMapTower ||
mapType == eMapType.MapNewbee ||
mapType == eMapType.SeaMapTower)
{
planesDungeon = true;
}
}
return scene != null || dungeon != null || ground != null;
}
/// <summary>
/// 获得场景路径
/// </summary>
/// <returns></returns>
public static string GetScenePath(int mapID)
{
eMapType mapType = CCommon.Key2MapType(mapID);
SceneContent scene = null; DungeonContent dungeon = null; BattleGroundContent ground = null;
bool state = false;
if (GetMapContent(mapID, ref scene, ref dungeon, ref ground, ref state))
{
if (scene != null) return scene.ResourcePath;
if (dungeon != null) return dungeon.ScenePath;
if (ground != null) return ground.ScenePath;
}
return "";
}
/// <summary>
/// 从表中解析需要的称号字段
/// </summary>
/// <param name="_str"></param>
/// <param name="_csprite"></param>
/// <param name="_uiAtlas"></param>
public static void SetTieleSprite(string _str, CSprite _csprite, UIAtlas _uiAtlas)
{
if (_str.Contains("."))
_str = _str.Substring(0, _str.LastIndexOf('.'));
string[] str = _str.Split('/');
_csprite.SetSprite(_uiAtlas, str[4], false);
}
/// <summary>
/// 显示副本样式奖励窗口
/// <param name="dropItemId">掉落表ID</param>
/// <param name="textContent">描述内容</param>
/// <param name="textTitle">标题内容</param>
/// <param name="gridMaxPerLine">Guid并排放最大数量</param>
/// </summary>
public static void ShowCopySweepingDialog(int dropItemId, string textContent, string textTitle, int gridMaxPerLine, bool setGet = false)
{
SingleObject<CopySweepingDialog>.Instance.dropItemId = dropItemId;
SingleObject<CopySweepingDialog>.Instance.textContent = textContent;
SingleObject<CopySweepingDialog>.Instance.textTitle = textTitle;
SingleObject<CopySweepingDialog>.Instance.gridMaxPerLine = gridMaxPerLine;
SingleObject<CopySweepingDialog>.Instance.setGet = setGet;
SingleObject<CopySweepingDialog>.Instance.Show(null);
}
public static bool GetWayGoto(int getWay, bool go = true, params object[] args)
{
if (getWay > 0)
{
var way = HolderManager.m_getwayHolder.GetStaticInfo(getWay);
if (way != null)
{
if (go)
{
if (way.Key == 1002)//拍卖行,需要特殊处理
{
CDialogManager.Instance.HideAllDialog();
SingleObject<StoreDialog>.Instance.SetOpenPanel(eStorePanelType.Stall);
SingleObject<StoreDialog>.Instance.Show(delegate
{
if (args != null && args.Length > 0 && args[0] is int)
{
BusinessContent content = BourseManager.Instance.GetBusinessContentByItemID((int)args[0]);
if (content != null)
BourseManager.Instance.Request_Auction_CS_SearchItem(true, content.Key, 0, 0, 0, 0, 0, BourseStatus.Public, true, 0, BourseManager.PrePageNum);
}
});
}
else if (way.JumpType == 0)//不指引
{
CCommon.ShowTextTip(CCommon.GetText(77000041));
}
else if (way.JumpType == 1)//直接打开对应界面
{
CDialog c = CDialogManager.Instance.GetDialog(way.JumpArg[0]);
if (c != null)
{
if (way.JumpArg.Count >= 2)
{
eOpenModule type = (eOpenModule)way.JumpArg[1];
if (COpenModule.CheckKeyIsOpen(type))
{
if (c is FunctionTabDialogBase && type != eOpenModule.None)//tab面板
(c as FunctionTabDialogBase).SetOpenToggle(type, args);
}
else return false;
}
c.Show(() =>
{
CDialogManager.Instance.CloseAllDialog(true, (uint)c.PanelID, CDialogManager.D_BACKPACK_ITEM.id, SingleObject<ItemAccessMethodDialog>.Instance.PanelID);
}, false, args);
}
}
else if (way.JumpType == 2)//直接进入活动场景
{
CCommon.RequestChangeScene((uint)way.JumpArg[0]);
CDialogManager.Instance.CloseAllDialog(false);
SingleObject<BattleUiDialog>.Instance.Show(null);
}
else if (way.JumpType == 3)//跳转场景并寻路到npc
{
CDialogManager.Instance.CloseAllDialog(false);
CCommon.RequestChangeScene((uint)way.JumpArg[0]);
FindNpcManager.Instance.FindNpc(way.JumpArg[1]);