1

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);
            }
                
        }

    }
}
Oran C
  • 109
  • 11

2 Answers2

1

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
IndieGameDev
  • 2,905
  • 3
  • 16
  • 29
  • From 0 to 9 there is 10 iterations, so it must enter the `if` stament :) – Delunado Jun 24 '20 at 17:19
  • Yeah get it now sry mb, edited my answer accordingly hope it helps now :D – IndieGameDev Jun 24 '20 at 17:25
  • Simplest answer often the best answer, thank you. I'm over complicating how I go about coding it. 10 was just a hardcoded number for testing. Giant pieces of ground will go in place :) – Oran C Jun 25 '20 at 09:02
-1

Why not using the Gameobject returned by the Instantiation?

GameObject newObject = Instantiate(ground1Obj, new Vector3(i * 100f, 0, 0), Quaternion.identity);
count++;

if (count == 10)
    {
        lastPosition = newObject .position;
        Debug.Log("Last Position: " + lastPosition);
    }
Hagi
  • 140
  • 1
  • 8