2017-02-21 63 views
0

我試圖用相同的標籤,從最後一個實例化到第一個,逐個銷燬實例化的預製件,並且我堅持如何實現這一點。從最後一個實例化到第一個,使用相同標記逐個銷燬實例化的預製?

這個想法是我想要一個自定義編輯器,它允許我實例化多個預製,然後分別用兩個GUI按鈕「放置對象」和「撤消」來「撤消」最後一個實例化。到目前爲止,我能夠成功實例化預製件,爲它們添加相同的標籤,然後逐個銷燬它們,但是它們從第一個到最後一個實例化被破壞。

我到目前爲止的代碼:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class ObjectInstantiateControl : MonoBehaviour { 

public List<GameObject> prefabList = new List<GameObject>(); 
[HideInInspector] 
public int objectSelectionIndex = 0; 
GameObject instance; 

public void PlaceObject() 
{ 
    switch (objectSelectionIndex) 
    { 
     case 1: 

      Debug.Log("Just received a number 1 from the editor"); 
      GameObject object_A = Resources.Load("Object_A") as GameObject; 
      instance = Instantiate(object_A, this.transform.position, this.transform.rotation, this.transform); 

      instance.tag = "UsedObject"; 
      prefabList.Add(instance); 

      break; 

     case 2: 

      Debug.Log("Just received a number 2 from the editor"); 
      GameObject object_B = Resources.Load("Object_B") as GameObject; 
      instance = Instantiate(object_B, this.transform.position, this.transform.rotation, this.transform); 

      instance.tag = "UsedObject"; 
      prefabList.Add(instance); 
      break; 

     case 3: 

      Debug.Log("Just received a number 3 from the editor"); 
      GameObject object_C = Resources.Load("Object_C") as GameObject; 
      instance = Instantiate(object_C, this.transform.position, this.transform.rotation, this.transform); 

      instance.tag = "UsedObject"; 
      prefabList.Add(instance); 
      break; 

     case 4: 

      Debug.Log("Just received a number 4 from the editor, deleting the object"); 

      prefabList.Remove(GameObject.FindWithTag("UsedObject")); 
      DestroyImmediate(GameObject.FindWithTag("UsedObject")); 
      break; 
    } 
} 

和零件從GUI按鈕「將對象」和「撤消」編輯腳本:

     GUILayout.BeginHorizontal(); 

        if (GUILayout.Button("Place object", GUILayout.Height(25))) 
        { 
         ObjectInstantiateControl myScript = (ObjectInstantiateControl)target; 
         myScript.objectSelectionIndex = 1; 
         myScript.PlaceObject()(); 

        } 

        if (GUILayout.Button("Undo", GUILayout.Height(25))) 
        { 
         ObjectInstantiateControl myScript = (ObjectInstantiateControl)target; 
         myScript.objectSelectionIndex = 4; 
         myScript.PlaceObject(); 

        } 
        GUILayout.EndHorizontal(); 

真的需要這方面的幫助,任何想法或建議都是受歡迎的。在此先感謝;)

+0

「撤消」部分看起來與「放置對象」部分完全相同嗎? –

+0

是否有一個原因,你正在使用'FindWithTag'而不是從列表中彈出最後一項並銷燬它? – rutter

回答

0

在這種情況下,我會選擇隊列或LinkList。你可以添加所有的遊戲對象,並以其他方式進行管理。

https://msdn.microsoft.com/en-us/library/system.collections.queue(v=vs.110).aspx 
https://msdn.microsoft.com/en-us/library/he2s3bh7(v=vs.110).aspx