-2
List<GameObject> myObjects = new List<GameObject>();
public GameObject prefab;
GameObject copyPrefab;
void Start()
{
     copyPrefab = prefab;
     copyPrefab.transform.position = new Vector2(1, 0);
     myObjects.Add(copyPrefab);
     copyPrefab.transform.position = new Vector2(2, 0);
     myObjects.Add(copyPrefab);
     foreach(var item in myObjects)
     {
         Debug.Log(item.transform.position);
     }
}

I have two game object in list but their position output always same, Why? I don't want to Instantiate, İ will Instantiate later. I just want to save gameobjects. How can I do that?

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
caatayk
  • 9
  • 4
  • 2
    Because your `copyprefab` always refers to exactly the same `GameObject` .. you never actually copy it which would happen if you used `Instantiate` – derHugo Mar 12 '20 at 06:27

2 Answers2

1

The positions are always the same because you they are the same. See the add lines

myObjects.Add(copyPrefab);
copyPrefab.transform.position = new Vector2(2, 0);
myObjects.Add(copyPrefab);

This is the same object and therefore it doesn't matter which index of the list you look at. You can't be in two places at once.

I don't know what you mean by not wanting to instantiate. Do you mean a second prefab? If so you can't have both of these being different. You would have to do :

copyPrefab = GameObject.Instantiate(prefab, someTrans, someRot);
myObjects.Add(copyPrefab);
Derek C.
  • 890
  • 8
  • 22
0

GameObject is a class that is a reference type. So you essentially referring to the same object when second time you are setting the position. You need modification like this:

void Start()
{
     myObjects.Add(Spawner(prefab,new Vector2(1, 0)));
     myObjects.Add(Spawner(prefab,new Vector2(2, 0)));
     foreach(var item in myObjects)
     {
         Debug.Log(item.transform.position);
     }
}

GameObject Spawner(GameObject prefab, Vector3 pos){
return GameObject.Instantiate(prefab, pos, Quaternion.identity;);

}

Warning: Untested code

Muhammad Faizan Khan
  • 10,013
  • 18
  • 97
  • 186
  • bit unnecessary to create a method wrapper for `Instantiate` ;) – derHugo Mar 12 '20 at 06:27
  • Just tried to create the simplest solution for the beginner :) – Muhammad Faizan Khan Mar 12 '20 at 06:30
  • 1
    The simplest solution would be simply using `copyprefab = Instantiate (prefab); copyprefab.transform.position = new Vector2(1, 0); myObject.Add(copyprefab);`. This would not overcomplicate it woth an additional method and woukd reuse OP's code so it is more clear what has to be changed. And then .. well exactly this was already done in [this answer](https://stackoverflow.com/a/60647914/7111561) ;) – derHugo Mar 12 '20 at 06:35