Search Unity

Foreach & Instantiate & Find & Transform

Discussion in 'Scripting' started by Slyrfecso1, Oct 31, 2015.

  1. Slyrfecso1

    Slyrfecso1

    Joined:
    Jul 16, 2012
    Posts:
    100
    Hi,

    I would like to instantiate prefabs from my list with position, rotation, scale and parent.

    1 Try:
    If I have only one object in the list it is working, but with 2 or more, without success.
    Code (CSharp):
    1. foreach(Prefabs obj in Prefabs.current.prefabDataFAL)
    2. {
    3. GameObject myPrefab = Resources.Load("Prefabs/"+obj.savedName) as GameObject;
    4. GameObject spawnedObject = Instantiate<GameObject>(myPrefab);
    5. spawnedObject.transform.position = obj.savedPos;
    6. spawnedObject.transform.rotation = obj.savedRot;
    7. spawnedObject.name = spawnedObject.name.Replace("(Clone)","").Trim();
    8.  
    9. foreach(Prefabs objFALNEV in Prefabs.current.prefabDataFALNEV)
    10. {
    11. spawnedObject.transform.parent = GameObject.Find(objFALNEV.savedName).transform;
    12. spawnedObject.transform.localScale = new Vector3 (obj.savedScale.x, obj.savedScale.y, obj.savedScale.z);
    13. }
    14. }


    2 Try:
    A little bit better, but the next object is parenting under the previous.
    This is wrong, because them must be parent to the objFALNEV.savedName.
    Every parent is under the first objFALNEV.savedName, not in new one.

    Code (CSharp):
    1. foreach(Prefabs obj in Prefabs.current.prefabDataFAL)
    2. {
    3. GameObject myPrefab = Resources.Load("Prefabs/"+obj.savedName) as GameObject;
    4. GameObject spawnedObject = Instantiate<GameObject>(myPrefab);
    5. spawnedObject.transform.position = obj.savedPos;
    6. spawnedObject.transform.rotation = obj.savedRot;
    7. spawnedObject.name = spawnedObject.name.Replace("(Clone)","").Trim();
    8.  
    9. foreach(Prefabs objFALNEV in Prefabs.current.prefabDataFALNEV)
    10. {
    11. GameObject wall0 = GameObject.Find(objFALNEV.savedName);
    12. if (wall0 != null)
    13. {
    14. spawnedObject.transform.parent = wall0.transform;
    15. spawnedObject.transform.localScale = new Vector3 (obj.savedScale.x, obj.savedScale.y, obj.savedScale.z);
    16. }
    17. }
     
    Last edited: Nov 1, 2015