Search code examples
arraysunity-game-engineclone

unity : put clones on array and add back button that destory the last clone till the first


i am very new on unity and im trying to do my first game. i want to put the clone objects on array and then add a back button that destory the last clone that made, ive tried to make array but it let me only clone 1 object and then i cant do anything, thank you for help. i have this code :

public class TouchSpwan : MonoBehaviour

public GameObject prefab;
public GameObject clone;
public Rigidbody rot;
public Camera mainCamera;
public FixedTouchField touchField;
public float gridsize;

void Update()
{
        if (Input.GetMouseButtonDown(0))
         {
                
             Vector3 touchPos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 9.8f));
             touchPos.x = Mathf.Floor(touchPos.x / gridsize);
             touchPos.z = Mathf.Floor(touchPos.z / gridsize);
             Vector3 result = new Vector3((float)touchPos.x * gridsize,touchPos.y, (float)touchPos.z * gridsize);
             if (touchField.Pressed == true)
             {
                    clone = Instantiate(prefab, result, prefab.transform.rotation);
                    clone.transform.parent = gameObject.transform;
            }
    }
}

Solution

  • First of all yor GameObject clone, does not have to be a public class member. Instead of

    clone = Instantiate(prefab, result, prefab.transform.rotation);
    clone.transform.parent = gameObject.transform;
    

    you could just say:

     GameObject clone = Instantiate(prefab, result, prefab.transform.rotation);
     clone.transform.parent = gameObject.transform;
    

    and get rid of the declaration at the top:

    public GameObject clone;
    

    After you check if the left mouse button has been pressed you do an additional check for some touchField.Pressed, not really sure why, but if you remove it you can spawn as many clone objects in a place where your mouse pointer is as you like.

    When it comes to storing these object in the array, you can just declare an array of GameObjects and add each clone after instantiating. You do need to have some sort of maxLimit for clones.

    1. declare the arr: private GameObject[] clonesArray;
    2. initialise it: clonesArray = new GameObject[maxNumberOfClones];

    Once you've done that you can add each clone to the array after its instantiating:

    GameObject clone = Instantiate(prefab, result, prefab.transform.rotation);
    clone.transform.parent = gameObject.transform;
    clonesArray[currentIndex] = clone;
    currentIndex++;
    

    You need to keep track of currentIndex, start with 0 and then increment it after you add a clone to the array. Then to destroy the clone you need to access it from the array and use Destroy(). Do not forget to decrement the index counter.

    Destroy(clonesArray[currentIndex]);
    currentIndex--;
    

    I hope that helps :D