Saturday, April 4, 2015

unity - Spawn prefabs from list one by one when trigger is touched


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 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

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...