Search code examples
c#unity-game-enginecloneobject-poolingobjectinstantiation

Unity: Get the position of the last cloned instantiated object


I'm trying to create an infinite ground for Android using Unity. Trying to use object pooling to achieve the ground repeating but is proving a bit tricky. I can get my ground to Instantiate and create the clones along x axis.

What I am trying to achieve is to get the position of the last cloned object and set that as the new position of and create new object in the new position and instantiate again.

Do I need to work with the transform parent? Am I going the right way about this?

Code below.

public class InfiniteGround : MonoBehaviour
{
    public Transform ground1Obj;
    private int count;
    private Vector3 lastPosition;
   
    void Start()
    {
        count = 0;
        for (int i = 0; i < 10; i++)
        {
            Instantiate(ground1Obj, new Vector3(i * 100f, 0, 0), Quaternion.identity);
            count++;
            if (count == 10)
            {
                lastPosition = ground1Obj.position;
                Debug.Log("Last Position: " + lastPosition);
            }
                
        }

    }
}

Solution

  • For the Instantiating it should work, but not the way you intend to. If you want to have infinite ground you should add ground depending on the player position

    • If the player moves forward instantiate new ground before him and destroy the old ground behind him.
    • If the player moves backward instantiate new ground behind him and destroy the old ground before him

    If you wanted to change your code. I would:

    1. Change the functionname for example (InstantiateFloor), because you want to call it more than once at the start
    2. Call the function depending on the player position (as described above)
    3. Just instantiate 1 big floor piece (instead of 10 smaller ones) and take the position of that