コード例 #1
0
ファイル: NestedFSM.cs プロジェクト: nemish/cubematters
        /////////
        protected override Status OnExecute(Component agent, IBlackboard blackboard)
        {
            if (nestedFSM == null || nestedFSM.primeNode == null){
                return Status.Failure;
            }

            if (status == Status.Resting){
                CheckInstance();
            }

            if (status == Status.Resting || nestedFSM.isPaused){
                status = Status.Running;
                nestedFSM.StartGraph(agent, blackboard, OnFSMFinish);
            }

            if (!string.IsNullOrEmpty(successState) && nestedFSM.currentStateName == successState){
                nestedFSM.Stop();
                return Status.Success;
            }

            if (!string.IsNullOrEmpty(failureState) && nestedFSM.currentStateName == failureState){
                nestedFSM.Stop();
                return Status.Failure;
            }

            return status;
        }
コード例 #2
0
ファイル: KDepBuild_NGUI.cs プロジェクト: s3chugo/KEngine
        public void Process(Component @object)
        {
            var label = (UILabel)@object;
            // 图片字体! 打包字
            if (label.bitmapFont != null)
            {
                string uiFontPath = KDepBuild_NGUI.BuildUIFont(label.bitmapFont);
                //CResourceDependencies.Create(label, CResourceDependencyType.BITMAP_FONT, uiFontPath);
                KAssetDep.Create<KBitmapFontDep>(label, uiFontPath);

                label.bitmapFont = null;
            }
            else if (label.trueTypeFont != null)
            {
                string fontPath = KDependencyBuild.BuildFont(label.trueTypeFont);

                //CResourceDependencies.Create(label, CResourceDependencyType.FONT, fontPath);
                KAssetDep.Create<KUILabelDep>(label, fontPath);
                label.trueTypeFont = null; // 挖空依赖的数据
            }
            else
            {
                Logger.LogWarning("找不到Label的字体: {0}, 场景: {1}", label.name, EditorApplication.currentScene);
            }
        }
コード例 #3
0
 public override Dictionary<string, object> getAttributesFrom(Component component)
 {
     Dictionary<string, object> scriptAttributes = new Dictionary<string, object>();
     addScriptFieldsToDictionary (scriptAttributes, component);
     addScriptPropertiesToDictionary (scriptAttributes, component);
     return scriptAttributes;
 }
コード例 #4
0
 static public int AddComponent(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(System.String)))
         {
             UnityEngine.GameObject self = (UnityEngine.GameObject)checkSelf(l);
             System.String          a1;
             checkType(l, 2, out a1);
             UnityEngine.Component ret = self.AddComponent(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (matchType(l, 2, typeof(System.Type)))
         {
             UnityEngine.GameObject self = (UnityEngine.GameObject)checkSelf(l);
             System.Type            a1;
             checkType(l, 2, out a1);
             UnityEngine.Component ret = self.AddComponent(a1);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #5
0
    public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
    {
        SerializedProperty target = prop.FindPropertyRelative("mTarget");
        Component          comp   = target.objectReferenceValue as Component;

        return((comp != null) ? 36f : 16f);
    }
コード例 #6
0
        public static Component ComponentField(Rect position, GUIContent label, Component value, System.Type inheritsFromType, bool allowSceneObjects, System.Type targetComponentType)
        {
            if (inheritsFromType == null) inheritsFromType = typeof(Component);
            else if (!typeof(Component).IsAssignableFrom(inheritsFromType) && !typeof(IComponent).IsAssignableFrom(inheritsFromType)) throw new TypeArgumentMismatchException(inheritsFromType, typeof(IComponent), "Type must inherit from IComponent or Component.", "inheritsFromType");
            if (targetComponentType == null) throw new System.ArgumentNullException("targetComponentType");
            if (!typeof(Component).IsAssignableFrom(targetComponentType)) throw new TypeArgumentMismatchException(targetComponentType, typeof(Component), "targetComponentType");
            if (value != null && !targetComponentType.IsAssignableFrom(value.GetType())) throw new TypeArgumentMismatchException(value.GetType(), inheritsFromType, "value must inherit from " + inheritsFromType.Name, "value");

            if (TypeUtil.IsType(inheritsFromType, typeof(Component)))
            {
                return EditorGUI.ObjectField(position, label, value, inheritsFromType, true) as Component;
            }
            else
            {
                value = EditorGUI.ObjectField(position, label, value, typeof(Component), true) as Component;
                var go = GameObjectUtil.GetGameObjectFromSource(value);
                if (go != null)
                {
                    foreach (var c in go.GetComponents(inheritsFromType))
                    {
                        if (TypeUtil.IsType(c.GetType(), targetComponentType))
                        {
                            return c as Component;
                        }
                    }
                }
            }

            return null;
        }
コード例 #7
0
        new void Start()
        {
            base.Start ();
            if (entity == null) {
                Debug.LogError("Serenity Method Trigger miss a gameObject");
                return;
            }
            if (method == null) {
                MethodInfo mi = entity.GetType().GetMethod(methodName);
                foreach(Component comp in entity.GetComponents<Component>()) {
                    mi = comp.GetType().GetMethod(methodName);
                    if(mi!=null)
                    {
                        component = comp;
                        break;
                    }
                }
                if(mi==null)
                {
                    Debug.LogError ("Serenity Method Trigger miss a boolean-returned method with name "+methodName);
                }
                else {

                    method = mi;
                }
            } else {
                methodName = method.Name;
            }
        }
コード例 #8
0
    public void DestroyObject(UnityEngine.Object obj)
    {
        if (obj == null)
        {
            return;
        }

        if (obj is Transform)
        {
            obj = (obj as Transform).gameObject;
        }

        UnityEngine.Component comp = obj as UnityEngine.Component;
        if (comp != null)
        {
            if (Application.isPlaying)
            {
                UnityEngine.GameObject.Destroy(obj);
            }
            else
            {
                UnityEngine.GameObject.DestroyImmediate(obj);
            }
            //UnityEngine.GameObject.DestroyImmediate(obj);
            return;
        }

        if (!UnLoadOrgObject(obj))
        {
            UnityEngine.GameObject gameObj = obj as GameObject;
            if (gameObj != null)
            {
                int instId = obj.GetInstanceID();

                // gameObj.transform.parent = null;
                if (Application.isPlaying)
                {
                    UnityEngine.GameObject.Destroy(obj);
                }
                else
                {
                    UnityEngine.GameObject.DestroyImmediate(obj);
                }
                //UnityEngine.GameObject.DestroyImmediate (obj);

                AssetCacheManager.Instance._OnDestroyGameObject(instId);
            }
            else
            {
                if (Application.isPlaying)
                {
                    UnityEngine.GameObject.Destroy(obj);
                }
                else
                {
                    UnityEngine.GameObject.DestroyImmediate(obj);
                }
            }
        }
    }
コード例 #9
0
ファイル: DamageAction.cs プロジェクト: gormed/darwin
    protected override void DoAction(UnityEngine.Component other)
    {
        if (other is IDamageable)
        {
            timer += Time.deltaTime;
            if (timer < Attack.Cooldown)
            {
                return;
            }
            timer = 0;

            IDamageable damageable = other as IDamageable;

            DamageContext damage = new DamageContext();
            damage.Attack   = Attack;
            damage.Attacker = null;
            damage.Enemy    = damageable;
            damage.IsMeele  = true;

            damageable.OnDamaged(damage);

            if (Util.Length(Force) > 0 &&
                other.gameObject.rigidbody != null)
            {
                other.gameObject.rigidbody.AddForce(Force);
            }
        }
    }
コード例 #10
0
 public void Clear()
 {
     this._triggerable = null;
     this._triggerableArgs = null;
     this._activationType = TriggerActivationType.TriggerAllOnTarget;
     this._methodName = null;
 }
コード例 #11
0
        public static KISItemModuleWrapper FromComponent(Component component)
        {
            if (component != null)
                return new KISItemModuleWrapper(component);

            return null;
        }
コード例 #12
0
    public SourceBindingProperty(Component target, string fieldName)
    {
        mTarget = target;
        mName   = fieldName;

        var strs = mName.Split(':');

        var strComps = strs[0].Split('.');

        object obj = target.GetComponent(strComps[strComps.Length - 1]);

        if (obj == null)
        {
            throw new Exception("bad root name");
        }

        for (var i = 1; i < strs.Length - 1; i++)
        {
            var type         = obj.GetType();
            var propertyInfo = type.GetProperty(strs[i]);
            obj = propertyInfo.GetGetMethod().Invoke(obj, new object[] {});
        }

        mNotifyPropertyChanged = obj as INotifyPropertyChanged;
        if (mNotifyPropertyChanged == null)
        {
            return;
        }
        mPropertyName = strs[strs.Length - 1];
    }
コード例 #13
0
ファイル: Flicked.cs プロジェクト: Jashengmato/TouchScript
 public override void Reset()
 {
     GameObject = null;
     Component = null;
     ScreenFlickVector = null;
     SendEvent = null;
 }
コード例 #14
0
        public object Apply(Type targetType, Injector activeInjector, Dictionary<string, object> injectParameters)
        {
            if (parentObject == null)
            {
                object contextViewObj = (IContextView) activeInjector.GetInstance(typeof(IContextView));
                if(contextViewObj != null)
                {
                    object contextView = ((IContextView) contextViewObj).view;
                    if(contextView != null)
                    {
                        if (contextView is Transform) parentObject = (Transform) contextView;
                        else if (contextView is GameObject) parentObject = ((GameObject) contextView).transform;
                    }
                }
            }
            if (parentObject == null)
            {
                destroyGameObjectWhenComplete = true;
                parentObject = new GameObject("Unity Component Provider").transform;
            }
            component = parentObject.gameObject.AddComponent(componentType);

            //TODO: Make auto InjectInto configurable
            activeInjector.InjectInto(component);

            if (_postApply != null)
            {
                _postApply(this, component);
            }
            return component;
        }
コード例 #15
0
 static public int constructor(IntPtr l)
 {
     UnityEngine.Component o;
     o = new UnityEngine.Component();
     pushObject(l, o);
     return(1);
 }
コード例 #16
0
 private void InternalAddPrefab(UnityEngine.Component o)
 {
     if (o != null)
     {
         _prefabs.Add(o.GetType(), o);
     }
 }
コード例 #17
0
		private static List<CoherentMethodBindingInfo> GetCoherentMethodsInComponent(Component component)
		{
			List<CoherentMethodBindingInfo> coherentMethods = new List<CoherentMethodBindingInfo>();
			
			Type type = component.GetType();
		
			List<CoherentMethodBindingInfo> cachedCoherentMethods;
			if (s_CoherentMethodsCache.TryGetValue(type, out cachedCoherentMethods))
			{
				return cachedCoherentMethods;
			}
			
			// Iterate methods of each type
			BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
			foreach (MethodInfo methodInfo in type.GetMethods(bindingFlags))
			{
				// Iterate custom attributes
				var attributes = methodInfo.GetCustomAttributes(typeof(CoherentMethodAttribute), true);	
				foreach (object customAttribute in attributes)
				{
					CoherentMethodAttribute coherentMethodAttribute = (customAttribute as CoherentMethodAttribute);
					Delegate func = CoherentMethodHelper.ToDelegate(methodInfo, component);
					coherentMethods.Add(new CoherentMethodBindingInfo(){
						ScriptEventName = coherentMethodAttribute.ScriptEventName,
						BoundFunction = func,
						IsEvent = coherentMethodAttribute.IsEvent
					});
				}
			}
			
			s_CoherentMethodsCache.Add(type, coherentMethods);
			
			return coherentMethods;
		}
コード例 #18
0
        /// <summary>
        /// Processes a single event listener phases
        /// </summary>
        /// <param name="adapter">Component descriptor referencing event handlers</param>
        /// <param name="component">Component dispatching events</param>
        /// <param name="mapping">Event mapping</param>
        /// <param name="enabled">Enabled state</param>
        public static void ProcessPhases(ComponentAdapter adapter, Components.Component component, EventMapping mapping, bool enabled)
        {
            if (null == component && null == adapter.Component)  // not instantiated (edit mode) and no component supplied
            {
                return;
            }

            Component script = adapter.GetComponent(mapping.ScriptName);

            if (null == script)
            {
                Debug.LogWarning("Component " + mapping.ScriptName + " not found on " + adapter.gameObject);
                return;
            }

            Type         type       = script.GetType();
            MethodInfo   methodInfo = type.GetMethod(mapping.MethodName, AllInstanceMethodsBindingFlags, null, TypeOfEvent, Modifiers); //type.GetMethod(mapping.MethodName, TypeOfEvent);
            EventHandler handler    = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), script, methodInfo);

            var cmp = component ?? adapter.Component;

            /**
             * 1. Remove all phases
             * */
            cmp.RemoveEventListener(mapping.EventType, handler, EventPhase.Capture | EventPhase.Target | EventPhase.Bubbling);

            /**
             * 2. If enabled, subscribe again
             * */
            if (enabled)
            {
                cmp.AddEventListener(mapping.EventType, handler, mapping.Phase);
            }
        }
コード例 #19
0
        Dictionary <string, object> SerializeComponent(UnityEngine.Component component)
        {
            var result = new Dictionary <string, object>();

            result["$type"]       = component.GetType().FullName;
            result["$instanceId"] = component.GetInstanceID();

            var data = new Dictionary <string, object>();

            result["data"] = data;

            var cTransform = component as Transform;

            if (cTransform != null)
            {
                data["position"] = ToDictionary(cTransform.position);
                data["rotation"] = ToDictionary(cTransform.rotation);
                data["scale"]    = ToDictionary(cTransform.localScale);
                return(result);
            }

            result["data"] = ToDictionary(component);

            return(result);
        }
コード例 #20
0
        public void WriteToJson(IResMgr resmgr, GameObject node, Component component, MyJson.JsonNode_Object json)
        {
            SkinnedMeshRenderer ic = component as SkinnedMeshRenderer;
            //json["type"] = new MyJson.JsonNode_ValueString(this.comptype.Name.ToLower());//必须的一行
            //放到外面去了

            //材质
            MyJson.JsonNode_Array mats = new MyJson.JsonNode_Array();

            json["mats"] = mats;

            foreach (var m in ic.sharedMaterials)
            {
                string hash = resmgr.SaveMat(m);
                mats.Add(new MyJson.JsonNode_ValueString(hash));
            }

            //bounds
            json["center"] = new MyJson.JsonNode_ValueString(StringHelper.ToString(ic.localBounds.center));
            json["size"] = new MyJson.JsonNode_ValueString(StringHelper.ToString(ic.localBounds.size));

            //mesh
            json["mesh"] = new MyJson.JsonNode_ValueString(resmgr.SaveMesh(ic.sharedMesh));

            json["rootboneobj"] = new MyJson.JsonNode_ValueNumber(ic.rootBone.gameObject.GetInstanceID());
            MyJson.JsonNode_Array bones = new MyJson.JsonNode_Array();
            foreach (var b in ic.bones)
            {
                bones.Add(new MyJson.JsonNode_ValueNumber(b.gameObject.GetInstanceID()));
            }
            json["boneobjs"] = bones;
            ic.rootBone.GetInstanceID();
        }
コード例 #21
0
ファイル: Iterator.cs プロジェクト: nemish/cubematters
        protected override Status OnExecute(Component agent, IBlackboard blackboard)
        {
            if (decoratedConnection == null)
                return Status.Resting;

            if (list == null || list.Count == 0)
                return Status.Failure;

            for (int i = currentIndex; i < list.Count; i++){

                current.value = list[i];
                status = decoratedConnection.Execute(agent, blackboard);

                if (status == Status.Success && terminationCondition == TerminationConditions.FirstSuccess)
                    return Status.Success;

                if (status == Status.Failure && terminationCondition == TerminationConditions.FirstFailure)
                    return Status.Failure;

                if (status == Status.Running){
                    currentIndex = i;
                    return Status.Running;
                }

                if (currentIndex == list.Count-1 || currentIndex == maxIteration.value-1){
                    return status;
                }

                decoratedConnection.Reset();
                currentIndex ++;
            }

            return Status.Running;
        }
コード例 #22
0
 public override void ReadFrom(object obj)
 {
     base.ReadFrom(obj);
     if (obj == null)
     {
         return;
     }
     UnityEngine.ParticleSystem.TriggerModule o = (UnityEngine.ParticleSystem.TriggerModule)obj;
     enabled     = o.enabled;
     inside      = o.inside;
     outside     = o.outside;
     enter       = o.enter;
     exit        = o.exit;
     radiusScale = o.radiusScale;
     if (o.maxColliderCount > 20)
     {
         UnityEngine.Debug.LogWarning("maxPlaneCount is expected to be 6 or at least <= 20");
     }
     colliders = new long[o.maxColliderCount];
     for (int i = 0; i < o.maxColliderCount; ++i)
     {
         UnityEngine.Component collider = o.GetCollider(i);
         colliders[i] = collider.GetMappedInstanceID();
     }
 }
コード例 #23
0
ファイル: NGDebug.cs プロジェクト: Hengle/clapotis
    public static void      LogHierarchy(UnityEngine.Component component)
    {
        if (Application.platform != RuntimePlatform.WindowsEditor && Application.platform != RuntimePlatform.OSXEditor)
        {
            return;
        }

        StringBuilder buffer = Utility.GetBuffer();

        buffer.Length = 0;
        buffer.Append(InternalNGDebug.MultiContextsStartChar);

        if (component != null)
        {
            Transform transform = component.transform;

            while (transform != null)
            {
                buffer.Append(transform.GetInstanceID());
                buffer.Append(InternalNGDebug.MultiContextsSeparator);

                transform = transform.parent;
            }

            // Remove last separator.
            buffer.Length -= 1;
        }

        buffer.Append(InternalNGDebug.MultiContextsEndChar);
        Debug.Log(Utility.ReturnBuffer(buffer));
    }
コード例 #24
0
ファイル: Action.cs プロジェクト: s76/testAI
        public override void Init(Reactor reactor)
        {
            base.Init(reactor);

            ComponentMethod cm = null;
            try {
                cm = reactor.FindMethod(actionMethod);
            } catch (ArgumentNullException e) {
                Debug.LogError("[Action Node] Could not find method :" + actionMethod + "\n" + NodeNamesInStack());
                throw e;
            }
            if(cm == null) {
                Debug.LogError("Could not load action method: " + actionMethod);
            } else {
                if(cm.methodInfo.ReturnType == typeof(IEnumerator<NodeResult>)) {
                    component = cm.component;
                    methodInfo = cm.methodInfo;
                    if( methodParams != null )
                    {
                        methodParams.ConvertParams(methodInfo);
                    }
                } else {
                    Debug.LogError("Action method has invalid signature: " + actionMethod);
                }
            }
        }
コード例 #25
0
    /// <summary>
    /// Draw a component field in inspector
    /// </summary>
    /// <param name="inspectedParameter"></param>
    /// <param name="label"></param>
    /// <param name="valueType"></param>
    /// <param name="oldValue"></param>
    /// <param name="fieldList"></param>
    /// <returns></returns>
    internal static object DrawComponent(InspectedField inspectedParameter, string label, Type valueType, object oldValue, List <InspectedField> fieldList)
    {
        UnityEngine.Component component = new UnityEngine.Component();

        if (inspectedParameter == null) // it's a newly add parameter for inspecting
        {
            //Make a new InspectedField and add it to the list.
            InspectedField iField = new InspectedField(label, component, true, valueType);
            fieldList.Add(iField);

            return(EditorGUILayout.ObjectField(label, component, valueType, true));
        }
        else
        {
            if (oldValue is UnityEngine.Component)
            {
                component = (UnityEngine.Component)oldValue;
                inspectedParameter.Value = EditorGUILayout.ObjectField(label, component, valueType, true);

                //Set the value return from user input from inspector to the InspectedParameterList
                return(inspectedParameter.Value);
            }
            else
            {
                Debug.LogFormat("{0} is not {1} type", label, valueType);
                return(null);
            }
        }
    }
コード例 #26
0
        private void OnUpdateComponentProperties(rdtTcpMessage message)
        {
            rdtDebug.Debug(this, "OnUpdateComponentProperties", new object[0]);
            rdtTcpMessageUpdateComponentProperties properties = (rdtTcpMessageUpdateComponentProperties)message;
            GameObject gob = this.FindGameObject(properties.m_gameObjectInstanceId);

            if (gob != null)
            {
                UnityEngine.Component owner = this.FindComponent(gob, properties.m_componentInstanceId);
                if (owner == null)
                {
                    rdtDebug.Error(this, "Tried to update component with id {0} (name={1}) but couldn't find it!", new object[] { properties.m_componentInstanceId, properties.m_componentName });
                }
                else
                {
                    if (owner is Behaviour)
                    {
                        ((Behaviour)owner).enabled = properties.m_enabled;
                    }
                    else if (owner is Renderer)
                    {
                        ((Renderer)owner).enabled = properties.m_enabled;
                    }
                    else if (owner is Collider)
                    {
                        ((Collider)owner).enabled = properties.m_enabled;
                    }
                    if (properties.m_properties != null)
                    {
                        this.m_server.SerializerRegistry.WriteAllFields(owner, properties.m_properties);
                    }
                }
            }
        }
コード例 #27
0
ファイル: AiRig.cs プロジェクト: Miista/TerrainGeneration
 //Should only be created as part of our base framework
 public static AiRig ExtractRigInfo(Component c)
 {
     var rig = c.GetComponent<AiRig>();
     if (rig == null)
         c.GetComponentInParent<AiRig>();
     return rig;
 }
コード例 #28
0
        protected override Status OnExecute(Component agent, IBlackboard blackboard)
        {
            currentProbability = probability;
            for (var i = 0; i < outConnections.Count; i++){

                if (failedIndeces.Contains(i))
                    continue;

                if (currentProbability > childWeights[i].value){
                    currentProbability -= childWeights[i].value;
                    continue;
                }

                status = outConnections[i].Execute(agent, blackboard);
                if (status == Status.Success || status == Status.Running)
                    return status;

                if (status == Status.Failure){
                    failedIndeces.Add(i);
                    var newTotal = GetTotal();
                    for (var j = 0; j < failedIndeces.Count; j++){
                        newTotal -= childWeights[j].value;
                    }
                    probability = Random.Range(0, newTotal);
                    return Status.Running;
                }
            }

            return Status.Failure;
        }
コード例 #29
0
        protected override Status OnExecute(Component agent, IBlackboard blackboard)
        {
            if (decoratedConnection == null)
                return Status.Resting;

            switch(filterMode)
            {
                case FilterMode.CoolDown:

                    if (currentTime > 0)
                        return inactiveWhenLimited? Status.Resting : Status.Failure;

                    status = decoratedConnection.Execute(agent, blackboard);
                    if (status == Status.Success || status == Status.Failure)
                        StartCoroutine(Cooldown());
                    break;

                case FilterMode.LimitNumberOfTimes:

                    if (executedCount >= maxCount.value)
                        return inactiveWhenLimited? Status.Resting : Status.Failure;

                    status = decoratedConnection.Execute(agent, blackboard);
                    if (status == Status.Success || status == Status.Failure)
                        executedCount += 1;
                    break;
            }

            return status;
        }
コード例 #30
0
 static int AddComponent(IntPtr L)
 {
     try
     {
         UnityEngine.GameObject self = LuaExtend.GetObject(L, 1) as UnityEngine.GameObject;
         if (self == null)
         {
             throw new LuaException(L, "Object is null");
         }
         string component             = LuaDLL.lua_tostring(L, 2);
         ComponentMethodDelegate func = null;
         if (typesAdd.TryGetValue(component, out func))
         {
             UnityEngine.Component com = func(self);
             LuaExtend.AddObject2Lua(L, com, null);
         }
         else
         {
             throw new LuaException(L, "Component is not registed:" + component);
         }
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.wluaL_error(L, e));
     }
 }
コード例 #31
0
        /// <summary>
        /// Returns an array of all components attached to the selected GameObject instance, except UnityEngine.Camera and UnityEngine.Transform
        /// </summary>
        private static U.Component[] GatherComponents(U.GameObject selected)
        {
            U.Component[] initialGather = selected.GetComponents <U.Component>();
            U.Component[] finalGather;
            uint          count = 0;

            for (uint i = 0; i < initialGather.Length; i++)
            {
                if (!(initialGather[i] is U.Camera) && !(initialGather[i] is U.Transform) && (initialGather[i] != null))
                {
                    count++;
                }
            }
            finalGather = new U.Component[count];
            count       = 0;
            for (uint i = 0; i < initialGather.Length; i++)
            {
                if (!(initialGather[i] is U.Camera) && !(initialGather[i] is U.Transform) && (initialGather[i] != null))
                {
                    finalGather[count] = initialGather[i];
                    count++;
                }
            }
            return(finalGather);
        }
コード例 #32
0
ファイル: DataBindingBase.cs プロジェクト: Hengle/Hermit
        protected (Component component, MemberInfo memberInfo) ParseViewEntry(Component viewProvider,
                                                                              string entry)
        {
            var(typeName, memberName) = ParseEntry2TypeMember(entry);

            var component = viewProvider.GetComponent(typeName);

            if (component == null)
            {
                Her.Error($"Can't find component of type: {typeName} on {viewProvider}.");
                return(null, null);
            }

            var viewMemberInfos = component.GetType().GetMember(memberName);

            if (viewMemberInfos.Length <= 0)
            {
                Her.Error($"Can't find member of name: {memberName} on {component}.");
                return(null, null);
            }

            var memberInfo = viewMemberInfos[0];

            return(component, memberInfo);
        }
コード例 #33
0
 public override void Reset()
 {
     GameObject = null;
     Component = null;
     ScreenPosition = null;
     SendEvent = null;
 }
コード例 #34
0
        protected override Status OnExecute(Component agent, IBlackboard blackboard)
        {
            if (outConnections.Count == 0)
                return Status.Failure;

            if (selectionMode == CaseSelectionMode.IndexBased){

                current = intCase.value;
                if (outOfRangeMode == OutOfRangeMode.LoopIndex)
                    current = Mathf.Abs(current) % outConnections.Count;

            } else {

                current = (int)System.Enum.Parse(enumCase.value.GetType(), enumCase.value.ToString());
            }

            if (runningIndex != current)
                outConnections[runningIndex].Reset();

            if (current < 0 || current >= outConnections.Count)
                return Status.Failure;

            status = outConnections[current].Execute(agent, blackboard);

            if (status == Status.Running)
                runningIndex = current;

            return status;
        }
コード例 #35
0
        /// <summary>
        /// Grab all the component instances that derive from the interface
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T[] FindComponentsOfType <T>()
        {
            Type lInterfaceType = typeof(T);

            Type[] lTypes = GetInterfaceTypes(lInterfaceType);
            if (lTypes == null || lTypes.Length == 0)
            {
                return(null);
            }

            List <T> lInstances = new List <T>();

            for (int i = 0; i < lTypes.Length; i++)
            {
                Type lType = lTypes[i];

                // Only grab components
                if (lType.IsSubclassOf(typeof(Component)))
                {
                    lInstances.AddRange(Component.FindObjectsOfType(lType).Cast <T>());
                }
            }

            // Grab the distinct set of objects
            return(lInstances.Distinct().ToArray());
        }
コード例 #36
0
 public UIShowHideController(GameObject go, Component panel)
 {
     this.panel = panel;
     this.animator = (go != null) ? go.GetComponent<Animator>() : null;
     if (animator == null && panel != null) animator = panel.GetComponent<Animator>();
     this.animCoroutine = null;
 }
コード例 #37
0
        protected override Status OnExecute(Component agent, IBlackboard blackboard)
        {
            for ( var i= 0; i < outConnections.Count; i++){

                if (!dynamic && finishedConnections.Contains(outConnections[i]))
                    continue;

                status = outConnections[i].Execute(agent, blackboard);

                if (status == Status.Failure && (policy == ParallelPolicy.FirstFailure || policy == ParallelPolicy.FirstSuccessOrFailure) ){
                    ResetRunning();
                    return Status.Failure;
                }

                if (status == Status.Success && (policy == ParallelPolicy.FirstSuccess || policy == ParallelPolicy.FirstSuccessOrFailure) ){
                    ResetRunning();
                    return Status.Success;
                }

                if (status != Status.Running && !finishedConnections.Contains(outConnections[i]))
                    finishedConnections.Add(outConnections[i]);
            }

            if ( finishedConnections.Count != outConnections.Count ) return Status.Running;
            switch(policy)
            {
                case ParallelPolicy.FirstFailure:
                    return Status.Success;
                case ParallelPolicy.FirstSuccess:
                    return Status.Failure;
            }

            return Status.Running;
        }
コード例 #38
0
        public static void MoveComponent(this UnityEngine.Component component, int offset) // : where T:UnityEngine.Component
        {
#if UNITY_EDITOR
            if (component == null)
            {
                return;
            }

#if UNITY_2018_3_OR_NEWER
            var status = UnityEditor.PrefabUtility.GetPrefabInstanceStatus(component.gameObject);
            if (status == PrefabInstanceStatus.Connected)
            {
                Debug.Log("cannot move component on prefab, aborting. remove this debug");
                return;
            }
#endif
            if (offset < 0)
            {
                for (int i = 0; i < -offset; i++)
                {
                    UnityEditorInternal.ComponentUtility.MoveComponentUp(component);
                }
            }
            else
            {
                for (int i = 0; i < offset; i++)
                {
                    UnityEditorInternal.ComponentUtility.MoveComponentDown(component);
                }
            }
#endif
        }
コード例 #39
0
 static public int GetComponentsInParent(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(System.Type)))
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             UnityEngine.Component[] ret = self.GetComponentsInParent(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (matchType(l, 2, typeof(System.Type), typeof(System.Boolean)))
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             UnityEngine.Component[] ret = self.GetComponentsInParent(a1, a2);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #40
0
    protected override void DoAction(UnityEngine.Component other)
    {
        //GameObject go = GameObject.Find(name);
        gameObject.rigidbody.useGravity = true;
        if (Util.Length(Force) > 0)
        {
            Vector3 force;
            if (UseRandomForce)
            {
                force = new Vector3((float)Util.Randomizer.NextDouble() * Force.x,
                                    (float)Util.Randomizer.NextDouble() * Force.y,
                                    (float)Util.Randomizer.NextDouble() * Force.z);
            }
            else
            {
                force = Force;
            }
//			gameObject.rigidbody.AddForce(
//				force);
//			gameObject.rigidbody.AddTorque(
//				force);
            gameObject.rigidbody.AddRelativeForce(
                force);
            gameObject.rigidbody.AddRelativeTorque(
                force);
            //gameObject.collider.ClosestPointOnBounds(gameObject.transform.position - (force.normalized * 100.0f)));
        }
        if (FadeTime > 0)
        {
            Destroy(gameObject, FadeTime);
        }
    }
コード例 #41
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            float w = position.width;

            position.width = w * .6f;
            EditorGUI.ObjectField(position, property, typeof(UnityEngine.Component), label);
            UnityEngine.Component content = null;//(UnityEngine.Component)property.objectReferenceValue;
            var obj = property.objectReferenceValue;

            if (obj != null && obj is UnityEngine.Component)
            {
                content = (UnityEngine.Component)obj;
                var comps = content.GetComponents <Component>();
                m_AllComponents.Clear();
                int selectIndex = 0;
                int i           = 0;
                foreach (var comp in comps)
                {
                    m_AllComponents.Add(comp.GetType().Name);
                    if (comp == content)
                    {
                        selectIndex = i;
                    }
                    i++;
                }
                position.x     = position.xMax;
                position.width = w - position.width;
                selectIndex    = EditorGUI.Popup(position, selectIndex, m_AllComponents.ToArray());
                content        = comps[selectIndex];
            }
            property.objectReferenceValue = content;
        }
コード例 #42
0
 public void CloseIfOurs(Component component)
 {
     if (component == m_component)
     {
         Close();
     }
 }
コード例 #43
0
 public static Component CreateChild(this Transform parent, Component child)
 {
     Component go = GameObject.Instantiate(child);
     go.transform.SetParent(parent);
     go.transform.Reset();
     return go;
 }
コード例 #44
0
 public ComponentData Serialize(Component component) {
     var placedItem = (PlacedItem) component;
     return new PlacedItemData {
         Id = placedItem.CatalogEntry.Id,
         Unique = placedItem.UniqueInSlot
     };
 }
コード例 #45
0
 /// <summary>
 /// Declares that the conversion result of the target Component depends on another component. Any changes to the
 /// dependency should trigger a reconversion of the dependent component.
 /// </summary>
 /// <param name="target">The Component that has a dependency.</param>
 /// <param name="dependsOn">The Component that the target depends on.</param>
 public void DeclareDependency(Component target, Component dependsOn)
 {
     if (target != null && dependsOn != null)
     {
         m_MappingSystem.Dependencies.DependOnGameObject(target.gameObject, dependsOn.gameObject);
     }
 }
コード例 #46
0
        private static BehaviorNodeConfig CreateNodeConfig(this BehaviorTreeConfig treeConfig, string name)
        {
            NodeMeta   proto = BTEditor.Instance.GetComponent <BTNodeInfoComponent>().GetNodeMeta(name);
            GameObject go    = new GameObject()
            {
                name = name
            };

            go.transform.parent = treeConfig.gameObject.transform;
            BehaviorNodeConfig node = go.AddComponent <BehaviorNodeConfig>();

            node.name     = name;
            node.describe = proto.describe;

            foreach (NodeFieldDesc args in proto.new_args_desc)
            {
                Type type = BTTypeManager.GetBTType(args.type);
                UnityEngine.Component comp = go.AddComponent(type);
                FieldInfo             info = type.GetField("fieldName");
                info.SetValue(comp, args.name);
                FieldInfo info1 = type.GetField("fieldValue");
                info1.SetValue(comp, args.value);
            }
            return(node);
        }
コード例 #47
0
ファイル: pb_ComponentDiff.cs プロジェクト: procore3d/giles
		/**
		 * Add a diff entry for a component.  `component` points to the edited component, name is the variable name, and 
		 * value is the new value.
		 */
		public static void AddDiff(Component component, string name, object value)
		{
			GameObject go = component.gameObject;

			pb_MetaDataComponent md_component = go.GetComponent<pb_MetaDataComponent>();

			if(md_component == null)
				md_component = go.AddComponent<pb_MetaDataComponent>();

			pb_ComponentDiff diff = md_component.metadata.componentDiff;

			Dictionary<string, object> v;

			if(diff.modifiedValues.TryGetValue(component, out v))
			{
				if(v.ContainsKey(name))
					v[name] = value;
				else
					v.Add(name, value);
			}
			else
			{
				diff.modifiedValues.Add(component, new Dictionary<string, object>() { {name, value} } );
			}
		}
コード例 #48
0
 static public int GetComponentsInChildren(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             var ret = self.GetComponentsInChildren(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (argc == 3)
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             var ret = self.GetComponentsInChildren(a1, a2);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #49
0
		void DoAddComponent(GameObject go)
		{
			addedComponent = go.AddComponent(script.Value);

			if (addedComponent == null)
				ActionHelpers.RuntimeError(this, "Can't add script: " + script.Value);
		}
コード例 #50
0
    static public bool GetComponent <COMPONENT>(this UnityEngine.Component pTarget, COMPONENT pComponent)
        where COMPONENT : UnityEngine.Component
    {
        pComponent = pTarget.GetComponent <COMPONENT>();

        return(pComponent != null);
    }
コード例 #51
0
        /// <summary>
        /// Grab all the component instances that derive from the interface
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T[] FindComponentsOfType <T>()
        {
            Type lInterfaceType = typeof(T);

            Type[] lTypes = GetInterfaceTypes(lInterfaceType);
            if (lTypes == null || lTypes.Length == 0)
            {
                return(null);
            }

            List <T> lInstances = new List <T>();

            for (int i = 0; i < lTypes.Length; i++)
            {
                Type lType = lTypes[i];

                // Only grab components
#if !UNITY_EDITOR && (NETFX_CORE || WINDOWS_UWP || UNITY_WP8 || UNITY_WP_8_1 || UNITY_WSA || UNITY_WSA_8_0 || UNITY_WSA_8_1 || UNITY_WSA_10_0)
                if (lType.GetTypeInfo().IsAssignableFrom(typeof(Component).GetTypeInfo()))
#else
                if (lType.IsSubclassOf(typeof(Component)))
#endif
                {
                    lInstances.AddRange(Component.FindObjectsOfType(lType).Cast <T>());
                }
            }

            // Grab the distinct set of objects
            return(lInstances.Distinct().ToArray());
        }
コード例 #52
0
 static public int GetComponent(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (matchType(l, argc, 2, typeof(string)))
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.String         a1;
             checkType(l, 2, out a1);
             var ret = self.GetComponent(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (matchType(l, argc, 2, typeof(System.Type)))
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             var ret = self.GetComponent(a1);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #53
0
 public MvxComponentOnEventTargetBinding(Component component, string eventName)
     : base(component)
 {
     _eventName = eventName;
     if (component == null)
     {
         MvxBindingTrace.Trace(MvxTraceLevel.Error, "Error - Component is null in MvxComponentOnEventTargetBinding");
     }
     else
     {
         _eventTarget = UIEventListener.Get(component.gameObject);
         switch (_eventName)
         {
             case "onClick":
                 _eventTarget.onClick += this.OnClick;
                 break;
             case "onPress":
                 _eventTarget.onPress += this.OnPress;
                 break;
             case "onDrag":
                 _eventTarget.onDrag += this.OnDrag;
                 break;
             case "OnDrop":
                 _eventTarget.onDrop += this.OnDrop;
                 break;
         }
     }
 }
コード例 #54
0
    static int GetComponent(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.GameObject), typeof(string)))
            {
                UnityEngine.GameObject obj = (UnityEngine.GameObject)ToLua.ToObject(L, 1);
                string arg0             = ToLua.ToString(L, 2);
                UnityEngine.Component o = obj.GetComponent(arg0);
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.GameObject), typeof(System.Type)))
            {
                UnityEngine.GameObject obj  = (UnityEngine.GameObject)ToLua.ToObject(L, 1);
                System.Type            arg0 = (System.Type)ToLua.ToObject(L, 2);
                UnityEngine.Component  o    = obj.GetComponent(arg0);
                ToLua.Push(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.GameObject.GetComponent"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
コード例 #55
0
ファイル: Invoke.cs プロジェクト: AlexGam/TowerIsland
		private IEnumerator InvokeMethod(Component component){
			yield return new WaitForSeconds(delay.Value);
			MethodInfo methodInfo=component.GetType().GetMethod(methodName);
			if (methodInfo != null) {
				methodInfo.Invoke (component, new object[]{});
			} 
		}
コード例 #56
0
 public static List <UnityEngine.Component> GetList(ref List <UnityEngine.Component> rList, long L, int nIndex)
 {
     try
     {
         long VM = FCLibHelper.fc_get_vm_ptr(L);
         if (rList == null)
         {
             rList = new List <UnityEngine.Component>();
         }
         else
         {
             rList.Clear();
         }
         long ptr        = FCLibHelper.fc_get_param_ptr(L, nIndex);
         int  nArraySize = FCLibHelper.fc_get_array_size(ptr);
         for (int i = 0; i < nArraySize; ++i)
         {
             long item_ptr = FCLibHelper.fc_get_array_node_temp_ptr(VM, ptr, i);
             UnityEngine.Component item = FCGetObj.GetObj <UnityEngine.Component>(item_ptr);
             rList.Add(item);
         }
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
     return(rList);
 }
コード例 #57
0
 static public int GetComponents(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             var ret = self.GetComponents(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 3)
         {
             UnityEngine.Component self = (UnityEngine.Component)checkSelf(l);
             System.Type           a1;
             checkType(l, 2, out a1);
             System.Collections.Generic.List <UnityEngine.Component> a2;
             checkType(l, 3, out a2);
             self.GetComponents(a1, a2);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #58
0
		protected override Status OnExecute(Component agent, IBlackboard bb){

			if (outConnections.Count == 0)
				return Error("There are no connections to the Multiple Choice Node!");

			var finalOptions = new Dictionary<IStatement, int>();

			for (var i = 0; i < availableChoices.Count; i++){
				var condition = availableChoices[i].condition;
				if (condition == null || condition.CheckCondition(finalActor.transform, bb)){
					var tempStatement = availableChoices[i].statement.BlackboardReplace(bb);
					finalOptions[tempStatement] = i;					
				}
			}

			if (finalOptions.Count == 0){
				Debug.Log("Multiple Choice Node has no available options. Dialogue Ends");
				DLGTree.Stop();
				return Status.Failure;
			}

			if (availableTime > 0)
				StartCoroutine(CountDown());

			var optionsInfo = new MultipleChoiceRequestInfo(finalOptions, availableTime, OnOptionSelected);
			DialogueTree.RequestMultipleChoices( optionsInfo );
			return Status.Running;
		}
コード例 #59
0
		public override void Reset()
		{
			gameObject = null;
			behaviour = null;
			component = null;
			enable = true;
			resetOnExit = true;
		}
コード例 #60
0
 public static bool AddClipToAnimationPlayerComponent(Component animationPlayer, AnimationClip newClip)
 {
     if (animationPlayer is Animator)
     {
         return AddClipToAnimatorComponent(animationPlayer as Animator, newClip);
     }
     return ((animationPlayer is Animation) && AddClipToAnimationComponent(animationPlayer as Animation, newClip));
 }