Search Unity

How to instantiate Resource Prefabs with they names from List?

Discussion in 'Scripting' started by Slyrfecso1, Sep 10, 2015.

  1. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    Hi,

    I have found objects and added names of them to the first list and the positions in the second and the rotation in third list.

    Code (CSharp):
    1. publicList<Game> prefabNameList = newList<Game>();
    2. publicList<Game> prefabNameTransform = newList<Game>();
    3. publicList<Game> prefabNameRotate = newList<Game>();
    I'd like to instantiate the objects from the list, back to saved position and rotation.

    WORKING CODE, I see all data in lists in the inspector
    Code (CSharp):
    1. GameObject[]go = GameObject.FindGameObjectsWithTag("Player");
    2.                         foreach(GameObject AllgameObjectsSave in go)
    3.                             {
    4.            
    5.                         Vector3 AllObjectsPOS = AllgameObjectsSave.transform.position;
    6.                         Vector3 AllObjectsROT = AllgameObjectsSave.transform.eulerAngles;
    7.                
    8.  
    9.                         prefabNameList.Add (new Game(AllgameObjectsSave.name));
    10.                         prefabNameTransform.Add (new Game(AllObjectsPOS.ToString("G4")));
    11.                         prefabNameRotate.Add (new Game(AllObjectsROT.ToString("G3")));


    WRONG CODE:
    Code (CSharp):
    1. for (int i = 0; i < prefabNameList.Length; i++)
    2. {
    3.     GameObject go = Instantiate(prefabNameList[i], prefabNameTransform, prefabNameRotate) as GameObject;
    4. }

     
    Last edited: Sep 10, 2015
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    How does the behavior you see differ from what you expect? Do you see any errors in the console? (I already know you do, I can see at least two. But if you get an error message, you should always include it with your forum post)
     
  3. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    You have right, but my instantiate code is a big mistake, just I putted in as an idea.

     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    OK. So, let's start with the obvious: You're using List for those, and List doesn't have .Length - List uses .Count instead.

    Second: what is "Game"? it looks to me like it's just a way to store a string. At best it's a poorly named class, but I suspect it's a completely unnecessary one, and you should probably just use strings directly. In any case, you need to create and use a way to extract Vector3's and Quaternions from your "Game" class or string. You'll probably need to parse them.

    Also, you're sending your Instantiate function the entire List of positions and rotations; you need after them.

    All of those are things to fix -before- we answer the question you actually asked. And it is pretty straightforward:

    Code (csharp):
    1. GameObject myPrefab = Resources.Load<GameObject>(prefabName);
    2. GameObject spawnedObject = Instantiate<GameObject>(myPrefab, pos, rot);
     
  5. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    Sorry for late answer, but I have tried to understand your describe.


    I rewrote the codes, please check again:
    I can save and reload the first found object with position and rotation.
    This method is save only one name of object, position and rotation.
    How can I save all objects, them positions and rotations?
    You can try my project:
    http://terberendezo.alexbutor.hu
    user: a
    pass: a
    First drag elsewhere all object with mouse, than:
    Click on 6th icon.
    Save the state (Az összeállítás mentése)
    Then load the state (Korábbi betöltése)
    (Only prefab save, not binary or network, therefore every time you open the project in browser, then saved will be deleted.)
    I hope you could help me, thanks.



    Character.cs
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Text.RegularExpressions;
    5.  
    6. [System.Serializable] // You need this part, so that you class can be 'serialized', meaning turned into 1s and 0s. Binary baby!
    7. public class Character {
    8.  
    9.     public string name;
    10.  
    11.  
    12.     public Character () {
    13.         this.name = "";
    14.  
    15.     }
    16.  
    17.  
    18. }
    19.  

    Prefabs.cs
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5.  
    6.  
    7. [System.Serializable]
    8. public class Prefabs {
    9.  
    10.     public static Prefabs current;
    11.     public Character vezetek;
    12.     public Character osszeallitas;
    13.     public Character savedPrefabName;
    14.     public Vector3 savedPos;
    15.     public Quaternion savedRot;
    16.  
    17.  
    18.     public Prefabs ()
    19.     {
    20.         vezetek = new Character();
    21.         osszeallitas = new Character();
    22.         savedPrefabName = new Character();
    23.         savedPos = new Vector3();
    24.         savedRot = new Quaternion();
    25.  
    26.     }
    27.  
    28.  
    29. }

    felhasznalo.cs
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Text.RegularExpressions;
    5.  
    6. public class felhasznalo : MonoBehaviour {
    7.  
    8.     public GUIStyle userStyel;
    9.     public GUIStyle userTooltipSytle;
    10.     public GUIStyle szoveg;
    11.     public int counterFE=0;
    12.  
    13.  
    14.  
    15.     public void helloFEL(){
    16.  
    17.         counterFE = 0;
    18.  
    19.     }
    20.  
    21.  
    22.  
    23. //    string email = "";
    24. //    string username = "";
    25. //    string password = "";
    26. //    string confirm = "";
    27.  
    28.     public enum Menu {
    29.         MainMenu,
    30.         NewGame,
    31.         Continue
    32.     }
    33.  
    34.     public Menu currentMenu;
    35.  
    36.  
    37.     public alapterulet caller1;
    38.     public measure caller2;
    39.     public Inventory caller3;
    40.     public ButorlapInventory caller4;
    41.     public FemfestekInventory caller5;
    42.  
    43.  
    44.  
    45.  
    46.  
    47.     void OnGUI () {
    48.  
    49.  
    50.         if (counterFE==2)
    51.         {
    52.             counterFE = counterFE-2;
    53.         }
    54.  
    55.  
    56.         if (GUI.Button (new Rect (Screen.width/2+35, 10, 50, 48), "" , userStyel))
    57.         {
    58.             counterFE++;
    59. //            Debug.Log("ButtonFELpressed");
    60.         }
    61.  
    62.  
    63.         if (counterFE == 1)
    64.         {
    65.         GUI.Box (new Rect (Screen.width / 2 - 200, 80, 405, 400), ""  ,userTooltipSytle);
    66.             GUI.Label(new Rect(Screen.width / 2 - 170, 100, 60, 25), "FELHASZNÁLÓI FELÜLET" ,szoveg);
    67. //            email = GUI.TextField (new Rect (Screen.width / 2 - 60, 135, 250, 25), email, 40);
    68. //            username = GUI.TextField ( new Rect (Screen.width / 2 - 60, 170, 250, 25), username, 40);
    69. //            password = GUI.PasswordField (new Rect (Screen.width / 2 - 60, 205, 250, 25), password, "*"[0], 40);
    70. //            confirm = GUI.PasswordField (new Rect (Screen.width / 2 - 60, 240, 200, 25), confirm, "*"[0], 40);
    71. //
    72.             GUI.Label(new Rect(Screen.width / 2 - 170, 380, 60, 25), "Hamarosan elérhető!\n\n" +
    73.                      "- árkalkulációt készíthet\n" +
    74.                       "- megrendelését elküldheti\n" +
    75.                       "- felhasználói adatokat módosíthat" ,szoveg);
    76.  
    77.  
    78.             caller1.helloAT ();
    79.             caller2.helloME ();
    80.             caller3.helloIN ();
    81.             caller4.helloBU ();
    82.             caller5.helloFEM ();
    83.  
    84.  
    85. //            if (GUI.Button (new Rect (Screen.width / 2 - 60, 280, 100, 30), "Belépés")) {
    86. //                Debug.Log(email + " " + username + " " + password + " " + confirm);
    87.  
    88.  
    89.  
    90.      
    91.         //--------------------------------
    92.  
    93.             GUILayout.BeginArea(new Rect(Screen.width / 2 -170,150,200, 300));
    94.          
    95.                 if(currentMenu == Menu.MainMenu) {
    96.              
    97.                     GUILayout.Box("Térberendezés");
    98.                     GUILayout.Space(10);
    99.              
    100.                     if(GUILayout.Button("ÚJ üres tér")) {
    101.                                                      
    102.                         foreach(GameObject AllgameObjectsDelete in GameObject.FindGameObjectsWithTag("Player"))
    103.                         {
    104.                         Destroy (AllgameObjectsDelete);
    105.                         }
    106.                         currentMenu = Menu.MainMenu;
    107.  
    108.  
    109.                     }
    110.  
    111.                     if(GUILayout.Button("Az összeállítás mentése")) {
    112.                         Prefabs.current = new Prefabs();
    113.                         currentMenu = Menu.NewGame;
    114.                     }
    115.              
    116.                     if(GUILayout.Button("Korábbi betöltése")) {
    117.                         SaveLoad.Load();
    118.                         currentMenu = Menu.Continue;
    119.                     }
    120.  
    121. //                    if(GUILayout.Button("A lista törlése")) {
    122. //                        SaveLoad.Load();
    123. //                        Game gameToRemove = SaveLoad.savedGames.First<game>; //Replace with game you want to remove
    124. //                        if (gameToRemove != null)
    125. //                        {
    126. //                        SaveLoad.savedGames.Remove(gameToRemove);
    127. //                        }
    128. //                        SaveLoad.Save();
    129. //                        }
    130.  
    131.  
    132.                 }
    133.          
    134.                 else if (currentMenu == Menu.NewGame) {
    135.              
    136.                     GUILayout.Box("Személyes adatok");
    137.                     GUILayout.Space(10);
    138.              
    139.                     GUILayout.Label(("Az Ön neve"), szoveg);
    140.                     Prefabs.current.vezetek.name = GUILayout.TextField(Prefabs.current.vezetek.name, 20);
    141.                     GUILayout.Label(("Az összeállítás megnevezése"), szoveg);
    142.                     Prefabs.current.osszeallitas.name = GUILayout.TextField(Prefabs.current.osszeallitas.name, 20);
    143.  
    144.              
    145.                     if(GUILayout.Button("Mentés")) {
    146.                  
    147.  
    148.                         //Save section
    149.  
    150.  
    151.                         GameObject[]go = GameObject.FindGameObjectsWithTag("Player");
    152.                         foreach(GameObject AllgameObjectsSave in go)
    153.                             {
    154.          
    155.                         AllgameObjectsSave.name = AllgameObjectsSave.name.Replace("Ü","U").Trim();
    156.                         Prefabs.current.savedPrefabName.name = AllgameObjectsSave.name;
    157.                         Vector3 AllObjectsPOS = AllgameObjectsSave.transform.position;
    158.                         Quaternion AllObjectsROT = AllgameObjectsSave.transform.rotation;
    159.  
    160.                         Prefabs.current.savedPos = AllObjectsPOS;
    161.                         Prefabs.current.savedRot = AllObjectsROT;
    162.  
    163.                             }
    164.  
    165.  
    166.  
    167.  
    168.                         SaveLoad.Save();
    169.                         //Move on to ...
    170.                         //Application.LoadLevel(1);
    171.                         currentMenu = Menu.MainMenu;
    172.                     }
    173.              
    174.                     GUILayout.Space(10);
    175.                     if(GUILayout.Button("Vissza")) {
    176.                         currentMenu = Menu.MainMenu;
    177.                     }
    178.              
    179.                 }
    180.          
    181.                 else if (currentMenu == Menu.Continue) {
    182.              
    183.                     GUILayout.Box("Mentés kiválasztása");
    184.                     GUILayout.Space(10);
    185.              
    186.                     foreach(Prefabs g in SaveLoad.savedTerberendezo) {
    187.                         if(GUILayout.Button(g.vezetek.name + " - " + g.osszeallitas.name)) {
    188.                         foreach(GameObject AllgameObjectsDelete in GameObject.FindGameObjectsWithTag("Player"))
    189.                         {
    190.                             Destroy (AllgameObjectsDelete);
    191.                         }
    192.  
    193.                         //Load section
    194.                         Prefabs.current = g;
    195.                         GameObject myPrefab = Resources.Load("Prefabs/"+g.savedPrefabName.name) as GameObject;
    196.  
    197.  
    198.                         Vector3 move = g.savedPos;
    199.                         Quaternion rotate = g.savedRot;
    200.                         GameObject spawnedObject = Instantiate<GameObject>(myPrefab);
    201.                         spawnedObject.transform.position = move;
    202.                         spawnedObject.transform.rotation = rotate;
    203.                         spawnedObject.name = spawnedObject.name.Replace("(Clone)","").Trim();
    204.                         spawnedObject.name = spawnedObject.name.Replace("U","Ü").Trim();
    205.  
    206.  
    207.                         }
    208.                  
    209.                     }
    210.              
    211.                     GUILayout.Space(10);
    212.                     if(GUILayout.Button("Vissza")) {
    213.                         currentMenu = Menu.MainMenu;
    214.                     }
    215.              
    216.                 }
    217.  
    218.                 GUILayout.EndArea();
    219.          
    220.             }
    221.  
    222.         }
    223.     }
    224.  
     
    Last edited: Sep 14, 2015