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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trigger : MonoBehaviour
{
public Transform spawnPoint;
//public GameObject Prefab;
public List items = new List();
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);
}
}
}
Answer
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);
}
}
No comments:
Post a Comment