Search code examples
c#unity-game-enginevuforia

How to limit the number of created objects with ground plane detection with Vuforia and Unity


I am creating an AR application with Unity and Vuforia. Right now an object is placed every time the user taps on the screen. I know it is possible to create the object only once and move it every time the user taps on the screen by unchecking the "Duplicate Stage" option but what I am looking for is to place only 2 instances of the object maximum. This means that when the user taps for the 3rd time, the object created in first is deleted and a new one is created. As I am new to Unity and Vuforia I would need some help doing it. Thank you !


Solution

  • Couple ways to do it. Using a list can provide some flexibility and scalability. Some example code:

    List<GameObject> myObjects = new List<GameObject>();
    
    if (Input.GetTouch(0).phase == TouchPhase.Began) // when user touches screen
    {
        myObjects.Add(SpawnObject()); //your method to spawn and return the spawned Gameobject to add to the list
    
        if (myObjects.Count > 2)
        {
            Destroy(myObjects[0]); // destroy the gameobject
            myObjects.RemoveAt(0); // remove from list
        }
    }