Esempio n. 1
0
        /// <summary>
        /// Creates a preset from a component instance at runtime.
        /// This action requires a temporary <see cref="GameObject"/> to be created.
        /// Call <see cref="Free"/> to remove it when you're done to remove it.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of <see cref="Component"/></typeparam>
        /// <param name="component"></param>
        /// <returns>A new Preset instance.</returns>
        public static Preset From <T>(T component) where T : Component
        {
            var componentContainer = new GameObject($"tmp_{Mathf.Abs(component.GetInstanceID())}");
            var preset             = componentContainer.GetOrCreateComponent <Preset>();
            var componentCopy      = componentContainer.GetOrCreateComponent <T>();

            componentCopy.TransferValuesFrom(component);
            preset.TargetComponent = componentCopy;
            componentContainer.SetActive(false);
            return(preset);
        }
Esempio n. 2
0
    public static SpriteRenderer InstantiateSprite(Sprite sprite, Vector3 position, GameObject parent = null, PositionSpace positionSpace = PositionSpace.Local, string name = null)
    {
        GameObject spriteGO = new GameObject();

        if (parent != null)
        {
            spriteGO.transform.parent = parent.transform;
            if (positionSpace == PositionSpace.Local)
            {
                spriteGO.transform.localPosition = position;
            }
            else
            {
                spriteGO.transform.position = position;
            }
        }
        else
        {
            spriteGO.transform.position = position;
        }

        if (name != null)
        {
            spriteGO.name = name;
        }

        SpriteRenderer sr = spriteGO.GetOrCreateComponent <SpriteRenderer> ();

        if (sprite == null)
        {
            Debug.LogWarning("InstantiateSprite : Sprite parameter is null");
        }
        sr.sprite = sprite;
        return(sr);
    }
        public IListObserver <T> Subscribe(HandleItemAdded <T> add, HandleItemRemoved <T> remove, GameObject scope)
        {
            IListObserver <T> observer = Subscribe(add, remove);

            scope.GetOrCreateComponent <ObserverScope>().AddUnsubscribe(() => Unsubscribe(observer));
            return(observer);
        }
Esempio n. 4
0
        private AudioSource PlayObject(GameObject go, string clipName, float volume, float time, AudioMixerGroup mixerGroup = null, bool isLoop = false, bool fadeIn = false)
        {
            AudioSource audioSource = go.GetOrCreateComponent <AudioSource>();

#if DATA_GENER
            if (isLocalization)
            {
                if (LanguageManager.ContainKey(clipName))
                {
                    clipName = LanguageManager.GetWord(clipName);
                }
            }
#endif
            audioSource.clip = ResourcesLoaderHelper.Instance.LoadResource <AudioClip>(clipName);
            audioSource.outputAudioMixerGroup = mixerGroup;
            audioSource.loop   = isLoop;
            audioSource.volume = volume;
            audioSource.Play();
            if (time > 0)
            {
                CoroutineTaskManager.Instance.WaitSecondTodo(() =>
                {
                    if (audioSource == null)
                    {
                        return;
                    }
                    audioSource.Stop();
                }, time);
            }
            return(audioSource);
        }
Esempio n. 5
0
 private void AddSelectionProxy(GameObject instance)
 {
     instance.GetOrCreateComponent <OnSelectionProxy>().Component = m_parentComponent;
     foreach (Transform child in instance.transform)
     {
         child.gameObject.GetOrCreateComponent <OnSelectionProxy>().Component = m_parentComponent;
     }
 }
Esempio n. 6
0
 /// <summary>
 /// Adds OnSelectionProxy to <paramref name="visualParent"/> and all its children.
 /// </summary>
 /// <param name="visualParent">Visual parent game object.</param>
 /// <param name="shape">Shape reference.</param>
 private static void CreateOnSelectionProxy(GameObject visualParent, Collide.Shape shape)
 {
     visualParent.GetOrCreateComponent <OnSelectionProxy>().Component = shape;
     foreach (Transform child in visualParent.transform)
     {
         child.gameObject.GetOrCreateComponent <OnSelectionProxy>().Component = shape;
     }
 }
        private T BuildUUIDComponent <T>(int classId)
            where T : UnityEngine.Component
        {
            var go           = new GameObject("UUID Component");
            T   newComponent = go.GetOrCreateComponent <T>();

            return(newComponent);
        }
Esempio n. 8
0
        private static void CreateRuntimePreset(MenuCommand command)
        {
            var sourceComponent = (Component)command.context;
            var dummyObject     = new GameObject();

            var targetComponent = dummyObject.GetOrCreateComponent(sourceComponent.GetType());
            var runtimePreset   = dummyObject.GetOrCreateComponent <Preset>();

            runtimePreset.TargetComponent = targetComponent;

            UnityEditorInternal.ComponentUtility.CopyComponent(sourceComponent);
            UnityEditorInternal.ComponentUtility.PasteComponentValues(targetComponent);

            var prefab = PrefabUtility.CreatePrefab("Assets/New Preset.prefab", dummyObject);

            Object.DestroyImmediate(dummyObject);
        }
 /// <summary>
 /// 添加监听器
 /// </summary>
 /// <param name="bindObject"></param>
 /// <param name="eventType"></param>
 /// <param name="handler"></param>
 public static void AddEventListener(this GameObject bindObject, string eventType, Action handler)
 {
     if (bindObject == null)
     {
         return;
     }
     MonoEventDispatcher.GetMonoController(bindObject).AddEventListener(eventType, handler, bindObject);
     bindObject.GetOrCreateComponent <MonoEventCleanUp>();
 }
Esempio n. 10
0
 private void Configure(Model.Track track, GameObject instance)
 {
     instance.hideFlags = HideFlags.DontSaveInEditor;
     instance.GetOrCreateComponent <OnSelectionProxy>().Component = track;
     foreach (Transform child in instance.transform)
     {
         Configure(track, child.gameObject);
     }
 }
    public static void OnObject(GameObject go, float duration, float blinkTime)
    {
        Renderer r = go.GetComponent <Renderer>();

        if (r != null)
        {
            BlinkVisibility blink = go.GetOrCreateComponent <BlinkVisibility>();
            blink.SetOptions(duration, blinkTime);
        }
    }
Esempio n. 12
0
    public static void BindOffLineDat(GameObject gameObject)
    {
        MResOffLineDataBase mResOffLineData = gameObject.GetOrCreateComponent <MResOffLineDataBase>();

        if (mResOffLineData != null)
        {
            mResOffLineData.BindBasicData();
            EditorUtility.SetDirty(gameObject);
            Resources.UnloadUnusedAssets();
        }
    }
Esempio n. 13
0
    public static void CreateNinePatch()
    {
        GameObject go = new GameObject ();
        go.name = "NinePatch";

        /* NinePatch ninePatch = */ go.GetOrCreateComponent<NinePatch> ();

        if ( Selection.activeGameObject != null )
        {
            go.transform.parent = Selection.activeGameObject.transform;
            go.transform.position = Selection.activeGameObject.transform.position;
        }
        Selection.activeObject = go;
    }
Esempio n. 14
0
    public static void Create()
    {
        if ( Selection.activeGameObject != null )
        {
            GameObject path = new GameObject ( "Path" );
            path.GetOrCreateComponent<PointPath> ();
            if ( Selection.activeGameObject.transform.parent != null )
                path.transform.parent = Selection.activeGameObject.transform.parent.transform;
            path.transform.position = Selection.activeGameObject.transform.position;

            PathFollower pathFollower = Selection.activeGameObject.GetOrCreateComponent<PathFollower> ();
            pathFollower.Path = path;
        }
    }
Esempio n. 15
0
    public static void CreateQuad()
    {
        GameObject go = new GameObject ();
        go.name = "Quad";

        /* Quad quad = */ go.GetOrCreateComponent<Quad> ();

        if ( Selection.activeGameObject != null )
        {
            go.transform.parent = Selection.activeGameObject.transform;
            go.transform.position = Selection.activeGameObject.transform.position;
        }
        Selection.activeObject = go;
    }
Esempio n. 16
0
    public static void CreateTextMeshEx()
    {
        GameObject go = new GameObject();
        go.name = "Text";

        TextMeshEx textMesh = go.GetOrCreateComponent<TextMeshEx> ();
        textMesh.Font = Resources.GetBuiltinResource ( typeof ( Font ), "Arial.ttf" ) as Font;

        if ( Selection.activeGameObject != null )
        {
            go.transform.parent = Selection.activeGameObject.transform;
            go.transform.position = Selection.activeGameObject.transform.position;
        }
        Selection.activeObject = go;
    }
Esempio n. 17
0
        private void AddSelectionProxy(GameObject instance)
        {
            // Handling old version where this object was used by the Wire only and
            // m_parentComponent wasn't present. I.e., if m_parenComponent == null
            // it has to be a Wire present.
            if (m_parentComponent == null)
            {
                m_parentComponent = m_segments.transform.parent.GetComponent <Wire>();
            }

            instance.GetOrCreateComponent <OnSelectionProxy>().Component = m_parentComponent;
            foreach (Transform child in instance.transform)
            {
                child.gameObject.GetOrCreateComponent <OnSelectionProxy>().Component = m_parentComponent;
            }
        }
Esempio n. 18
0
    public static void CreateTextMeshEx()
    {
        GameObject go = new GameObject();

        go.name = "Text";

        TextMeshEx textMesh = go.GetOrCreateComponent <TextMeshEx> ();

        textMesh.Font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;

        if (Selection.activeGameObject != null)
        {
            go.transform.parent   = Selection.activeGameObject.transform;
            go.transform.position = Selection.activeGameObject.transform.position;
        }
        Selection.activeObject = go;
    }
Esempio n. 19
0
        private AudioSource PlayObject(GameObject go, string clipBundle, string clipName, float volume, float time, AudioMixerGroup mixerGroup = null, bool isLoop = false, bool fadeIn = false)
        {
            AudioSource audioSource = go.GetOrCreateComponent <AudioSource>();

            audioSource.clip = AssetLoader.GetAudio(clipBundle, clipName);
            audioSource.outputAudioMixerGroup = mixerGroup;
            audioSource.loop   = isLoop;
            audioSource.volume = volume;
            audioSource.Play();
            if (time > 0)
            {
                CoroutineTaskManager.Instance.WaitSecondTodo(() =>
                {
                    if (audioSource == null)
                    {
                        return;
                    }
                    audioSource.Stop();
                }, time);
            }
            return(audioSource);
        }
Esempio n. 20
0
 public virtual void Subscribe(TCollectionObserver observer, GameObject scope)
 {
     Subscribe(observer);
     scope.GetOrCreateComponent <ObserverScope>().AddUnsubscribe(() => Unsubscribe(observer));
 }
        public void OnInspectorGUI(GUISkin skin)
        {
            GUILayout.BeginHorizontal();
            {
                GUILayout.Label(GUI.MakeLabel("Disable: ", true), skin.label);
                GUILayout.Label(SelectGameObjectDropdownMenuTool.GetGUIContent(m_mainObject), skin.textField);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                GUILayout.Label(GUI.MakeLabel(GUI.Symbols.Synchronized.ToString()), skin.label);
                GUILayout.BeginVertical();
                {
                    if (m_selected.Count == 0)
                    {
                        GUILayout.Label(GUI.MakeLabel("None", true), skin.label, GUILayout.Width(180));
                    }
                    else
                    {
                        int removeIndex = -1;
                        for (int i = 0; i < m_selected.Count; ++i)
                        {
                            GUILayout.BeginHorizontal();
                            {
                                GUILayout.Label(SelectGameObjectDropdownMenuTool.GetGUIContent(m_selected[i]), GUI.Align(skin.textField, TextAnchor.MiddleLeft), GUILayout.Height(20));
                                using (GUI.NodeListButtonColor)
                                    if (GUILayout.Button(GUI.MakeLabel(GUI.Symbols.ListEraseElement.ToString()), skin.button, GUILayout.Width(18), GUILayout.Height(18)))
                                    {
                                        removeIndex = i;
                                    }
                            }
                            GUILayout.EndHorizontal();
                        }

                        if (removeIndex >= 0)
                        {
                            m_selected.RemoveAt(removeIndex);
                        }
                    }
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(12);

            bool applyPressed  = false;
            bool cancelPressed = false;

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();

                UnityEngine.GUI.enabled = m_selected.Count > 0;
                applyPressed            = GUILayout.Button(GUI.MakeLabel("Apply", true, "Apply current configuration"), skin.button, GUILayout.Width(86), GUILayout.Height(26));
                UnityEngine.GUI.enabled = true;

                GUILayout.BeginVertical();
                {
                    GUILayout.Space(11);
                    cancelPressed = GUILayout.Button(GUI.MakeLabel("Cancel", false, "Cancel/reset"), skin.button, GUILayout.Width(64), GUILayout.Height(18));
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            if (applyPressed)
            {
                string selectedGroupName   = m_mainObject.GetInstanceID().ToString();
                string mainObjectGroupName = "";
                for (int i = 0; i < m_selected.Count; ++i)
                {
                    mainObjectGroupName += m_selected[i].GetInstanceID().ToString() + (i != m_selected.Count - 1 ? "_" : "");
                }

                m_mainObject.GetOrCreateComponent <CollisionGroups>().AddGroup(mainObjectGroupName, ShouldPropagateToChildren(m_mainObject));
                foreach (var selected in m_selected)
                {
                    selected.GetOrCreateComponent <CollisionGroups>().AddGroup(selectedGroupName, ShouldPropagateToChildren(selected));
                }

                CollisionGroupsManager.Instance.SetEnablePair(mainObjectGroupName, selectedGroupName, false);

                PerformRemoveFromParent();
            }
            else if (cancelPressed)
            {
                PerformRemoveFromParent();
            }
        }
Esempio n. 22
0
    static void Create()
    {
        GameObject go = new GameObject ( "PolyMesh", typeof ( MeshFilter ), typeof ( MeshRenderer ) );
        PolyMesh polyMesh = go.AddComponent<PolyMesh> ();
        CreateSquare ( polyMesh, 10 );

        MeshRenderer renderer = go.GetOrCreateComponent<MeshRenderer> ();
        Shader shader = Shader.Find ( "Sprites/Default" );
        if ( shader != null )
        {
            Material material = new Material ( shader );
            material.name = "PolyMesh Material";
            material.SetColor ( "_Color", Color.gray );
            // material.hideFlags = HideFlags.DontSave;
            renderer.material = material;
        }

        if ( Selection.activeGameObject != null )
        {
            go.transform.parent = Selection.activeGameObject.transform;
            go.transform.position = Selection.activeGameObject.transform.position;
        }
        Selection.activeObject = go;
    }
 public override void Subscribe(IOrderedListObserver <T> observer, GameObject scope)
 {
     Subscribe(observer);
     scope.GetOrCreateComponent <ObserverScope>().AddUnsubscribe(() => Unsubscribe(observer));
 }
Esempio n. 24
0
        public BaseComponent EntityComponentCreateOrUpdate(string entityId, CLASS_ID_COMPONENT classId, string data, out CleanableYieldInstruction yieldInstruction)
        {
            yieldInstruction = null;

            DecentralandEntity entity = GetEntityForUpdate(entityId);

            if (entity == null)
            {
                Debug.LogError($"scene '{sceneData.id}': Can't create entity component if the entity {entityId} doesn't exist!");
                return(null);
            }

            if (classId == CLASS_ID_COMPONENT.TRANSFORM)
            {
                MessageDecoder.DecodeTransform(data, ref DCLTransform.model);

                if (!entity.components.ContainsKey(classId))
                {
                    entity.components.Add(classId, null);
                }

                if (entity.OnTransformChange != null)
                {
                    entity.OnTransformChange.Invoke(DCLTransform.model);
                }
                else
                {
                    entity.gameObject.transform.localPosition = DCLTransform.model.position;
                    entity.gameObject.transform.localRotation = DCLTransform.model.rotation;
                    entity.gameObject.transform.localScale    = DCLTransform.model.scale;

                    Environment.i.world.sceneBoundsChecker?.AddEntityToBeChecked(entity);
                }

                Environment.i.platform.physicsSyncController.MarkDirty();
                Environment.i.platform.cullingController.MarkDirty();
                return(null);
            }

            BaseComponent            newComponent = null;
            IRuntimeComponentFactory factory      = ownerController.componentFactory;

            Assert.IsNotNull(factory, "Factory is null?");

            // HACK: (Zak) will be removed when we separate each
            // uuid component as a different class id
            if (classId == CLASS_ID_COMPONENT.UUID_CALLBACK)
            {
                string type = "";

                OnPointerEvent.Model model = JsonUtility.FromJson <OnPointerEvent.Model>(data);

                type = model.type;

                if (!entity.uuidComponents.ContainsKey(type))
                {
                    //NOTE(Brian): We have to contain it in a gameObject or it will be pooled with the components attached.
                    var go = new GameObject("UUID Component");
                    go.transform.SetParent(entity.gameObject.transform, false);

                    switch (type)
                    {
                    case OnClick.NAME:
                        newComponent = go.GetOrCreateComponent <OnClick>();
                        break;

                    case OnPointerDown.NAME:
                        newComponent = go.GetOrCreateComponent <OnPointerDown>();
                        break;

                    case OnPointerUp.NAME:
                        newComponent = go.GetOrCreateComponent <OnPointerUp>();
                        break;
                    }

                    if (newComponent != null)
                    {
                        UUIDComponent uuidComponent = newComponent as UUIDComponent;

                        if (uuidComponent != null)
                        {
                            uuidComponent.Setup(this, entity, model);
                            entity.uuidComponents.Add(type, uuidComponent);
                        }
                        else
                        {
                            Debug.LogError("uuidComponent is not of UUIDComponent type!");
                        }
                    }
                    else
                    {
                        Debug.LogError("EntityComponentCreateOrUpdate: Invalid UUID type!");
                    }
                }
                else
                {
                    newComponent = EntityUUIDComponentUpdate(entity, type, model);
                }
            }
            else
            {
                if (!entity.components.ContainsKey(classId))
                {
                    newComponent = factory.CreateItemFromId <BaseComponent>(classId);

                    if (newComponent != null)
                    {
                        newComponent.scene  = this;
                        newComponent.entity = entity;

                        entity.components.Add(classId, newComponent);

                        newComponent.transform.SetParent(entity.gameObject.transform, false);
                        newComponent.UpdateFromJSON(data);
                    }
                }
                else
                {
                    newComponent = EntityComponentUpdate(entity, classId, data);
                }
            }

            if (newComponent != null)
            {
                if (newComponent is IOutOfSceneBoundariesHandler)
                {
                    Environment.i.world.sceneBoundsChecker?.AddEntityToBeChecked(entity);
                }

                if (newComponent.isRoutineRunning)
                {
                    yieldInstruction = newComponent.yieldInstruction;
                }
            }

            Environment.i.platform.physicsSyncController.MarkDirty();
            Environment.i.platform.cullingController.MarkDirty();
            return(newComponent);
        }
Esempio n. 25
0
        public BaseComponent EntityComponentCreateOrUpdateFromUnity(string entityId, CLASS_ID_COMPONENT classId, object data)
        {
            DecentralandEntity entity = GetEntityForUpdate(entityId);

            if (entity == null)
            {
                Debug.LogError($"scene '{sceneData.id}': Can't create entity component if the entity {entityId} doesn't exist!");
                return(null);
            }

            if (classId == CLASS_ID_COMPONENT.TRANSFORM)
            {
                if (!(data is DCLTransform.Model))
                {
                    Debug.LogError("Data is not a DCLTransform.Model type!");
                    return(null);
                }

                DCLTransform.Model modelRecovered = (DCLTransform.Model)data;

                if (!entity.components.ContainsKey(classId))
                {
                    entity.components.Add(classId, null);
                }


                if (entity.OnTransformChange != null)
                {
                    entity.OnTransformChange.Invoke(modelRecovered);
                }
                else
                {
                    entity.gameObject.transform.localPosition = modelRecovered.position;
                    entity.gameObject.transform.localRotation = modelRecovered.rotation;
                    entity.gameObject.transform.localScale    = modelRecovered.scale;

                    Environment.i.world.sceneBoundsChecker?.AddEntityToBeChecked(entity);
                }

                Environment.i.platform.physicsSyncController.MarkDirty();
                Environment.i.platform.cullingController.MarkDirty();
                return(null);
            }

            BaseComponent            newComponent = null;
            IRuntimeComponentFactory factory      = ownerController.componentFactory;

            Assert.IsNotNull(factory, "Factory is null?");

            if (classId == CLASS_ID_COMPONENT.UUID_CALLBACK)
            {
                string type = "";
                if (!(data is OnPointerEvent.Model))
                {
                    Debug.LogError("Data is not a DCLTransform.Model type!");
                    return(null);
                }

                OnPointerEvent.Model model = (OnPointerEvent.Model)data;

                type = model.type;

                if (!entity.uuidComponents.ContainsKey(type))
                {
                    //NOTE(Brian): We have to contain it in a gameObject or it will be pooled with the components attached.
                    var go = new GameObject("UUID Component");
                    go.transform.SetParent(entity.gameObject.transform, false);

                    switch (type)
                    {
                    case OnClick.NAME:
                        newComponent = go.GetOrCreateComponent <OnClick>();
                        break;

                    case OnPointerDown.NAME:
                        newComponent = go.GetOrCreateComponent <OnPointerDown>();
                        break;

                    case OnPointerUp.NAME:
                        newComponent = go.GetOrCreateComponent <OnPointerUp>();
                        break;
                    }

                    if (newComponent != null)
                    {
                        UUIDComponent uuidComponent = newComponent as UUIDComponent;

                        if (uuidComponent != null)
                        {
                            uuidComponent.Setup(this, entity, model);
                            entity.uuidComponents.Add(type, uuidComponent);
                        }
                        else
                        {
                            Debug.LogError("uuidComponent is not of UUIDComponent type!");
                        }
                    }
                    else
                    {
                        Debug.LogError("EntityComponentCreateOrUpdate: Invalid UUID type!");
                    }
                }
                else
                {
                    newComponent = EntityUUIDComponentUpdate(entity, type, model);
                }
            }
            else
            {
                if (!entity.components.ContainsKey(classId))
                {
                    newComponent = factory.CreateItemFromId <BaseComponent>(classId);

                    if (newComponent != null)
                    {
                        newComponent.scene  = this;
                        newComponent.entity = entity;

                        entity.components.Add(classId, newComponent);

                        newComponent.transform.SetParent(entity.gameObject.transform, false);
                        newComponent.UpdateFromJSON((string)data);
                    }
                }
                else
                {
                    newComponent = EntityComponentUpdate(entity, classId, (string)data);
                }
            }

            Environment.i.platform.physicsSyncController.MarkDirty();
            Environment.i.platform.cullingController.MarkDirty();
            return(newComponent);
        }
Esempio n. 26
0
        /// <summary>
        /// Creates native instance and adds it to the simulation if this constraint
        /// is properly configured.
        /// </summary>
        /// <returns>True if successful.</returns>
        protected override bool Initialize()
        {
            if (AttachmentPair.ReferenceObject == null)
            {
                Debug.LogError("Unable to initialize constraint - reference object must be valid and contain a rigid body component.", this);
                return(false);
            }

            // Synchronize frames to make sure connected frame is up to date.
            AttachmentPair.Synchronize();

            // TODO: Disabling rigid body game object (activeSelf == false) and will not be
            //       able to create native body (since State == Constructed and not Awake).
            //       Do: GetComponentInParent<RigidBody>( true <- include inactive ) and wait
            //           for the body to become active?
            //       E.g., rb.AwaitInitialize += ThisConstraintInitialize.
            RigidBody rb1 = AttachmentPair.ReferenceObject.GetInitializedComponentInParent <RigidBody>();

            if (rb1 == null)
            {
                Debug.LogError("Unable to initialize constraint - reference object must contain a rigid body component.", AttachmentPair.ReferenceObject);
                return(false);
            }

            // Native constraint frames.
            agx.Frame f1 = new agx.Frame();
            agx.Frame f2 = new agx.Frame();

            // Note that the native constraint want 'f1' given in rigid body frame, and that
            // 'ReferenceFrame' may be relative to any object in the children of the body.
            f1.setLocalTranslate(AttachmentPair.ReferenceFrame.CalculateLocalPosition(rb1.gameObject).ToHandedVec3());
            f1.setLocalRotate(AttachmentPair.ReferenceFrame.CalculateLocalRotation(rb1.gameObject).ToHandedQuat());

            RigidBody rb2 = AttachmentPair.ConnectedObject != null?AttachmentPair.ConnectedObject.GetInitializedComponentInParent <RigidBody>() : null;

            if (rb1 == rb2)
            {
                Debug.LogError("Unable to initialize constraint - reference and connected rigid body is the same instance.", this);
                return(false);
            }

            if (rb2 != null)
            {
                // Note that the native constraint want 'f2' given in rigid body frame, and that
                // 'ReferenceFrame' may be relative to any object in the children of the body.
                f2.setLocalTranslate(AttachmentPair.ConnectedFrame.CalculateLocalPosition(rb2.gameObject).ToHandedVec3());
                f2.setLocalRotate(AttachmentPair.ConnectedFrame.CalculateLocalRotation(rb2.gameObject).ToHandedQuat());
            }
            else
            {
                f2.setLocalTranslate(AttachmentPair.ConnectedFrame.Position.ToHandedVec3());
                f2.setLocalRotate(AttachmentPair.ConnectedFrame.Rotation.ToHandedQuat());
            }

            try {
                Native = (agx.Constraint)Activator.CreateInstance(NativeType, new object[] { rb1.Native, f1, (rb2 != null ? rb2.Native : null), f2 });

                // Assigning native elementary constraints to our elementary constraint instances.
                foreach (ElementaryConstraint ec in ElementaryConstraints)
                {
                    if (!ec.OnConstraintInitialize(this))
                    {
                        throw new Exception("Unable to initialize elementary constraint: " + ec.NativeName + " (not present in native constraint). ConstraintType: " + Type);
                    }
                }

                bool added = GetSimulation().add(Native);
                Native.setEnable(IsEnabled);

                // Not possible to handle collisions if connected frame parent is null/world.
                if (CollisionsState != ECollisionsState.KeepExternalState && AttachmentPair.ConnectedObject != null)
                {
                    string     groupName            = gameObject.name + "_" + gameObject.GetInstanceID().ToString();
                    GameObject go1                  = null;
                    GameObject go2                  = null;
                    bool       propagateToChildren1 = false;
                    bool       propagateToChildren2 = false;
                    if (CollisionsState == ECollisionsState.DisableReferenceVsConnected)
                    {
                        go1 = AttachmentPair.ReferenceObject;
                        go2 = AttachmentPair.ConnectedObject;
                    }
                    else
                    {
                        go1 = rb1.gameObject;
                        propagateToChildren1 = true;
                        go2 = rb2 != null ? rb2.gameObject : AttachmentPair.ConnectedObject;
                        propagateToChildren2 = true;
                    }

                    go1.GetOrCreateComponent <CollisionGroups>().GetInitialized <CollisionGroups>().AddGroup(groupName, propagateToChildren1);
                    go2.GetOrCreateComponent <CollisionGroups>().GetInitialized <CollisionGroups>().AddGroup(groupName, propagateToChildren2);
                    CollisionGroupsManager.Instance.GetInitialized <CollisionGroupsManager>().SetEnablePair(groupName, groupName, false);
                }

                Native.setName(name);

                bool valid = added && Native.getValid();
                Simulation.Instance.StepCallbacks.PreSynchronizeTransforms += OnPreStepForwardUpdate;

                // It's not possible to check which properties an animator
                // is controlling, for now we update all properties in the
                // controllers if we have an animator.
                m_isAnimated = GetComponent <Animator>() != null;

                return(valid);
            }
            catch (System.Exception e) {
                Debug.LogException(e, gameObject);
                return(false);
            }
        }
Esempio n. 27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="go"></param>
 public static GameObjectCallBack GetCallbacks(this GameObject go)
 {
     return(go.GetOrCreateComponent <GameObjectCallBack>());
 }
Esempio n. 28
0
 public static T GetOrCreateComponent <T>(this GameObject target) where T : Component
 {
     return((T)target.GetOrCreateComponent(typeof(T)));
 }
Esempio n. 29
0
 /// <summary>
 /// 添加监听器
 /// </summary>
 /// <param name="bindObject"></param>
 /// <param name="eventType"></param>
 /// <param name="handler"></param>
 public static void AddEventListener <T, U, V, W>(this GameObject bindObject, string eventType, Action <T, U, V, W> handler)
 {
     MonoEventDispatcher.GetMonoController(bindObject).AddEventListener <T, U, V, W>(eventType, handler);
     bindObject.GetOrCreateComponent <MonoEventCleanUp>();
 }