コード例 #1
0
ファイル: qd_Mesh.cs プロジェクト: zjucsxxd/UnityRepository
        public static GameObject CreateDecal(Material mat, Rect uvCoords, float scale)
        {
            GameObject decal = new GameObject();
            decal.name = "Decal" + decal.GetInstanceID();

            decal.AddComponent<MeshFilter>().sharedMesh = DecalMesh("DecalMesh" + decal.GetInstanceID(), mat, uvCoords, scale);
            decal.AddComponent<MeshRenderer>().sharedMaterial = mat;

            #if UNITY_5
            decal.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            #else
            decal.GetComponent<MeshRenderer>().castShadows = false;
            #endif

            qd_Decal decalComponent = decal.AddComponent<qd_Decal>();

            decalComponent.SetScale(scale);
            decalComponent.SetTexture( (Texture2D)mat.mainTexture );
            decalComponent.SetUVRect(uvCoords);

            #if DEBUG
            decal.AddComponent<qd_DecalDebug>();
            #endif

            return decal;
        }
コード例 #2
0
        public static UnityEngine.GameObject Instantiate(UnityEngine.GameObject prefab, Transform parent, bool reset)
        {
            int instanceId = prefab.GetInstanceID();

            if (Pools.TryGetValue(instanceId, out Pool pool))
            {
                var result = pool.GetObjectFromPool(prefab, parent);

                if (reset)
                {
                    result.transform.Reset();
                }

                return(result);
            }
            else
            {
                var result = GameObject.Instantiate(prefab, parent);

                if (reset)
                {
                    result.transform.Reset();
                }

                return(result);
            }
        }
コード例 #3
0
        protected IEnumerator TestEmbodiment()
        {
            //we're going to break the action out because we don't care about memory management right here and we
            //want to clearly see what we're doing
            bool didConnect = false;

            System.Action <string> report = x => didConnect = (String.Compare(x, "true") == 0);

            //get the player object, if it exists
            UnityEngine.GameObject playerObject = GameObject.FindGameObjectWithTag("Player");
            string masterId   = playerObject.GetInstanceID().ToString();
            string masterName = playerObject.name;


            //This was the original way I did it until I enumerated manually.
            yield return(StartCoroutine(GameManager.entity.load.AtRunTime(embodimentSpawn, embodimentPrefab, "", masterName, masterId, report)));

            //note, this should handle everything appropriately even if the last yield return i tells the game to wait 20 minutes or what have you for the OAC to connect.
            //because it doesn't rely on the end value to determine connection.
            if (didConnect)
            {
                Debug.Log(OCLogSymbol.PASS + "Testing the Embodiment, Succeeded");
            }
            else
            {
                Debug.Log(OCLogSymbol.FAIL + "Testing the Embodiment, Failed");
                results[(int)TestTypes.EMBODIMENT] = false;
                result = false;
            }
            yield break;
        }
コード例 #4
0
 public void OnDestroyInstObject(UnityEngine.GameObject instObj)
 {
     if (instObj == null)
     {
         return;
     }
     OnDestroyInstObject(instObj.GetInstanceID());
 }
コード例 #5
0
        /// <summary>
        ///Returns a SphericalObstacle from the current gameObject 
        /// </summary>
        /// <param name="gameObject">
        /// A game object to create the obstacle from<see cref="GameObject"/>
        /// </param>
        /// <returns>
        /// A SphericalObstacle encompassing the game object<see cref="Obstacle"/>
        /// </returns>
        public static Obstacle GetObstacle( GameObject gameObject )
    	{
    		SphericalObstacle obstacle;
    		int id = gameObject.GetInstanceID();
    		Component[] colliders;
    		float radius = 0.0f, currentRadius;

    		if(!ObstacleCache.ContainsKey( id ))
    		{
				var obstacleData = gameObject.GetComponent<SphericalObstacleData>();
				// If the object provides his own spherical obstacle information,
				// use it instead of calculating a sphere that encompasses the 
				// whole collider.
				if (obstacleData != null) 
				{
					ObstacleCache[id] = new SphericalObstacle(obstacleData.Radius, gameObject.transform.position + obstacleData.Center);
				}
				else 
				{
	    			colliders = gameObject.GetComponentsInChildren<Collider>();
	
	    			if( colliders == null )
	    			{
	    				Debug.LogError( "Obstacle '" + gameObject.name + "' has no colliders" );
	    				return null;
	    			}
	
	    			foreach( Collider collider in colliders )
	    			{
	    				if( collider.isTrigger )
	    				{
	    					continue;
	    				}
	    				// Get the maximum extent to create a sphere that encompasses the whole obstacle
	    				float maxExtents = Mathf.Max(Mathf.Max(collider.bounds.extents.x, collider.bounds.extents.y),
	    				                             collider.bounds.extents.z);
	    				
					    /*
					     * Calculate the displacement from the object center to the 
					     * collider, and add in the maximum extents of the bounds.
					     * Notice that we don't need to multiply by the object's 
					     * local scale, since that is already considered in the 
					     * bounding rectangle.
					     */
					    float distanceToCollider = Vector3.Distance(gameObject.transform.position, collider.bounds.center);
	                    currentRadius = distanceToCollider + maxExtents;
	    				if( currentRadius > radius )
	    				{
	    					radius = currentRadius;
	    				}
	    			}
	    			ObstacleCache[id] = new SphericalObstacle( radius, gameObject.transform.position );
				}
    		}
    		obstacle = ObstacleCache[ id ] as SphericalObstacle;

    		return obstacle;
    	}
コード例 #6
0
ファイル: PolydrawObject.cs プロジェクト: wtrebella/Grappler
		public static PolydrawObject CreateInstance()
		{
			GameObject go = new GameObject();
			go.name = "Polydraw"+go.GetInstanceID();
			go.AddComponent<MeshFilter>();
			go.AddComponent<MeshRenderer>();

			return go.AddComponent<PolydrawObject>();
		}
コード例 #7
0
ファイル: SceneBuilder.cs プロジェクト: robgdl/Babylon.js
        string GetID(GameObject gameObject)
        {
            var key = gameObject.GetInstanceID();

            if (!uniqueGuids.ContainsKey(key))
            {
                uniqueGuids[key] = Guid.NewGuid().ToString();
            }

            return uniqueGuids[key];
        }
コード例 #8
0
ファイル: LuaBehaviour.cs プロジェクト: youxibuhaowana/01ulua
 // 添加单击事件
 public void AddClick(GameObject go)
 {
     if (go == null) return;
     string btnKey = go.name + go.GetInstanceID();
     buttons.Add(btnKey, go.name);
     go.GetComponent<Button>().onClick.AddListener(
         delegate() {
             luaMgr.CallFunction("DialogClickEvent.OnClick", btnKey);
         }
     );
 }
コード例 #9
0
ファイル: qd_Mesh.cs プロジェクト: benlewis/unhinged_vr
	public static GameObject CreateDecal(Material mat, Rect uvCoords, float scale)
	{
		GameObject decal = new GameObject();
		decal.name = "Decal" + decal.GetInstanceID();
		
		decal.AddComponent<MeshFilter>().sharedMesh = DecalMesh("DecalMesh" + decal.GetInstanceID(), mat, uvCoords, scale);
		decal.AddComponent<MeshRenderer>().sharedMaterial = mat;

		qd_Decal decalComponent = decal.AddComponent<qd_Decal>();

		decalComponent.SetScale(scale);
		decalComponent.SetTexture( (Texture2D)mat.mainTexture );
		decalComponent.SetUVRect(uvCoords);

		#if DEBUG
		decal.AddComponent<qd_DecalDebug>();
		#endif

		return decal;
	}
コード例 #10
0
    private static void SetFoldValueForGameObjectInHiearchyRecursive(GameObject gameObject, FoldValue fv) {
      var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.SceneHierarchyWindow");
      var methodInfo = type.GetMethod("SetExpandedRecursive");

      EditorApplication.ExecuteMenuItem("Window/Hierarchy");
      EditorWindow window = EditorWindow.focusedWindow;

      methodInfo.Invoke(window, new object[] {
        gameObject.GetInstanceID(),
        fv.BoolValue()
      });
    }
コード例 #11
0
ファイル: TopInfo.cs プロジェクト: rgebauer/snail
 public void UnlinkOnDestroyRemove(UnityEngine.GameObject obj)
 {
                 #if DEBUG
     string[] containing = _unlinkOnDestroy.Select(x => x.ToString()).ToArray();
     Debug.Log("GameObjectTopInfo.UnlinkOnDestroyRemove " + obj + " id " + obj.GetInstanceID() + " from " + gameObject + " id " + gameObject.GetInstanceID() + " containing: " + string.Join(",", containing));
                 #endif
     if (!_unlinkOnDestroy.Contains(obj))
     {
         //				Picus.Sys.Debug.Throw("GameObjectTopInfo.UnlinkToDestroyRemove " + obj + " not in", true);
         return;
     }
     _unlinkOnDestroy.Remove(obj);
 }
コード例 #12
0
ファイル: TopInfo.cs プロジェクト: rgebauer/snail
 public void UnlinkOnDestroyAdd(UnityEngine.GameObject obj)
 {
                 #if DEBUG
     string[] containing = _unlinkOnDestroy.Select(x => x.ToString()).ToArray();
     Debug.Log("GameObjectTopInfo.UnlinkOnDestroyAdd " + obj + " id " + obj.GetInstanceID() + " to " + gameObject + " id " + gameObject.GetInstanceID() + " containing: " + string.Join(",", containing));
                 #endif
     if (_unlinkOnDestroy.Contains(obj))
     {
         Picus.Sys.Debug.Throw("GameObjectTopInfo.UnlinkToDestroyAdd " + obj + " already added", true);
         return;
     }
     _unlinkOnDestroy.Add(obj);
 }
コード例 #13
0
ファイル: ResourceManager.cs プロジェクト: rgebauer/snail
        public new virtual UnityEngine.GameObject Instantiate(UnityEngine.GameObject prefab)
        {
            if (prefab == null)
            {
                Picus.Sys.Debug.Throw("ResourceManager.Instantiate null", true);
                return(null);
            }

            UnityEngine.GameObject obj = UnityEngine.GameObject.Instantiate(prefab) as UnityEngine.GameObject;
            Debug.Log("Instantiate " + obj + " id " + obj.GetInstanceID());
            obj.transform.parent = RuntimeParent();
            Picus.Utils.GO.Finder.FindComponentAddIfNotExist <Picus.Utils.GO.TopInfo>(obj);
            return(obj);
        }
コード例 #14
0
        public static UnityEngine.GameObject Instantiate(UnityEngine.GameObject prefab, Transform parent, bool instantiateInWorldSpace)
        {
            int  instanceId = prefab.GetInstanceID();
            Pool pool       = null;

            if (pools.TryGetValue(instanceId, out pool))
            {
                return(pool.GetObjectFromPool(prefab, parent, instantiateInWorldSpace));
            }
            else
            {
                return(GameObject.Instantiate(prefab, parent, instantiateInWorldSpace));
            }
        }
コード例 #15
0
    public AltUnityObject GameObjectToAltUnityObject(UnityEngine.GameObject altGameObject, UnityEngine.Camera camera = null)
    {
        int cameraId = -1;

        //if no camera is given it will iterate through all cameras until  found one that sees the object if no camera sees the object it will return the position from the last camera
        //if there is no camera in the scene it will return as scren position x:-1 y=-1, z=-1 and cameraId=-1
        if (camera == null)
        {
            _position = new UnityEngine.Vector3(-1, -1, -1);
            foreach (var camera1 in UnityEngine.Camera.allCameras)
            {
                _position = getObjectScreePosition(altGameObject, camera1);
                cameraId  = camera1.GetInstanceID();
                if (_position.x > 0 && _position.y > 0 && _position.x < UnityEngine.Screen.width && _position.y < UnityEngine.Screen.height && _position.z >= 0)//Check if camera sees the object
                {
                    break;
                }
            }
        }
        else
        {
            _position = getObjectScreePosition(altGameObject, camera);
            cameraId  = camera.GetInstanceID();
        }
        int parentId = 0;

        if (altGameObject.transform.parent != null)
        {
            parentId = altGameObject.transform.parent.GetInstanceID();
        }


        AltUnityObject altObject = new AltUnityObject(name: altGameObject.name,
                                                      id: altGameObject.GetInstanceID(),
                                                      x: System.Convert.ToInt32(UnityEngine.Mathf.Round(_position.x)),
                                                      y: System.Convert.ToInt32(UnityEngine.Mathf.Round(_position.y)),
                                                      z: System.Convert.ToInt32(UnityEngine.Mathf.Round(_position.z)),//if z is negative object is behind the camera
                                                      mobileY: System.Convert.ToInt32(UnityEngine.Mathf.Round(UnityEngine.Screen.height - _position.y)),
                                                      type: "",
                                                      enabled: altGameObject.activeSelf,
                                                      worldX: altGameObject.transform.position.x,
                                                      worldY: altGameObject.transform.position.y,
                                                      worldZ: altGameObject.transform.position.z,
                                                      idCamera: cameraId,
                                                      transformId: altGameObject.transform.GetInstanceID(),
                                                      parentId: parentId);

        return(altObject);
    }
コード例 #16
0
ファイル: LuaBehaviour.cs プロジェクト: youxibuhaowana/01ulua
 public void RemoveClick(GameObject go)
 {
     if (go == null) return;
     string btnKey = go.name + go.GetInstanceID();
     if(buttons.ContainsKey(btnKey))
     {
         buttons.Remove(btnKey);
     }
     else
     {
        Debug.Log("Empty Operation: RemoveClick target is empty");
        return;
     }
     go.GetComponent<Button>().onClick.RemoveAllListeners();
 }
コード例 #17
0
    private void addObjectToPool(UnityEngine.GameObject sourceObject, int number)
    {
        int uniqueId = sourceObject.GetInstanceID();

        //Add new entry if it doesn't exist
        if (!instantiatedObjects.ContainsKey(uniqueId))
        {
            instantiatedObjects.Add(uniqueId, new List <UnityEngine.GameObject>());
            poolCursors.Add(uniqueId, 0);
        }

        //Add the new objects
        UnityEngine.GameObject newObj;
        for (int i = 0; i < number; i++)
        {
            newObj = (UnityEngine.GameObject)Instantiate(sourceObject);
            newObj.SetActive(false);

            //Set flag to not destruct object
            CFX_AutoDestructShuriken[] autoDestruct = newObj.GetComponentsInChildren <CFX_AutoDestructShuriken>(true);
            foreach (CFX_AutoDestructShuriken ad in autoDestruct)
            {
                ad.OnlyDeactivate = true;
            }
            //Set flag to not destruct light
            CFX_LightIntensityFade[] lightIntensity = newObj.GetComponentsInChildren <CFX_LightIntensityFade>(true);
            foreach (CFX_LightIntensityFade li in lightIntensity)
            {
                li.autodestruct = false;
            }

            instantiatedObjects[uniqueId].Add(newObj);

            if (hideObjectsInHierarchy)
            {
                newObj.hideFlags = HideFlags.HideInHierarchy;
            }

            if (spawnAsChildren)
            {
                newObj.transform.parent = this.transform;
            }
        }
    }
コード例 #18
0
ファイル: UnityEventEx.cs プロジェクト: osmanzeki/bmachine
        public void InvokeOnTarget(GameObject target)
        {
            UnityAction call;

            int id = target.GetInstanceID ();

            //try for runtime added listeners
            if(m_Calls.TryGetValue(id,out call)){

                call.Invoke();
            }else{//try persistant(editor) added listeners
                int listenerNumber = this.GetPersistentEventCount();

                if(listenerNumber!=m_PersistentCallsDelegate.Length)
                    m_PersistentCallsDelegate=new PersistantCallDelegate[listenerNumber];

                MonoBehaviour listener;

                for (int i=0; i<listenerNumber; i++) {
                    listener=this.GetPersistentTarget(i) as MonoBehaviour;

                    if(listener.gameObject==target){

                        PersistantCallDelegate callDelegate=m_PersistentCallsDelegate[i];

                        if(callDelegate==null){
                            MethodInfo methodInfo=listener.GetType().GetMethod(this.GetPersistentMethodName(i));

                            //Call thru reflection is slow
                            //methodInfo.Invoke(listener,new object[]{damage,null});

                            m_PersistentCallsDelegate[i]=callDelegate=System.Delegate.CreateDelegate(typeof(PersistantCallDelegate),listener,methodInfo) as PersistantCallDelegate;

                        }

                        callDelegate.Invoke();

                    }
                }

            }
        }
コード例 #19
0
ファイル: XOEd_Main.cs プロジェクト: Klanly/UnityClient
        public static void AddObjDic(UnityEngine.GameObject origin, UnityEngine.GameObject newone)
        {
            XOCp_OptimizerHandler oph = XOGloble.Root.GetComponent <XOCp_OptimizerHandler>();

            if (oph != null)
            {
                Dictionary <int, OriginItermedia> p2O = oph.p2O;
                if (p2O != null)
                {
                    int instid = origin.GetInstanceID();
                    if (p2O.ContainsKey(instid) == false)
                    {
                        OriginItermedia objdata = new OriginItermedia();
                        objdata.origin = origin;
                        objdata.Iterm  = newone;
                        p2O.Add(instid, objdata);
                    }
                }
            }
        }
コード例 #20
0
    private void removeObjectsFromPool(UnityEngine.GameObject sourceObject)
    {
        int uniqueId = sourceObject.GetInstanceID();

        if (!instantiatedObjects.ContainsKey(uniqueId))
        {
            Debug.LogWarning("[CFX_SpawnSystem.removeObjectsFromPool()] There aren't any preloaded object for: " + sourceObject.name + " (ID:" + uniqueId + ")\n", this.gameObject);
            return;
        }

        //Destroy all objects
        for (int i = instantiatedObjects[uniqueId].Count - 1; i >= 0; i--)
        {
            UnityEngine.GameObject obj = instantiatedObjects[uniqueId][i];
            instantiatedObjects[uniqueId].RemoveAt(i);
            UnityEngine.GameObject.Destroy(obj);
        }

        //Remove pool entry
        instantiatedObjects.Remove(uniqueId);
        poolCursors.Remove(uniqueId);
    }
コード例 #21
0
ファイル: XOEd_Main.cs プロジェクト: Klanly/UnityClient
        public static UnityEngine.GameObject NewIterM(UnityEngine.GameObject origin)
        {
            UnityEngine.GameObject backobj = UnityEngine.GameObject.Instantiate(origin, origin.transform.position, origin.transform.rotation) as UnityEngine.GameObject;
            backobj.transform.parent     = XOGloble.IterM.transform;
            backobj.transform.localScale = origin.transform.lossyScale;
            backobj.name = XOUtil.Path(origin);
            XOCp_MarkIntermediate mi = backobj.AddComponent <XOCp_MarkIntermediate>();

            mi.OriginInstID = origin.GetInstanceID();
            mi.goOrigin     = origin;
            backobj.SetActive(true);

            XOCp_OptimizerHandler xoh = XOGloble.Root.GetComponent <XOCp_OptimizerHandler>();

            if (xoh != null)
            {
                xoh.AddObjLstByShaderMaterial(backobj);
            }

            XOUtil.Display(backobj, false);
            return(backobj);
        }
コード例 #22
0
ファイル: GameObjectPool.cs プロジェクト: dot123/UnityUtils
 public GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation)
 {
     int instanceID = original.GetInstanceID(); // 缓存池创建时不检查GUID参数,因为外部可能进行改变
     ObjectPoolItem item;
     
     if (!ObjectPoolItems.TryGetValue(instanceID, out item))
     {
         var newObj = GameObject.Instantiate(original, position, rotation) as GameObject;
         var parameter = newObj.AddMissingComponent<ObjectPoolParameter>();
         parameter.InstanceID = instanceID;
         newObj.BroadcastMessage("OnSpawned", SendMessageOptions.DontRequireReceiver);
         return newObj; 
     }
     
     var obj = item.GameObjects.Pop();
     if (item.GameObjects.Count == 0)
         ObjectPoolItems.Remove(instanceID);
     
     obj.transform.SetParent(null, false);
     obj.transform.position = position;
     obj.transform.rotation = rotation;
     obj.BroadcastMessage("OnSpawned", SendMessageOptions.DontRequireReceiver);
     return obj;
 }
コード例 #23
0
 // record listener, if not already recorded
 private bool recordListener(string eventType, GameObject listener, string function)
 {
     if (!checkForListener(eventType, listener)) {
         ArrayList listenerList = _listeners[eventType] as ArrayList;
         EventListener callback = new EventListener();
         callback.name = listener.GetInstanceID().ToString();
         callback.listener = listener;
         callback.function = function;
         listenerList.Add(callback);
         return true;
     } else {
         if (allowWarningOutputs) {
             Debug.LogWarning("Event Manager: Listener: " + listener.name + " is already in list for event: " + eventType);
         }
         return false;
     }
 }
コード例 #24
0
        // Remove event listener
        public bool removeEventListener(string eventType, GameObject listener)
        {
            if (!checkForEvent(eventType)) return false;

            ArrayList listenerList = _listeners[eventType] as ArrayList;
            foreach (EventListener callback in listenerList) {
                if (callback.name == listener.GetInstanceID().ToString()) {
                    listenerList.Remove(callback);
                    return true;
                }
            }
            return false;
        }
コード例 #25
0
        // check if listener exists
        private bool checkForListener(string eventType, GameObject listener)
        {
            if (!checkForEvent(eventType)) {
                recordEvent(eventType);
            }

            ArrayList listenerList = _listeners[eventType] as ArrayList;
            foreach (EventListener callback in listenerList) {
                if (callback.name == listener.GetInstanceID().ToString()) return true;
            }
            return false;
        }
		}//Update()





		// /// <summary>
		// ///Process inputs and update state of ui element.
		// /// </summary>
		// public void UpdateOld()
		// {
		// 	//Log.Debug("UI Update");
		// 	//
		// 	if(modalWindow != null)
		// 	{
		// 		if(!modalWindow.active)
		// 		{
		// 			//modal not active anymore, remove it
		// 			modalWindow = null;
		// 		}
		// 	}
			
		// 	GameObject obj = GetObjectUnderCursor();
		// 	if(obj != null)
		// 	{
							
		// 		//check if we are in modal mode
		// 		if(modalWindow != null)
		// 		{
		// 			//check if obj is in the modals list
		// 			if(!modals.ContainsKey(obj.GetInstanceID()))
		// 			{
		// 				if(lastButton != null)
		// 				{
		// 					lastButton.Release();
		// 					lastButton = null;
		// 				}
		// 				//not in the list
		// 				return;
		// 			}
		// 		}

		// 		//check if this is a button.
				
		// 		// Log.Info("HIT something:"+obj.name+" images:"+images.Count);
		// 		UIButton button = null;
		// 		if(images.ContainsKey(obj.GetInstanceID()))
		// 		{	
		// 			try
		// 			{
		// 				UIObject b = (UIObject)images[obj.GetInstanceID()];
		// 				UIType t = b.GetType();
		// 				// if(t ==  UIType.Button
		// 				// ||	t.GetType().IsSubclassOf(typeof(UIButton)))
		// 				if(t == UIType.Button 
		// 					|| t == UIType.ToggleButton
		// 					|| t == UIType.Slider
		// 					|| t == UIType.Checkbox)
		// 				{
		// 					button = (UIButton)b;
		// 				}
		// 			}
		// 			catch(System.Exception e)
		// 			{
		// 			 	Log.Debug("Could not find ui key:"+obj.name);
		// 			 	Log.Debug("error :"+e.ToString());
		// 			}
		// 		}

		// 		// if(button!=null)
		// 		//  	Log.Debug("---------------- Button:"+button.Name);
		// 		// else
		// 		// 	Log.Debug("---------------- Button NULL");

		// 		if(button != null && lastButton != null
		// 		 	&& button != lastButton )
		// 		{
		// 			//Log.Debug("Release!!");
		// 			lastButton.OverExit();
		// 			lastButton.Release();
		// 			lastButton = null;

		// 			return;
		// 		}
				
		// 		if(button == null && lastButton != null )
		// 		{
		// 			lastButton.OverExit();
		// 			lastButton.Release();
		// 			lastButton = null;
		// 			return;
		// 		}

		// 		if(button != null 
		// 		   && button.State != UIButtonState.OVER
		// 		   && button.State != UIButtonState.DISABLED
		// 		   && button.State != UIButtonState.ACTIVE_DISABLED
		// 		   && GameManager.Instance.hidTouch
		// 		   )
		// 		{
		// 			if(lastButton != null)
		// 			{
		// 				lastButton.Release();
		// 				lastButton = button;
		// 				lastButton.Push();
						
		// 			}
		// 			activeButton = button;
		// 		}
		// 		else if(button != null && button.State != UIButtonState.DISABLED && button.State != UIButtonState.ACTIVE_DISABLED)
		// 		{
		// 			//Log.Debug("button:"+button.Name);
		// 			if(Input.GetMouseButtonDown((int)MouseButton.Left))
		// 			{
		// 				//Log.Debug("button Push1:"+button.Name);
		// 				if(lastButton != null)
		// 				{
		// 					lastButton.Release();
		// 				}
		// 				lastButton = button;
		// 				button.Push();

		// 				activeButton = button;
		// 			}					
		// 			else if(Input.GetMouseButton((int)MouseButton.Left))
		// 			{
		// 				//Log.Debug("button push:"+button.Name);
		// 				//lastButton = button;
		// 				if(activeButton == button)
		// 				{
		// 					button.Push();
		// 					lastButton = button;
		// 				}
		// 				else if(lastButton != null)
		// 				{
		// 					lastButton.Release();
		// 				}
				
		// 			}				
		// 			else if (Input.GetMouseButtonUp((int)MouseButton.Left))
		// 			{
		// 				//Log.Debug("button Up:"+button.Name+" ab:"+lastButton.Name+" s:"+button.State);
						
		// 				if(activeButton == button)
		// 				{								
		// 					button.Click();
		// 					button.Release();
		// 				}
		// 				if(lastButton != null)
		// 					lastButton.Release();

		// 				lastButton = null;
		// 				activeButton = null;

		// 			}
		// 			else
		// 			{
		// 				if(lastButton != null && button != lastButton)
		// 				{
		// 					lastButton.OverExit();
		// 					lastButton.Release();
		// 				}
		// 				else if(activeButton == null)
		// 				{
		// 					lastButton = button;
		// 					button.Over();
		// 				}
		// 			}
		// 		}
		// 	}//tophit
		// 	else if(lastButton != null)
		// 	{
		// 		lastButton.OverExit();
		// 		//Log.Debug("***********************");
		// 		lastButton.Release();
		// 		lastButton = null;
		// 		//WebPlayerDebugManager.addOutput("------------- not tophit, activeButton="+activeButton+", lastButton="+lastButton,1);
				
		// 	}
		
		// }//Update()

		/// <summary>
		/// Check if the tooltip can be visible at the moment
		/// or should be hidden
		/// </summary>
		public bool CheckTooltipVisibility(GameObject obj)
		{
			if (modalWindow != null && modalWindow.active == true && !modals.ContainsKey(obj.GetInstanceID()))
			{
				return false;
			}
			return true;
		}
コード例 #27
0
		public void Start()
		{

			if (HighLogic.LoadedSceneIsEditor)
				return;

			try {
				// Parse bloody KSPField colors.
				if (!string.IsNullOrEmpty(backgroundColor))
					backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);
				if (!string.IsNullOrEmpty(ballColor))
					ballColorValue = ConfigNode.ParseColor32(ballColor);
				if (!string.IsNullOrEmpty(progradeColor))
					progradeColorValue = ConfigNode.ParseColor32(progradeColor);
				if (!string.IsNullOrEmpty(maneuverColor))
					maneuverColorValue = ConfigNode.ParseColor32(maneuverColor);
				if (!string.IsNullOrEmpty(targetColor))
					targetColorValue = ConfigNode.ParseColor32(targetColor);
				if (!string.IsNullOrEmpty(normalColor))
					normalColorValue = ConfigNode.ParseColor32(normalColor);
				if (!string.IsNullOrEmpty(radialColor))
					radialColorValue = ConfigNode.ParseColor32(radialColor);
				if (!string.IsNullOrEmpty(dockingColor))
					dockingColorValue = ConfigNode.ParseColor32(dockingColor);

				Shader unlit = Shader.Find("KSP/Alpha/Unlit Transparent");
				overlayMaterial = new Material(unlit);
				overlayMaterial.mainTexture = GameDatabase.Instance.GetTexture(staticOverlay.EnforceSlashes(), false);

				if (!string.IsNullOrEmpty(headingBar)) {
					headingMaterial = new Material(unlit);
					headingMaterial.mainTexture = GameDatabase.Instance.GetTexture(headingBar.EnforceSlashes(), false);
				}
				horizonTex = GameDatabase.Instance.GetTexture(horizonTexture.EnforceSlashes(), false);

				gizmoTexture = JUtil.GetGizmoTexture();

				// Ahaha, that's clever, does it work?
				stockNavBall = GameObject.Find("NavBall").GetComponent<NavBall>();
				// ...well, it does, but the result is bizarre,
				// apparently, because the stock BALL ITSELF IS MIRRORED.

				navBall = GameDatabase.Instance.GetModel(navBallModel.EnforceSlashes());
				Destroy(navBall.collider);
				navBall.name = "RPMNB" + navBall.GetInstanceID();
				navBall.layer = drawingLayer;
				navBall.transform.position = Vector3.zero;
				navBall.transform.rotation = Quaternion.identity;
				navBall.transform.localRotation = Quaternion.identity;

				if (ballIsEmissive) {
					navBall.renderer.material.shader = Shader.Find("KSP/Emissive/Diffuse");
					navBall.renderer.material.SetTexture("_MainTex", horizonTex);
					navBall.renderer.material.SetTextureOffset("_Emissive", navBall.renderer.material.GetTextureOffset("_MainTex"));
					navBall.renderer.material.SetTexture("_Emissive", horizonTex);
					navBall.renderer.material.SetColor("_EmissiveColor", ballColorValue);
				} else {
					navBall.renderer.material.shader = Shader.Find("KSP/Unlit");
					navBall.renderer.material.mainTexture = horizonTex;
					navBall.renderer.material.color = ballColorValue;
				}
				navBall.renderer.material.SetFloat("_Opacity", ballOpacity);

				markerPrograde = BuildMarker(0, 2, progradeColorValue);
				markerRetrograde = BuildMarker(1, 2, progradeColorValue);
				markerManeuver = BuildMarker(2, 0, maneuverColorValue);
				markerManeuverMinus = BuildMarker(1, 2, maneuverColorValue);
				markerTarget = BuildMarker(2, 1, targetColorValue);
				markerTargetMinus = BuildMarker(2, 2, targetColorValue);
				markerNormal = BuildMarker(0, 0, normalColorValue);
				markerNormalMinus = BuildMarker(1, 0, normalColorValue);
				markerRadial = BuildMarker(1, 1, radialColorValue);
				markerRadialMinus = BuildMarker(0, 1, radialColorValue);

				markerDockingAlignment = BuildMarker(0, 2, dockingColorValue);

				// Non-moving parts...
				cameraBody = new GameObject();
				cameraBody.name = "RPMPFD" + cameraBody.GetInstanceID();
				cameraBody.layer = drawingLayer;
				ballCamera = cameraBody.AddComponent<Camera>();
				ballCamera.enabled = false;
				ballCamera.orthographic = true;
				ballCamera.clearFlags = CameraClearFlags.Nothing;
				ballCamera.eventMask = 0;
				ballCamera.farClipPlane = 3f;
				ballCamera.orthographicSize = cameraSpan;
				ballCamera.cullingMask = 1 << drawingLayer;
				ballCamera.clearFlags = CameraClearFlags.Depth;
				// -2,0,0 seems to get the orientation exactly as the ship.
				// But logically, forward is Z+, right?
				// Which means that 
				ballCamera.transform.position = new Vector3(0, 0, 2);
				ballCamera.transform.LookAt(Vector3.zero, Vector3.up);
				ballCamera.transform.position = new Vector3(cameraShift.x, cameraShift.y, 2);

				overlay = CreateSimplePlane("RPMPFDOverlay" + internalProp.propID, 1f, drawingLayer);
				overlay.layer = drawingLayer;
				overlay.transform.position = new Vector3(0, 0, 1.5f);
				overlay.renderer.material = overlayMaterial;
				overlay.transform.parent = cameraBody.transform;
				FaceCamera(overlay);

				if (headingMaterial != null) {
					heading = CreateSimplePlane("RPMPFDHeading" + internalProp.propID, 1f, drawingLayer);
					heading.layer = drawingLayer;
					heading.transform.position = new Vector3(headingBarPosition.x, headingBarPosition.y, headingAboveOverlay ? 1.55f : 1.45f);
					heading.transform.parent = cameraBody.transform;
					heading.transform.localScale = new Vector3(headingBarPosition.z, 0, headingBarPosition.w);
					heading.renderer.material = headingMaterial;
					heading.renderer.material.SetTextureScale("_MainTex", new Vector2(headingSpan, 1f));
					FaceCamera(heading);
				}

				ShowHide(false, navBall, cameraBody, overlay, heading);
				startupComplete = true;
			} catch {
				JUtil.AnnoyUser(this);
				throw;
			}
		}
コード例 #28
0
        public static void CombineGameObjects(GameObject[] gos, GameObject staticBatchRoot, bool isEditorPostprocessScene)
        {
            Matrix4x4 lhs = Matrix4x4.identity;
            Transform staticBatchRootTransform = null;

            if (staticBatchRoot)
            {
                lhs = staticBatchRoot.transform.worldToLocalMatrix;
                staticBatchRootTransform = staticBatchRoot.transform;
            }
            int batchIndex = 0;
            int num        = 0;
            List <MeshSubsetCombineUtility.MeshContainer> list = new List <MeshSubsetCombineUtility.MeshContainer>();

            Array.Sort(gos, new InternalStaticBatchingUtility.SortGO());
            for (int i = 0; i < gos.Length; i++)
            {
                GameObject gameObject = gos[i];
                MeshFilter meshFilter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter;
                if (!(meshFilter == null))
                {
                    Mesh sharedMesh = meshFilter.sharedMesh;
                    if (!(sharedMesh == null) && (isEditorPostprocessScene || sharedMesh.canAccess))
                    {
                        Renderer component = meshFilter.GetComponent <Renderer>();
                        if (!(component == null) && component.enabled)
                        {
                            if (component.staticBatchIndex == 0)
                            {
                                Material[] array = component.sharedMaterials;
                                if (!array.Any((Material m) => m != null && m.shader != null && m.shader.disableBatching != DisableBatchingType.False))
                                {
                                    int vertexCount = sharedMesh.vertexCount;
                                    if (vertexCount != 0)
                                    {
                                        MeshRenderer meshRenderer = component as MeshRenderer;
                                        if (meshRenderer != null && meshRenderer.additionalVertexStreams != null)
                                        {
                                            if (vertexCount != meshRenderer.additionalVertexStreams.vertexCount)
                                            {
                                                goto IL_387;
                                            }
                                        }
                                        if (num + vertexCount > 64000)
                                        {
                                            InternalStaticBatchingUtility.MakeBatch(list, staticBatchRootTransform, batchIndex++);
                                            list.Clear();
                                            num = 0;
                                        }
                                        MeshSubsetCombineUtility.MeshInstance instance = default(MeshSubsetCombineUtility.MeshInstance);
                                        instance.meshInstanceID     = sharedMesh.GetInstanceID();
                                        instance.rendererInstanceID = component.GetInstanceID();
                                        if (meshRenderer != null && meshRenderer.additionalVertexStreams != null)
                                        {
                                            instance.additionalVertexStreamsMeshInstanceID = meshRenderer.additionalVertexStreams.GetInstanceID();
                                        }
                                        instance.transform                   = lhs * meshFilter.transform.localToWorldMatrix;
                                        instance.lightmapScaleOffset         = component.lightmapScaleOffset;
                                        instance.realtimeLightmapScaleOffset = component.realtimeLightmapScaleOffset;
                                        MeshSubsetCombineUtility.MeshContainer item = default(MeshSubsetCombineUtility.MeshContainer);
                                        item.gameObject       = gameObject;
                                        item.instance         = instance;
                                        item.subMeshInstances = new List <MeshSubsetCombineUtility.SubMeshInstance>();
                                        list.Add(item);
                                        if (array.Length > sharedMesh.subMeshCount)
                                        {
                                            Debug.LogWarning(string.Concat(new object[]
                                            {
                                                "Mesh '",
                                                sharedMesh.name,
                                                "' has more materials (",
                                                array.Length,
                                                ") than subsets (",
                                                sharedMesh.subMeshCount,
                                                ")"
                                            }), component);
                                            Material[] array2 = new Material[sharedMesh.subMeshCount];
                                            for (int j = 0; j < sharedMesh.subMeshCount; j++)
                                            {
                                                array2[j] = component.sharedMaterials[j];
                                            }
                                            component.sharedMaterials = array2;
                                            array = array2;
                                        }
                                        for (int k = 0; k < Math.Min(array.Length, sharedMesh.subMeshCount); k++)
                                        {
                                            MeshSubsetCombineUtility.SubMeshInstance item2 = default(MeshSubsetCombineUtility.SubMeshInstance);
                                            item2.meshInstanceID       = meshFilter.sharedMesh.GetInstanceID();
                                            item2.vertexOffset         = num;
                                            item2.subMeshIndex         = k;
                                            item2.gameObjectInstanceID = gameObject.GetInstanceID();
                                            item2.transform            = instance.transform;
                                            item.subMeshInstances.Add(item2);
                                        }
                                        num += sharedMesh.vertexCount;
                                    }
                                }
                            }
                        }
                    }
                }
                IL_387 :;
            }
            InternalStaticBatchingUtility.MakeBatch(list, staticBatchRootTransform, batchIndex);
        }
コード例 #29
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }
            try
            {
                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);

                cameraBody = new GameObject();
                cameraBody.name = "RPMPFD" + cameraBody.GetInstanceID();
                cameraBody.layer = drawingLayer;
                hudCamera = cameraBody.AddComponent<Camera>();
                hudCamera.enabled = false;
                hudCamera.orthographic = true;
                hudCamera.eventMask = 0;
                hudCamera.farClipPlane = 3f;
                hudCamera.orthographicSize = 1.0f;
                hudCamera.cullingMask = 1 << drawingLayer;
                // does this actually work?
                hudCamera.backgroundColor = backgroundColorValue;
                hudCamera.clearFlags = CameraClearFlags.Depth | CameraClearFlags.Color;
                hudCamera.transparencySortMode = TransparencySortMode.Orthographic;
                hudCamera.transform.position = Vector3.zero;
                hudCamera.transform.LookAt(new Vector3(0.0f, 0.0f, 1.5f), Vector3.up);

                if (!string.IsNullOrEmpty(progradeColor))
                {
                    progradeColorValue = ConfigNode.ParseColor32(progradeColor);
                }

                persistence = new PersistenceAccessor(internalProp);
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Start() failed with an exception: {0}", e);
                JUtil.AnnoyUser(this);
                throw;
            }

            startupComplete = true;
        }
コード例 #30
0
        public void StopByNode(GameObject controllingObject, InAudioNode nodeToStop, float fadeOutTime = 0.0f, LeanTweenType tweenType = LeanTweenType.easeOutCubic)
        {
            ObjectAudioList infoList;
            GOAudioNodes.TryGetValue(controllingObject.GetInstanceID(), out infoList);

            if (infoList != null)
            {
                var list = infoList.InfoList;
                for (int i = 0; i < list.Count; ++i)
                {
                    if (list[i].Node == nodeToStop)
                    {
                        list[i].Player.Stop(fadeOutTime, tweenType);
                    }
                }
            }
        }
コード例 #31
0
 private ObjectAudioList GetValue(Dictionary<int, ObjectAudioList> dictionary, GameObject go)
 {
     ObjectAudioList infoList;
     int instanceID = go.GetInstanceID();
     if (!dictionary.TryGetValue(instanceID, out infoList))
     {
         infoList = AudioListPool.GetObject();
         dictionary.Add(instanceID, infoList);
     }
     return infoList;
 }
コード例 #32
0
        public void GetPlayers(GameObject go, IList<InPlayer> copyTo)
        {
            ObjectAudioList infoList;
            GOAudioNodes.TryGetValue(go.GetInstanceID(), out infoList);

            if (infoList != null)
            {
                var list = infoList.InfoList;
                for (int i = 0; i < list.Count && i < copyTo.Count; i++)
                {
                    copyTo[i] = infoList.InfoList[i].Player;
                }
            }
        }
コード例 #33
0
 public void Break(GameObject controllingObject, InAudioNode toBreak)
 {
     ObjectAudioList infoList;
     GOAudioNodes.TryGetValue(controllingObject.GetInstanceID(), out infoList);
     if (infoList != null)
     {
         var list = infoList.InfoList;
         for (int i = 0; i < list.Count; ++i)
         {
             if (list[i].Node == toBreak)
             {
                 list[i].Player.Break();
             }
         }
     }
 }
コード例 #34
0
        public InPlayer[] GetPlayers(GameObject go)
        {
            ObjectAudioList infoList;
            GOAudioNodes.TryGetValue(go.GetInstanceID(), out infoList);

            if (infoList != null)
            {
                InPlayer[] players = new InPlayer[infoList.InfoList.Count];
                var list = infoList.InfoList;
                for (int i = 0; i < list.Count; i++)
                {
                    players[i] = infoList.InfoList[i].Player;
                }
                return players;
            }
            return null;
        }
コード例 #35
0
 public void SetVolumeForGameObject(GameObject controllingObject, float newVolume)
 {
     ObjectAudioList outInfoList;
     GOAudioNodes.TryGetValue(controllingObject.GetInstanceID(), out outInfoList);
     if (outInfoList != null)
     {
         List<RuntimeInfo> infoList = outInfoList.InfoList;
         int count = infoList.Count;
         for (int i = 0; i < count; ++i)
         {
             var player = infoList[i].Player;
             player.Volume = newVolume;
         }
     }
 }
コード例 #36
0
ファイル: AkAutoObject.cs プロジェクト: saestrada/examples
 public AkAutoObject(UnityEngine.GameObject GameObj)
 {
     m_id = (int)GameObj.GetInstanceID();
     AkSoundEngine.RegisterGameObj(GameObj, "AkAutoObject.cs", 0x01);
 }
コード例 #37
0
        public static void Combine(GameObject[] gos, GameObject staticBatchRoot)
        {
            Matrix4x4 lhs = Matrix4x4.identity;
            Transform staticBatchRootTransform = null;

            if (staticBatchRoot)
            {
                lhs = staticBatchRoot.transform.worldToLocalMatrix;
                staticBatchRootTransform = staticBatchRoot.transform;
            }
            int batchIndex = 0;
            int num        = 0;
            List <MeshSubsetCombineUtility.MeshInstance>    list  = new List <MeshSubsetCombineUtility.MeshInstance>();
            List <MeshSubsetCombineUtility.SubMeshInstance> list2 = new List <MeshSubsetCombineUtility.SubMeshInstance>();
            List <GameObject> list3 = new List <GameObject>();

            Array.Sort(gos, new InternalStaticBatchingUtility.SortGO());
            for (int i = 0; i < gos.Length; i++)
            {
                GameObject gameObject = gos[i];
                MeshFilter meshFilter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter;
                if (!(meshFilter == null))
                {
                    Mesh sharedMesh = meshFilter.sharedMesh;
                    if (!(sharedMesh == null) && sharedMesh.canAccess)
                    {
                        Renderer component = meshFilter.GetComponent <Renderer>();
                        if (!(component == null) && component.enabled)
                        {
                            if (component.staticBatchIndex == 0)
                            {
                                Material[] array = meshFilter.GetComponent <Renderer>().sharedMaterials;
                                if (!array.Any((Material m) => m != null && m.shader != null && m.shader.disableBatching != DisableBatchingType.False))
                                {
                                    if (num + meshFilter.sharedMesh.vertexCount > 64000)
                                    {
                                        InternalStaticBatchingUtility.MakeBatch(list, list2, list3, staticBatchRootTransform, batchIndex++);
                                        list.Clear();
                                        list2.Clear();
                                        list3.Clear();
                                        num = 0;
                                    }
                                    MeshSubsetCombineUtility.MeshInstance item = default(MeshSubsetCombineUtility.MeshInstance);
                                    item.meshInstanceID     = sharedMesh.GetInstanceID();
                                    item.rendererInstanceID = component.GetInstanceID();
                                    MeshRenderer meshRenderer = component as MeshRenderer;
                                    if (meshRenderer != null && meshRenderer.additionalVertexStreams != null)
                                    {
                                        item.additionalVertexStreamsMeshInstanceID = meshRenderer.additionalVertexStreams.GetInstanceID();
                                    }
                                    item.transform                   = lhs * meshFilter.transform.localToWorldMatrix;
                                    item.lightmapScaleOffset         = component.lightmapScaleOffset;
                                    item.realtimeLightmapScaleOffset = component.realtimeLightmapScaleOffset;
                                    list.Add(item);
                                    if (array.Length > sharedMesh.subMeshCount)
                                    {
                                        Debug.LogWarning(string.Concat(new object[]
                                        {
                                            "Mesh has more materials (",
                                            array.Length,
                                            ") than subsets (",
                                            sharedMesh.subMeshCount,
                                            ")"
                                        }), meshFilter.GetComponent <Renderer>());
                                        Material[] array2 = new Material[sharedMesh.subMeshCount];
                                        for (int j = 0; j < sharedMesh.subMeshCount; j++)
                                        {
                                            array2[j] = meshFilter.GetComponent <Renderer>().sharedMaterials[j];
                                        }
                                        meshFilter.GetComponent <Renderer>().sharedMaterials = array2;
                                        array = array2;
                                    }
                                    for (int k = 0; k < Math.Min(array.Length, sharedMesh.subMeshCount); k++)
                                    {
                                        list2.Add(new MeshSubsetCombineUtility.SubMeshInstance
                                        {
                                            meshInstanceID       = meshFilter.sharedMesh.GetInstanceID(),
                                            vertexOffset         = num,
                                            subMeshIndex         = k,
                                            gameObjectInstanceID = gameObject.GetInstanceID(),
                                            transform            = item.transform
                                        });
                                        list3.Add(gameObject);
                                    }
                                    num += sharedMesh.vertexCount;
                                }
                            }
                        }
                    }
                }
            }
            InternalStaticBatchingUtility.MakeBatch(list, list2, list3, staticBatchRootTransform, batchIndex);
        }
コード例 #38
0
        public float GetMinVolume(GameObject go, InAudioNode node)
        {

            ObjectAudioList infoList;
            int instanceID = go.GetInstanceID();
            float minVolume = -1; //volume should be (0-1)

            if (GOAudioNodes.TryGetValue(instanceID, out infoList))
            {
                var list = infoList.InfoList;
                int count = list.Count;
                minVolume = 10000f; //volume should be (0-1)
                for (int i = 0; i < count; i++)
                {
                    var info = list[i];
                    float volume = info.Player.Volume;
                    if (volume < minVolume)
                    {
                        minVolume = volume;
                    }
                }
            }
            else
            {
                Debug.LogWarning("InAudio: Node not found");
            }
            return minVolume;
        }
コード例 #39
0
ファイル: nodeParser.cs プロジェクト: lightszero/EgretUnity
        void Obj2Json(GameObject _obj, MyJson.JsonNode_Object _json)
        {
            _json["name"] = new MyJson.JsonNode_ValueString(_obj.name);
            _json["id"] = new MyJson.JsonNode_ValueNumber(_obj.GetInstanceID());
            //遍历填充组件
            MyJson.JsonNode_Array comps = new MyJson.JsonNode_Array();
            _json["components"] = comps;
            foreach (var c in _obj.GetComponents<Component>())
            {
                if (c == null)
                {
                    Debug.LogWarning("got a commponet null.");
                    continue;
                }
                string type = c.GetType().Name.ToLower();
                var _cjson = new MyJson.JsonNode_Object();
                _cjson["type"] = new MyJson.JsonNode_ValueString(type);
                if (componentParsers.ContainsKey(type) == false)
                {
                    Debug.LogWarning("can't find comparser:" + type);
                    continue;
                }

                componentParsers[type].WriteToJson(resmgr, _obj, c, _cjson);
                comps.Add(_cjson);
            }

            //遍历填充树
            if (_obj.transform.childCount > 0)
            {
                MyJson.JsonNode_Array children = new MyJson.JsonNode_Array();
                _json["children"] = children;

                for (int i = 0; i < _obj.transform.childCount; i++)
                {
                    var subobj = _obj.transform.GetChild(i).gameObject;
                    MyJson.JsonNode_Object _subjson = new MyJson.JsonNode_Object();
                    Obj2Json(subobj, _subjson);
                    children.Add(_subjson);
                }
            }

        }
コード例 #40
0
 private static ulong InternalGameObjectHash(UnityEngine.GameObject gameObject)
 {
     return(gameObject == null ? AK_INVALID_GAME_OBJECT : (ulong)gameObject.GetInstanceID());
 }
コード例 #41
0
ファイル: GameController.cs プロジェクト: p-dahlback/ld-33
        void MarkForPickup(GameObject headObject, Joint2D[] joints, GameObject[] playerParts)
        {
            Hashtable table = new Hashtable ();
            table.Add (headObject.GetInstanceID (), headObject);

            if (joints != null) {
                foreach (Joint2D joint in joints) {

                    if (joint != null && joint.connectedBody != null && joint.connectedBody.gameObject != null) {
                        GameObject obj = joint.connectedBody.gameObject;
                        if (!table.ContainsKey (obj.GetInstanceID ())) {
                            table.Add (obj.GetInstanceID (), obj);
                            ProcessConnectedObjects (obj, table);
                        }
                    } else {
                        DestroyImmediate (joint);
                    }
                }
            }

            if (table.Count < playerParts.Length + 1) {
                foreach (GameObject part in playerParts) {
                    if (part.tag.Equals (Constants.TAG_CURRENT_PLAYER))
                        continue;

                    if (!table.ContainsKey (part.GetInstanceID ())) {
                        MarkForPickup (part);
                    }
                }
            }
        }
コード例 #42
0
        private void OnActiveChanged(UnityEngine.GameObject obj, bool active)
        {
            if (active)
            {
                int instId = obj.GetInstanceID();
                int layer;
                if (m_LayerDict.TryGetValue(instId, out layer))
                {
                    SetLayer(obj, layer);
                }

                ParticleSystem[] pss = obj.GetComponentsInChildren <ParticleSystem>(true);
                for (int i = 0; i < pss.Length; i++)
                {
                    if (null != pss[i] && pss[i].main.playOnAwake)
                    {
                        //pss[i].Clear(true);
                        pss[i].Play(true);
                    }
                }
                AudioSource[] audioSources = obj.GetComponentsInChildren <AudioSource>(true);
                for (int i = 0; i < audioSources.Length; i++)
                {
                    if (null != audioSources[i] && audioSources[i].playOnAwake)
                    {
                        audioSources[i].Play();
                    }
                }
                NavMeshAgent agent = obj.GetComponent <NavMeshAgent>();
                if (null != agent)
                {
                    agent.enabled = false;
                }
                AbstractScriptBehavior[] scriptBehaviors = obj.GetComponentsInChildren <AbstractScriptBehavior>(true);
                for (int i = 0; i < scriptBehaviors.Length; ++i)
                {
                    if (null != scriptBehaviors[i])
                    {
                        scriptBehaviors[i].ResourceEnabled = true;
                    }
                }
            }
            else
            {
                ParticleSystem[] pss = obj.GetComponentsInChildren <ParticleSystem>(true);
                for (int i = 0; i < pss.Length; i++)
                {
                    if (null != pss[i] && pss[i].main.playOnAwake)
                    {
                        pss[i].Clear(true);
                        pss[i].Stop(true);
                    }
                }
                AudioSource[] audioSources = obj.GetComponentsInChildren <AudioSource>(true);
                for (int i = 0; i < audioSources.Length; i++)
                {
                    if (null != audioSources[i] && audioSources[i].playOnAwake)
                    {
                        audioSources[i].Stop();
                    }
                }

                NavMeshAgent agent = obj.GetComponent <NavMeshAgent>();
                if (null != agent)
                {
                    agent.enabled = false;
                }
                AbstractScriptBehavior[] scriptBehaviors = obj.GetComponentsInChildren <AbstractScriptBehavior>(true);
                for (int i = 0; i < scriptBehaviors.Length; ++i)
                {
                    if (null != scriptBehaviors[i])
                    {
                        scriptBehaviors[i].ResourceEnabled = false;
                    }
                }
            }
        }
コード例 #43
0
        private void CameraSetup(int index, string sourceName)
        {
            Camera sourceCam = JUtil.GetCameraByName(sourceName);

            if (sourceCam != null)
            {
                var cameraBody = new GameObject();
                cameraBody.name = typeof(RasterPropMonitor).Name + index + cameraBody.GetInstanceID();
                cameraObject[index] = cameraBody.AddComponent<Camera>();

                // Just in case to support JSITransparentPod.
                cameraObject[index].cullingMask &= ~(1 << 16 | 1 << 20);

                cameraObject[index].CopyFrom(sourceCam);
                cameraObject[index].enabled = false;
                cameraObject[index].targetTexture = screenTexture;
                cameraObject[index].aspect = cameraAspect;
            }
        }
コード例 #44
0
        public OCObjectMapInfo(UnityEngine.GameObject gameObject)
        {
            System.Console.WriteLine(OCLogSymbol.RUNNING + "OCObjectMapInfo::OCObjectMapInfo, passed object is of type: " + gameObject.GetType().ToString() + ", and name " + gameObject.name);

            _id = gameObject.GetInstanceID().ToString();

//			// Get id of a game object
//			_id = gameObject.GetInstanceID ().ToString ();
            // Get name
            _name = gameObject.name;

            // TODO [UNTESTED]: By default, we are using object type.
            _type = OCEmbodimentXMLTags.ORDINARY_OBJECT_TYPE;

            // Convert from unity coordinate to OAC coordinate.

            this.position = Utility.VectorUtil.ConvertToOpenCogCoord(gameObject.transform.position);
            // Get rotation
            _rotation = new Utility.Rotation(gameObject.transform.rotation);
            // Calculate the velocity later
            _velocity = UnityEngine.Vector3.zero;

            // Get size
            if (gameObject.collider != null)
            {
                // Get size information from collider.
                _width  = gameObject.collider.bounds.size.z;
                _height = gameObject.collider.bounds.size.y;
                _length = gameObject.collider.bounds.size.x;
            }
            else
            {
                Debug.LogWarning(OCLogSymbol.WARN + "No collider for gameobject " + gameObject.name + ", assuming a point.");

                // Set default value of the size.
                _width  = 0.1f;
                _height = 0.1f;
                _length = 0.1f;
            }

            if (gameObject.tag == "OCAGI")
            {
                // This is an OC avatar, we will use the brain id instead of unity id.
                OCConnectorSingleton connector = OCConnectorSingleton.Instance;

                if (connector != null)
                {
                    _id   = connector.BrainID;
                    _type = OCEmbodimentXMLTags.PET_OBJECT_TYPE;
                }

                System.Console.WriteLine(OCLogSymbol.RUNNING + "Just made an OCObjectMapInfo stating the AGI is at [" + this.position.x + ", " + this.position.y + ", " + this.position.z + "]");
            }
            else if (gameObject.tag == "OCNPC")
            {
                // This is a human player avatar.
                _type   = OCEmbodimentXMLTags.AVATAR_OBJECT_TYPE;
                _length = OCObjectMapInfo.DEFAULT_AVATAR_LENGTH;
                _width  = OCObjectMapInfo.DEFAULT_AVATAR_WIDTH;
                _height = OCObjectMapInfo.DEFAULT_AVATAR_HEIGHT;
            }

            if (gameObject.tag == "OCNPC" || gameObject.tag == "OCAGI" || gameObject.tag == "Player")
            {
                if (_height > 1.1f)                 // just to make sure that the center point of the character will not be in the block where the feet are
                {
                    this.position = new UnityEngine.Vector3(this.position.x, this.position.y, this.position.z + 1.0f);
                }
            }


            if (gameObject.name == "Hearth")
            {
                this.AddProperty("petHome", "TRUE", System.Type.GetType("System.Boolean"));
            }

            // Get weight
            if (gameObject.rigidbody != null)
            {
                _weight = gameObject.rigidbody.mass;
            }
            else
            {
                _weight = 0.0f;
            }

            if (gameObject.GetComponent <OpenCog.Extensions.OCConsumableData>() != null)
            {
                System.Console.WriteLine(OCLogSymbol.RUNNING + "Adding edible and foodbowl tags to '" + gameObject.name + "' with ID " + gameObject.GetInstanceID());
                this.AddProperty("edible", "TRUE", System.Type.GetType("System.Boolean"));
                this.AddProperty("pickupable", "TRUE", System.Type.GetType("System.Boolean"));
                this.AddProperty("holder", "none", System.Type.GetType("System.String"));
            }

            // Get a property manager instance
            // TODO [BLOCKED]: may need to re-enable this for other object types.
//			OCPropertyManager manager = gameObject.GetComponent<OCPropertyManager> () as OCPropertyManager;
//			if (manager != null) {
//				// Copy all OC properties from the manager, if any.
//				foreach (OpenCog.Serialization.OCPropertyField ocp in manager.propertyList) {
//					this.AddProperty (ocp.Key, ocp.value, ocp.valueType);
//				}
//			}

            this.AddProperty("visibility-status", "visible", System.Type.GetType("System.String"));
            this.AddProperty("detector", "true", System.Type.GetType("System.Boolean"));

            string gameObjectName = gameObject.name;

            if (gameObjectName.Contains("("))
            {
                gameObjectName = gameObjectName.Remove(gameObjectName.IndexOf('('));
            }



            // For Einstein puzzle
            if (gameObject.name.Contains("_man"))
            {
                _id = _name;
                this.AddProperty("class", "people", System.Type.GetType("System.String"));
            }
            else
            {
                this.AddProperty("class", gameObjectName, System.Type.GetType("System.String"));
            }
        }
		///<summary>
		/// Internal helper to get a uiButton from an object
		///</summary>
		private UIButton GetUIButtonFromObject(GameObject obj)
		{
			UIButton button = null;
			if(images.ContainsKey(obj.GetInstanceID()))
			{	
				try
				{
					UIObject b = (UIObject)images[obj.GetInstanceID()];
					UIType t = b.GetType();
					// if(t ==  UIType.Button
					// ||	t.GetType().IsSubclassOf(typeof(UIButton)))
					if(t == UIType.Button 
						|| t == UIType.ToggleButton
						|| t == UIType.Slider
						|| t == UIType.Checkbox)
					{
						button = (UIButton)b;
					}
				}
				catch(System.Exception e)
				{
				 	Log.Debug("Could not find ui key:"+obj.name);
				 	Log.Debug("error :"+e.ToString());
				 	button = null;
				}
			}

			return button;
		}
コード例 #46
0
 public AddCurvesPopupGameObjectNode(GameObject gameObject, TreeViewItem parent, string displayName) : base(gameObject.GetInstanceID(), (parent == null) ? -1 : (parent.depth + 1), parent, displayName)
 {
 }
		}//LoadSprite()
		
		/// <summary>
		/// Adds a UI button.		
		/// </summary>
		/// <param name="obj">Parent game object.</param>
		/// <param name="fileName">Resource file name with path, relative to Rersources folder.</param>
		public UIObject Add(UIType type, GameObject obj, string fileName, Sprite spr = null)
		{
			Log.Info("Add: <color=yellow>"+obj.name+" - id:"+obj.GetComponent<GUIText>()+"</color> type:"+type);

			//// Log.GameTimes("_______________-_-_-_-_-_ <color=yellow>"+fileName+" _____ obj: "+obj+"</color>, type: "+type);


			if(images.ContainsKey(obj.GetInstanceID()))
			{
			 	//give warning, then return existing one (ignore new registration)
			 	Log.Debug("This button already registered, ignoring new registration. <color=cyan>" + obj.name+"</color> ");
			 	return images[obj.GetInstanceID()];
			}

			Sprite[] sprList = new Sprite[1];
			if(fileName.Length == 0)
			{

				if(spr == null)
				{
					Log.Debug("This button <color=yellow>"+obj.name+"</color> has no image.");
				}
				else
				{
					Log.Debug("Sprite >>>>>>>>>>>>>>>>> "+spr.name);
					sprList[0] = spr;
				}
			}
			else
			{
				sprList = LoadSprite(fileName);
			}



			UIObject image = null;
			switch(type)
			{
				case UIType.Image:
					Log.Debug("Add UIImage");
					image = new UIImage(obj, sprList);
					break;

				case UIType.Button:
					Log.Debug("Add UIButton");
					image = new UIButton(obj, sprList);
					break;

				case UIType.ToggleButton:
					Log.Debug("Add UIToggleButton");
					image = new UIToggleButton(obj, sprList);
					break;
					
				case UIType.Slider:
					Log.Debug("Add UISlider");
					image = new UISlider(obj, sprList);
					break;

				case UIType.Character:
					Log.Debug("Add UICharacter");
					image = new UICharacter(obj, sprList);
					break;

				case UIType.ChartPie:
					Log.Debug("Add UIChartPie");
					image = new UIChartPie(obj);
					break;

				case UIType.ChartLine:
					Log.Debug("Add UIChartLine");
					image = new UIChartLine(obj);
					break;

				case UIType.Checkbox:
					Log.Debug("Add Checkbox");
					image = new UICheckbox(obj, sprList);
					break;

				default:
					Log.Exception("Invalid UIType to add:" + type);
					break;
			}

			//TODO remove this
			images.Add(obj.GetInstanceID(), image);
			
			//
			//images.Add(""+lastId++, image);
			//Log.Info("Button added:"+obj.name+" image:"+image.Name);

			return image;

		}//Add()
コード例 #48
0
        public void StopAll(GameObject controllingObject, float fadeOutTime, LeanTweenType type)
        {
            ObjectAudioList infoList;
            GOAudioNodes.TryGetValue(controllingObject.GetInstanceID(), out infoList);

            if (infoList != null)
            {
                var list = infoList.InfoList;
                for (int i = 0; i < list.Count; ++i)
                {
                    if (fadeOutTime > 0)
                        list[i].Player.Stop(fadeOutTime, type);
                    else
                        list[i].Player.Stop();
                }
            }
        }