示例#1
0
    public bool AddMesh(GameObject go)
    {
        if (_lut.ContainsKey(go.GetInstanceID())) {
            return true;
        }

        // returns false if renderer is not available
        if (go.GetComponent<Renderer>() == null) {
            return false;
        }

        // returns false if not a mesh
        MeshFilter mf = (MeshFilter)go.GetComponent (typeof(MeshFilter));
        if (mf == null) {
            return false;
        }

        MeshData md = new MeshData ();
        md._instID = go.GetInstanceID ();
        md._vertCount = mf.mesh.vertexCount;
        md._triCount = mf.mesh.triangles.Length / 3;
        md._materialCount = go.GetComponent<Renderer>().sharedMaterials.Length;
        md._boundSize = go.GetComponent<Renderer>().bounds.size.magnitude;
        _lut.Add (md._instID, md);
        return true;
    }
示例#2
0
    /// <summary>
    /// プールからオブジェクトを取得する
    /// </summary>
    /// <param name="prefab">プーリングしたゲームオブジェクト</param>
    /// <param name="position">セットする座標</param>
    /// <param name="rotation">セットする回転</param>
    /// <param name="parent">parentに設定するGameObjectのTransform</param>
    /// <returns>Active状態にしたゲームオブジェクト</returns>
    public GameObject GetObject(GameObject prefab, Vector3 position, Quaternion rotation, Transform parent = null)
    {
        // キーが存在しない
        if (!pooledObject.ContainsKey(prefab.GetInstanceID()))
        {
            return null;
        }

        // プールを取得
        List<GameObject> pool = pooledObject[prefab.GetInstanceID()];

        // 既に生成した分で足りている場合
        foreach (var list in pool)
        {
            if (!list.activeInHierarchy)
            {
                list.transform.position = position;
                list.transform.rotation = rotation;
                list.transform.parent = parent;
                list.SetActive(true);
                return list;
            }
        }

        // 不足していた場合
        var obj = Instantiate(prefab, position, rotation) as GameObject;
        obj.transform.parent = parent;
        pool.Add(obj);

        return obj;
    }
示例#3
0
    public GameObject Request(GameObject prefab, Transform parent, Vector3 position, Quaternion rotation)
    {
        if (id == 0) id = prefab.GetInstanceID ();

        if(id != prefab.GetInstanceID())
        {
            Debug.LogError(string.Format("Cannot create an isntance of {0} from pool {1}", prefab.name, id));
            return null;
        }

        GameObject instance;

        if(free.Count > 0)
        {
            instance = free[0];
            free.Remove(instance);
        }
        else
        {
            instance = (GameObject)GameObject.Instantiate(prefab);
        }

        PlaceObject(instance.transform, parent, position, rotation);

        used.Add(instance);
        instance.name = prefab.name;

        return instance;
    }
示例#4
0
    public void castSpell(GameObject target)
    {
        if(target.GetComponent("Enchantable") == null)
        {
            TraceLogger.LogKVtime("attempt", getSpellName());
            TraceLogger.LogKV("target", target.GetInstanceID().ToString()+", "+target.name+", "+target.transform.position);
            TraceLogger.LogKV("player", ""+ObjectManager.FindById("Me").transform.position);
            (GameObject.Find("Popup").GetComponent("Popup") as Popup).popup("Target ("+target.name+") immune to magic.");
            SetHidden(false);
            return;
        }

        TraceLogger.LogKVtime("spell", getSpellName());
        ProgramLogger.LogKVtime("spell", getSpellName());
        TraceLogger.LogKV("target", target.GetInstanceID().ToString()+", "+target.name+", "+target.transform.position);
        TraceLogger.LogKV("player", ""+ObjectManager.FindById("Me").transform.position);

        June june = new June(target, file_name);

        SetHidden(false);

        item_name = "Blank";
        file_name = "";
        animate = false;

        inventoryTexture = Resources.Load( "Textures/Scroll") as Texture2D;

        (target.GetComponent("Enchantable") as Enchantable).enchant(june, delegate(GameObject t){absorbSpell(t); });
    }
示例#5
0
    public static bool RecycleGO(GameObject prefab,GameObject instGO)
    {
        if (msPoolsDict == null)
        {
            msPoolsDict = new Dictionary<int, Pool_GameObj>();
        }

        //�ҳ���Ӧ��PoolGameObject
        if(prefab == null)
        {
            IPoolObj poolObj = instGO.GetComponent(typeof(IPoolObj)) as IPoolObj;
            prefab = poolObj.Prefab;
            if (prefab == null)
            {
                //Debug.LogWarning("noPrefab ="+instGO.name);
                return false;
            }
         }

        Pool_GameObj poolGo = null;
        if (!msPoolsDict.TryGetValue(prefab.GetInstanceID(), out poolGo))
        {
            poolGo = new Pool_GameObj(prefab);
            msPoolsDict.Add(prefab.GetInstanceID(), poolGo);
        }
        poolGo.RecycleGO(instGO);
        return true;
    }
示例#6
0
    public static PoolCollection PoolCollectionForGameObject(GameObject go)
    {
        if( instance._instanceIdToPoolCollection.ContainsKey(go.GetInstanceID())) {
            return instance._instanceIdToPoolCollection[go.GetInstanceID()];
        }

        return null;
    }
示例#7
0
    /// <summary>
    /// 新しいプールを生成する
    /// </summary>
    /// <param name="prefab">プーリングするオブジェクト</param>
    /// <param name="createCount">プーリングする数</param>
    public void SetObject(GameObject prefab, int createCount)
    {
        // 連想配列にセット
        pooledObject.Add(prefab.GetInstanceID(), new List<GameObject>());

        // プーリング
        for (int i = 0; i < createCount; i++)
        {
            GameObject obj = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
            pooledObject[prefab.GetInstanceID()].Add(obj);
            obj.SetActive(false);
        }
    }
示例#8
0
        public void PrefabsWillNotGetNewIds()
        {
            GameObject go = new GameObject(true);
            TestComponent cmp = new TestComponent();
            go.AddComponent(cmp);

            int oldId = go.GetInstanceID();
            int oldCmpId = cmp.GetInstanceID();
            go.SetNewId(new Dictionary<int, UnityObject>());

            Assert.That(go.GetInstanceID(), Is.EqualTo(oldId));
            Assert.That(cmp.GetInstanceID(), Is.EqualTo(oldCmpId));
        }
示例#9
0
 public void RemoveCache(GameObject tmp)
 {
     if (cachedItem != null && tmp != null)
         if (tmp.GetInstanceID() == cachedItem.GetInstanceID())
             tmp = null;
                
 }
 void OnBeamStay(GameObject obj, Light2DEmitter emitter)
 {
     if (obj.GetInstanceID() == gameObject.GetInstanceID() && emitter.eventPassedFilter == "BlockChange")
     {
         transform.Rotate(0, 0, Time.deltaTime * 50);
     }
 }
示例#11
0
        /// <summary>
        /// Gets or creates the instance of the specified type out of the specified prefab object.
        /// </summary>
        /// <typeparam name="T">The component type.</typeparam>
        /// <param name="prefab">The prefab.</param>
        /// <param name="position">The position.</param>
        /// <param name="rotation">The rotation.</param>
        /// <returns>The instance.</returns>
        /// <exception cref="ArgumentNullException">prefab</exception>
        /// <exception cref="NullReferenceException">instance</exception>
        public T GetOrCreate <T>(GameObject prefab, Vector3 position, Quaternion rotation)
            where T : Component, IPoolableObject
        {
            var id      = prefab?.GetInstanceID() ?? throw new ArgumentNullException(nameof(prefab));
            var objects = GetObjects(id);

            T instance;

            if (objects.Count > 0)
            {
                instance = (T)objects.Pop();
                instance.transform.position = position;
                instance.transform.rotation = rotation;
                instance.gameObject.SetActive(true);
            }
            else
            {
                var newObject = Instantiate(prefab, position, rotation, transform);
                instance = newObject.GetComponent <T>() ?? newObject.AddComponent <T>();
                instance.OnDestroyAsPoolableObject += OnDestroyHandler;
                instance.PrefabInstanceID           = id;
            }

            return(instance ?? throw new NullReferenceException(nameof(instance)));
        }
示例#12
0
    public RopeTubeRenderer(GameObject _gameObject, bool useMeshOnly)
    {
        if (!useMeshOnly)
        {
            this._gameObject = _gameObject;
            this._transform = _gameObject.transform;

            // ensure necessary components //
            MeshFilter filter = _gameObject.GetComponent<MeshFilter>();
            if (filter == null) filter = _gameObject.AddComponent<MeshFilter>();
            MeshRenderer renderer = _gameObject.GetComponent<MeshRenderer>();
            if (renderer == null) renderer = _gameObject.AddComponent<MeshRenderer>();

            _mesh = new Mesh();
            _mesh.name = "RopeTube_" + _gameObject.GetInstanceID();
            _mesh.hideFlags = HideFlags.HideAndDontSave;
            filter.mesh = _mesh;

            if (renderer.sharedMaterial == null)
                renderer.sharedMaterial = (Material)Resources.Load("Materials/Rope", typeof(Material));
        }
        else
        {
            this._gameObject = _gameObject;
            this._transform = _gameObject.transform;

            _mesh = new Mesh();
            _mesh.name = "RopeTube_" + _gameObject.GetInstanceID();
            _mesh.hideFlags = HideFlags.HideAndDontSave;
        }
    }
示例#13
0
 // here is the function we call from Spawnscript
 // scan the array created by the above events
 // return a match number
 public int DetectMatches(GameObject other)
 {
     int matches = 0;
     if (!other) {
         Debug.Log("missing gameobject (other)");
         return 0;
     }
     foreach (GameObject collided in CollidingWith) {
         if (!collided) {
             Debug.Log("missing gameobject (collided)");
             continue;
         }
         if (other.GetInstanceID() == collided.GetInstanceID()) {
             Debug.Log("Avoid nasty hard loop");
             continue;
         }
         if (other.tag == collided.tag) {
             matches++;
             CurrentMatches.Add(collided);
             //CellScript cScript = collided.GetComponent<CellScript>();
             //matches += cScript.DetectMatches(collided);
             //Debug.Log("Matched: " + matches);
         }
     }
     return matches;
 }
示例#14
0
	public GameObject GetGameObject(GameObject prefab, Vector3 position, Quaternion rotation)
	{
		// 受け取ったprefabのインスタンスIDをkeyとする
		int key = prefab.GetInstanceID ();

		// オブジェクトプールに指定のKeyなければ新しく生成する
		if (pooledGameObjects.ContainsKey (key) == false) {
			pooledGameObjects.Add(key, new List<GameObject>());
		}

		List<GameObject> gameObjects = pooledGameObjects[key];

		// ゲームオブジェクトが非アクティブなものを探す
		foreach (var tmpGO in gameObjects) {
			if(tmpGO.activeInHierarchy == false) {
				tmpGO.transform.position = position;
				tmpGO.transform.rotation = rotation;
				tmpGO.SetActive(true);
				return tmpGO;
			}
		}

		// 使用できるものがないのでゲームオブジェクトを新しく生成する
		GameObject go = (GameObject)Instantiate (prefab, position, rotation);
		go.transform.parent = this.transform;
		return go;
	}
示例#15
0
	static public GameObject GetNextObject(GameObject sourceObj, bool activateObject = true)
	{
		int uniqueId = sourceObj.GetInstanceID();
		
		if(!instance.poolCursors.ContainsKey(uniqueId))
		{
			Debug.LogError("[CFX_SpawnSystem.GetNextPoolObject()] Object hasn't been preloaded: " + sourceObj.name + " (ID:" + uniqueId + ")");
			return null;
		}
		
		int cursor = instance.poolCursors[uniqueId];
		instance.poolCursors[uniqueId]++;
		if(instance.poolCursors[uniqueId] >= instance.instantiatedObjects[uniqueId].Count)
		{
			instance.poolCursors[uniqueId] = 0;
		}
		
		GameObject returnObj = instance.instantiatedObjects[uniqueId][cursor];
		if(activateObject)
			#if UNITY_3_5
					returnObj.SetActiveRecursively(true);
			#else
					returnObj.SetActive(true);
			#endif
		
		return returnObj;
	}
示例#16
0
    public static PolyCollider CreateInstance()
    {
        GameObject go = new GameObject();
        go.name = "PolyCollider" + go.GetInstanceID();

        return go.AddComponent<PolyCollider>();
    }
示例#17
0
    public override ActionResult Execute(RAIN.Core.AI ai)
    {
        _allMatches = suspects.Evaluate<IList<RAIN.Entities.Aspects.RAINAspect>>(ai.DeltaTime, ai.WorkingMemory);
        if (_allMatches == null || _hellephant == null)
        {
            ai.WorkingMemory.SetItem<GameObject>(boyObject.VariableName, null);
            return ActionResult.FAILURE;
        }
        AIRig attackedAI = _hellephant.GetComponentInChildren<AIRig>();
        _attacker = attackedAI.AI.WorkingMemory.GetItem<GameObject>("attacker");

        GameObject result = null;
        Debug.Log("isIn:\n\tCount: " + _allMatches.Count);
        foreach (RAIN.Entities.Aspects.RAINAspect aspect in _allMatches)
        {
            Debug.Log("isIn:\n\tTAG: " + aspect.Entity.Form.tag);
            if (aspect.Entity.Form.GetInstanceID() == _attacker.GetInstanceID())
            {
                result = _attacker;
                break;
            }
        }
        ai.WorkingMemory.SetItem<GameObject>(boyObject.VariableName, result);
        return ActionResult.SUCCESS;
    }
示例#18
0
    public void ProducePart( GameInfo gameInfo, GameObject myGO, int amount = 1 )
    {
        int myGOTeam = myGO.GetComponent<Generic_Team>().TeamNum;

        if (isServer)
        {
            List<GameObject> parts = new List<GameObject>();
            for ( int i = 0; i < amount; i++ )
            {
                parts.Add(MakePart( new Vector2( i, 0 ), Vector2.zero, 0.0f, myGOTeam ));
            }

            List<GameObject> myGO_parts;
            myGO_parts = myGO.GetComponent<Unit_PartPlacement>().parts;
            myGO_parts.Clear();
            int gOID = myGO.GetInstanceID();
            //u16 playerID = blob.getPlayer().getNetworkID();
            for (int i = 0; i < parts.Count; i++)
            {
                GameObject gO = parts[i];
                myGO_parts.Add( gO );
                gO.GetComponent<Part_Info>().OwnerID = gOID;
                //b.set_u16( "playerID", playerID );
                gO.GetComponent<Part_Info>().ShipID = -1; // don't push on ship
            }
        }
    }
    public GameObject GetGameObject( GameObject prefab, Vector3 position, Quaternion rotation )
    {
        int key = prefab.GetInstanceID();

        if( !pooledEntities.ContainsKey( key ) )
        {
            pooledEntities.Add( key, new Stack<PoolEntity>() );
        }

        var entities = pooledEntities[key];
        GameObject go = null;
        PoolEntity entity = null;

        if( entities.Count <= 0 )
        {
            go = Instantiate( prefab, position, rotation ) as GameObject;
            entity = go.AddComponent( typeof( PoolEntity ) ) as PoolEntity;
            entity.Initialize( key );
            this.poolEntities.Add( entity );
            PoolableComponentsAction( go, (poolable) => poolable.OnAwakeByPool( false ) );
        }
        else
        {
            entity = entities.Pop();
            entity.Reuse();
            go = entity.gameObject;
            go.transform.position = position;
            go.transform.rotation = rotation;
            go.SetActive( true );
            PoolableComponentsAction( go, (poolable) => poolable.OnAwakeByPool( true ) );
        }

        return go;
    }
示例#20
0
 void OnLightStay(Light2D l, GameObject g)
 {
     if (g.GetInstanceID() == id)
     {
         isDetected = true;
     }
 }
 void OnLightEnter(Light2D l, GameObject o)
 {
     if(o.GetInstanceID() == id)
     {
         Debug.Break();
     }
 }
    void OnLightExit(Light2D l, GameObject o)
    {
        if (o.GetInstanceID() == id)
        {

        }
    }
示例#23
0
 private void OnLightEnter(Light2D l, GameObject g)
 {
     if (g.GetInstanceID() == id){
         c += l.LightColor;
         AudioSource.PlayClipAtPoint(hitSound, transform.position, 0.1f);
     }
 }
 private void addObjectToPool(GameObject sourceObject, int number)
 {
     int instanceID = sourceObject.GetInstanceID();
     if (!this.instantiatedObjects.ContainsKey(instanceID))
     {
         this.instantiatedObjects.Add(instanceID, new List<GameObject>());
         this.poolCursors.Add(instanceID, 0);
     }
     for (int i = 0; i < number; i++)
     {
         GameObject item = (GameObject) UnityEngine.Object.Instantiate(sourceObject);
         item.SetActive(false);
         foreach (CFX_AutoDestructShuriken shuriken in item.GetComponentsInChildren<CFX_AutoDestructShuriken>(true))
         {
             shuriken.OnlyDeactivate = true;
         }
         foreach (CFX_LightIntensityFade fade in item.GetComponentsInChildren<CFX_LightIntensityFade>(true))
         {
             fade.autodestruct = false;
         }
         this.instantiatedObjects[instanceID].Add(item);
         if (this.hideObjectsInHierarchy)
         {
             item.hideFlags = HideFlags.HideInHierarchy;
         }
     }
 }
示例#25
0
	public static GameObject CreateDecal(Material mat, Rect uvCoords, float scale)
	{
		GameObject decal = new GameObject();
		decal.name = "Decal" + decal.GetInstanceID();
		
		float w = uvCoords.width, h = uvCoords.height;
		
		if(mat != null && mat.mainTexture != null)
		{
			if(mat.mainTexture.width > mat.mainTexture.height)	
				h *= mat.mainTexture.height/(float)mat.mainTexture.width;
			else
				w *= mat.mainTexture.width/(float)mat.mainTexture.height;
		}
		
		Vector3 aspectScale = w > h ? new Vector3(1f, h/w, 1f) : new Vector3(w/h, 1f, 1f);

		Mesh m = new Mesh();
		Vector3[] v = new Vector3[4];
		for(int i = 0; i < 4; i++)
			v[i] = Vector3.Scale(BILLBOARD_VERTICES[i], aspectScale) * scale;

		Vector2[] uvs = new Vector2[4]
		{
			new Vector2(uvCoords.x + uvCoords.width, uvCoords.y),
			new Vector2(uvCoords.x, uvCoords.y),
			new Vector2(uvCoords.x + uvCoords.width, uvCoords.y + uvCoords.height),
			new Vector2(uvCoords.x, uvCoords.y + uvCoords.height)
		};

		m.vertices 	= v;
		m.triangles = BILLBOARD_TRIANGLES;
		m.normals 	= BILLBOARD_NORMALS;
		m.tangents 	= BILLBOARD_TANGENTS;
		m.uv 		= uvs;
		m.uv2 		= BILLBOARD_UV2;
		m.name		= "DecalMesh" + decal.GetInstanceID();

		decal.AddComponent<MeshFilter>().sharedMesh = m;
		decal.AddComponent<MeshRenderer>().sharedMaterial = mat;

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

		return decal;
	}
示例#26
0
 void OnLightEnter(Light2D l, GameObject g)
 {
     if (g.GetInstanceID() == id)
     {
         Debug.Log("Enter");
         c = mOriginColor + l.LightColor;
     }
 }
示例#27
0
 void OnLightStay(Light2D l, GameObject g)
 {
     if (g.GetInstanceID() == id)
     {
         Debug.Log("Stay");
         isDetected = true;
     }
 }
示例#28
0
    public static GameObject GetObj(GameObject prefab)
    {
        if (msPoolsDict == null)
        {
            msPoolsDict = new Dictionary<int, Pool_GameObj>();
        }

        //�ҳ���Ӧ��PoolGameObject
        Pool_GameObj poolGo = null;
        if (!msPoolsDict.TryGetValue(prefab.GetInstanceID(),out poolGo))
        {
            poolGo = new Pool_GameObj(prefab);
            msPoolsDict.Add(prefab.GetInstanceID(), poolGo);
        }

        return poolGo.GetGO();
    }
示例#29
0
    void OnLightExit(Light2D l, GameObject g)
    {
        if (g.GetInstanceID() == id)
        {
            Debug.Log("Exit");

        }
    }
 void OnBeamEnter(GameObject obj, Light2DEmitter emitter)
 {
     if (obj.GetInstanceID() == gameObject.GetInstanceID() && emitter.eventPassedFilter == "BlockChange")
     {
         renderer.material.color = emitter.lightColor;
         Debug.Log("Entered: " + emitter.name);
     }
 }
示例#31
0
 protected IEnumerator Broadcast(GameObject other)
 {
     while (other && other.activeSelf == true && m_dangerZone.Contains(other.gameObject))
     {
         Messenger.Broadcast<string, string, float>("modstat", other.GetInstanceID().ToString(), m_stat, ammountToModBy);
         print (other.name);
         yield return new WaitForSeconds(timer);
     }
 }
示例#32
0
 public bool Equals(UserMessageInfo other)
 {
     return(GameObject?.GetInstanceID() == other.GameObject?.GetInstanceID() &&
            SenderID == other.SenderID &&
            Position == other.Position &&
            Type == other.Type &&
            string.Equals(User, other.User, StringComparison.CurrentCultureIgnoreCase) &&
            string.Equals(Text, other.Text, StringComparison.CurrentCultureIgnoreCase)
            );
 }
示例#33
0
 public bool Equals(Chat.WorldTextInstance other)
 {
     return(GameObject?.GetInstanceID() == other.m_go?.GetInstanceID() &&
            SenderID == other.m_talkerID &&
            Position == other.m_position &&
            Type == other.m_type &&
            string.Equals(User, other.m_name, StringComparison.CurrentCultureIgnoreCase) &&
            string.Equals(Text, other.m_text, StringComparison.CurrentCultureIgnoreCase)
            );
 }
示例#34
0
        /// <summary>
        /// Gets the count of the all created instances out of the given prefab object.
        /// </summary>
        /// <param name="prefab">The prefab.</param>
        /// <returns>The instances count.</returns>
        /// <exception cref="ArgumentNullException">prefab</exception>
        public int GetInstancesCount(GameObject prefab)
        {
            var id = prefab?.GetInstanceID() ?? throw new ArgumentNullException(nameof(prefab));

            if (!pool.TryGetValue(id, out var objects))
            {
                return(0);
            }

            return(objects.Count);
        }
 string GetInstanceFileName(GameObject baseObject)
 {
     return(System.IO.Path.GetTempPath() + baseObject.name + "_" + baseObject.GetInstanceID() + ".keepTerrain.txt");
 }
示例#36
0
    //private void LockAllCards(bool b)
    //{
    //    ///Locking or Unlocking all cards by putting bool charakter
    //
    //    for (int j = 0; j < 25; j++)
    //    {
    //        if (SetOfCard[j] != null)
    //        {
    //            CardBihevior Card = SetOfCard[j].GetComponent<CardBihevior>();
    //            Card.SetBlock(b);
    //        }
    //
    //    }
    //}

    private void CheckOfArkan(GameObject go)
    {
        CardBihevior bihevCard = go.GetComponent <CardBihevior>();

        float[] position     = bihevCard.getPosition();
        int     chanseOption = UnityEngine.Random.Range(0, 100);

        chanseOption = (chanseOption % 2 == 0) ? chanseOption = 0 : chanseOption = 1;
        byte number   = 0;
        int  addScore = 0;
        byte arcan    = 0;

        switch (go.name)
        {
        case "moon(Clone)":
            //количество открытых карт
            break;

        case "sun(Clone)":
            GameObject[] cardSunOpen = new GameObject[5];
            foreach (GameObject cO in SetOfCard)
            {
                if (cO != null)    //find cards in the line
                {
                    if (chanseOption == 0)
                    {
                        if (go.transform.position.x == cO.transform.position.x & cO.GetInstanceID() != go.GetInstanceID() & cO != null)
                        {
                            cardSunOpen[number] = cO;
                            number++;

                            //& cO.GetInstanceID() != go.GetInstanceID() & number >= cardSunOpen.Length
                        }
                    }
                    else
                    {
                        if (go.transform.position.y == cO.transform.position.y & cO.GetInstanceID() != go.GetInstanceID() & cO != null)
                        {
                            //& cO.GetInstanceID() != go.GetInstanceID() & number >= cardSunOpen.Length
                            cardSunOpen[number] = cO;
                            number++;
                        }
                    }
                }
            }
            if (BufCard1 != null)
            {
                if (BufCard1.GetInstanceID() != go.GetInstanceID())
                {
                    int co = 0;
                    foreach (GameObject soc in cardSunOpen)
                    {
                        if (soc == null)
                        {
                            break;
                        }
                        else
                        {
                            co++;
                        }
                        if (soc.GetInstanceID() == BufCard1.GetInstanceID())
                        {
                            co = 0;
                            break;
                        }
                    }
                    if (co > 0)
                    {
                        cardSunOpen[co] = BufCard1;
                    }
                    foreach (GameObject cso in cardSunOpen)
                    {
                        if (cso != null)
                        {
                            //if (cso.GetInstanceID() != BufCard1.GetInstanceID() & cso.name == BufCard1.name)
                            //{
                            //    destroingCard(BufCard1);
                            //    BufCard1 = null;
                            //    destroingCard(cso);
                            //    scoreArcan4cards(20);
                            //    break;
                            //}
                        }
                    }
                }
            }
            //samecards in line destroy
            for (int i = 0; i < cardSunOpen.Length; i++)
            {
                for (int j = 0; j < cardSunOpen.Length; j++)
                {
                    if (cardSunOpen[i] != null & cardSunOpen[j] != null)
                    {
                        if (cardSunOpen[i].GetInstanceID() != cardSunOpen[j].GetInstanceID() & cardSunOpen[i].name == cardSunOpen[j].name)
                        {
                            destroingCard(cardSunOpen[i]);
                            destroingCard(cardSunOpen[j]);
                            cardSunOpen[j] = null;
                            cardSunOpen[i] = null;

                            scoreArcan4cards(20);
                        }
                    }
                }
            }
            //othercard for para
            foreach (GameObject cso in cardSunOpen)
            {
                foreach (GameObject co in SetOfCard)
                {
                    if (co != null & cso != null)
                    {
                        if (co.name == cso.name & co.GetInstanceID() != cso.GetInstanceID())
                        {
                            destroingCard(cso);
                            destroingCard(co);
                            scoreArcan4cards(20);
                            break;
                        }
                    }
                }
            }
            destroingCard(go);

            BufCard1 = null;
            BufCard2 = null;
            LockAllCards(false);
            break;

        case "star(Clone)":
            //количество открытых карт


            break;

        case "tower(Clone)":
            //количество открытых карт



            break;
        }

        switch (deletedCards)
        {
        case 0:
            addScore = arcan * 10;
            break;

        case 24:
            addScore = arcan * 10;
            break;

        default:
            if (arcan > 0)
            {
                addScore = deletedCards * 10;
            }
            break;
        }

        Score += addScore;
    }
示例#37
0
        /// <summary>
        /// Serialize this game object into a DataNode.
        /// Note that the prefab references can only be resolved if serialized from within the Unity Editor.
        /// You can instantiate this game object directly from DataNode format by using DataNode.Instantiate().
        /// Ideal usage: save a game object hierarchy into a file. Serializing a game object will also serialize its
        /// mesh data, making it possible to export entire 3D models. Any references to prefabs or materials located
        /// in the Resources folder will be kept as references and their hierarchy won't be serialized.
        /// </summary>

        static public DataNode Serialize(this GameObject go, bool fullHierarchy = true, bool isRootNode = true)
        {
            DataNode root = new DataNode(go.name, go.GetInstanceID());

            // Save a reference to a prefab, if there is one
            string prefab = UnityTools.LocateResource(go, !isRootNode);

            if (!string.IsNullOrEmpty(prefab))
            {
                root.AddChild("prefab", prefab);
            }

            // Save the transform and the object's layer
            Transform trans = go.transform;

            root.AddChild("position", trans.localPosition);
            root.AddChild("rotation", trans.localEulerAngles);
            root.AddChild("scale", trans.localScale);

            int layer = go.layer;

            if (layer != 0)
            {
                root.AddChild("layer", go.layer);
            }

            // If this was a prefab instance, don't do anything else
            if (!string.IsNullOrEmpty(prefab))
            {
                return(root);
            }

            // Collect all meshes
            if (isRootNode)
            {
                DataNode child = new DataNode("Resources");
#if UNITY_EDITOR
                go.SerializeSharedResources(child, UnityEditor.PrefabUtility.GetPrefabType(go) == UnityEditor.PrefabType.Prefab);
#else
                go.SerializeSharedResources(child);
#endif
                if (child.children.size != 0)
                {
                    root.children.Add(child);
                }
                mFullSerialization = false;
            }

            Component[] comps    = go.GetComponents <Component>();
            DataNode    compRoot = null;

            for (int i = 0, imax = comps.Length; i < imax; ++i)
            {
                Component c = comps[i];

                System.Type type = c.GetType();
                if (type == typeof(Transform))
                {
                    continue;
                }

                if (compRoot == null)
                {
                    compRoot = root.AddChild("Components");
                }
                DataNode child = compRoot.AddChild(Serialization.TypeToName(type), c.GetInstanceID());
                c.Serialize(child, type);
            }

            if (fullHierarchy && trans.childCount > 0)
            {
                DataNode children = root.AddChild("Children");

                for (int i = 0, imax = trans.childCount; i < imax; ++i)
                {
                    GameObject child = trans.GetChild(i).gameObject;
                    if (child.activeInHierarchy)
                    {
                        children.children.Add(child.Serialize(true, false));
                    }
                }
            }
            if (isRootNode)
            {
                mFullSerialization = true;
            }
            return(root);
        }
    static void Build(GameObject go)
    {
        if (go == null)
        {
            return;
        }

        BuildAssetBundleOptions options =
            BuildAssetBundleOptions.CollectDependencies |
            BuildAssetBundleOptions.CompleteAssets |
            BuildAssetBundleOptions.DeterministicAssetBundle;

        UIAssetbundleInfo.Dependency dep = new UIAssetbundleInfo.Dependency();
        dep.name = go.name;
        UIAssetbundleInfo.Dependency exist = UIAssetbundleInfo.instance.dependencies.Find(p => p.name == go.name);
        if (exist != null)
        {
            UIAssetbundleInfo.instance.dependencies.Remove(exist);
        }
        UIAssetbundleInfo.instance.dependencies.Add(dep);

        UISprite[]      ws        = go.GetComponentsInChildren <UISprite>(true);
        List <Texture>  textures  = new List <Texture>();
        List <Material> materials = new List <Material>();

        foreach (var w in ws)
        {
            Texture tex = w.atlas.texture;
            if (tex != null && !textures.Contains(tex))
            {
                textures.Add(tex);
            }
            Material mat = w.atlas.spriteMaterial;
            if (mat != null && !materials.Contains(mat))
            {
                materials.Add(mat);
            }
        }
        //UITexture will use another strategy



        UILabel[]     labels       = go.GetComponentsInChildren <UILabel>(true);
        List <UIFont> uiFonts      = new List <UIFont>();
        List <Font>   dynamicfonts = new List <Font>();

        foreach (var label in labels)
        {
            UIFont uifont = label.font;
            if (uifont == null)
            {
                continue;
            }
            if (uifont.isDynamic)
            {
                Font f = uifont.dynamicFont;
                if (f != null && !dynamicfonts.Contains(f))
                {
                    dynamicfonts.Add(f);
                }
            }
            else
            {
                Texture tex = uifont.texture;
                if (tex != null && !textures.Contains(tex))
                {
                    textures.Add(tex);
                }
                Material mat = uifont.material;
                if (mat != null && !materials.Contains(mat))
                {
                    materials.Add(mat);
                }
            }
        }

        UIPlaySound[]    sounds = go.GetComponentsInChildren <UIPlaySound>(true);
        List <AudioClip> clips  = new List <AudioClip>();

        foreach (var sound in sounds)
        {
            AudioClip audio = sound.audioClip;
            if (audio != null && !clips.Contains(sound.audioClip))
            {
                clips.Add(sound.audioClip);
            }
        }
        //////////////////////////////////////////////////////////////////////////
        BuildPipeline.PushAssetDependencies();
        foreach (var tex in textures)
        {
            string path = AssetDatabase.GetAssetPath(tex.GetInstanceID());
            //Debug.Log(UIAssetbundleSettings.buildTextureTargetPath);
            string fileName = "tex_" + tex.name + UIAssetbundleInfo.ext;
            BuildPipeline.BuildAssetBundle(
                AssetDatabase.LoadMainAssetAtPath(path),
                null,
                UIAssetbundleSettings.buildTextureTargetPath + "/" + fileName,
                options,
                UIAssetbundleSettings.instance.buildTarget);

            dep.atlasPaths.Add(fileName);
        }
        foreach (var font in dynamicfonts)
        {
            string path     = AssetDatabase.GetAssetPath(font.GetInstanceID());
            string fileName = "font_" + font.name + UIAssetbundleInfo.ext;
            BuildPipeline.BuildAssetBundle(
                AssetDatabase.LoadMainAssetAtPath(path),
                null,
                UIAssetbundleSettings.buildFontTargetPath + "/" + fileName,
                options,
                UIAssetbundleSettings.instance.buildTarget);
            dep.dynamicFontPaths.Add(fileName);
        }
        foreach (var clip in clips)
        {
            string path     = AssetDatabase.GetAssetPath(clip.GetInstanceID());
            string fileName = "audio_" + clip.name + UIAssetbundleInfo.ext;
            BuildPipeline.BuildAssetBundle(
                AssetDatabase.LoadMainAssetAtPath(path),
                null,
                UIAssetbundleSettings.buildAudioTargetPath + "/" + fileName,
                options,
                UIAssetbundleSettings.instance.buildTarget);
            dep.audioPaths.Add(fileName);
        }
        foreach (var mat in materials)
        {
            string path     = AssetDatabase.GetAssetPath(mat.GetInstanceID());
            string fileName = "mat_" + mat.name + UIAssetbundleInfo.ext;
            BuildPipeline.BuildAssetBundle(
                AssetDatabase.LoadMainAssetAtPath(path),
                null,
                UIAssetbundleSettings.buildMaterialTargetPath + "/" + fileName,
                options,
                UIAssetbundleSettings.instance.buildTarget);
            dep.materialPaths.Add(fileName);
        }
        //////////////////////////////////////////////////////////////////////////



        BuildPipeline.PushAssetDependencies();
        string goPath = AssetDatabase.GetAssetPath(go.GetInstanceID());

        BuildPipeline.BuildAssetBundle(
            AssetDatabase.LoadMainAssetAtPath(goPath),
            null,
            UIAssetbundleSettings.buildTargetPath + "/" + go.name + UIAssetbundleInfo.ext,
            options,
            UIAssetbundleSettings.instance.buildTarget);

        BuildPipeline.PopAssetDependencies();
        BuildPipeline.PopAssetDependencies();
    }
示例#39
0
    /* Parameters:
     * o: list of changes to make to the gameObject, as well as new gameObjects to instantiate and behaviors to attatch to the new gameObjects.
     * gameObject: the gameObject to change
     *
     * Description:
     * changes the gameObject as specified by 'o', instantiates new objects as specified by 'o'.
     */
    public static void Update(ObjectUpdate o, GameObject gameObject)
    {
        //handling all the instantiation requests
        foreach (InstantiationRequest i in o.instatiationRequests)
        {
            GameObject resource = (GameObject)Resources.Load(i.resourcePath);

            /*
             * if (i.triangle != null)
             * {
             *  bool existsInCache = false;
             *  for(int a = 0; a < cachedObjects.Count; a++)
             *  {
             *      if (cachedObjects[a].name.Equals(i.resourcePath))
             *      {
             *          cachedObjects[a].positions.Add(i.position);
             *          cachedObjects[a].orientations.Add(i.orientation);
             *
             *          if(cacheObjMap[i.triangle[0], i.triangle[1]] == null)
             *          {
             *              cacheObjMap[i.triangle[0], i.triangle[1]] = new List<CacheObjTuple>();
             *          }
             *          if (cacheObjMap[i.triangle[0], i.triangle[2]] == null)
             *          {
             *              cacheObjMap[i.triangle[0], i.triangle[2]] = new List<CacheObjTuple>();
             *          }
             *          if (cacheObjMap[i.triangle[1], i.triangle[2]] == null)
             *          {
             *              cacheObjMap[i.triangle[1], i.triangle[2]] = new List<CacheObjTuple>();
             *          }
             *          CacheObjTuple t = new CacheObjTuple { cacheObjIndex = a, objIndex = cachedObjects[a].positions.Count - 1 };
             *
             *          cacheObjMap[i.triangle[0], i.triangle[1]].Add(t);
             *          cacheObjMap[i.triangle[0], i.triangle[2]].Add(t);
             *          cacheObjMap[i.triangle[1], i.triangle[2]].Add(t);
             *
             *          existsInCache = true;
             *          break;
             *      }
             *  }
             *  if (!existsInCache)
             *  {
             *      Debug.Log("making new cache " + i.resourcePath);
             *      CacheObject newCache = new CacheObject(i.resourcePath, new List<Vector3> { i.position },
             *          new List<Quaternion> { i.orientation }, resource);
             *
             *      if (cacheObjMap[i.triangle[0], i.triangle[1]] == null)
             *      {
             *          cacheObjMap[i.triangle[0], i.triangle[1]] = new List<CacheObjTuple>();
             *      }
             *      if (cacheObjMap[i.triangle[0], i.triangle[2]] == null)
             *      {
             *          cacheObjMap[i.triangle[0], i.triangle[2]] = new List<CacheObjTuple>();
             *      }
             *      if (cacheObjMap[i.triangle[1], i.triangle[2]] == null)
             *      {
             *          cacheObjMap[i.triangle[1], i.triangle[2]] = new List<CacheObjTuple>();
             *      }
             *      CacheObjTuple t = new CacheObjTuple { cacheObjIndex = cachedObjects.Count, objIndex = 0 };
             *
             *      cacheObjMap[i.triangle[0], i.triangle[1]].Add(t);
             *      cacheObjMap[i.triangle[0], i.triangle[2]].Add(t);
             *      cacheObjMap[i.triangle[1], i.triangle[2]].Add(t);
             *
             *      for (int i1 = 0; i1 < newCache.numInCache; i1++)
             *      {
             *          newCache.objs.Add(UnityEngine.Object.Instantiate(resource, new Vector3(100000,100000,100000), Quaternion.Euler(Vector3.zero)));
             *      }
             *      cachedObjects.Add(newCache);
             *  }
             *  continue;
             * }
             */
            foreach (IClass c in i.behaviorsToAdd)
            {
                if (c == null)
                {
                    throw new Exception("gameObjectID: " + gameObject.GetInstanceID() + " gameObject Name: " + gameObject.name + " Error: the class of type " + c.GetType().Name + " is null!");
                }
                IMono comp = (IMono)resource.AddComponent(c.MonoScript);
                if (comp == null)
                {
                    throw new Exception("gameObjectID: " + gameObject.GetInstanceID() + " gameObject Name: " + gameObject.name + " Error: Monobehavior " + c.MonoScript.Name + " for class " + c.GetType().Name + " does not exist, is not a Monobehavior, or does not implement the IMono interface");
                }
                comp.SetMainClass(c);
            }
            //instantiating the new gameobject with the behaviors added above
            GameObject gameObj = GameObject.Instantiate(resource, i.position, i.orientation) as GameObject;
            if (gameObj == null)
            {
                Debug.Log("gameObject is NULL!!!");
            }
            server.Create(gameObj, i.resourcePath);
        }

        //setting all of the values here

        //set position and orientation
        if (o.position != null)
        {
            gameObject.transform.position = o.position.GetVector();
        }
        if (o.rotation != null)
        {
            gameObject.transform.rotation = o.rotation.GetQuaternion();
        }

        //if you're trying to set the velocity or force of the object, but there is no Rigidbody, throw an exception
        Rigidbody r = gameObject.GetComponent <Rigidbody>();

        if (o.velocity != null || o.force != null && r == null)
        {
            throw new Exception("gameObjectID: " + gameObject.GetInstanceID() + " gameObject Name: " + gameObject.name + " Error: there is no rigidbody component for this gameObject");
        }

        //set velocity and force
        if (o.velocity != null)
        {
            r.velocity = o.velocity.GetVector();
        }
        if (o.force != null)
        {
            r.AddForce(o.force.GetVector());
        }

        ///@TODO: when faces are implemented, they'll need another if statement here.
        //setting mesh
        if (o.meshPoints != null)
        {
            List <Vector3> meshPointsUnwrapped = new List <Vector3>();
            foreach (Vector3Wrapper v in o.meshPoints)
            {
                meshPointsUnwrapped.Add(v.GetVector());
            }
            if (o.triangles != null)
            {
                /*Mesh newMesh = MeshBuilder3D.GetMeshFrom(meshPointsUnwrapped, o.triangles);
                 * gameObject.GetComponent<MeshFilter>().mesh = newMesh;
                 * gameObject.GetComponent<MeshCollider>().sharedMesh = newMesh;*/
            }
        }
    }
示例#40
0
 public AkAutoObject(GameObject GameObj)
 {
     this.m_id = GameObj.GetInstanceID();
     AkSoundEngine.RegisterGameObj(GameObj, "AkAutoObject.cs");
 }
    ///// Bone creation /////
    private static Uni2DSmoothBindingBone CreateNewBone(Transform a_rTransform, bool a_bCreateFakeBone = false)
    {
        GameObject             oBoneGameObject = new GameObject( );
        Transform              oBoneTransform  = oBoneGameObject.transform;
        Uni2DSmoothBindingBone oBone           = oBoneGameObject.AddComponent <Uni2DSmoothBindingBone>( );

        oBoneGameObject.name = (a_bCreateFakeBone ? "Uni2DFakeBone_" : "Uni2DBone_") + Mathf.Abs(oBoneGameObject.GetInstanceID( ));

        oBoneTransform.parent        = a_rTransform;
        oBoneTransform.localPosition = Vector3.zero;
        oBoneTransform.localRotation = Quaternion.identity;
        oBoneTransform.localScale    = Vector3.one;

        return(oBone);
    }
示例#42
0
        // PUBLIC METHODS: ------------------------------------------------------------------------

        public Character GetCharacter(GameObject invoker)
        {
            switch (this.target)
            {
            case Target.Player:
                if (HookPlayer.Instance != null)
                {
                    this.cacheCharacter = HookPlayer.Instance.Get <Character>();
                }
                break;

            case Target.Invoker:
                if (invoker == null)
                {
                    this.cacheCharacter = null;
                    break;
                }

                if (this.cacheCharacter == null)
                {
                    this.cacheCharacter = invoker.GetComponentInChildren <Character>();
                }
                if (this.cacheCharacter == null)
                {
                    this.cacheCharacter = invoker.GetComponentInParent <Character>();
                }
                break;

            case Target.Character:
                if (this.character != null)
                {
                    this.cacheCharacter = this.character;
                }
                break;

            case Target.LocalVariable:
                GameObject localResult = this.local.Get(invoker) as GameObject;
                if (localResult != null && localResult.GetInstanceID() != this.cacheInstanceID)
                {
                    this.cacheCharacter = localResult.GetComponentInChildren <Character>();
                    if (this.cacheCharacter == null)
                    {
                        localResult.GetComponentInParent <Character>();
                    }
                }
                break;

            case Target.GlobalVariable:
                GameObject globalResult = this.global.Get(invoker) as GameObject;
                if (globalResult != null && globalResult.GetInstanceID() != this.cacheInstanceID)
                {
                    this.cacheCharacter = globalResult.GetComponentInChildren <Character>();
                    if (this.cacheCharacter == null)
                    {
                        globalResult.GetComponentInParent <Character>();
                    }
                }
                break;

            case Target.ListVariable:
                GameObject listResult = this.list.Get(invoker) as GameObject;
                if (listResult != null && listResult.GetInstanceID() != this.cacheInstanceID)
                {
                    this.cacheCharacter = listResult.GetComponentInChildren <Character>();
                    if (this.cacheCharacter == null)
                    {
                        listResult.GetComponentInParent <Character>();
                    }
                }
                break;
            }

            this.cacheInstanceID = (this.cacheCharacter == null
                ? 0
                : this.cacheCharacter.gameObject.GetInstanceID()
                                    );

            return(this.cacheCharacter);
        }
示例#43
0
        private void DrawVolumeProperties(AmplifyColorVolumeBase volume)
        {
            GameObject obj = volume.gameObject;

            GUILayout.BeginHorizontal();
            GUILayout.Space(10);

            volumeIcon = (volumeIcon == null) ? Resources.Load("volume-icon", typeof(Texture2D)) as Texture2D : volumeIcon;
            GUILayout.Label("", GUILayout.MinWidth(iconMinWidth), GUILayout.MaxWidth(iconMaxWidth));
            GUILayout.Space(-iconMinWidth * 2);
            GUILayout.Label(volumeIcon, GUILayout.Width(20), GUILayout.Height(20));
            GUILayout.Space(16);

            GUILayout.Space(0);

            bool active = obj.activeInHierarchy;
            bool keep   = EditorGUILayout.Toggle(active, GUILayout.MinWidth(activeMinWidth), GUILayout.MaxWidth(activeMaxWidth));

            if (keep != active)
            {
                obj.SetActive(keep);
            }

            GUILayout.Space(6);

            volume.ShowInSceneView = EditorGUILayout.Toggle(volume.ShowInSceneView, GUILayout.MinWidth(visibleMinWidth), GUILayout.MaxWidth(visibleMaxWidth));

            GUILayout.Space(6);

            GUI.skin.textField.fontSize  = 10;
            GUI.skin.textField.alignment = TextAnchor.UpperCenter;
            if (GUILayout.Button((Selection.activeObject == obj) ? "●" : "", EditorStyles.textField, GUILayout.Width(16), GUILayout.Height(16)))
            {
                Selection.activeObject = (Selection.activeObject == obj) ? null : obj;
            }

            GUILayout.Space(0);

            GUI.skin.textField.fontSize  = 11;
            GUI.skin.textField.alignment = TextAnchor.MiddleLeft;

            string instId = obj.GetInstanceID().ToString();

            GUI.SetNextControlName(instId);

            if (editObject != obj)
            {
                EditorGUILayout.TextField(obj.name, GUILayout.MinWidth(nameMinWidth), GUILayout.MaxWidth(nameMaxWidth));
            }
            else
            {
                editName = EditorGUILayout.TextField(editName, GUILayout.MinWidth(nameMinWidth), GUILayout.MaxWidth(nameMaxWidth));
            }

            if (GUI.GetNameOfFocusedControl() == instId)
            {
                if (editObject != obj)
                {
                    editName   = obj.name;
                    editObject = obj;
                }
            }
            if (Event.current.type == EventType.KeyUp && Event.current.keyCode == KeyCode.Return && editObject == obj)
            {
                obj.name   = editName;
                editName   = "";
                editObject = null;
                Repaint();
            }

            GUILayout.Space(3);

            EditorGUIUtility.labelWidth = 5;
            volume.EnterBlendTime       = EditorGUILayout.FloatField(" ", volume.EnterBlendTime, GUILayout.MinWidth(blendMinWidth), GUILayout.MaxWidth(blendMaxWidth));

            GUILayout.Space(3);

            volume.Exposure = EditorGUILayout.FloatField(" ", volume.Exposure, GUILayout.MinWidth(exposureMinWidth), GUILayout.MaxWidth(exposureMaxWidth));

            GUILayout.Space(3);

            volume.Priority = EditorGUILayout.IntField(" ", volume.Priority, GUILayout.MinWidth(priorityMinWidth), GUILayout.MaxWidth(priorityMaxWidth));

            GUILayout.EndHorizontal();
        }
示例#44
0
    void OnGUI()
    {
        if (_dirty)
        {
            dicKeys.Clear();
            _dirty = false;
        }

        EditorGUILayout.BeginVertical();
        _scroll = GUILayout.BeginScrollView(_scroll);

        #region target
        // set, select gameobject
        EditorGUILayout.BeginHorizontal();
        goTarget = EditorGUILayout.ObjectField("Target", goTarget, typeof(GameObject), true) as GameObject;
        EditorGUILayout.EndHorizontal();

        // revert, apply prefab
        DrawGOBehavior(goTarget);
        #endregion target

        if (goTarget)
        {
            // delete key if not same valid GameObject
            if (_instanceID != goTarget.GetInstanceID())
            {
                _instanceID = goTarget.GetInstanceID();
                foreach (string tmpkey in dicKeys.Keys)
                {
                    if (EditorPrefs.HasKey(tmpkey))
                    {
                        EditorPrefs.DeleteKey(tmpkey);
                    }
                }
            }

            // update sprites inforamtion
            SpriteManager.Update(goTarget);

            #region draw call information
            GUILayout.BeginHorizontal();
            GUILayout.Label(string.Format("Draw calls: {0}", SpriteManager.DrawCalls), GUILayout.Width(200f));
            if (GUILayout.Button("Get Draw Call"))
            {
                SpriteManager.GetDrawCalls(true);
            }
            GUILayout.EndHorizontal();
            #endregion draw call information

            for (int i = 0; i < SpriteManager.Count; i++)
            {
                #region layer main
                SRLayer layer = SpriteManager.list[i];

                // set color
                GUI.backgroundColor = allColors[i % allColors.Length];
                GUI.color           = Color.white;
                Color oldColor = defaultColor;

                #region layer field
                GUILayout.BeginHorizontal();

                // layer field
                int    currentLayer = layer.Index;
                string keyStr       = string.Format("L_{0}", currentLayer);
                int    massLayer    = currentLayer;
                if (dicKeys.ContainsKey(keyStr))
                {
                    massLayer = dicKeys[keyStr];
                }
                GUILayout.Label("Layer ID", GUILayout.Width(60f));
                dicKeys[keyStr] = EditorGUILayout.IntField(massLayer, GUILayout.Width(50f));

                GUILayout.EndHorizontal();
                #endregion layer field

                #region layer apply/reset
                if (massLayer != currentLayer)
                {
                    GUILayout.BeginHorizontal();
                    oldColor = GUI.backgroundColor;

                    // apply
                    GUI.backgroundColor = new Color(0.4f, 1f, 0.4f);
                    if (GUILayout.Button("Apply", GUILayout.Width(100f)))
                    {
                        // set new layer
                        for (int o = 0; o < layer.Orders.Count; o++)
                        {
                            tempOrders = layer.Orders[o];
                            for (int iO = 0; iO < tempOrders.Count; iO++)
                            {
                                tempOrders[iO].SetLayerID(massLayer);
                            }
                        }

                        // delete key
                        EditorPrefs.DeleteKey(keyStr);
                        for (int o = 0; o < layer.Orders.Count; o++)
                        {
                            tempOrders = layer.Orders[o];
                            if (tempOrders.Count == 0)
                            {
                                continue;
                            }

                            string okey = string.Format("L_{0}O_{1}", currentLayer, tempOrders[0].Index);
                            EditorPrefs.DeleteKey(okey);
                        }

                        _dirty = true;
                        GUI.FocusControl(null);
                        EditorUtility.SetDirty(goTarget);
                    }

                    // reset
                    GUI.backgroundColor = new Color(1f, 0.8f, 0.8f);
                    if (GUILayout.Button("Reset", GUILayout.Width(100f)))
                    {
                        dicKeys[keyStr] = currentLayer;
                        GUI.FocusControl(null);
                        EditorUtility.SetDirty(goTarget);
                    }

                    GUI.backgroundColor = oldColor;
                    GUILayout.EndHorizontal();
                }
                #endregion layer apply/reset

                // layer fold
                string headerStr      = string.Format("<b>Sorting Layer {0} ({1}) - Count: {2}</b>", layer.Index, layer.LayerName, layer.Count);
                bool   layerFoldedOut = DrawHeader(headerStr, keyStr);
                if (!layerFoldedOut)
                {
                    continue;
                }
                #endregion layer main

                StyleEx.BeginContent();

                #region orders main
                for (int o = 0; o < layer.Orders.Count; o++)
                {
                    tempOrders = layer.Orders[o];
                    if (tempOrders.Count == 0)
                    {
                        continue;
                    }

                    #region order field, fold
                    GUILayout.BeginHorizontal();

                    // order field
                    int currentOrder = tempOrders[0].Index;
                    keyStr = string.Format("L_{0}O_{1}", currentLayer, currentOrder);
                    bool orderFoldedOut = EditorPrefs.GetBool(keyStr, false);
                    int  massOrder      = currentOrder;
                    if (dicKeys.ContainsKey(keyStr))
                    {
                        massOrder = dicKeys[keyStr];
                    }
                    GUILayout.Label("Order", GUILayout.Width(40f));
                    dicKeys[keyStr] = EditorGUILayout.IntField(massOrder, GUILayout.Width(50f));

                    // order fold
                    string collapserName = string.Format("<b>Cont: {0}</b> - Click to {1}", tempOrders.Count, (orderFoldedOut ? "collapse" : "expand"));
                    bool   foldedOut     = DrawOrderCollapser(collapserName, keyStr, orderFoldedOut);

                    GUILayout.EndHorizontal();
                    #endregion order field, fold

                    #region order apply/reset
                    if (massOrder != currentOrder)
                    {
                        GUILayout.BeginHorizontal();
                        oldColor = GUI.backgroundColor;

                        // apply
                        GUI.backgroundColor = new Color(0.4f, 1f, 0.4f);
                        if (GUILayout.Button("Apply", GUILayout.Width(100f)))
                        {
                            // set new order
                            for (int iO = 0; iO < tempOrders.Count; iO++)
                            {
                                tempOrders[iO].SetOrder(massOrder);
                            }

                            // delete key
                            EditorPrefs.DeleteKey(keyStr);

                            _dirty = true;
                            GUI.FocusControl(null);
                            EditorUtility.SetDirty(goTarget);
                        }

                        // reset
                        GUI.backgroundColor = new Color(1f, 0.8f, 0.8f);
                        if (GUILayout.Button("Reset", GUILayout.Width(100f)))
                        {
                            dicKeys[keyStr] = currentOrder;
                            GUI.FocusControl(null);
                            EditorUtility.SetDirty(goTarget);
                        }

                        GUI.backgroundColor = oldColor;
                        GUILayout.EndHorizontal();
                    }
                    #endregion order apply/reset

                    #region same set of order
                    if (foldedOut)
                    {
                        var alignBefore = GUI.skin.button.alignment;
                        oldColor = GUI.backgroundColor;
                        GUI.skin.button.alignment = TextAnchor.MiddleLeft;
                        // draw GameObject button
                        for (int iW = 0; iW < tempOrders.Count; iW++)
                        {
                            GUILayout.BeginHorizontal();
                            GUILayout.Space(10f);

                            // button to select gameobject
                            GUI.backgroundColor = defaultColor;
                            if (GUILayout.Button(tempOrders[iW].Name, GUILayout.ExpandWidth(false)))
                            {
                                Selection.activeGameObject = tempOrders[iW].gameObject;
                            }

                            // order field
                            GUI.backgroundColor = oldColor;
                            GUILayout.Label("Order", GUILayout.Width(40f));
                            keyStr       = tempOrders[iW].SpriteRender.GetInstanceID().ToString();
                            currentOrder = tempOrders[iW].Index;
                            int singleOrder = currentOrder;
                            if (dicKeys.ContainsKey(keyStr))
                            {
                                singleOrder = dicKeys[keyStr];
                            }
                            dicKeys[keyStr] = EditorGUILayout.IntField(singleOrder, GUILayout.Width(50f));

                            #region single order apply/reset, show texture
                            GUI.skin.button.alignment = alignBefore;
                            if (singleOrder != currentOrder)
                            {
                                oldColor = GUI.backgroundColor;

                                // apply
                                GUI.backgroundColor = new Color(0.4f, 1f, 0.4f);
                                if (GUILayout.Button("Apply", GUILayout.Width(100f)))
                                {
                                    // set new order
                                    tempOrders[iW].SetOrder(singleOrder);
                                    // delete key
                                    EditorPrefs.DeleteKey(keyStr);

                                    _dirty = true;
                                    GUI.FocusControl(null);
                                    EditorUtility.SetDirty(goTarget);
                                }

                                // reset
                                GUI.backgroundColor = new Color(1f, 0.8f, 0.8f);
                                if (GUILayout.Button("Reset", GUILayout.Width(100f)))
                                {
                                    dicKeys[keyStr] = currentOrder;
                                    GUI.FocusControl(null);
                                    EditorUtility.SetDirty(goTarget);
                                }

                                GUI.backgroundColor = oldColor;
                            }
                            else
                            {
                                // todo show texture
                            }
                            #endregion single order apply/reset, show texture

                            GUILayout.EndHorizontal();
                        }
                        GUI.backgroundColor       = oldColor;
                        GUI.skin.button.alignment = alignBefore;
                    }
                    #endregion same set of order

                    GUILayout.Space(3f);
                }
                #endregion orders main

                StyleEx.EndContent();
            }
            GUI.color           = Color.white;
            GUI.backgroundColor = Color.white;
        }

        GUILayout.EndScrollView();
        EditorGUILayout.EndVertical();
    }
示例#45
0
        private void Initialize(GameObject go)
        {
            CheckBackwardCompatiblity(go);

            gameObjectAttached = go;
            isProBuilderObject = false;

#if PROBUILDER_4_0_OR_NEWER
            if (ProBuilderBridge.ProBuilderExists())
            {
                isProBuilderObject = ProBuilderBridge.IsValidProBuilderMesh(gameObjectAttached);
            }
#endif
            Mesh         mesh         = null;
            MeshRenderer meshRenderer = gameObjectAttached.GetComponent <MeshRenderer>();
            meshFilter        = gameObjectAttached.GetComponent <MeshFilter>();
            _skinMeshRenderer = gameObjectAttached.GetComponent <SkinnedMeshRenderer>();

            originalMesh = go.GetMesh();

            if (originalMesh == null && _skinMeshRenderer != null)
            {
                originalMesh = _skinMeshRenderer.sharedMesh;
            }

            m_PolybrushMesh = gameObjectAttached.GetComponent <PolybrushMesh>();

            if (m_PolybrushMesh == null)
            {
                m_PolybrushMesh = Undo.AddComponent <PolybrushMesh>(gameObjectAttached);
                m_PolybrushMesh.Initialize();
                m_PolybrushMesh.mode = (s_UseAdditionalVertexStreams) ? PolybrushMesh.Mode.AdditionalVertexStream : PolybrushMesh.Mode.Mesh;
            }

            //attach the skinmesh ref to the polybrushmesh
            //it will be used when making a prefab containing a skin mesh. The limitation here is that the skin mesh must comes from an asset (which is 99.9999% of the time)
            if (_skinMeshRenderer != null)
            {
                Mesh sharedMesh = _skinMeshRenderer.sharedMesh;
                if (AssetDatabase.Contains(sharedMesh))
                {
                    m_PolybrushMesh.skinMeshRef = sharedMesh;
                }
            }

#if PROBUILDER_4_0_OR_NEWER
            // if it's a probuilder object rebuild the mesh without optimization
            if (isProBuilderObject)
            {
                if (ProBuilderBridge.IsValidProBuilderMesh(gameObjectAttached))
                {
                    ProBuilderBridge.ToMesh(gameObjectAttached);
                    ProBuilderBridge.Refresh(gameObjectAttached);
                }
            }
#endif
            if (meshRenderer != null || _skinMeshRenderer != null)
            {
                mesh = m_PolybrushMesh.storedMesh;

                if (mesh == null)
                {
                    mesh             = PolyMeshUtility.DeepCopy(originalMesh);
                    hadVertexStreams = false;
                }
                else
                {
                    //prevents leak
                    if (!MeshInstanceMatchesGameObject(mesh, gameObjectAttached))
                    {
                        mesh = PolyMeshUtility.DeepCopy(mesh);
                    }
                }

                mesh.name = k_MeshInstancePrefix + gameObjectAttached.GetInstanceID();
            }

            polybrushMesh.SetMesh(mesh);
            PrefabUtility.RecordPrefabInstancePropertyModifications(polybrushMesh);
            _graphicsMesh = m_PolybrushMesh.storedMesh;

            source = polybrushMesh.mode == PolybrushMesh.Mode.AdditionalVertexStream? ModelSource.AdditionalVertexStreams : PolyEditorUtility.GetMeshGUID(originalMesh);

            GenerateCompositeMesh();
        }
示例#46
0
        /// <summary>
        /// 打开UI窗体
        /// </summary>
        /// <param name="uiFormId"></param>
        /// <param name="userData"></param>
        internal void OpenUIForm(int uiFormId, object userData = null, BaseAction <UIFormBase> onOpen = null)
        {
            if (IsExists(uiFormId))
            {
                return;
            }

            Sys_UIFormEntity entity = GameEntry.DataTable.DataTableManager.Sys_UIFormDBModel.Get(uiFormId);

            if (entity == null)
            {
                Debug.Log("对应的UI窗体数据不存在,id:" + uiFormId);
                return;
            }

            UIFormBase formBase = GameEntry.UI.Dequeue(uiFormId);

            if (formBase == null)
            {
                //TODO:异步加载UI需要时间 过滤正在加载的UI

                string assetPath = string.Empty;
                switch (GameEntry.Localization.CurrLanguage)
                {
                case LocalizationComponent.LanguageEnum.Chinese:
                    assetPath = entity.AssetPath_Chinese;
                    break;

                case LocalizationComponent.LanguageEnum.English:
                    assetPath = entity.AssetPath_English;
                    break;
                }
                LoadUIAsset(assetPath, (ResourceEntity resourceEntity) =>
                {
                    GameObject UIObj = Object.Instantiate((Object)resourceEntity.Target) as GameObject;

                    //把克隆出来的资源加入实例对象资源池
                    GameEntry.Pool.RegisterInstanceResource(UIObj.GetInstanceID(), resourceEntity);

                    UIObj.transform.SetParent(GameEntry.UI.GetUIGroup(entity.UIGroupId).Group);
                    UIObj.transform.localPosition = Vector3.zero;
                    UIObj.transform.localScale    = Vector3.one;

                    formBase = UIObj.GetComponent <UIFormBase>();
                    formBase.Init(uiFormId, entity.UIGroupId, entity.DisableUILayer == 1, entity.IsLock == 1, userData);
                    m_OpenUIFormList.AddLast(formBase);

                    if (onOpen != null)
                    {
                        onOpen(formBase);
                    }
                });
            }
            else
            {
                formBase.gameObject.SetActive(true);
                formBase.Open(userData);
                m_OpenUIFormList.AddLast(formBase);

                if (onOpen != null)
                {
                    onOpen(formBase);
                }
            }
        }
示例#47
0
 private void OnCollisionEnter(Collision col)
 {
     if (hit == false)
     {
         hit = true;
         if (col.gameObject.CompareTag("Stage") || col.gameObject.CompareTag("Wall"))
         {
             bounceAble--;
             if (bounceAble < 0)
             {
                 DestroyBullet(this.gameObject);
             }
             else
             {
                 SEManager.PlayBounceBulletSound();
             }
         }
         if (col.gameObject.CompareTag("DestroyableObject"))
         {
             DestroyByAttack dos = col.gameObject.GetComponent <DestroyByAttack>();
             dos.hitBullet();
             DestroyBullet(this.gameObject);
         }
         if (col.gameObject.CompareTag("Bullet") || col.gameObject.CompareTag("EnemyBullet") || col.gameObject.CompareTag("SpecialBullet"))
         {
             DestroyBullet(this.gameObject);
         }
         if (col.gameObject.CompareTag("Enemy"))
         {
             //Debug.Log(col.gameObject);
             try
             {
                 if (!shooterHitAble && shooterTank.GetInstanceID() == col.gameObject.GetInstanceID())
                 {
                     Debug.Log("発射直後の自分の弾に当たろうとした");
                 }
                 else
                 {
                     this.DestroyEnemy(col.gameObject);
                 }
             }
             catch (NullReferenceException e)
             {
                 Debug.Log(e);
             }
         }
         if (col.gameObject.CompareTag("Player"))
         {
             try
             {
                 if (!shooterHitAble && shooterTank.GetInstanceID() == col.gameObject.GetInstanceID())
                 {
                     Debug.Log("発射直後の自分の弾に当たろうとした");
                 }
                 else
                 {
                     this.PlayerDestroy(col.gameObject);
                 }
             }
             catch (NullReferenceException e)
             {
                 Debug.Log(e);
             }
         }
     }
 }
 public AddCurvesPopupGameObjectNode(GameObject gameObject, TreeViewItem parent, string displayName)
     : base(gameObject.GetInstanceID(), parent == null ? -1 : parent.depth + 1, parent, displayName)
 {
 }
示例#49
0
        public override void NewFrameStarting(RecordingSession session)
        {
            switch (cbSettings.source)
            {
            case ImageSource.ActiveCamera:
            {
                if (targetCamera == null)
                {
                    var displayGO = new GameObject();
                    displayGO.name             = "CameraHostGO-" + displayGO.GetInstanceID();
                    displayGO.transform.parent = session.recorderGameObject.transform;
                    var camera = displayGO.AddComponent <Camera>();
                    camera.clearFlags    = CameraClearFlags.Nothing;
                    camera.cullingMask   = 0;
                    camera.renderingPath = RenderingPath.DeferredShading;
                    camera.targetDisplay = 0;
                    camera.rect          = new Rect(0, 0, 1, 1);
                    camera.depth         = float.MaxValue;

                    targetCamera = camera;
                }
                break;
            }

            case ImageSource.MainCamera:
            {
                if (targetCamera != Camera.main)
                {
                    targetCamera    = Camera.main;
                    m_cameraChanged = true;
                }
                break;
            }

            case ImageSource.TaggedCamera:
            {
                var tag = ((CameraInputSettings)settings).cameraTag;

                if (targetCamera == null || !targetCamera.gameObject.CompareTag(tag))
                {
                    try
                    {
                        var objs = GameObject.FindGameObjectsWithTag(tag);

                        var cams = objs.Select(obj => obj.GetComponent <Camera>()).Where(c => c != null);
                        if (cams.Count() > 1)
                        {
                            Debug.LogWarning("More than one camera has the requested target tag '" + tag + "'");
                        }

                        targetCamera = cams.FirstOrDefault();
                    }
                    catch (UnityException)
                    {
                        Debug.LogWarning("No camera has the requested target tag '" + tag + "'");
                        targetCamera = null;
                    }
                }
                break;
            }
            }

            var newTexture = PrepFrameRenderTexture();

            if (m_Camera != null)
            {
                // initialize command buffer
                if (m_cameraChanged || newTexture)
                {
                    if (m_cbCopyFB != null)
                    {
                        m_Camera.RemoveCommandBuffer(CameraEvent.AfterEverything, m_cbCopyFB);
                        m_cbCopyFB.Release();
                    }

                    var tid = Shader.PropertyToID("_TmpFrameBuffer");
                    m_cbCopyFB = new CommandBuffer {
                        name = "Recorder: copy frame buffer"
                    };
                    m_cbCopyFB.GetTemporaryRT(tid, -1, -1, 0, FilterMode.Bilinear);
                    m_cbCopyFB.Blit(BuiltinRenderTextureType.CurrentActive, tid);
                    m_cbCopyFB.SetRenderTarget(outputRT);
                    m_cbCopyFB.DrawMesh(m_quad, Matrix4x4.identity, copyMaterial, 0, 0);
                    m_cbCopyFB.ReleaseTemporaryRT(tid);
                    m_Camera.AddCommandBuffer(CameraEvent.AfterEverything, m_cbCopyFB);

                    m_cameraChanged = false;
                }

                if (Math.Abs(1 - m_Camera.rect.width) > float.Epsilon || Math.Abs(1 - m_Camera.rect.height) > float.Epsilon)
                {
                    Debug.LogWarning(string.Format(
                                         "Recording output of camera '{0}' who's rectangle does not cover the viewport: resulting image will be up-sampled with associated quality degradation!",
                                         m_Camera.gameObject.name));
                }
            }
        }
示例#50
0
    public void In(
        Camera Camera,
        [FriendlyName("Screen Position")] Vector2 ScreenPosition,
        [FriendlyName("Distance"), SocketState(false, false), DefaultValue(100f)] float Distance,
        [FriendlyName("Layer Mask"), SocketState(false, false)] LayerMask layerMask,
        //TODO: Uncomment when array support is added
        //[FriendlyName("Layer Masks"), SocketState(false, false)] LayerMask[] layerMasks,
        [FriendlyName("Include Masked Layers"), DefaultValue(true), SocketState(false, false)] bool include,
        [FriendlyName("Show Ray"), SocketState(false, false)] bool showRay,
        [FriendlyName("Instance")] GameObject A,
        [FriendlyName("Compare By Tag"), SocketState(false, false)] bool CompareByTag,
        [FriendlyName("Compare By Name"), SocketState(false, false)] bool CompareByName,
        //[FriendlyName("Hit GameObject")] out GameObject HitObject,
        [FriendlyName("Hit Distance"), SocketState(false, false)] out float HitDistance,
        [FriendlyName("Hit Location")] out Vector3 HitLocation,
        [FriendlyName("Hit Normal"), SocketState(false, false)] out Vector3 HitNormal
        )
    {
        bool    hitTrue        = false;
        float   tmpHitDistance = 0F;
        Vector3 tmpHitLocation = Vector3.zero;
        Vector3 tmpHitNormal   = new Vector3(0, 1, 0);
        //GameObject tmpHitObject = null;
        //TODO: Remove the following line when array support is added
        //LayerMask[] layerMasks = new LayerMask[] { layerMask };

        Ray ray = Camera.ScreenPointToRay(ScreenPosition);

        if (Distance <= 0)
        {
            Distance = Mathf.Infinity;
        }
        float castDistance = Distance;

        /*
         * //RaycastHit hit;
         * int bitmask = 0;
         *
         * foreach (LayerMask mask in layerMasks) {
         *      bitmask |= 1 << mask;
         * }
         *
         * if (!include) bitmask = ~bitmask;
         */

        if (!include)
        {
            layerMask = ~layerMask;
        }

        if (true == showRay)
        {
            Debug.DrawLine(ray.origin, ray.origin + (ray.direction * castDistance));
        }

        RaycastHit[] hits;
        hits = Physics.RaycastAll(ray.origin, ray.direction, castDistance, layerMask);
        int i = 0;

        while (i < hits.Length)
        {
            RaycastHit hit = hits[i];
            GameObject B   = hit.collider.gameObject;
            if (true == CompareByTag || CompareByName)
            {
                m_CompareValue = true;
                if (true == CompareByTag)
                {
                    m_CompareValue = m_CompareValue && A.tag == B.tag;
                }
                if (true == CompareByName)
                {
                    m_CompareValue = m_CompareValue && A.name == B.name;
                }
            }
            else
            {
                m_CompareValue = A.GetInstanceID() == B.GetInstanceID();
            }
            if (true == m_CompareValue)
            {
                tmpHitDistance = hit.distance;
                tmpHitLocation = hit.point;
                //tmpHitObject = hit.collider.gameObject;
                tmpHitNormal = hit.normal;
                hitTrue      = true;
                break;
            }
            i++;
        }

        HitDistance = tmpHitDistance;
        HitLocation = tmpHitLocation;
        //HitObject = tmpHitObject;
        HitNormal = tmpHitNormal;

        m_Obstructed    = hitTrue;
        m_NotObstructed = !m_Obstructed;
    }
示例#51
0
 public bool IsCorpse(GameObject obj)
 {
     return(Corpses.ContainsKey(obj.GetInstanceID()));
 }
 private void Start()
 {
     ui = GameObject.FindGameObjectWithTag("Canvas").GetComponent <UIManager>();
     explodeListener = new UnityAction(Explode);
     EventManager.StartListening("explode" + chillSkeleton.GetInstanceID(), explodeListener);
 }
 private static bool WasScanned(GameObject obj)
 {
     return(scannedObjects.Contains(obj.GetInstanceID()));
 }
示例#54
0
 public bool IsCell(GameObject obj)
 {
     return(CellsObject.ContainsKey(obj.GetInstanceID()));
 }
示例#55
0
        public override void Update()
        {
            if (GlobalVariables.GetGlobalVariables().keyBindShowItemListUI.IsDown())
            {
                GlobalVariables.GetGlobalVariables().itemTransmitter.isShowWindow = !GlobalVariables.GetGlobalVariables().itemTransmitter.isShowWindow;
            }

            if (GlobalVariables.GetGlobalVariables().keyBindAddGameObjectToItemList.IsDown())
            {
                if (GlobalVariables.GetGlobalVariables().physicsRaycast.mainCameraRaycastHits != null && GlobalVariables.GetGlobalVariables().physicsRaycast.mainCameraRaycastHits.Length > 0)
                {
                    foreach (RaycastHit hitInfo in GlobalVariables.GetGlobalVariables().physicsRaycast.mainCameraRaycastHits)
                    {
                        GameObject targetGameObject = hitInfo.collider.gameObject;
                        if (targetGameObject != null && CanPickUp(targetGameObject))
                        {
                            string partName = targetGameObject.name.Replace("(Clone)", "").Replace("(itemx)", "").Replace("(xxxxx)", "");
                            string text     = partName + "(" + GlobalVariables.GetGlobalVariables().mscTranslate.translateText.TranslateString(partName, TranslateText.DICT_PARTNAME) + ")" + "|" + targetGameObject.GetInstanceID();
                            if (!itemDict.ContainsKey(text))
                            {
                                itemDict.Add(text, targetGameObject);
                            }
                            else
                            {
                                logger.LOG(targetGameObject + "已经在背包,不允许拾取(再次传送到垃圾堆)");
                            }
                            targetGameObject.transform.parent = null;
                            GlobalVariables.GetGlobalVariables().teleport.TeleportTo(targetGameObject, GlobalVariables.GetGlobalVariables().gameObjectLandfillSpawn);
                        }
                    }
                }
            }

            float scrollWheel    = Input.GetAxis("Mouse ScrollWheel");
            int   scrollWheelInt = 0;

            if (scrollWheel > 0)
            {
                scrollWheelInt = -1;
            }
            else if (scrollWheel < 0)
            {
                scrollWheelInt = 1;
            }
            selectItemKeyIndex += scrollWheelInt;
            if (itemDict.Keys.Count <= selectItemKeyIndex || selectItemKeyIndex < 0)
            {
                selectItemKeyIndex = itemDict.Keys.Count - 1;
            }

            if (GlobalVariables.GetGlobalVariables().keyBindRemoveGameObjectFormItemList.IsDown())
            {
                if (itemDict.Count > 0 && selectItemKey != null && !"".Equals(selectItemKey))
                {
                    logger.LOG("是否在菜单:" + GlobalVariables.GetGlobalVariables().fsmBoolPlayerInMenu.Value);
                    if (GlobalVariables.GetGlobalVariables().fsmBoolPlayerInMenu.Value)
                    {
                        GlobalVariables.GetGlobalVariables().teleport.TeleportTo(itemDict[selectItemKey], GlobalVariables.GetGlobalVariables().gameObjectPalyer);
                    }
                    else
                    {
                        TeleportToCamera(itemDict[selectItemKey]);
                    }

                    itemDict.Remove(selectItemKey);
                    selectItemKey = null;
                    selectItemKeyIndex--;
                    if (selectItemKeyIndex < 0)
                    {
                        selectItemKeyIndex = 0;
                    }
                }
            }
        }
示例#56
0
    void OnGUI()
    {
        bool created = false;

        if (GUI.RepeatButton(redRect, "Capsule"))
        {
            go = GameObject.CreatePrimitive(PrimitiveType.Capsule);
            TypeHolder typeH = go.AddComponent <TypeHolder>();
            typeH.type = PrimitiveType.Capsule;
            go.name    = "Capsule" + go.GetInstanceID();
            created    = true;
        }

        if (GUI.RepeatButton(greenRect, "Cube"))
        {
            go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            TypeHolder typeH = go.AddComponent <TypeHolder>();
            typeH.type = PrimitiveType.Cube;
            go.name    = "Cube" + go.GetInstanceID();
            created    = true;
        }

        if (GUI.RepeatButton(blueRect, "Cylinder"))
        {
            go = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
            TypeHolder typeH = go.AddComponent <TypeHolder>();
            typeH.type = PrimitiveType.Cylinder;
            go.name    = "Cylinder" + go.GetInstanceID();
            created    = true;
        }

        /*
         * if (GUI.Button(resetRect, "SAVE"))
         * BinarySaver.Save(GetObjectsToSave(), fileName);
         *
         * if (GUI.Button(loadRect, "LOAD"))
         * {
         * List<ObjectSaver> toLoad = BinarySaver.Load(fileName) as List<ObjectSaver>;
         * if (toLoad == null)
         * {
         * Debug.Log("No Binary File Found");
         * return;
         * }
         *
         * CreateObjectsFromList(toLoad);
         * }
         */

        if (GUI.Button(resetXMLRect, "SAVE XML"))
        {
            XMLSaver <List <ObjectSaver> > .Save(GetObjectsToSave(), fileNameXML);
        }

        if (GUI.Button(loadXMLRect, "LOAD XML"))
        {
            List <ObjectSaver> toLoad = XMLSaver <List <ObjectSaver> > .Load(fileNameXML);

            if (toLoad == null)
            {
                Debug.Log("No XML File Found");
                return;
            }

            CreateObjectsFromList(toLoad);
        }

        if (!created)
        {
            return;
        }

        go.transform.position = Random.insideUnitSphere * 5;
        go.GetComponent <Renderer>().material.color = new Color(Random.insideUnitSphere.x, Random.insideUnitSphere.y, Random.insideUnitSphere.z);
        objects.Add(go);
    }
示例#57
0
    public virtual void ResistancyOutput(GameObject SourceInstance)
    {
        float Resistance = ElectricityFunctions.WorkOutResistance(Data.ResistanceComingFrom[SourceInstance.GetInstanceID()]);

        InputOutputFunctions.ResistancyOutput(Resistance, SourceInstance, this);
    }
示例#58
0
 public static string GetGameObjectInfo(GameObject obj)
 {
     return("(" + obj.GetInstanceID() + ":" + obj.name + ")");
 }
示例#59
0
 public void SaveObjectState(GameObject i_GameObject, LevelUnitStates i_State)
 {
     map[Stage.value][i_GameObject.GetInstanceID()] = i_State;
 }
示例#60
0
    //draw custom editor window GUI
    void OnGUI()
    {
        //display label and object field for projectile model slot
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Projectile Model:");
        projectileModel = (GameObject)EditorGUILayout.ObjectField(projectileModel, typeof(GameObject), false);
        EditorGUILayout.EndHorizontal();

        //display label and enum list for collider type
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Collider Type:");
        colliderType = (ColliderType)EditorGUILayout.EnumPopup(colliderType);
        EditorGUILayout.EndHorizontal();

        //display label and layer field for projectile layer
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Projectile Layer:");
        layer = EditorGUILayout.LayerField(layer);
        EditorGUILayout.EndHorizontal();

        //display label and checkbox for Projectile component
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Attach Projectile:");
        attachProjectile = EditorGUILayout.Toggle(attachProjectile);
        EditorGUILayout.EndHorizontal();

        //display label and checkbox for Rigidbody component
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Attach Rigidbody:");
        attachRigidbody = EditorGUILayout.Toggle(attachRigidbody);
        EditorGUILayout.EndHorizontal();

        //display info box below all settings
        EditorGUILayout.Space();
        EditorGUILayout.HelpBox("By clicking on 'Apply!' all chosen components are added and a prefab will be created next to your projectile model.", MessageType.Info);
        EditorGUILayout.Space();

        //apply button
        if (GUILayout.Button("Apply!"))
        {
            //cancel further execution if no tower model is set
            if (projectileModel == null)
            {
                Debug.LogWarning("No projectile model chosen. Aborting Projectile Setup execution.");
                return;
            }

            //get model's asset path in this project to place the new prefab next to it
            string assetPath = AssetDatabase.GetAssetPath(projectileModel.GetInstanceID());
            //e.g. assetPath = "Assets/Models/model.fbx
            //split folder structure for renaming the existing model name as prefab
            string[] folders = assetPath.Split('/');
            //e.g. folders[0] = "Assets", folders[1] = "Models", folders[2] = "model.fbx"
            //then we replace the last part, the model name in folders[2], with the new prefab name
            assetPath = assetPath.Replace(folders[folders.Length - 1], projectileModel.name + ".prefab");
            //new asset path: "Assets/Models/model.prefab"


            //instantiate, convert and setup model to new prefab
            ProcessModel();

            //if Projectile checkbox is checked
            if (attachProjectile)
            {
                //attach Projectile component
                projectileModel.AddComponent <Projectile>();
            }

            //if Rigidbody checkbox is checked, add component
            if (attachRigidbody)
            {
                //attach and store rigidbody component
                Rigidbody rigid = projectileModel.AddComponent <Rigidbody>();
                //make rigidbody kinematic
                rigid.isKinematic = true;
                //disable gravity
                rigid.useGravity = false;
            }

            //initialize prefab gameobject
            GameObject prefab = null;

            //perform check if we already have a prefab in our project (null if none)
            if (AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)))
            {
                //display custom dialog and wait for user input to overwrite prefab
                if (EditorUtility.DisplayDialog("Are you sure?",
                                                "The prefab already exists. Do you want to overwrite it?",
                                                "Yes",
                                                "No"))
                {
                    //user clicked "Yes", create and overwrite existing prefab
                    prefab = PrefabUtility.CreatePrefab(assetPath, projectileModel.gameObject);
                }
            }
            else
            {
                //we haven't created a prefab before nor the project contains one,
                //create prefab next to the model at assetPath
                prefab = PrefabUtility.CreatePrefab(assetPath, projectileModel.gameObject);
            }

            //destroy temporary instantiated projectile model in the editor
            DestroyImmediate(projectileModel.gameObject);
            //if we created a prefab
            if (prefab)
            {
                //select it within the project panel
                Selection.activeGameObject = prefab;
                //close this editor window
                this.Close();
            }
        }
    }