Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do I unload current prefabs

Discussion in 'Scripting' started by Langdelliooo, Oct 11, 2018.

  1. Langdelliooo

    Langdelliooo

    Joined:
    Sep 20, 2018
    Posts:
    17
    Hi,

    I have written the following;

    Code (CSharp):
    1. public void LoadBuildingCards()
    2. {
    3. List<BuildingTypeData> types = BuildingManager.GetInstance().GetAllBuildingTypes().ToList();
    4. buildingSelectPanels = new List<UIBuildingSelectView>();
    5. foreach (BuildingTypeData type in types)
    6. {
    7. if (type.BuildingCategory == SelectedCategory)
    8. {
    9. AddBuildingPanel(type);
    10. }  
    11. }
    Code (CSharp):
    1.         private void AddBuildingPanel(BuildingTypeData type)
    2.         {
    3.             GameObject panelGo = (GameObject)Instantiate(buildingPanelPrefab);
    4.             UIBuildingSelectView panel = panelGo.GetComponent<UIBuildingSelectView>();
    5.             panelGo.transform.SetParent(buildingScrollPanel.transform);
    6.             panelGo.transform.localScale = Vector3.one;
    7.             panel.InitialiseWithBuildingType(type);
    8.             buildingSelectPanels.Add(panel);
    9.         }

    The code is working exactly how I want it to, as my interface uses tabs which set the building category (SelectedCategory) and load the prefabs with the buildings required.

    My question is that when I click a tab to show military buildings for instance, i need it to remove all the current prefabs that are being shown and then do this code. How do I achieve this?
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,294
    Best pratice is to pre-populate the UI, and then simply gameObject.SetActive(true/false) them when it's needed.

    If you're 100% want to unload, use Destroy(*prefab_gameObject*) to do that.
     
  3. Langdelliooo

    Langdelliooo

    Joined:
    Sep 20, 2018
    Posts:
    17
    The prefab that i use is called UIBuildingSelectPanel, but when I call Destroy(UIBuildingSelectPanel) I get the following error;

    CS0118: is a 'type' but a 'variable' was expected.
    CS0119: Expression denotes a 'type', where a 'variable', 'value' or 'method group' was expected.
     
  4. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,294
    You need to specify an actual that prefab's instance gameObject, in order to destroy it. Not a name of it.
    Code (CSharp):
    1. GameObject someInstance = Instantiate(SomePrefab);
    2.  
    3. // To destroy, you have to do Destroy on the
    4. Destroy(someInstance);
    So, in order to do that, you should keep the reference after the instantiation.