Coatl
Coatl

Reputation: 592

Unity2D: instantiating multiple prefabs

I have a composite prefab with multiple sprites and a script attached to it. The problem is, when I instantiate it more than once, the instances go crazy:

  1. Their position on the screen is partly OK and partly determined by the prefab's setup in the editor. But Debug.Log reveals that the transform.position variable is set to the same value for all the instances. (It's the value that was used by the last instantiation.)

  2. Their script, when accessed by GetComponent<>, behaves strangely. It doesn't access some members correctly. (Complicated to define.)

Here is a function that instantiates the prefab:

private GameObject SpawnEntity(GameObject p, Vector2 coords)
    {
        Instantiate(p);
        ...
        p.transform.position = coords;
        return p;
    }

It is called like this:

public GameObject humanoid;
...
SpawnEntity(humanoid, new Vector2(-1,-3));

The Unity version is 2018.2.1f1.

Upvotes: 0

Views: 617

Answers (1)

ryeMoss
ryeMoss

Reputation: 4343

The problem is that you are changing the position of the referenced Gameobject, not the instantiated object. You need to create a new reference to the instantiated object like so:

private GameObject SpawnEntity(GameObject p, Vector2 coords)
    {
        Gameobject myobj = Instantiate(p);
        ...
        myobj.transform.position = coords;
        return myobj;
    }

I imagine this will solve number 2 as well if you are using GetComponent on the returned object, since you were previously returning the original prefab and not the instantiated object.

Upvotes: 1

Related Questions