Exemple #1
0
 private static StateMachine[] FindFsms()
 {
     StateMachine[]   fsms       = UnityEditorUtility.GetAssetsOfType <StateMachine> (".asset");
     ICodeBehaviour[] behaviours = UnityEditorUtility.FindInScene <ICodeBehaviour>().ToArray();
     fsms = ArrayUtility.AddRange <StateMachine>(fsms, behaviours.Where(x => !EditorUtility.IsPersistent(x.stateMachine)).Select(y => y.stateMachine).ToArray());
     return(fsms);
 }
Exemple #2
0
			void LoadGenerator (Vector2 pos)
			{
				string path= UnityEditor.EditorUtility.OpenFilePanel(
						"Load Node",
						"Assets",
						"asset");
				if (path==null || path.Length==0) return;
				path = path.Replace(Application.dataPath, "Assets");

				GeneratorsAsset loadedGens = (GeneratorsAsset)AssetDatabase.LoadAssetAtPath(path, typeof(GeneratorsAsset));

				for (int i=loadedGens.list.Length-1; i>=0; i--)
				{
					//cloning
					//loadedGens.list[i] = loadedGens.list[i].ReflectionCopy();
					Generator gen = loadedGens.list[i];

					//offset
					gen.guiRect.position += pos;
					
					//ignoring already existing outputs
					if (gen is IOutput && MapMagic.instance.gens.GetGenerator(gen.GetType())!=null)
					{
						Debug.Log ("MapMagic: tried to load Output which already exists (" + gen + "). Skipping.");
						loadedGens.UnlinkGenerator(gen);
						ArrayUtility.RemoveAt(ref loadedGens.list, i);
					}

				}

				ArrayUtility.AddRange(ref MapMagic.instance.gens.list, loadedGens.list);
				MapMagic.instance.gens.ChangeGenerator(null);
				repaint=true; Repaint();
			}
Exemple #3
0
        private static void HandleScriptsChange(string[] importedAssets, string[] deletedAssets, string[] movedAssets)
        {
            bool hasScriptAssets = false;

            string[] assets = new string[0];
            ArrayUtility.AddRange(ref assets, importedAssets);
            ArrayUtility.AddRange(ref assets, deletedAssets);
            ArrayUtility.AddRange(ref assets, movedAssets);

            if (assets != null)
            {
                foreach (var item in assets)
                {
                    if (Utility.IsScriptAsset(item))
                    {
                        hasScriptAssets = true;
                        break;
                    }
                }
            }

            if (hasScriptAssets)
            {
                APCache.SaveToLocalAsync();
            }
        }
    private static void ArraySizeField <T>(string label, ref T[] array, Object target)
    {
        int oldLength = array != null ? array.Length : 0;
        int newLength = EditorGUILayout.IntField(label, oldLength);

        if (newLength > oldLength)
        {
            if (array == null)
            {
                array = new T[newLength];
            }
            else
            {
                ArrayUtility.AddRange(ref array, new T[newLength - oldLength]);
            }
            EditorUtility.SetDirty(target);
        }
        else if (newLength < oldLength)
        {
            for (int count = 0; count < oldLength - newLength; ++count)
            {
                ArrayUtility.RemoveAt(ref array, array.Length - 1);
            }

            EditorUtility.SetDirty(target);
        }
    }
Exemple #5
0
        public int GetVariablesOfType(FsmVariable variable, out string[] names)
        {
            if (FsmEditor.Root == null)
            {
                names = new string[0];
                return(0);
            }
            FsmVariable[] variables = FsmEditor.Root.Variables;
            variables = ArrayUtility.AddRange <FsmVariable> (variables, GlobalVariables.GetVariables());
            int           count = 0;
            List <string> strs  = new List <string> ()
            {
                "None"
            };

            for (int i = 0; i < variables.Length; i++)
            {
                Type propertyType = variables[i].GetType().GetProperty("Value").PropertyType;
                if (variable == null || propertyType.Equals(variable.GetType().GetProperty("Value").PropertyType))
                {
                    strs.Add(variables[i].Name);
                    if (variable != null && variables[i].Name.Equals(variable.Name))
                    {
                        count = strs.Count - 1;
                    }
                }
            }
            names = strs.ToArray();
            return(count);
        }
Exemple #6
0
        public static void IncreaseVersion(SemanticVersionType increaseVersionType, char separator)
        {
            string[] parts   = PlayerSettings.bundleVersion.Split(separator);
            int      version = 1;
            int      index   = (int)increaseVersionType;

            if (index >= parts.Length)
            {
                string[] versions = new string[(index + 1) - parts.Length];
                for (int i = 0; i < versions.Length; i++)
                {
                    versions[i] = "0";
                }
                ArrayUtility.AddRange(ref parts, versions);
            }
            else if (int.TryParse(parts[index], out version))
            {
                version += 1;
            }

            for (int i = index + 1; i < parts.Length;)
            {
                ArrayUtility.RemoveAt(ref parts, i);
            }

            parts[index] = version.ToString();
            PlayerSettings.bundleVersion = string.Join(separator.ToString(), parts);
        }
Exemple #7
0
        public void Merge(MeshData m)
        {
            if (m.verts == null)
            {
                return;
            }

            if (verts == null)
            {
                verts = m.verts;
                uvs   = m.uvs;
                tris  = m.tris;
                return;
            }

            int count = verts.Length;

            ArrayUtility.AddRange(ref verts, m.verts);
            ArrayUtility.AddRange(ref uvs, m.uvs);

            for (int i = 0; i < m.tris.Length; i++)
            {
                ArrayUtility.Add(ref tris, m.tris[i] + count);
            }
        }
        EditorCurveBinding[] GetAllCurveBindings(AnimationClip clip)
        {
            EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings(clip);
            EditorCurveBinding[] objectReferenceBindings = AnimationUtility.GetObjectReferenceCurveBindings(clip);

            ArrayUtility.AddRange <EditorCurveBinding>(ref bindings, objectReferenceBindings);
            return(bindings);
        }
Exemple #9
0
        public static void onSceneGUI(SceneView sceneView)
        {
            if (!PreferenceSettings.i.EnableSceneView2GameView.Value)
            {
                selected = 0;
                gameview = false;
                return;
            }


            Handles.BeginGUI();

            var cameras = UnityEngine.Object.FindObjectsOfType <Camera>();

            string[] displayNames = new string[] { "None", "" };
            ArrayUtility.AddRange(ref displayNames, cameras.Select <Camera, string>(c => c.name).ToArray());


            rcPop.y = Screen.height - (24 * 2) - (8 * 2);
            //rcBak.y = rcPop.y - 16 - 4;
            //GUI.skin = EditorGUIUtility.GetBuiltinSkin( EditorSkin.Inspector );
            //GUI.Label( rcBak, "", "HelpBox" );

            GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
            selected = EditorGUI.Popup(rcPop, selected, displayNames, (GUIStyle)"Popup");

            rcToggle.y             = rcPop.y;
            sceneView.orthographic = GUI.Toggle(rcToggle, sceneView.orthographic, "");

            int index = selected - 2;

            if (index >= 0 && index < cameras.Length)
            {
                var camera = cameras[index];
                if (gameview)
                {
                    var a = camera.transform.rotation * Vector3.forward;
                    a *= 25.0f;
                    sceneView.pivot    = camera.transform.position + a;
                    sceneView.rotation = camera.transform.rotation;
                    sceneView.size     = 25.0f;

                    gameview = false;
                }
                else
                {
                    camera.transform.position = sceneView.camera.transform.position;
                    camera.transform.rotation = sceneView.camera.transform.rotation;
                }
            }
            else
            {
                rcRad.y  = rcPop.y - 16;
                GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
                gameview = GUI.Toggle(rcRad, gameview, "Align Game View");
            }
            Handles.EndGUI();
        }
Exemple #10
0
        static bool Renderer_Color(GameObject target, Type type, Color color, float fBlendWeight, bool includeBody, bool includeAttachment, bool bApplyToTileOverlay = true)
        {
            List <SpriteRenderer> exceptions = new List <SpriteRenderer>();
            List <SpriteRenderer> overlays   = new List <SpriteRenderer>();
            var renderers           = target.GetComponentsInChildren <SpriteRenderer>();
            var renderersEnumerater = renderers.GetEnumerator();

            if (bApplyToTileOverlay)
            {
                while (renderersEnumerater.MoveNext())
                {
                    var current = renderersEnumerater.Current as SpriteRenderer;
                    var iso2D   = current != null?current.GetComponent <Iso2DObject>() : null;

                    if (iso2D != null)
                    {
                        if (!((includeBody && iso2D.IsSideOfTile) || (includeAttachment && iso2D.IsAttachment)))
                        {
                            exceptions.Add(current);
                            continue;
                        }

                        if (iso2D.IsSideOfTile)
                        {
                            IsoTile tile = iso2D.Tile;
                            overlays.AddRange(tile._attachedList.childList.
                                              Where(r => r.AttachedObj.IsTileRCAttachment && r.AttachedObj._Type == Iso2DObject.Type.Overlay).
                                              Select(r => r.AttachedObj.sprr).ToArray());
                        }
                    }
                }
                if (overlays.Count > 0)
                {
                    ArrayUtility.AddRange(ref renderers, overlays.ToArray());
                }
                renderersEnumerater = renderers.GetEnumerator();
            }

            Undo.RecordObjects(renderers, "Tile Control Wand: Material Color");
            while (renderersEnumerater.MoveNext())
            {
                var current = renderersEnumerater.Current as SpriteRenderer;
                if (current != null && (!exceptions.Contains(current) || overlays.Contains(current)))
                {
                    var isoLightReciver = current.GetComponent <IsoLightReciver>();
                    if (isoLightReciver != null)
                    {
                        isoLightReciver.UpdateBaseColor(CalcColor(isoLightReciver.GetBaseColor, color, type, fBlendWeight));
                    }
                    else
                    {
                        current.color = CalcColor(current.color, color, type, fBlendWeight);
                    }
                }
            }
            return(true);
        }
        public void SetSelectedNodes(Node[] nodes)
        {
            bool difference = false;

            UnityEngine.Object[] currentObjects = Selection.objects;

            if (currentObjects.Length != nodes.Length)
            {
                difference = true;
            }
            else
            {
                for (int i = 0; i < currentObjects.Length; i++)
                {
                    Object obj = currentObjects[i];

                    if (!obj.IsTypeOf <Node> ())
                    {
                        difference = true;
                        break;
                    }

                    Node node            = obj as Node;
                    bool alreadySelected = false;

                    for (int j = 0; j < nodes.Length; j++)
                    {
                        if (node == nodes[j])
                        {
                            alreadySelected = true;
                            break;
                        }
                    }

                    if (!alreadySelected)
                    {
                        difference = true;
                        break;
                    }
                }
            }

            if (difference)
            {
                ArrayUtility.Clear(ref m_selectedNodes);
                ArrayUtility.AddRange(ref m_selectedNodes, nodes);
                Selection.objects = nodes;

                // add all new selected nodes at the first entry's in the sortedList.
                for (int i = 0; i < nodes.Length; i++)
                {
                    m_lastSelectedNodes.Push(nodes[i]);
                }

                onNodesSelected?.Invoke(GetSelectedNodes());
            }
        }
Exemple #12
0
        // TODO: Make everything with loops and lists instead of LINQ
        public void LoadAssets()
        {
            if (_paths == null)
            {
                return;
            }

            _paths = _paths.Where(x => !string.IsNullOrEmpty(x) && AssetDatabase.IsValidFolder(x)).ToArray();

            if (_paths.Length == 0)
            {
                return;
            }

            List <Object> assets;

            assets = AssetDatabase
                     .FindAssets("t:Object", _paths)
                     .Select(AssetDatabase.GUIDToAssetPath)
                     .Select(AssetDatabase.LoadAssetAtPath <Object>)
                     .Where(x =>
            {
                string fileNamespace = x.GetType().Namespace;

                return(x != null && (fileNamespace == null || !fileNamespace.Contains("UnityEditor")));
            })                     // Change UnityEditor to Editor?
                     .ToList();

            var newEntries = new List <AssetEntry>();

            foreach (var asset in assets)
            {
                string path = AssetDatabase.GetAssetPath(asset);
                string guid = AssetDatabase.AssetPathToGUID(path);

                if (!TryGetValue(asset, out _))
                {
                    newEntries.Add(new AssetEntry(guid, asset));
                }

                var childAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(asset));

                for (int i = 0; i < childAssets.Length; i++)
                {
                    var child = childAssets[i];

                    if (!TryGetValue(child, out _))
                    {
                        string childGuid = System.Guid.NewGuid().ToString();
                        newEntries.Add(new AssetEntry(childGuid, child));
                    }
                }
            }

            ArrayUtility.AddRange(ref _savedAssets, newEntries.ToArray());
            EditorUtility.SetDirty(this);
        }
Exemple #13
0
    public static void SelectSceneCustomAction()
    {
        UnityEngine.Object[] _list = GetSceneCustomActionDependencies();

        var _sel = Selection.objects;

        ArrayUtility.AddRange <UnityEngine.Object>(ref _sel, _list);
        Selection.objects = _sel;
    }
        protected virtual void OnEnable()
        {
            this.m_Script            = base.serializedObject.FindProperty("m_Script");
            this.m_Name              = base.serializedObject.FindProperty("name");
            this.m_Focus             = base.serializedObject.FindProperty("focus");
            this.m_Interactable      = base.serializedObject.FindProperty("interactable");
            this.m_EaseType          = base.serializedObject.FindProperty("easeType");
            this.m_Duration          = base.serializedObject.FindProperty("duration");
            this.m_ShowSound         = base.serializedObject.FindProperty("showSound");
            this.m_CloseSound        = base.serializedObject.FindProperty("closeSound");
            this.m_DelegatesProperty = base.serializedObject.FindProperty("m_Delegates");

            this.m_PropertyPathToDrawForBaseClasses     = new string[] { this.m_Script.propertyPath, this.m_Name.propertyPath, this.m_Focus.propertyPath, this.m_Interactable.propertyPath, this.m_EaseType.propertyPath, this.m_Duration.propertyPath, this.m_ShowSound.propertyPath, this.m_CloseSound.propertyPath };
            this.m_PropertyPathToExcludeForChildClasses = new string[this.m_PropertyPathToDrawForBaseClasses.Length];
            Array.Copy(this.m_PropertyPathToDrawForBaseClasses, this.m_PropertyPathToExcludeForChildClasses, this.m_PropertyPathToDrawForBaseClasses.Length);
            ArrayUtility.Add <string> (ref this.m_PropertyPathToExcludeForChildClasses, this.m_DelegatesProperty.propertyPath);

            this.m_DynamicContainer = base.serializedObject.FindProperty("dynamicContainer");

            if (this.m_DynamicContainer != null)
            {
                this.m_Grid       = serializedObject.FindProperty("grid");
                this.m_SlotPrefab = serializedObject.FindProperty("slotPrefab");
                if (this.m_Grid.objectReferenceValue == null)
                {
                    GridLayoutGroup group = ((MonoBehaviour)target).gameObject.GetComponentInChildren <GridLayoutGroup>();
                    if (group != null)
                    {
                        serializedObject.Update();
                        this.m_Grid.objectReferenceValue = group.transform;
                        serializedObject.ApplyModifiedProperties();
                    }
                }
                this.m_ShowDynamicContainer = new AnimBool(this.m_DynamicContainer.boolValue);
                this.m_ShowDynamicContainer.valueChanged.AddListener(new UnityAction(this.Repaint));
                ArrayUtility.AddRange <string>(ref this.m_PropertyPathToExcludeForChildClasses, new string[] { m_DynamicContainer.propertyPath, this.m_Grid.propertyPath, this.m_SlotPrefab.propertyPath });
            }

            this.m_AddButonContent  = new GUIContent("Add New Trigger");
            this.m_EventIDName      = new GUIContent(string.Empty);
            this.m_IconToolbarMinus = new GUIContent(EditorGUIUtility.IconContent("Toolbar Minus"))
            {
                tooltip = "Remove all events in this list."
            };
            string[] names = Enum.GetNames(typeof(UIWidget.TriggerType));
            this.m_EventTypes = new GUIContent[(int)names.Length];
            for (int i = 0; i < (int)names.Length; i++)
            {
                this.m_EventTypes[i] = new GUIContent(names[i]);
            }
        }
Exemple #15
0
			void LoadGenerator (Vector2 pos)
			{
				if (MapMagic.instance.guiGens == null) MapMagic.instance.guiGens = MapMagic.instance.gens;	

				string path= UnityEditor.EditorUtility.OpenFilePanel(
						"Import Nodes",
						"", 
						"nodes");
				if (path==null || path.Length==0) return;

				//preparing serialization arrays
				List<string> classes = new List<string>();
				List<UnityEngine.Object> objects = new List<UnityEngine.Object>();
				List<object> references = new List<object>();
				List<float> floats = new List<float>();

				//loading
				System.IO.StreamReader reader = new System.IO.StreamReader(path);
				CustomSerialization.ImportXML(reader.ReadToEnd(), out classes, out objects, out floats);
				Generator[] loadedGens = (Generator[])CustomSerialization.ReadClass(0, classes, objects, floats, references);

				//offset 
				for (int i=loadedGens.Length-1; i>=0; i--) loadedGens[i].guiRect.position += pos;
				

				//GeneratorsAsset loadedGens = (GeneratorsAsset)AssetDatabase.LoadAssetAtPath(path, typeof(GeneratorsAsset));

				/*for (int i=loadedGens.list.Length-1; i>=0; i--)
				{
					//cloning
					//loadedGens.list[i] = loadedGens.list[i].ReflectionCopy();
					Generator gen = loadedGens.list[i];

					//offset
					gen.guiRect.position += pos;
					
					//ignoring already existing outputs
					if (gen is Generator.IOutput && MapMagic.instance.guiGens.GetGenerator(gen.GetType())!=null)
					{
						Debug.Log ("MapMagic: tried to load Output which already exists (" + gen + "). Skipping.");
						loadedGens.UnlinkGenerator(gen);
						ArrayUtility.RemoveAt(ref loadedGens.list, i);
					}

				}*/

				ArrayUtility.AddRange(ref MapMagic.instance.guiGens.list, loadedGens);
				MapMagic.instance.guiGens.ChangeGenerator(null);
				repaint=true; forceAll=true; Repaint();
			}
        static void GetMessages()
        {
            Directory.CreateDirectory(DeployGateUtility.messageLogFolderPath);
            string[] files = Directory.GetFiles(DeployGateUtility.messageLogFolderPath, "*.json");

            foreach (string file in files)
            {
                messages.Add(MiniJSON.Json.Deserialize <Message>(File.ReadAllText(file)));
            }
            messages.Add(new Message {
                title = "new Message"
            });
            messages.Reverse();
            ArrayUtility.AddRange(ref displayOptions, messages.Select((message, i) => message.title).ToArray());
        }
        private void ShowAddTrackMenu()
        {
            Event.current.Use();

            GenericMenu menu = new GenericMenu();

            System.Reflection.Assembly fluxAssembly = typeof(FEvent).Assembly;
            //獲取FEvent類所在程序集的所有類型
            Type[] types = typeof(FEvent).Assembly.GetTypes();


            if (fluxAssembly.GetName().Name != "Assembly-CSharp")
            {
                // if we are in the flux trial, basically allow to get the types in the project assembly
                ArrayUtility.AddRange <Type>(ref types, System.Reflection.Assembly.Load("Assembly-CSharp").GetTypes());
            }

            List <KeyValuePair <Type, FEventAttribute> > validTypeList = new List <KeyValuePair <Type, FEventAttribute> >();

            foreach (Type t in types)
            {
                //Fish:typeof(FEvent).IsAssignableFrom(t) 類型t是否間接或直接實現了FEvent(t是不是FEvent的後代或者後代的後代)

                if (!typeof(FEvent).IsAssignableFrom(t))
                {
                    continue;
                }
                object[] attributes = t.GetCustomAttributes(typeof(FEventAttribute), false);
                if (attributes.Length == 0 || ((FEventAttribute)attributes[0]).menu == null)
                {
                    continue;
                }

                validTypeList.Add(new KeyValuePair <Type, FEventAttribute>(t, (FEventAttribute)attributes[0]));
            }

            validTypeList.Sort(delegate(KeyValuePair <Type, FEventAttribute> x, KeyValuePair <Type, FEventAttribute> y)
            {
                return(x.Value.menu.CompareTo(y.Value.menu));
            });

            foreach (KeyValuePair <Type, FEventAttribute> kvp in validTypeList)
            {
                menu.AddItem(new GUIContent(kvp.Value.menu), false, AddTrackMenu, kvp);
            }

            menu.ShowAsContext();
        }
        /**
         * Inserts a range of T[] at index.
         */
        public static bool InsertRange <T>(ref T[] source, int index, T[] range)
        {
            if (index >= source.Length || index < 0)
            {
                ArrayUtility.AddRange(ref source, range);
                return(true);
            }

            T[] full = new T[source.Length + range.Length];
            System.Array.Copy(source, 0, full, 0, index);
            System.Array.Copy(range, 0, full, index, range.Length);
            System.Array.Copy(source, index, full, index + range.Length, source.Length - index);

            source = full;

            return(true);
        }
Exemple #19
0
			void DuplicateGenerator (Generator gen)
			{
				if (MapMagic.instance.guiGens == null) MapMagic.instance.guiGens = MapMagic.instance.gens;

				Generator[] copyGens = SmartCopyGenerators(gen);
				
				//ignoring already existing outputs
				for (int i=copyGens.Length-1; i>=0; i--)
				{
					Generator copyGen = copyGens[i];

					copyGen.guiRect.position += new Vector2(0, gen.guiRect.height + 10);
				}

				ArrayUtility.AddRange(ref MapMagic.instance.guiGens.list, copyGens);
				MapMagic.instance.guiGens.ChangeGenerator(null);
				repaint=true; Repaint();
			}
    public override void Initialize(Object[] targets)
    {
        base.Initialize(targets);

        var sprites = new Object[0];

        foreach (AnimationClip animationClip in targets)
        {
            ArrayUtility.AddRange(ref sprites, GetSprites(animationClip));
        }

        foreach (var sprite in sprites)
        {
            AssetPreview.GetAssetPreview(sprite);
        }

        m_Targets = sprites;
    }
Exemple #21
0
        private static void MigrateAllIgnores(ICollection <string> oldFilters, ref FilterItem[] newFilters, FilterKind filterKind)
        {
            if (oldFilters == null || oldFilters.Count == 0)
            {
                return;
            }

            var newFiltersList = new List <FilterItem>(oldFilters.Count);

            foreach (var oldFilter in oldFilters)
            {
                if (CSFilterTools.IsValueMatchesAnyFilter(oldFilter, newFilters))
                {
                    continue;
                }
                newFiltersList.Add(FilterItem.Create(oldFilter, filterKind));
            }

            ArrayUtility.AddRange(ref newFilters, newFiltersList.ToArray());
        }
Exemple #22
0
        public override void Initialize(UnityEngine.Object[] targets)
        {
            base.Initialize(targets);

            var sprites = new UnityEngine.Object[0];

            if (tile.Patterns != null)
            {
                foreach (FangAutoTilePattern pattern in tile.Patterns)
                {
                    if (pattern.Frames != null)
                    {
                        ArrayUtility.AddRange(ref sprites, pattern.Frames);
                    }
                }
            }
            if (sprites.Length != 0)
            {
                m_Targets = sprites;
            }
        }
        public override void OnEnter()
        {
            if (!arrays.Contains(result))
            {
                _source = result.Values;
            }
            else
            {
                _source = new object[0];
            }

            foreach (FsmArray fsmArray in arrays)
            {
                ArrayUtility.AddRange(ref _source, fsmArray.Values);
            }

            result.Values = _source;
            result.SaveChanges();

            Finish();
        }
Exemple #24
0
        //Change the length of the array.
        //If it is shorter than the original length it is clipped and
        //if it is longer than the original length an empty element is added.
        //配列の長さを変更する。元の長さより短い場合は切り取られ、元の長さより長い場合は空の要素が追加される。
        public bool ResizeLength(int length)
        {
            if (objects == null || objects.Length == 0 || objects.Length == length || length < 0)
            {
                return(false);
            }

            executing = true;

            if (length < objects.Length)
            {
                objects = objects.Where((e, i) => i < length).ToArray();
            }
            else
            {
                ArrayUtility.AddRange(ref objects, new GameObject[length - objects.Length]);
            }

            executing = false;
            return(true);
        }
Exemple #25
0
        private static bool MigrateAllIgnores(string[] oldFilters, ref FilterItem[] newFilters, FilterKind filterKind)
        {
            if (oldFilters == null || oldFilters.Length == 0)
            {
                return(false);
            }

            var newFiltersList = new List <FilterItem>(oldFilters.Length);

            foreach (var oldFilter in oldFilters)
            {
                if (CSFilterTools.IsValueMatchesAnyFilter(oldFilter, newFilters))
                {
                    continue;
                }
                newFiltersList.Add(FilterItem.Create(oldFilter, filterKind));
            }

            ArrayUtility.AddRange(ref newFilters, newFiltersList.ToArray());

            return(true);
        }
Exemple #26
0
			void DuplicateGenerator (Generator gen)
			{
				GeneratorsAsset copyGens = SmartCopyGenerator(gen);
				
				//ignoring already existing outputs
				for (int i=copyGens.list.Length-1; i>=0; i--)
				{
					Generator copyGen = copyGens.list[i];

					if (copyGen is IOutput && MapMagic.instance.gens.GetGenerator(gen.GetType())!=null)
					{
						Debug.Log ("MapMagic: tried to copy Output which already exists (" + copyGen + "). Skipping.");
						copyGens.UnlinkGenerator(copyGen);
						ArrayUtility.RemoveAt(ref copyGens.list, i);
					}

					copyGen.guiRect.position += new Vector2(0, gen.guiRect.height + 10);
				}

				ArrayUtility.AddRange(ref MapMagic.instance.gens.list, copyGens.list);
				MapMagic.instance.gens.ChangeGenerator(null);
				repaint=true; Repaint();
			}
Exemple #27
0
    static SyncCamera()
    {
        SceneView.onSceneGUIDelegate += (sceneView) => {
            if (SceneView.focusedWindow != sceneView)
            {
                return;
            }

            var cameras = Object.FindObjectsOfType <Camera> ();

            Handles.BeginGUI();

            GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);

            int windowID = EditorGUIUtility.GetControlID(FocusType.Passive, windowRect);

            windowRect = GUILayout.Window(windowID, windowRect, (id) => {
                string[] displayNames = new string[] { "None", "" };
                ArrayUtility.AddRange(ref displayNames, cameras.Select <Camera, string> (c => c.name).ToArray());
                selected = EditorGUILayout.Popup(selected, displayNames);

                GUI.DragWindow();
            }, "Sync Camera");

            Handles.EndGUI();

            int index = selected - 2;


            if (index >= 0)
            {
                var camera = cameras [index];
                camera.transform.position = sceneView.camera.transform.position;
                camera.transform.rotation = sceneView.camera.transform.rotation;
            }
        };
    }
        public override void Execute(UMake umake, UMakeTarget target)
        {
            Undo.RecordObject(umake, "UMakeBuildAction");

            string[] parts   = umake.version.Split(separator);
            int      version = 1;
            int      index   = (int)increaseVersionType;

            if (index >= parts.Length)
            {
                string[] versions = new string[(index + 1) - parts.Length];
                for (int i = 0; i < versions.Length; i++)
                {
                    versions[i] = "0";
                }
                ArrayUtility.AddRange(ref parts, versions);
            }
            else if (int.TryParse(parts[index], out version))
            {
                version += 1;
            }

            for (int i = index + 1; i < parts.Length;)
            {
                ArrayUtility.RemoveAt(ref parts, i);
            }

            parts[index]  = version.ToString();
            umake.version = string.Join(separator.ToString(), parts);

            if (updateApplicationVersion)
            {
                PlayerSettings.bundleVersion = umake.version;
                Debug.Log("The application is now with version " + Application.version);
            }
            EditorUtility.SetDirty(umake);
        }
Exemple #29
0
        ///<summary>Construct a tilemap from Tiled, adding named prefab instances based on Type.</summary>
        public override void OnImportAsset(AssetImportContext context)
        {
            var assetPathPrefix = Path.GetDirectoryName(assetPath) + Path.DirectorySeparatorChar;
            // TODO: Support ../source.tsx
            var tmx = new TMX(XDocument.Load(assetPath).Element("map"), assetPathPrefix);
            // if (tmx.infinite) {
            //throw new NotImplementedException("Infinite: " + tmx.infinite);
            // }
            var layout = tmx.orientation == "orthogonal"
                                ? GridLayout.CellLayout.Rectangle
                                : tmx.orientation == "isometric"
                                        ? GridLayout.CellLayout.Isometric
                                        : GridLayout.CellLayout.Hexagon;

            var gids   = new uint[tmx.layers.Length][][];
            var gidSet = new HashSet <uint>();

            // TODO: & 0x1fffffff the gidSet values from tile gids[]
            for (var i = 0; i < tmx.layers.Length; ++i)
            {
                var layer = tmx.layers[i];
                if (layer.data.chunks != null)                   // Tile layer
                {
                    gids[i] = new uint[layer.data.chunks.Length][];
                    for (var j = 0; j < gids[i].Length; ++j)
                    {
                        gids[i][j] = ParseGIDs(
                            layer.data.encoding,
                            layer.data.compression,
                            layer.data.chunks[j].value,
                            layer.width,
                            layout
                            );
                        gidSet.UnionWith(gids[i][j]);
                    }
                }
                else                     // Object layer
                {
                    foreach (var @object in layer.objects)
                    {
                        gidSet.Add(@object.gid & 0x1fffffff);
                    }
                }
            }

            // Tilesets
            var tiles = new Tile[1];             // Global Tile IDs start from 1

            foreach (var tsx in tmx.tilesets)
            {
                Tileset tileset = null;
                if (tsx.source == null)                   // Embedded tileset
                {
                    tileset = TSXImporter.Load(context, tsx);
                }
                else                     // External tileset
                {
                    var tilesetSource = "Assets" + Path.GetFullPath(assetPathPrefix + tsx.source).Substring(Application.dataPath.Length);
                    tileset = AssetDatabase.LoadAssetAtPath <Tileset>(tilesetSource);
                    context.DependsOnSourceAsset(tilesetSource);
                }
                var tilesetTiles = new Tile[tileset.tiles.Length];
                for (var i = 0; i < tilesetTiles.Length; ++i)
                {
                    if (!gidSet.Contains((uint)(i + tsx.firstgid)))
                    {
                        continue;
                    }
                    tilesetTiles[i] = tileset.tiles[i].Instantiate(tmx.tilewidth);
                    context.AddObjectToAsset($"tile{i + tsx.firstgid:0000}", tilesetTiles[i]);
                    context.AddObjectToAsset($"sprite{i + tsx.firstgid:0000}", tilesetTiles[i].sprite);
                    for (var j = 0; j < tilesetTiles[i].sprites.Length; ++j)
                    {
                        context.AddObjectToAsset($"frame{i + tsx.firstgid:0000}:{j}", tilesetTiles[i].sprites[j]);
                    }
                }
                ArrayUtility.AddRange(ref tiles, tilesetTiles);
            }

            // Grid
            var grid = new GameObject(Path.GetFileNameWithoutExtension(assetPath), typeof(Grid));

            grid.AddComponent <Rigidbody2D>().bodyType = RigidbodyType2D.Static;
            grid.isStatic = true;
            grid.GetComponent <Grid>().cellLayout = layout;
            grid.GetComponent <Grid>().cellSize   = new Vector3(1f, (float)tmx.tileheight / tmx.tilewidth, 1f);
            context.AddObjectToAsset("grid", grid);
            context.SetMainObject(grid);
            var collider = grid.AddComponent <CompositeCollider2D>();

            collider.generationType = CompositeCollider2D.GenerationType.Manual;

            // Layers
            PrefabHelper.cache.Clear();
            for (var i = 0; i < tmx.layers.Length; ++i)
            {
                var layer       = tmx.layers[i];
                var layerObject = new GameObject(layer.name);
                layerObject.transform.parent = grid.transform;
                layerObject.isStatic         = true;

                // Tile layer
                if (layer.data.chunks != null)
                {
                    // Tilemap
                    var tilemap  = layerObject.AddComponent <Tilemap>();
                    var renderer = layerObject.AddComponent <TilemapRenderer>();
                    layerObject.AddComponent <TilemapCollider2D>().usedByComposite = true;
                    tilemap.color             = new Color(1f, 1f, 1f, layer.opacity);
                    tilemap.orientation       = layout == GridLayout.CellLayout.Hexagon ? Tilemap.Orientation.Custom : Tilemap.Orientation.XY;
                    tilemap.orientationMatrix = Matrix4x4.TRS(
                        Vector3.zero,
                        Quaternion.Euler(0f, 180f, 180f),
                        Vector3.one
                        );
                    tilemap.transform.localScale = layout == GridLayout.CellLayout.Hexagon ? new Vector3(1f, -1f, 1f) : Vector3.one;
                    // Chunks
                    for (var j = 0; j < layer.data.chunks.Length; ++j)
                    {
                        var layerTiles = new Tile[gids[i][j].Length];
                        for (var k = 0; k < layerTiles.Length; ++k)
                        {
                            layerTiles[k] = tiles[gids[i][j][k] & 0x1ffffff];                             // 3 MSB are for flipping
                        }
                        var size   = new Vector3Int(layer.data.chunks[j].width, layer.data.chunks[j].height, 1);
                        var bounds = new BoundsInt(
                            new Vector3Int(
                                layer.width - layer.data.chunks[j].width + layer.data.chunks[j].x,
                                layer.height - layer.data.chunks[j].height - layer.data.chunks[j].y,
                                0
                                ),
                            size);
                        tilemap.SetTilesBlock(bounds, layerTiles);

                        // Flipped tiles
                        for (var k = 0; k < gids[i][j].Length; ++k)
                        {
                            var diagonal   = (gids[i][j][k] >> 29) & 1;
                            var vertical   = (gids[i][j][k] >> 30) & 1;
                            var horizontal = (gids[i][j][k] >> 31) & 1;
                            var flips      = new Vector4(diagonal, vertical, horizontal, 0);
                            if (flips.sqrMagnitude > 0f)
                            {
                                var position = new Vector3Int(
                                    layer.width - layer.data.chunks[j].width + k % layer.data.chunks[j].width,
                                    layer.height - layer.data.chunks[j].height + k / layer.data.chunks[j].width,
                                    0
                                    );
                                var transform = Matrix4x4.TRS(
                                    Vector3.zero,
                                    Quaternion.AngleAxis(diagonal * 180, new Vector3(1, 1, 0)),
                                    Vector3.one - (diagonal == 1 ? new Vector3(flips.y, flips.z, flips.w) : new Vector3(flips.z, flips.y, flips.w)) * 2
                                    );
                                tilemap.SetTransformMatrix(position, transform);
                            }
                        }
                    }


                    renderer.sortOrder    = layout == GridLayout.CellLayout.Hexagon ? TilemapRenderer.SortOrder.BottomLeft : TilemapRenderer.SortOrder.TopLeft;
                    renderer.sortingOrder = i;

                    // Object layer
                }
                else
                {
                    var objects = layer.objects;                    //layer.Elements("object").ToArray();
                    foreach (var @object in objects)
                    {
                        var        tile = tiles[@object.gid & 0x1fffffff];
                        string     icon = null;
                        GameObject gameObject;                         // Doubles as prefab when object has type

                        // Default instantiation when object has no set type
                        if (string.IsNullOrEmpty(@object.type))
                        {
                            gameObject = new GameObject($"{@object.name} {@object.id}".Trim());
                            icon       = "sv_label_0";

                            // Warn instantiation when object has type but no prefab was found
                        }
                        else if (null == (gameObject = PrefabHelper.Load(@object.type, context)))
                        {
                            var gameObjectName = string.IsNullOrEmpty(@object.name) ? @object.type : @object.name;
                            gameObject = new GameObject($"{gameObjectName} {@object.id}".Trim());
                            icon       = "sv_label_6";

                            // Prefab instantiation based on object type
                        }
                        else
                        {
                            gameObject      = PrefabUtility.InstantiatePrefab(gameObject) as GameObject;
                            gameObject.name = $"{@object.name} {@object.id}".Trim();
                            foreach (var component in gameObject.GetComponentsInChildren <MonoBehaviour>())
                            {
                                ApplyProperties(@object.properties, component);
                            }
                        }

                        gameObject.transform.parent = layerObject.transform;

                        // Object sprite
                        var sprite = tile?.sprite;
                        if (sprite)
                        {
                            var diagonal   = ((@object.gid >> 29) & 1) == 1 ? true : false;
                            var vertical   = ((@object.gid >> 30) & 1) == 1 ? true : false;
                            var horizontal = ((@object.gid >> 31) & 1) == 1 ? true : false;
                            gameObject.transform.localRotation *= Quaternion.Euler(0f, 0f, [email protected]);
                            gameObject.transform.localRotation *= Quaternion.Euler(vertical ? 180f : 0f, horizontal ? 180f : 0f, 0f);
                            gameObject.transform.localPosition  = new Vector3(@object.x / tmx.tilewidth, [email protected] / tmx.tileheight + tmx.height, 0);
                            gameObject.transform.localPosition += horizontal ? -gameObject.transform.right * @object.width / tmx.tilewidth : Vector3.zero;
                            gameObject.transform.localPosition += vertical ? -gameObject.transform.up * @object.height / tmx.tileheight : Vector3.zero;
                            var renderer = new GameObject("Renderer").AddComponent <SpriteRenderer>();
                            renderer.transform.SetParent(gameObject.transform, worldPositionStays: false);
                            renderer.sprite                  = sprite;
                            renderer.sortingOrder            = i;
                            renderer.spriteSortPoint         = SpriteSortPoint.Pivot;
                            renderer.drawMode                = SpriteDrawMode.Sliced;              // HACK: Makes renderer.size work
                            renderer.size                    = new Vector2(@object.width, @object.height) / tmx.tilewidth;
                            renderer.color                   = new Color(1f, 1f, 1f, layer.opacity);
                            renderer.transform.localPosition = new Vector3(@object.width / tmx.tilewidth / 2f, @object.height / tmx.tileheight / 2f);
                        }
                        else
                        {
                            gameObject.transform.localPosition =
                                new Vector3(@object.x / tmx.tileheight, [email protected] / tmx.tileheight + tmx.height - @object.height / tmx.tileheight, 0);
                        }

                        // Icon
                        if (icon != null)
                        {
                            InternalEditorGUIHelper.SetIconForObject(
                                gameObject,
                                EditorGUIUtility.IconContent(icon).image
                                );
                        }
                    }
                }
            }

            collider.generationType = CompositeCollider2D.GenerationType.Synchronous;
        }
Exemple #30
0
    private void Update()
    {
        if (Application.isPlaying)
        {
            return;
        }

        if (Image == null)
        {
            Image = GetComponentInChildren <BackgroundImage>();
        }

        // Change image
        if (BackgroundImg != _currentImgType)
        {
            _currentImgType = BackgroundImg;

            var imgName        = BackgroundImg.ToString().ToLower();
            var imgAssetAtPath = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/Sprites/backgrounds/" + imgName + "-bg.png");
            Image.texture = imgAssetAtPath;
        }

        if (Image == null)
        {
            return;
        }

        // Get lists of ArchetypeMove transforms ordered by x/y pos
        MonoBehaviour[] layoutObjects = FindObjectsOfType <ArchetypeMove>();
        MonoBehaviour[] props         = FindObjectsOfType <ArchetypeProp>();
        ArrayUtility.AddRange(ref layoutObjects, props);

        var transformsY = layoutObjects.Select(t => t.transform).Where(t => t.gameObject.layer != 8).OrderBy(t => t.position.y).ToArray();
        var transformsX = layoutObjects.Select(t => t.transform).Where(t => t.gameObject.layer != 8).OrderBy(t => t.position.x).ToArray();

        if (transformsX.Length == 0 || transformsY.Length == 0)
        {
            return;
        }

        var xPosFirst = transformsX.First().position;
        var yPosLast  = transformsY.Last().position;

        var topLeftPos = new Vector3(xPosFirst.x, yPosLast.y);

        // L/R game boundaries
        var rightBound = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, Camera.main.nearClipPlane)).x;
        var leftBound  = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, Camera.main.nearClipPlane)).x;

        if (_canvasRect == null)
        {
            _canvasRect = GetComponent <RectTransform>();
        }

        // Size and position canvas of sprite
        _canvasRect.sizeDelta = new Vector2(rightBound - leftBound, topLeftPos.y + 6);

        var sizeY = _canvasRect.rect.height;
        var repY  = sizeY / SquareSize;

        var imgRect = Image.uvRect;

        imgRect.height = repY;
        Image.uvRect   = imgRect;
    }