Esempio n. 1
0
        void DrawCustomInspector()
        {
            GUILayoutOption option = GUILayout.MinWidth(82f);

            GUILayout.BeginHorizontal();
            {
                bool reset = GUILayout.Button("Reset", option);
                bool copy  = GUILayout.Button("Copy", option);
                bool paste = GUILayout.Button("Paste", option);

                if (reset)
                {
                    SerializedProperties["m_AnchoredPosition"].vector2Value = Vector2.zero;
                    SerializedProperties["m_LocalPosition"].vector3Value    = Vector3.zero;
                    SerializedProperties["m_SizeDelta"].vector2Value        = Vector2.zero;
                    SerializedProperties["m_AnchorMin"].vector2Value        = new Vector2(.5f, .5f);
                    SerializedProperties["m_AnchorMax"].vector2Value        = new Vector2(.5f, .5f);
                    SerializedProperties["m_Pivot"].vector2Value            = new Vector2(.5f, .5f);
                    SerializedProperties["m_LocalRotation"].quaternionValue = Quaternion.identity;
                    SerializedProperties["m_LocalScale"].vector3Value       = Vector3.one;
                }
                if (copy)
                {
                    ComponentUtility.CopyComponent(serializedObject.targetObject as Component);
                }
                if (paste)
                {
                    foreach (var targetObject in serializedObject.targetObjects)
                    {
                        ComponentUtility.PasteComponentValues(targetObject as Component);
                    }
                }
            }
            GUILayout.EndHorizontal();
        }
Esempio n. 2
0
        private static void     Clone(MenuCommand menuCommand)
        {
            Component component = menuCommand.context as Component;

            if (ComponentUtility.CopyComponent(component) == true)
            {
                if (ComponentUtility.PasteComponentAsNew(component.gameObject) == true)
                {
                    Component[] c = component.gameObject.GetComponents <Component>();

                    for (int i = 0; i < c.Length; i++)
                    {
                        if (c[i] == component)
                        {
                            while (i++ < c.Length - 2 && ComponentUtility.MoveComponentUp(c[c.Length - 1]) == true)
                            {
                                ;
                            }
                            break;
                        }
                    }
                }
                else
                {
                    EditorUtility.DisplayDialog(LC.G("CloneComponent_Error_Title"), LC.G("CloneComponent_Error_Message"), LC.G("Yes"));
                }
            }
        }
Esempio n. 3
0
        private void OnEnable()
        {
            this.m_Script     = serializedObject.FindProperty("m_Script");
            this.m_WindowName = serializedObject.FindProperty("m_WindowName");
            EquipmentHandler handler = target as EquipmentHandler;

            gameObject = handler.gameObject;

            VisibleItem[] visibleItems = gameObject.GetComponents <VisibleItem>();
            for (int i = 0; i < visibleItems.Length; i++)
            {
                visibleItems[i].hideFlags = EditorPrefs.GetBool("InventorySystem.showAllComponents") ? HideFlags.None : HideFlags.HideInInspector;
            }

            if (!EditorApplication.isPlaying)
            {
                for (int i = 0; i < handler.VisibleItems.Count; i++)
                {
                    if (handler.VisibleItems[i].gameObject != gameObject)
                    {
                        if (ComponentUtility.CopyComponent(handler.VisibleItems[i]))
                        {
                            VisibleItem compoent = gameObject.AddComponent(handler.VisibleItems[i].GetType()) as VisibleItem;
                            ComponentUtility.PasteComponentValues(compoent);
                            handler.VisibleItems[i] = compoent;
                        }
                    }
                }
            }
            EditorApplication.playModeStateChanged += PlayModeState;
        }
Esempio n. 4
0
        protected void Paste()
        {
            var block     = target as Block;
            var flowchart = (Flowchart)block.GetFlowchart();

            if (flowchart == null ||
                flowchart.SelectedBlock == null)
            {
                return;
            }

            CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance();

            // Find where to paste commands in block (either at end or after last selected command)
            int pasteIndex = flowchart.SelectedBlock.CommandList.Count;

            if (flowchart.SelectedCommands.Count > 0)
            {
                for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; ++i)
                {
                    Command command = flowchart.SelectedBlock.CommandList[i];

                    foreach (Command selectedCommand in flowchart.SelectedCommands)
                    {
                        if (command == selectedCommand)
                        {
                            pasteIndex = i + 1;
                        }
                    }
                }
            }

            foreach (Command command in commandCopyBuffer.GetCommands())
            {
                // Using the Editor copy / paste functionality instead instead of reflection
                // because this does a deep copy of the command properties.
                if (ComponentUtility.CopyComponent(command))
                {
                    if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject))
                    {
                        Command[] commands      = flowchart.GetComponents <Command>();
                        Command   pastedCommand = commands.Last <Command>();
                        if (pastedCommand != null)
                        {
                            pastedCommand.ItemId = flowchart.NextItemId();
                            flowchart.SelectedBlock.CommandList.Insert(pasteIndex++, pastedCommand);
                        }
                    }

                    // This stops the user pasting the command manually into another game object.
                    ComponentUtility.CopyComponent(flowchart.transform);
                }
            }

            // Because this is an async call, we need to force prefab instances to record changes
            PrefabUtility.RecordPrefabInstancePropertyModifications(block);

            Repaint();
        }
Esempio n. 5
0
    void DoPrefabAction(GameObject target, bool connect)
    {
        if (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab)
        {
            return;
        }

        GameObject newTarget;

        if (connect)
        {
            Undo.RegisterCreatedObjectUndo(newTarget = (GameObject)PrefabUtility.InstantiatePrefab(prefab), "Created Prefab Instance of " + (prefab ? prefab.name : "null"));
        }
        else
        {
            Undo.RegisterCreatedObjectUndo(newTarget = new GameObject(), "Created non-Prefab Instance of " + (prefab ? prefab.name : "null"));
        }

        Component[] components = target.GetComponents <Component>();

        newTarget.name             = target.name;
        newTarget.transform.parent = target.transform.parent;
        for (int i = 0; i < components.Length; i++)
        {
            if (ComponentUtility.CopyComponent(components[i]))
            {
                var comp = newTarget.GetComponent(components[i].GetType());
                if (comp)
                {
                    ComponentUtility.PasteComponentValues(comp);
                }
                else
                {
                    ComponentUtility.PasteComponentAsNew(newTarget);
                }
            }
        }

        ObjectReferenceUtility.ReplaceAllReferences(target, newTarget);

        if (keepChildren)
        {
            foreach (Transform child in target.transform)
            {
                Vector3    localPos   = child.localPosition;
                Quaternion localRot   = child.localRotation;
                Vector3    localScale = child.localScale;
                child.parent        = newTarget.transform;
                child.localPosition = localPos;
                child.localRotation = localRot;
                child.localScale    = localScale;
            }
        }

        Undo.DestroyObjectImmediate(target);

        Selection.activeGameObject = newTarget;
    }
Esempio n. 6
0
        private void OnEnable()
        {
            this.m_Controller = target as ThirdPersonController;
            this.m_GameObject = this.m_Controller.gameObject;
            this.m_Script     = serializedObject.FindProperty("m_Script");
            this.m_Motions    = serializedObject.FindProperty("m_Motions");

            this.m_MotionList = new ReorderableList(serializedObject, this.m_Motions, true, true, true, true)
            {
                drawHeaderCallback            = new ReorderableList.HeaderCallbackDelegate(DrawMotionHeader),
                drawElementCallback           = new ReorderableList.ElementCallbackDelegate(DrawMotion),
                onAddDropdownCallback         = new ReorderableList.AddDropdownCallbackDelegate(AddMotion),
                onRemoveCallback              = new ReorderableList.RemoveCallbackDelegate(RemoveMotion),
                onSelectCallback              = new ReorderableList.SelectCallbackDelegate(SelectMotion),
                drawElementBackgroundCallback = new ReorderableList.ElementCallbackDelegate(DrawMotionBackground)
            };
            int motionIndex = EditorPrefs.GetInt("MotionIndex" + target.GetInstanceID().ToString(), -1);

            if (this.m_MotionList.count > motionIndex)
            {
                this.m_MotionList.index = motionIndex;
                SelectMotion(this.m_MotionList);
            }
            MotionState[] states = this.m_Controller.GetComponents <MotionState> ();
            for (int i = 0; i < states.Length; i++)
            {
                states [i].hideFlags = HideFlags.HideInInspector;
            }

            this.m_NotReferencedMotions = new List <MotionState>();
            for (int i = 0; i < states.Length; i++)
            {
                if (!this.m_Controller.Motions.Contains(states[i]))
                {
                    this.m_NotReferencedMotions.Add(states[i]);
                }
            }


            for (int i = 0; i < this.m_Controller.Motions.Count; i++)
            {
                if (this.m_Controller.Motions[i] != null)
                {
                    if (this.m_Controller.Motions[i].gameObject != this.m_GameObject)
                    {
                        if (ComponentUtility.CopyComponent(this.m_Controller.Motions[i]))
                        {
                            MotionState component = this.m_GameObject.AddComponent(this.m_Controller.Motions[i].GetType()) as MotionState;
                            ComponentUtility.PasteComponentValues(component);
                            this.m_Controller.Motions[i] = component;
                        }
                    }
                }
            }
            EditorApplication.playModeStateChanged += PlayModeState;
        }
Esempio n. 7
0
    private void GeneratePaths()
    {
        if (_pathsCount == 0 || !_pathsTransform)
        {
            return;
        }
        if (!ComponentUtility.CopyComponent(_track))
        {
            return;
        }

        _paths = new PathCreator[_pathsCount];

        while (_pathsTransform.childCount > 0)
        {
            DestroyImmediate(_pathsTransform.GetChild(0).gameObject);
        }

        var trackTransform  = _track.transform;
        var trackPath       = _track.path;
        var trackBezierPath = _track.bezierPath;

        for (var i = 0; i < _pathsCount; i++)
        {
            var go = new GameObject($"Path {i}");
            go.transform.SetParent(_pathsTransform);

            var xOffset = Mathf.Lerp(-_pathWidth, _pathWidth, (float)i / (_pathsCount - 1));

            go.transform.position = trackTransform.position;
            _paths[i]             = go.AddComponent <PathCreator>();
            ComponentUtility.PasteComponentValues(_paths[i]);

            for (var j = 0; j < trackBezierPath.NumPoints; j++)
            {
                var point = trackBezierPath.GetPoint(j);
                var time  = (float)j / (trackBezierPath.NumPoints - 1);

                var normal    = trackPath.GetNormal(time, EndOfPathInstruction.Stop);
                var direction = trackPath.GetDirection(time, EndOfPathInstruction.Stop);

                var positionOffset = xOffset * -Vector3.Cross(normal, direction);

                if (j < 2)
                {
                    positionOffset += direction * _pathStartOffset;
                }
                else if (j > trackBezierPath.NumPoints - 3)
                {
                    positionOffset += -direction * _pathEndOffset;
                }

                _paths[i].bezierPath.SetPoint(j, point + positionOffset, true);
            }
        }
    }
Esempio n. 8
0
        protected static void DuplicateBlock(object obj)
        {
            var   flowchart = GetFlowchart();
            Block block     = obj as Block;

            Vector2 newPosition = new Vector2(block._NodeRect.position.x +
                                              block._NodeRect.width + 20,
                                              block._NodeRect.y);

            Block oldBlock = block;

            Block newBlock = FlowchartWindow.CreateBlock(flowchart, newPosition);

            newBlock.BlockName = flowchart.GetUniqueBlockKey(oldBlock.BlockName + " (Copy)");

            Undo.RecordObject(newBlock, "Duplicate Block");

            var commandList = oldBlock.CommandList;

            foreach (var command in commandList)
            {
                if (ComponentUtility.CopyComponent(command))
                {
                    if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject))
                    {
                        Command[] commands      = flowchart.GetComponents <Command>();
                        Command   pastedCommand = commands.Last <Command>();
                        if (pastedCommand != null)
                        {
                            pastedCommand.ItemId = flowchart.NextItemId();
                            newBlock.CommandList.Add(pastedCommand);
                        }
                    }

                    // This stops the user pasting the command manually into another game object.
                    ComponentUtility.CopyComponent(flowchart.transform);
                }
            }

            if (oldBlock._EventHandler != null)
            {
                if (ComponentUtility.CopyComponent(oldBlock._EventHandler))
                {
                    if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject))
                    {
                        EventHandler[] eventHandlers      = flowchart.GetComponents <EventHandler>();
                        EventHandler   pastedEventHandler = eventHandlers.Last <EventHandler>();
                        if (pastedEventHandler != null)
                        {
                            pastedEventHandler.ParentBlock = newBlock;
                            newBlock._EventHandler         = pastedEventHandler;
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        public static void CopyToPasteboardAsTransform(Vector3 position, Vector3 rotation)
        {
            GameObject gameObject = new GameObject();

            gameObject.transform.position = position;
            gameObject.transform.rotation = Quaternion.Euler(rotation);

            ComponentUtility.CopyComponent(gameObject.transform);
            Object.DestroyImmediate(gameObject);
        }
Esempio n. 10
0
 void UpdateCamFromMain()
 {
     if (targetCam != null)
     {
         if (ComponentUtility.CopyComponent(targetCam))
         {
             ComponentUtility.PasteComponentValues(previewCam);
         }
     }
 }
Esempio n. 11
0
        protected void Paste()
        {
            Sequence     sequence     = target as Sequence;
            FungusScript fungusScript = sequence.GetFungusScript();

            if (fungusScript == null ||
                fungusScript.selectedSequence == null)
            {
                return;
            }

            CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance();

            // Find where to paste commands in sequence (either at end or after last selected command)
            int pasteIndex = fungusScript.selectedSequence.commandList.Count;

            if (fungusScript.selectedCommands.Count > 0)
            {
                for (int i = 0; i < fungusScript.selectedSequence.commandList.Count; ++i)
                {
                    Command command = fungusScript.selectedSequence.commandList[i];

                    foreach (Command selectedCommand in fungusScript.selectedCommands)
                    {
                        if (command == selectedCommand)
                        {
                            pasteIndex = i + 1;
                        }
                    }
                }
            }

            foreach (Command command in commandCopyBuffer.GetCommands())
            {
                // Using the Editor copy / paste functionality instead instead of reflection
                // because this does a deep copy of the command properties.
                if (ComponentUtility.CopyComponent(command))
                {
                    if (ComponentUtility.PasteComponentAsNew(fungusScript.gameObject))
                    {
                        Command[] commands      = fungusScript.GetComponents <Command>();
                        Command   pastedCommand = commands.Last <Command>();
                        if (pastedCommand != null)
                        {
                            fungusScript.selectedSequence.commandList.Insert(pasteIndex++, pastedCommand);
                        }
                    }

                    // This stops the user pasting the command manually into another game object.
                    ComponentUtility.CopyComponent(fungusScript.transform);
                }
            }

            Repaint();
        }
Esempio n. 12
0
 public void Load()
 {
     foreach (var item in toLoad.GetComponents <MonoBehaviour>())
     {
         if (item.GetType() != typeof(Package))
         {
             ComponentUtility.CopyComponent(item);
             ComponentUtility.PasteComponentAsNew(gameObject);
         }
     }
     loaded = true;
 }
Esempio n. 13
0
    static void CopyComponentIfExist <T>(GameObject src, GameObject dest, bool isOnlyValue = false) where T : Component
    {
        T t = src.GetComponent <T>();

        if (t)
        {
            ComponentUtility.CopyComponent(t);
            if (isOnlyValue && dest.GetComponent <T>())
            {
                ComponentUtility.PasteComponentValues(dest.GetComponent <T>());
            }
            else
            {
                ComponentUtility.PasteComponentAsNew(dest);
            }
        }
    }
Esempio n. 14
0
        private void DrawControlsToolbar()
        {
            EditorGUILayout.BeginHorizontal();
            {
                if (eGUI.ButtonMini("▼", "Move Down", eGUI.greenLt, 30))
                {
                    ComponentUtility.MoveComponentDown(_target);
                }
                if (eGUI.ButtonMini("▲", "Move Up", eGUI.greenLt, 30))
                {
                    ComponentUtility.MoveComponentUp(_target);
                }
                if (eGUI.ButtonMini("", eIcons.Get("Assets/Smart/Core/Editor/Icons/Tools/ClipboardPaste.png"), "Past New Component After This One", eGUI.greenLt, 30) && ComponentUtility.PasteComponentAsNew(_target.gameObject))
                {
                    var components   = _target.GetComponents <Component>();
                    var newComponent = components.Last();
                    var cnt          = components.Length - components.IndexOf(_target) - 2;
                    while (cnt-- > 0)
                    {
                        ComponentUtility.MoveComponentUp(newComponent);
                    }
                }

                GUILayout.FlexibleSpace();

                if (eGUI.ButtonMini("", eIcons.Get("Assets/Smart/Core/Editor/Icons/Tools/ClipboardCopy.png"), "Copy Component", eGUI.azureLt, 30))
                {
                    ComponentUtility.CopyComponent(_target);
                }
                if (eGUI.ButtonMini("", eIcons.Get("Assets/Smart/Core/Editor/Icons/Tools/ClipboardPaste.png"), eGUI.azureLt, 30))
                {
                    ComponentUtility.PasteComponentValues(_target);
                }

                GUILayout.FlexibleSpace();

                if (eGUI.ButtonMini("", eIcons.Get("icons/d_p4_deletedlocal.png"), "Remove Component", eGUI.crimsonLt, 30))
                {
                    DestroyImmediate(_target);
                }
            }
            EditorGUILayout.EndHorizontal();
        }
Esempio n. 15
0
 private void AddSecondaryCameraComponents(Camera targetCamera, MonoBehaviour vuforiaBehaviour)
 {
     if (targetCamera.GetComponent <VideoBackgroundAbstractBehaviour>() == null)
     {
         VideoBackgroundAbstractBehaviour[] componentsInChildren = vuforiaBehaviour.GetComponentsInChildren <VideoBackgroundAbstractBehaviour>(true);
         if (componentsInChildren.Length != 0 && ComponentUtility.CopyComponent(componentsInChildren[0]))
         {
             ComponentUtility.PasteComponentAsNew(targetCamera.gameObject);
         }
     }
     if (targetCamera.GetComponent <HideExcessAreaAbstractBehaviour>() == null)
     {
         HideExcessAreaAbstractBehaviour[] componentsInChildren2 = vuforiaBehaviour.GetComponentsInChildren <HideExcessAreaAbstractBehaviour>(true);
         if (componentsInChildren2.Length != 0 && ComponentUtility.CopyComponent(componentsInChildren2[0]))
         {
             ComponentUtility.PasteComponentAsNew(targetCamera.gameObject);
         }
     }
 }
        private void OnGUI()
        {
            this.m_Source      = EditorGUILayout.ObjectField("Source", this.m_Source, typeof(GameObject), true) as GameObject;
            this.m_Destination = EditorGUILayout.ObjectField("Destination", this.m_Destination, typeof(GameObject), true) as GameObject;
            if (this.m_Source == null || this.m_Destination == null)
            {
                return;
            }

            if (this.m_ComponentMap == null)
            {
                this.m_ComponentMap = new Dictionary <Component, bool>();
                Component[] components = this.m_Source.GetComponents <Component>().Where(x => x.hideFlags == HideFlags.None).ToArray();
                for (int i = 0; i < components.Length; i++)
                {
                    if (ComponentUtility.CopyComponent(components[i]))
                    {
                        this.m_ComponentMap.Add(components[i], true);
                    }
                }
            }
            this.m_ScrollPosition = EditorGUILayout.BeginScrollView(this.m_ScrollPosition);
            GUILayout.Label("Components", EditorStyles.boldLabel);
            for (int i = 0; i < this.m_ComponentMap.Count; i++)
            {
                this.m_ComponentMap[this.m_ComponentMap.ElementAt(i).Key] = EditorGUILayout.Toggle(this.m_ComponentMap.ElementAt(i).Key.GetType().Name, this.m_ComponentMap.ElementAt(i).Value);
            }
            EditorGUILayout.EndScrollView();

            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Copy Components"))
            {
                foreach (KeyValuePair <Component, bool> kvp in this.m_ComponentMap)
                {
                    if (kvp.Value && ComponentUtility.CopyComponent(kvp.Key))
                    {
                        Component component = this.m_Destination.AddComponent(kvp.Key.GetType()) as Component;
                        ComponentUtility.PasteComponentValues(component);
                    }
                }
                Selection.activeObject = m_Destination;
            }
        }
Esempio n. 17
0
            private bool CopyValue <T>(GameObject srcGO, GameObject destGO) where T : Component
            {
                T src = srcGO.GetComponent <T>();

                if (src == null)
                {
                    return(false);
                }
                T dest = destGO.GetComponent <T>();

                if (dest == null)
                {
                    dest = destGO.AddComponent <T>();
                }
                //复制粘贴Component的值
                ComponentUtility.CopyComponent(src);
                ComponentUtility.PasteComponentValues(dest);
                return(true);
            }
 private void SetTarget()
 {
     _selected = Selection.activeGameObject;
     if (_selected != null && _selected.GetComponent <RectTransform>() != null)
     {
         _targetTransform = _selected.GetComponent <RectTransform>();
         _isValidTarget   = true;
         _tempTransform.transform.SetParent(_targetTransform, false);
         _sourceTransform.transform.SetParent(_targetTransform, false);
         ComponentUtility.CopyComponent(_targetTransform);
         ComponentUtility.PasteComponentValues(_tempTransform);
     }
     else
     {
         _isValidTarget = false;
         _tempGameObject.transform.SetParent(_canvas.transform, false);
         _sourceGameObject.transform.SetParent(_canvas.transform, false);
     }
 }
Esempio n. 19
0
    /// <summary>
    /// Encapsulate all object components into child brick.
    /// </summary>
    void Encapsualte(AgaQBrick brick)
    {
        //create new GameObject
        var childBrick = new GameObject("brick");

        childBrick.transform.SetParent(brick.transform);
        childBrick.transform.localPosition = Vector3.zero;

        //move all children from brick to childBrick
        for (int i = brick.transform.childCount - 1; i >= 0; i--)
        {
            var child = brick.transform.GetChild(i);
            if (child != childBrick.transform)
            {
                child.SetParent(childBrick.transform);
            }
        }

        //move all colliders
        var colliders = brick.GetComponents <Collider>();

        foreach (var collider in colliders)
        {
            ComponentUtility.CopyComponent(collider);
            ComponentUtility.PasteComponentAsNew(childBrick);
            DestroyImmediate(collider);
        }

        //move mesh
        var meshFilter = brick.GetComponent <MeshFilter>();
        var renderer   = brick.GetComponent <MeshRenderer>();

        if (meshFilter != null && renderer != null)
        {
            ComponentUtility.CopyComponent(meshFilter);
            ComponentUtility.PasteComponentAsNew(childBrick);
            ComponentUtility.CopyComponent(renderer);
            ComponentUtility.PasteComponentAsNew(childBrick);
            DestroyImmediate(renderer);
            DestroyImmediate(meshFilter);
        }
    }
Esempio n. 20
0
    public bool AddRendererToEditorCamera()
    {
        //Get The editor cam
        Camera editorCam = EditorWindow.GetWindow <SceneView>().camera;
        //see the number of renderers attached to it
        int nbOfRenderers = editorCam.gameObject.GetComponents <Tex3DRenderer>().Length;

        print(nbOfRenderers);

        //No renderers are attached
        if (nbOfRenderers == 0)
        {
            //add a renderer with default params
            editorRenderer = editorCam.gameObject.AddComponent <Tex3DRenderer>();
        }

        //Get the renderer with the needed params
        Component mainRenderer = rendererHolder.GetComponent <Tex3DRenderer>();

        //copy its values
        if (ComponentUtility.CopyComponent(mainRenderer))
        {
            print("Component copied!");
            if (ComponentUtility.PasteComponentValues(editorRenderer))
            {
                print("Component values pasted!");
                print("Added Tex3DRenderer to editor camera");
            }
            else
            {
                return(false);
            }
        }
        else
        {
            return(false);
        }


        this.editorRenderer = editorCam.GetComponent <Tex3DRenderer>();
        return(true);
    }
            public void Copy()
            {
                if (!m_SourceComponent)
                {
                    return;
                }

                if (!Target)
                {
                    Debug.LogError("Expected m_Target, but it's null.");
                    return;
                }

                m_TargetComponent = m_TargetComponent ? m_TargetComponent : Target.AddComponent(m_SourceComponent.GetType());

                if (ComponentUtility.CopyComponent(m_SourceComponent))
                {
                    ComponentUtility.PasteComponentValues(m_TargetComponent);
                }
            }
    static void PasteAllComponents()
    {
        var selection = Selection.activeGameObject;

        if (selection != null)
        {
            for (int i = 0; i < Clipboard.Length; i++)
            {
                ComponentUtility.CopyComponent(Clipboard[i]);
                var component = selection.GetComponent(Clipboard[i].GetType());
                if (component != null)
                {
                    ComponentUtility.PasteComponentValues(component);
                }
                else
                {
                    ComponentUtility.PasteComponentAsNew(selection);
                }
            }
        }
    }
Esempio n. 23
0
    // see: http://answers.unity3d.com/questions/458207/copy-a-component-at-runtime.html
    public static bool CopyComponent <T>(T src, GameObject destinationObj) where T : Component
    {
        System.Type type = typeof(T);
        var         dst  = destinationObj.GetComponent <T> ();

        if (dst == null)
        {
            dst = (T)destinationObj.AddComponent(type);
        }

        // see: http://answers.unity3d.com/answers/603984/view.html
        return(ComponentUtility.CopyComponent(src) && ComponentUtility.PasteComponentValues(dst));

        //		System.Reflection.FieldInfo[] fields = type.GetFields(
        //			BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly | BindingFlags.FlattenHierarchy);
        //		foreach (System.Reflection.FieldInfo field in fields)
        //		{
        //			field.SetValue(dst, field.GetValue(original));
        //		}
        //		return dst as T;
    }
        /// <summary>
        /// コピー先にVRMSpringBoneColliderGroupが存在しなければ、コピー元のVRMSpringBoneColliderGroupをすべてコピーします。
        /// </summary>
        /// <param name="sourceBone"></param>
        /// <param name="destinationBone"></param>
        private static void CopySpringBoneColliderGroups(Transform sourceBone, Transform destinationBone)
        {
            if (destinationBone.GetComponent <VRMSpringBoneColliderGroup>())
            {
                return;
            }

            foreach (var sourceColliderGroup in sourceBone.GetComponents <VRMSpringBoneColliderGroup>())
            {
                ComponentUtility.CopyComponent(sourceColliderGroup);
                ComponentUtility.PasteComponentAsNew(destinationBone.gameObject);

                // 正規化されていないモデルに対応するため、オフセットをルートからの相対的な向きに
                var colliderGroup = destinationBone.GetComponents <VRMSpringBoneColliderGroup>().Last();
                foreach (var collider in colliderGroup.Colliders)
                {
                    collider.Offset = destinationBone.InverseTransformPoint(
                        sourceBone.TransformPoint(collider.Offset) - sourceBone.transform.position
                        + destinationBone.position
                        );
                }
            }
        }
Esempio n. 25
0
        private void OnGUI()
        {
            this.m_Source      = EditorGUILayout.ObjectField("Source", this.m_Source, typeof(GameObject), true) as GameObject;
            this.m_Destination = EditorGUILayout.ObjectField("Destination", this.m_Destination, typeof(GameObject), true) as GameObject;
            if (this.m_Source == null || this.m_Destination == null)
            {
                return;
            }

            Component[] components = this.m_Source.GetComponents <Component>().Where(x => x.hideFlags == HideFlags.None).ToArray();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Copy Components"))
            {
                for (int i = 0; i < components.Length; i++)
                {
                    if (ComponentUtility.CopyComponent(components[i]))
                    {
                        Component component = this.m_Destination.AddComponent(components[i].GetType()) as Component;
                        ComponentUtility.PasteComponentValues(component);
                    }
                }
                Selection.activeObject = m_Destination;
            }
        }
Esempio n. 26
0
        private static void ApplyTransformToColliders(Transform tr)
        {
            foreach (var go in tr.gameObject.GetAllChildrenAndThisDescending())
            {
                if (!go.activeSelf)
                {
                    continue;
                }
                if (go.transform.localRotation != Quaternion.identity)
                {
                    continue;
                }

                var pos = go.transform.localPosition;
                go.transform.localPosition = Vector3.zero;

                var size = go.transform.localScale;
                go.transform.localScale = Vector3.one;

                foreach (var bc in go.GetFirstDepthChildrenComponents <BoxCollider>())
                {
                    if (bc.transform != go.transform && bc.transform.rotation == go.transform.rotation)
                    {
                        bc.center += Vector3.Scale(bc.transform.localPosition, bc.transform.localScale);
                        bc.size    = Vector3.Scale(bc.size, bc.transform.localScale);
                    }

                    bc.size    = Vector3.Scale(bc.size, size);
                    bc.center  = Vector3.Scale(bc.center, size);
                    bc.center += pos;

                    if (bc.transform != go.transform && bc.transform.rotation == go.transform.rotation)
                    {
                        ComponentUtility.CopyComponent(bc);
                        ComponentUtility.PasteComponentAsNew(go);
                        DestroyImmediate(bc);
                    }
                }

                foreach (var cc in go.GetFirstDepthChildrenComponents <CapsuleCollider>())
                {
                    if (cc.transform != go.transform && cc.transform.rotation == go.transform.rotation)
                    {
                        cc.center += Vector3.Scale(cc.transform.localPosition, cc.transform.localScale);
                        var lcs = cc.transform.localScale;
                        cc.height *= lcs[cc.direction];
                        cc.radius *=
                            cc.direction == 0
                                ? Mathf.Max(lcs.y, lcs.z)
                                : cc.direction == 1
                                    ? Mathf.Max(lcs.x, lcs.z)
                                    : Mathf.Max(lcs.x, lcs.y);
                    }

                    cc.center  = Vector3.Scale(cc.center, size);
                    cc.center += pos;
                    cc.height *= size[cc.direction];
                    cc.radius *=
                        cc.direction == 0
                            ? Mathf.Max(size.y, size.z)
                            : cc.direction == 1
                                ? Mathf.Max(size.x, size.z)
                                : Mathf.Max(size.x, size.y);


                    if (cc.transform != go.transform && cc.transform.rotation == go.transform.rotation)
                    {
                        ComponentUtility.CopyComponent(cc);
                        ComponentUtility.PasteComponentAsNew(go);
                        DestroyImmediate(cc);
                    }
                }

                foreach (var sc in go.GetFirstDepthChildrenComponents <SphereCollider>())
                {
                    if (sc.transform != go.transform && sc.transform.rotation == go.transform.rotation)
                    {
                        sc.center += Vector3.Scale(sc.transform.localPosition, sc.transform.localScale);
                        var lcs = sc.transform.localScale;
                        sc.radius *= Mathf.Max(lcs.x, lcs.y, lcs.z);
                    }

                    sc.center  = Vector3.Scale(sc.center, size);
                    sc.center += pos;
                    sc.radius *= Mathf.Max(size.x, size.y, size.z);

                    if (sc.transform != go.transform && sc.transform.rotation == go.transform.rotation)
                    {
                        ComponentUtility.CopyComponent(sc);
                        ComponentUtility.PasteComponentAsNew(go);
                        DestroyImmediate(sc);
                    }
                }
            }
        }
Esempio n. 27
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            if (s_Contents == null)
            {
                s_Contents = new Contents();
            }

            serializedObject.Update();
            Event e = Event.current;

            if (e != null)
            {
                if (image) //Auto set Image's native size if Image.sprite is not null
                {
                    if (e.type == EventType.DragPerform || e.type == EventType.MouseDown)
                    {
                        autoSetNativeSize = !image.sprite;
                    }

                    if (autoSetNativeSize && image.sprite && image.type == Image.Type.Simple)
                    {
                        autoSetNativeSize = false;
                        RectTransform tf = target as RectTransform;
                        float         x  = image.sprite.rect.width / image.pixelsPerUnit;
                        float         y  = image.sprite.rect.height / image.pixelsPerUnit;
                        tf.anchorMax = tf.anchorMin;
                        tf.sizeDelta = new Vector2(x, y);
                    }
                }

                //Keyboard control move by pixel style like Photoshop's move tool
                if (e.type == EventType.KeyDown && e.control)
                {
                    int nUnit = e.shift ? 10 : 1;
                    switch (e.keyCode)
                    {
                    case KeyCode.UpArrow:
                        Undo.RecordObjects(targets, "UpArrow");
                        MoveTargetAnchoredPosition(Vector2.up * nUnit);
                        e.Use();
                        break;

                    case KeyCode.DownArrow:
                        Undo.RecordObjects(targets, "DownArrow");
                        MoveTargetAnchoredPosition(Vector2.down * nUnit);
                        e.Use();
                        break;

                    case KeyCode.LeftArrow:
                        Undo.RecordObjects(targets, "LeftArrow");
                        MoveTargetAnchoredPosition(Vector2.left * nUnit);
                        e.Use();
                        break;

                    case KeyCode.RightArrow:
                        Undo.RecordObjects(targets, "RightArrow");
                        MoveTargetAnchoredPosition(Vector2.right * nUnit);
                        e.Use();
                        break;
                    }
                }
            }

            const float fButtonWidth = 21;

            if (stylePivotSetup == null)
            {
                stylePivotSetup = new GUIStyle("PreButton")
                {
                    normal     = new GUIStyle("CN Box").normal,
                    active     = new GUIStyle("AppToolbar").normal,
                    overflow   = new RectOffset(),
                    padding    = new RectOffset(0, 0, -1, 0),
                    fixedWidth = 19
                };

                styleMove = new GUIStyle(stylePivotSetup)
                {
                    padding = new RectOffset(0, 0, -2, 0)
                };
            }

            GUILayout.BeginHorizontal();
            {
                GUILayout.BeginVertical();
                {
                    #region Tools
                    GUILayout.BeginHorizontal();
                    {
                        EditorGUIUtility.labelWidth = 64;
                        float newScale = EditorGUILayout.FloatField(s_Contents.scaleContent, scaleAll);
                        if (!Mathf.Approximately(scaleAll, newScale))
                        {
                            scaleAll = newScale;
                            spLocalScale.vector3Value = Vector3.one * scaleAll;
                        }
                    }

                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button(s_Contents.anchoredPosition0Content, strButtonLeft, GUILayout.Width(fButtonWidth)))
                        {
                            foreach (Object item in targets)
                            {
                                RectTransform rtf = item as RectTransform;
                                rtf.LocalPositionIdentity();
                            }
                        }

                        if (GUILayout.Button(s_Contents.deltaSize0Content, strButtonMid, GUILayout.Width(fButtonWidth)))
                        {
                            spSizeDelta.vector2Value = Vector2.zero;
                        }

                        if (GUILayout.Button(s_Contents.rotation0Content, strButtonMid, GUILayout.Width(fButtonWidth)))
                        {
                            Undo.RecordObjects(targets, "rotationContent");
                            MethodInfo method =
                                typeof(Transform).GetMethod("SetLocalEulerAngles", BindingFlags.Instance | BindingFlags.NonPublic);
                            object[] clear = { Vector3.zero, 0 };
                            for (int i = 0; i < targets.Length; i++)
                            {
                                method.Invoke(targets[i], clear);
                            }

                            Event.current.type = EventType.Used;
                        }

                        if (GUILayout.Button(s_Contents.scale0Content, strButtonRight, GUILayout.Width(fButtonWidth)))
                        {
                            spLocalScale.vector3Value = Vector3.one;
                            scaleAll = spLocalScale.FindPropertyRelative("x").floatValue;
                        }

                        if (GUILayout.Button(s_Contents.roundContent))
                        {
                            Vector2 v2 = spAnchoredPosition.vector2Value;
                            spAnchoredPosition.vector2Value = new Vector2(Mathf.Round(v2.x), Mathf.Round(v2.y));
                            v2 = spSizeDelta.vector2Value;
                            spSizeDelta.vector2Value = new Vector2(Mathf.Round(v2.x), Mathf.Round(v2.y));
                        }
                    }
                    GUILayout.EndHorizontal();
                    #endregion

                    #region Copy Paste
                    GUILayout.BeginHorizontal();
                    Color c = GUI.color;
                    GUI.color = new Color(1f, 1f, 0.5f, 1f);
                    if (GUILayout.Button(s_Contents.copyContent, strButtonLeft, GUILayout.Width(fButtonWidth)))
                    {
                        ComponentUtility.CopyComponent(target as RectTransform);
                    }

                    GUI.color = new Color(1f, 0.5f, 0.5f, 1f);
                    if (GUILayout.Button(s_Contents.pasteContent, strButtonMid, GUILayout.Width(fButtonWidth)))
                    {
                        foreach (Object item in targets)
                        {
                            ComponentUtility.PasteComponentValues(item as RectTransform);
                        }
                    }

                    GUI.color = c;
                    if (GUILayout.Button(s_Contents.fillParentContent, strButtonMid, GUILayout.Width(fButtonWidth)))
                    {
                        Undo.RecordObjects(targets, "F");
                        foreach (Object item in targets)
                        {
                            RectTransform rtf = item as RectTransform;
                            rtf.anchorMax = Vector2.one;
                            rtf.anchorMin = Vector2.zero;
                            rtf.offsetMax = Vector2.zero;
                            rtf.offsetMin = Vector2.zero;
                        }
                    }

                    if (GUILayout.Button(s_Contents.normalSizeDeltaContent, strButtonRight, GUILayout.Width(fButtonWidth)))
                    {
                        Undo.RecordObjects(targets, "N");
                        foreach (Object item in targets)
                        {
                            RectTransform rtf  = item as RectTransform;
                            Rect          rect = rtf.rect;
                            rtf.anchorMax = new Vector2(0.5f, 0.5f);
                            rtf.anchorMin = new Vector2(0.5f, 0.5f);
                            rtf.sizeDelta = rect.size;
                        }
                    }

                    GUILayout.Label(s_Contents.readmeContent);
                    GUILayout.EndHorizontal();
                    #endregion
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical();
                {
                    #region Pivot
                    GUILayout.Label("Pivot", "ProfilerPaneSubLabel"); //┌─┐
                    GUILayout.BeginHorizontal();                      //│┼│
                    {
                        //└─┘
                        if (GUILayout.Button("◤", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0, 1);
                        }

                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0.5f, 1);
                        }

                        if (GUILayout.Button("◥", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(1, 1);
                        }
                    }

                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0, 0.5f);
                        }

                        if (GUILayout.Button("+", styleMove))
                        {
                            spPivot.vector2Value = new Vector2(0.5f, 0.5f);
                        }

                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(1, 0.5f);
                        }
                    }

                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button("◣", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0, 0);
                        }

                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0.5f, 0);
                        }

                        if (GUILayout.Button("◢", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(1, 0);
                        }
                    }

                    GUILayout.EndHorizontal();
                }
                #endregion

                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            TransformInspector.DrawBottomPanel(target, targets);
            serializedObject.ApplyModifiedProperties();
        }
        /// <summary>
        /// VRMSpringBone、およびVRMSpringBoneColliderGroupをコピーします。
        /// </summary>
        /// <param name="sourceSpringBone"></param>
        /// <param name="destination"></param>
        /// <param name="sourceSkeletonBones"></param>
        /// <param name="transformMapping"></param>
        /// <returns>更新された <c>transformMapping</c> を返します。</returns>
        private static IDictionary <Transform, Transform> CopySpringBone(
            VRMSpringBone sourceSpringBone,
            GameObject destination,
            Dictionary <HumanBodyBones, Transform> sourceSkeletonBones,
            IDictionary <Transform, Transform> transformMapping
            )
        {
            var destinationSecondary = destination.transform.Find("secondary").gameObject;

            ComponentUtility.CopyComponent(sourceSpringBone);
            ComponentUtility.PasteComponentAsNew(destinationSecondary);
            var destinationSpringBone = destinationSecondary.GetComponents <VRMSpringBone>().Last();

            if (destinationSpringBone.m_center)
            {
                destinationSpringBone.m_center = transformMapping.ContainsKey(destinationSpringBone.m_center)
                    ? transformMapping[destinationSpringBone.m_center]
                    : (transformMapping[destinationSpringBone.m_center] = BoneMapper.FindCorrespondingBone(
                           sourceBone: destinationSpringBone.m_center,
                           source: sourceSpringBone.transform.root.gameObject,
                           destination,
                           sourceSkeletonBones
                           ));
            }

            for (var i = 0; i < destinationSpringBone.RootBones.Count; i++)
            {
                var sourceSpringBoneRoot = destinationSpringBone.RootBones[i];

                destinationSpringBone.RootBones[i] = sourceSpringBoneRoot
                    ? (transformMapping.ContainsKey(sourceSpringBoneRoot)
                        ? transformMapping[sourceSpringBoneRoot]
                        : (transformMapping[sourceSpringBoneRoot] = BoneMapper.FindCorrespondingBone(
                               sourceBone: sourceSpringBoneRoot,
                               source: sourceSpringBone.transform.root.gameObject,
                               destination,
                               sourceSkeletonBones
                               )))
                    : null;
            }

            for (var i = 0; i < destinationSpringBone.ColliderGroups.Length; i++)
            {
                var sourceColliderGroup = destinationSpringBone.ColliderGroups[i];

                var destinationColliderGroupTransform = sourceColliderGroup
                    ? (transformMapping.ContainsKey(sourceColliderGroup.transform)
                        ? transformMapping[sourceColliderGroup.transform]
                        : (transformMapping[sourceColliderGroup.transform] = BoneMapper.FindCorrespondingBone(
                               sourceBone: sourceColliderGroup.transform,
                               source: sourceSpringBone.transform.root.gameObject,
                               destination,
                               sourceSkeletonBones
                               )))
                    : null;

                VRMSpringBoneColliderGroup destinationColliderGroup = null;
                if (destinationColliderGroupTransform)
                {
                    CopyVRMSpringBones.CopySpringBoneColliderGroups(
                        sourceBone: sourceColliderGroup.transform,
                        destinationBone: destinationColliderGroupTransform
                        );
                    destinationColliderGroup
                        = destinationColliderGroupTransform.GetComponent <VRMSpringBoneColliderGroup>();
                }
                destinationSpringBone.ColliderGroups[i] = destinationColliderGroup;
            }

            return(transformMapping);
        }
Esempio n. 29
0
        public void AttachColliders()
        {
            colliderAtachment = GameObject.Find(setUp.editorGeneratorLevel.name);

            if (colliderAtachment == null)
            {
                colliderAtachment = new GameObject(setUp.editorGeneratorLevel.name);
            }

            if (colliderAtachment.transform.childCount != 0)
            {
                var temp = colliderAtachment.transform.Cast <Transform> ().ToList();
                foreach (var child in temp)
                {
                    if (child.gameObject.name != "Blocks")
                    {
                        DestroyImmediate(child.gameObject);
                    }
                }
            }

            GameObject go;

            GameObject wall  = new GameObject("WallColliders");
            GameObject floor = new GameObject("FloorColliders");

            SerializedObject   tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset") [0]);
            SerializedProperty tagsProp   = tagManager.FindProperty("tags");

            bool found = false;

            for (int i = 0; i < tagsProp.arraySize; i++)
            {
                SerializedProperty temp = tagsProp.GetArrayElementAtIndex(i);
                if (temp.stringValue.Equals(wallTag))
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                tagsProp.InsertArrayElementAtIndex(0);
                SerializedProperty temp = tagsProp.GetArrayElementAtIndex(0);
                temp.stringValue = wallTag;
            }
            found = false;
            for (int i = 0; i < tagsProp.arraySize; i++)
            {
                SerializedProperty temp = tagsProp.GetArrayElementAtIndex(i);
                if (temp.stringValue.Equals(floorTag))
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                tagsProp.InsertArrayElementAtIndex(0);
                SerializedProperty temp = tagsProp.GetArrayElementAtIndex(0);
                temp.stringValue = floorTag;
            }

            tagManager.ApplyModifiedProperties();

            wall.tag  = wallTag;
            floor.tag = floorTag;

            for (int i = 0; i < colliders.childCount; i++)
            {
                go = colliders.GetChild(i).gameObject;

                ComponentUtility.CopyComponent(go.GetComponent <BoxCollider> ());

                if (go.name == floorTag)
                {
                    ComponentUtility.PasteComponentAsNew(floor);
                }
                else if (go.name == wallTag)
                {
                    ComponentUtility.PasteComponentAsNew(wall);
                }
            }

            wall.transform.parent  = colliderAtachment.transform;
            floor.transform.parent = colliderAtachment.transform;

            if (setUp.deathZonePrefab != null)
            {
                go = Instantiate(setUp.deathZonePrefab, new Vector3(0, -1, 0), Quaternion.identity, colliderAtachment.transform);
            }

            if (!AssetDatabase.IsValidFolder("Assets/Prefabs/Levels"))
            {
                AssetDatabase.CreateFolder("Assets", "Prefabs");
                AssetDatabase.CreateFolder("Assets/Prefabs", "Levels");
            }

            PrefabUtility.CreatePrefab("Assets/Prefabs/Levels/" + colliderAtachment.name + ".prefab", colliderAtachment, ReplacePrefabOptions.ConnectToPrefab);
        }
Esempio n. 30
0
        public bool             CopyComponentToGameObjectAndClipboard(GameObject go)
        {
            GameObject newGO = null;

            if (go == null)
            {
                go = newGO = new GameObject();
            }

            try
            {
                IncompleteGameObjectException incompleteEx = null;
                Component c;

                go.GetComponents(this.type, ClientComponent.reuseComponents);

                int componentIndex = 0;

                if (newGO != null)
                {
                    c = go.AddComponent(this.type);
                }
                else
                {
                    for (int i = 0; i < this.parent.components.Count; i++)
                    {
                        if (this.parent.components[i].type == this.type)
                        {
                            if (this.parent.components[i] == this)
                            {
                                break;
                            }

                            ++componentIndex;
                        }
                    }

                    if (ClientComponent.reuseComponents.Count <= componentIndex)
                    {
                        c = go.AddComponent(this.type);
                    }
                    else
                    {
                        c = ClientComponent.reuseComponents[componentIndex];
                    }
                }

                for (int i = 0; i < this.fields.Length; i++)
                {
                    try
                    {
                        this.SetValue(c.GetType().FullName + "#" + componentIndex + "." + this.fields[i].name, c, this.fields[i].name, this.fields[i].value);
                    }
                    catch (IncompleteGameObjectException ex)
                    {
                        if (incompleteEx == null)
                        {
                            incompleteEx = ex;
                        }
                        else
                        {
                            incompleteEx.Aggregate(ex);
                        }
                    }
                }

                if (incompleteEx != null)
                {
                    throw incompleteEx;
                }

                if (ComponentUtility.CopyComponent(c) == false)
                {
                    Debug.LogError("Copy component failed.");
                }
                else
                {
                    return(true);
                }
            }
            catch (IncompleteGameObjectException)
            {
                throw;
            }
            catch (Exception ex)
            {
                InternalNGDebug.LogException("Copy component failed.", ex);
            }
            finally
            {
                if (newGO != null)
                {
                    GameObject.DestroyImmediate(newGO);
                }
            }

            return(false);
        }