public static Texture2D LoadEditorTexture(string relativePath, StringBuilder log = null) { #if UNITY_EDITOR var path = _scriptFolder + ImagesPath + relativePath; Texture2D tex; if (_cachedTextures.TryGetValue(path, out tex)) { return(tex); } tex = AssetDatabase.LoadAssetAtPath <Texture2D>(path); _cachedTextures[path] = tex; #if VERBOSE string logText = string.Format(" > {0} -> {1}", ImagesPath + relativePath, tex != null ? loadedStr : notFoundStr); if (log != null) { log.AppendLine(logText); } else { PrettyLog.Log(logText); } #endif return(tex); #else return(null); #endif }
Color32[] ExtractColorsFromTex(Sprite sprite) { var spriteRect = sprite.rect; var spriteId = sprite.GetInstanceID(); var tex = sprite.texture; Color32[] ret; if (!SpritePixelColors.TryGetValue(spriteId, out ret)) { if (_showDebugInfo) { PrettyLog.Log("making tex... id: {0} name: {1}", spriteId, tex.name); } var w = (int)spriteRect.width; var h = (int)spriteRect.height; var colors = new List <Color32>(); for (int xOffset = 0; xOffset < w; xOffset++) { var x = xOffset + (int)spriteRect.x; for (int yOffset = 0; yOffset < h; yOffset++) { var y = yOffset + (int)spriteRect.y; var pixelColor = tintByPixels ? tex.GetPixel(x, y) : Color.white; if (Mathf.Approximately(pixelColor.a, 0)) { continue; } colors.Add(pixelColor); } } ret = colors.ToArray(); SpritePixelColors[spriteId] = ret; } return(ret); }
private void TrySwapElements(Element source, Element target) { int sourceIndex; int targetIndex; try { sourceIndex = int.Parse(source.name); targetIndex = int.Parse(target.name); } catch (Exception e) { #if UNITY_EDITOR print(PrettyLog.GetMessage($"Swap object name parse error: {e.Message}")); #endif return; } var canSwap = _playground.CanSwap(sourceIndex, targetIndex); if (canSwap) { StartCoroutine(MakeSwap(sourceIndex, targetIndex)); } #if UNITY_EDITOR print(PrettyLog.GetMessage($"Opportunity to swap {sourceIndex} with {targetIndex} is {canSwap}")); #endif }
private void OnMouseUp() { if (!_isDragging) { return; } var upPosition = transform.position; transform.position = _startPosition; #if UNITY_EDITOR print(PrettyLog.GetMessage(OnMouseUp, $"transform.position = {transform.position}")); #endif if (OnTrySwap != null) { if (Input.GetMouseButtonDown(0)) { return; } RaycastHit hit; Physics.Raycast(upPosition, new Vector3(0f, 0f, 1f), out hit); var selectedItem = hit.transform?.gameObject.GetComponent <Element>(); #if UNITY_EDITOR print(PrettyLog.GetMessage(OnMouseUp, $"selectedItem: {selectedItem}")); #endif if (this != selectedItem) { OnTrySwap(this, selectedItem); } } }
/// <summary> /// 获取字段信息,支持使用“.”分隔的多级路径 /// </summary> /// <returns>The object field info.</returns> /// <param name="objType">Object type.</param> /// <param name="fieldPath">Field path.</param> public static FieldInfo GetObjectFieldInfo(System.Type objType, string fieldPath) { var hierarchy = fieldPath.Split(new[] { '.' }, 2); var field = GetFieldInfoByType(objType, hierarchy[0]); if (field == null) { return(null); } if (hierarchy.Length > 1) { var nextPath = hierarchy[1]; if (!nextPath.StartsWith(ArrayDataPrefix)) { return(GetObjectFieldInfo(field.FieldType, nextPath)); } else if (field.FieldType.IsArray || typeof(IList).IsAssignableFrom(field.FieldType)) { ParseArrayPath(nextPath, out nextPath); if (string.IsNullOrEmpty(nextPath)) { return(field); } else { var fieldType = field.FieldType; Type elementType = null; if (fieldType.IsArray) { elementType = fieldType.GetElementType(); } else if (fieldType.IsGenericType) { var gTypes = fieldType.GetGenericArguments(); if (gTypes.Length != 1) { PrettyLog.Error("Unknown array or list type: {0}", fieldType); return(null); } elementType = gTypes[0]; } else { PrettyLog.Error("Only array and List<T> can retrieve FieldInfo by propertyPath (not {0})", fieldType); return(null); } return(GetObjectFieldInfo(elementType, nextPath)); } } else { return(null); } } else { return(field); } }
public void Toss() { var dir = Quaternion.Euler(0, 0, tossAngle) * Vector2.right; GetComponent <Rigidbody2D>().AddForce(dir * speed, ForceMode2D.Impulse); PrettyLog.Log("toss"); }
protected override void Start(PlayerBlackboard snapshot) { PrettyLog.Log("take action: {0}", snapshot.action == null ? "(no action)" : snapshot.action.type.ToString()); if (snapshot.HasOrder) { snapshot.order.actionCallback = snapshot.action.startAction; } }
//[See] //void TestFallingAliveAndDie() //{ // var request = new PlayerBlackboard() // { // action = new PlayerAction(PlayerActionType.Die, null, null, null), // posture = PlayerPosture.Idle, // isOnGround = false, // isGravityEnabled = true, // playingAction = null, // }; // ExecuteTest(request); //} //[See] //void TestFallingDead() //{ // var request = new PlayerBlackboard() // { // action = new PlayerAction(PlayerActionType.Die, null, null, null), // posture = PlayerPosture.Dead, // isOnGround = false, // isGravityEnabled = true, // }; // ExecuteTest(request); //} void ExecuteTest(PlayerBlackboard request) { if (!Application.isPlaying) { PrettyLog.Error("Run only when playing"); return; } StartCoroutine(ExecuteTestCo(request)); }
private void Start() { #if UNITY_EDITOR print(PrettyLog.GetMessage(Start)); #endif _mainMenu.Init(StartGame); _ingameMenu.Init(EndGame); _ingameMenu.gameObject.SetActive(false); }
private void OnMouseDown() { _startPosition = transform.position; transform.position -= new Vector3(0f, 0f, 1f); _screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); #if UNITY_EDITOR print(PrettyLog.GetMessage(OnMouseDown, $"_startPosition = {_startPosition}")); #endif }
public void SetNodeWeight(Node child, float weight) { var childIndex = children.IndexOf(child); if (childIndex < 0) { PrettyLog.Error("Set weight error: '{0}' is not a child of '{1}'", child, this); return; } SetNodeWeight(childIndex, weight); }
void Say(TalkType type, System.Action onComplete) { PlayAnim(type); var content = FindTalk(type); if (bubble == null) { PrettyLog.Error("{0} has no bubble!", name); return; } bubble.Say(type, content, onComplete); }
public override void OnInspectorGUI() { base.OnInspectorGUI(); Type refType = null; Obj[] targets = null; if (!serializedObject.isEditingMultipleObjects && serializedObject.targetObject != null) { refType = serializedObject.targetObject.GetType(); targets = new[] { serializedObject.targetObject }; } else if (serializedObject.targetObjects != null) { refType = TypeUtility.FindCommonTypeWithin(serializedObject.targetObjects .Select(obj => obj != null ? obj.GetType() : null) .Where(t => t != null).ToArray()); targets = serializedObject.targetObjects; } if (refType == null) { return; } var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; var members = refType.GetMembers(flags).Where(m => GetCheersAttribute(m) != null) .Union( refType.GetInterfaceHierarchy().SelectMany(i => i.GetMembers(flags)) ); foreach (var member in members.Where(m => GetCheersAttribute(m) != null)) { var attr = GetCheersAttribute(member); if (attr == null) { continue; } switch (member.MemberType) { case MemberTypes.Method: DrawMethod((MethodInfo)member, attr, targets); break; case MemberTypes.Property: DrawProperty((PropertyInfo)member, attr, targets); break; default: PrettyLog.Log("TODO...Or never to be done. >_< Just use SerializedField instead"); break; } } }
public void GameOver(GameEndType end) { if (isOver) { return; } if (end > GameEndType.None) { isOver = true; } PrettyLog.Log("Game Over: {0}", end); ending.Show(end); }
static void InitializeAssets() { #pragma warning disable 0219 var assetPathRet = GetEditorAssetPath(); #pragma warning restore 0219 #if VERBOSE StringBuilder log = new StringBuilder("<color=maroon>[ Initializing Editor Assets... ]</color>\n"); log.AppendLine(assetPathRet); PrettyLog.Log(log.ToString()); #endif //VERBOSE }
bool ValidateSnapshot(Blackboard snapshot, out T typedSnapshot) { var actualType = snapshot.GetType(); if (actualType != typeof(T) && actualType.IsSubclassOf(typeof(T)) && typeof(T).IsAssignableFrom(actualType)) { PrettyLog.Error("{0} can not be converted to {1}", actualType, typeof(T)); typedSnapshot = null; return(false); } typedSnapshot = (T)snapshot; return(true); }
void DrawToolbar() { // toolbar EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); EditorGUI.BeginDisabledGroup(!_hasTarget); if (GUILayout.Button("Save", EditorStyles.toolbarButton)) { _treeData.SaveAsset(); } if (GUILayout.Button("Load", EditorStyles.toolbarButton)) { _treeData.LoadAsset(); } if (GUILayout.Button("Clear", EditorStyles.toolbarButton)) { _treeData.rootNode.Clear(); } if (GUILayout.Button("Load Clipboard", EditorStyles.toolbarButton)) { _treeData.DeserializeFromClipboard(); } if (GUILayout.Button("Print Last Log", EditorStyles.toolbarButton)) { PrettyLog.Log(BTLogger.PrintLastLog(_treeData.rootNode)); } GUILayout.Space(10f); if (GUILayout.Button("Pan To (0,0)", EditorStyles.toolbarButton)) { _pan = Vector2.zero + CanvasRect.size * .5f; } if (GUILayout.Button("Scale -0.1", EditorStyles.toolbarButton)) { _scale -= .1f; } if (GUILayout.Button("Scale +0.1", EditorStyles.toolbarButton)) { _scale += .1f; } if (GUILayout.Button("Reset scale", EditorStyles.toolbarButton)) { _scale = 1f; } GUILayout.FlexibleSpace(); EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); }
public void DeserializeFromClipboard() { var data = GUIUtility.systemCopyBuffer; try { _serializedData = data; Deserialize(); PrettyLog.Log("<color=maroon>{0} is loaded. Data size: {1}</color>", name, _serializedData.Length); } catch (JsonReaderException ex) { PrettyLog.Error("<color=red>Load failed: Invalid behaviour tree data</color>\n<color=blue>Exception:</color>\n{0}\n\n<color=blue>Data</color>\n{1}", ex, data); } }
public void Rearrange() { var rearrangedElements = new List <Tuple <int, byte> >(); for (var i = 0; i < Width; i++) { rearrangedElements.AddRange(GetSortedColumn(i)); } OnPlaygroundUpdated?.Invoke(rearrangedElements); #if UNITY_EDITOR Debug.Log(PrettyLog.GetMessage(nameof(Playground), nameof(Rearrange), rearrangedElements)); #endif }
public Playground(byte n, byte m, byte elementTypesCount) { Width = n; Height = m; ElementTypesCount = elementTypesCount; _elements = new List <byte>(); for (var i = 0; i < n * m; i++) { Add((byte)new Random().Next(1, new Random().Next(1, new Random().Next(1, elementTypesCount)))); } #if UNITY_EDITOR Debug.Log(PrettyLog.GetMessage(nameof(Playground), "Ctor", _elements)); #endif }
public static Color ByWeb(string htmlString) { Color ret; if (string.IsNullOrEmpty(htmlString)) { ret = Color.clear; } else if (!ColorUtility.TryParseHtmlString(htmlString, out ret)) { PrettyLog.Error( "Invalid HTML color string: {0}. It needs to be a web color name, or a hex color with a leading '#'", htmlString); ret = Color.clear; } return(ret); }
Color32[] MakePieceColors(SpriteRenderer rdr) { var colors = ExtractColorsFromTex(rdr.sprite); var pieceCount = Mathf.RoundToInt(colors.Length / (chunkSize * chunkSize)); if (_showDebugInfo) { PrettyLog.Log("pixels: {0}, chunk size: {1}, piece count: {2}", colors.Length, chunkSize, pieceCount); } var ret = new Color32[pieceCount]; for (int colorIndex = 0, pieceIndex = 0; pieceIndex < pieceCount; colorIndex += chunkSize, pieceIndex++) { ret[pieceIndex] = colors[colorIndex]; } return(ret); }
public void StartGame(byte n, byte m, byte count) { Assert.IsTrue(count < n * m, "Element types count higher than n * m!"); var nValue = n != 0 ? n : _n; var mValue = m != 0 ? m : _m; var typesCountValue = count != 0 ? count : _elementTypesCount; _playground = new Playground(nValue, mValue, typesCountValue); _playgroundView = new GameObject(nameof(PlaygroundView)).AddComponent <PlaygroundView>(); _playgroundView.Init(_playground); _mainCamera.orthographicSize = Math.Max(n, m); _ingameMenu.gameObject.SetActive(true); #if UNITY_EDITOR print(PrettyLog.GetMessage(nameof(App), nameof(StartGame), $"n = {n}, m = {m}, count = {count}")); #endif }
bool ValidateType(Node node) { var nodeType = node.GetType(); var selfType = GetType(); var attr = selfType.GetAttribute <CustomNodeEditorAttribute>(false); if (attr == null) { PrettyLog.Error("{0} has no CustomNodeEditor attribute", selfType); return(false); } if (nodeType != attr.nodeType) { PrettyLog.Error("{0} can only be used as {1}'s editor ({2} given)", selfType, attr.nodeType, nodeType); return(false); } return(true); }
protected override Node Select(Blackboard snapshot) { if (children.Count == 0) { return(null); } // initialize the weights with same values if not correctly set if (weights == null || weights.Length == 0 || Array.TrueForAll(weights, w => w == 0)) { if (weights == null || weights.Length == 0) { weights = new float[children.Count]; } for (int i = 0; i < weights.Length; i++) { weights[i] = 1; } } var arrCdf = new float[weights.Length]; for (int i = 0; i < arrCdf.Length; i++) { if (i == 0) { arrCdf[i] = weights[i]; } else { arrCdf[i] = arrCdf[i - 1] + weights[i]; } } var rnd = UnityEngine.Random.Range(0, arrCdf[arrCdf.Length - 1]); int min = 0, max = arrCdf.Length - 1; var index = BinarySearchInRanges(arrCdf, rnd, min, max); if (index < 0 || index >= children.Count) { PrettyLog.Error("Random weighted sampling error: result index is {0}", index); } return(children[index]); }
public Node AddNodes(params Node[] newChildren) { if (IsLeaf) { PrettyLog.Error("{0} is a leaf node that can't hold any child", DisplayName); } if (newChildren == null || newChildren.Length == 0) { return(this); } for (int i = 0; i < newChildren.Length; i++) { var newChild = newChildren[i]; newChild.UpdateParent(this); children.Add(newChild); } return(this); }
void DrawMethod(MethodInfo method, See attr, Obj[] targets) { var @params = method.GetParameters(); var btnText = new GUIContent(GetCheersTitle(attr, method)); var canPress = true; if (@params.Length > 0) { btnText.text += "\n(Parameters are not supported yet)"; btnText.image = EditorHelper.icons.warning; canPress = false; } EditorGUI.BeginDisabledGroup(!canPress); var bgColor = attr.BackgroundColor == Color.clear ? GUI.backgroundColor : attr.BackgroundColor; var oldBgColor = GUI.backgroundColor; GUI.backgroundColor = bgColor; var btnStyle = new GUIStyle(EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).button); if (attr.TextColor != Color.clear) { btnStyle.normal.textColor = attr.TextColor; btnStyle.hover.textColor = attr.TextColor; btnStyle.focused.textColor = attr.TextColor; btnStyle.active.textColor = attr.TextColor; } if (GUILayout.Button(btnText, btnStyle)) { StringBuilder retSb = new StringBuilder("=== Call Returns ===\n"); foreach (var t in targets) { var ret = method.Invoke(t, null); retSb.AppendLine(string.Format(" - {0} >> {1}", t.name, ret ?? "(null)")); } PrettyLog.Log(retSb.ToString()); } GUI.backgroundColor = oldBgColor; EditorGUI.EndDisabledGroup(); }
public void CleanAt(int index) { #if UNITY_EDITOR Debug.Log(PrettyLog.GetMessage(nameof(Playground), nameof(CleanAt), $"{index}")); #endif var list = GetRemovableElements(index); if (list.Count == 1) { return; } list.ForEach(RemoveAt); var result = list.Select(element => Tuple.Create(element, (byte)0)).ToList(); OnPlaygroundUpdated?.Invoke(result); #if UNITY_EDITOR Debug.Log(PrettyLog.GetMessage(nameof(Playground), nameof(CleanAt), result)); #endif }
public void Fill() { var filledElements = new List <Tuple <int, byte> >(); var i = 0; _elements.ForEach(element => { if (element == 0) { filledElements.Add(Tuple.Create(i, (byte)new Random().Next(1, new Random().Next(1, ElementTypesCount)))); } i++; }); filledElements.ForEach(element => _elements[element.Item1] = element.Item2); OnPlaygroundUpdated?.Invoke(filledElements); #if UNITY_EDITOR Debug.Log(PrettyLog.GetMessage(nameof(Playground), nameof(Fill), filledElements)); #endif }
//No parameters static public void Broadcast(string eventType) { PrettyLog.Log("<color=maroon>Broadcasting»</color> {0}", eventType); #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\""); #endif OnBroadcasting(eventType); Delegate d; if (eventTable.TryGetValue(eventType, out d)) { Callback callback = d as Callback; if (callback != null) { callback(); } else { throw CreateBroadcastSignatureException(eventType); } } }