0
\$\begingroup\$

I am trying to spawn one gameobject from a list of gameobjects each time I touch the trigger with the controller.

But when I do this, all the game objects from the list spawn together at the same time. I couldn't figure out how to solve this problem and make them spawn one at a time instead, where the next touch spawns the next object in the list, and so on.

Trigger Button

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trigger : MonoBehaviour
{

    public Transform spawnPoint;
    //public GameObject Prefab;
    public List<GameObject> items = new List<GameObject>();

    void OnTriggerEnter(Collider other)
    {
        //GameObject Prefab = new GameObject("prefab");

        for (int i = 0; i < items.Count; i++)
        {
            Instantiate(items[i], spawnPoint.position, spawnPoint.rotation);
            Debug.Log("Hello World" +i);
        }

    }

}
\$\endgroup\$
1
\$\begingroup\$

Assuming you want to spawn one GameObject per touch, you could store the spawnIndex outside the method, and increment it by one each time you spawn.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trigger : MonoBehaviour
{
  public Transform spawnPoint; //public GameObject Prefab;
  public List items = new List();
  private int spawnIndex = 0;

  void OnTriggerEnter(Collider other)
  {
    //GameObject Prefab = new GameObject("prefab");
    int i = spawnIndex++ % items.Count;
    // int i = Random.Range(0, items.Count); // for random each time
    Instantiate(items[i], spawnPoint.position, spawnPoint.rotation);
    Debug.Log("Hello World" + i);
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.