I have this script that spawns one Object only after i press on a game object that spawns it. i want to spawn a list of items like 15 or so. and spawn random 3 out of those each time i press it spawns different three from that list. how do i Achieve that. this is the script i have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HerbSpawner : MonoBehaviour
{
//Here, we declare variables.
public GameObject objToSpawn;
public Transform groupTransform;
//public means the var is exposed in the inspector, which is super helpful.
// Start is called before the first frame update
Vector2 spawnPos;
void Start()
{
spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
}
// Update is called once per frame
void Update()
{
//let's also spawn on button press:
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));
if (hit.collider && hit.collider.CompareTag("Bush"))
{
SpawnIt();
}
}
void SpawnIt()
{
Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.7f));
Instantiate(objToSpawn, spawnPos, Quaternion.identity, groupTransform);
}
}
}
CodePudding user response:
You can assign all the objects to a list via the editor and spawn it randomly by choosing randomly from the list index
public class HerbSpawner : MonoBehaviour {
public Transform groupTransform;
public GameObject[] allObjsToSpawnFrom;
Vector2 spawnPos;
void Start() {
spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
}
void Update() {
// let's also spawn on button press:
if (Input.GetMouseButtonDown(0)) {
RaycastHit2D hit = Physics2D.GetRayIntersection(
Camera.main.ScreenPointToRay(Input.mousePosition));
if (hit.collider && hit.collider.CompareTag("Bush")) {
for (int i = 0; i < 3; i ) SpawnRandomly();
}
}
}
void SpawnRandomly() {
int ind = Random.Range(0, allObjsToSpawnFrom.Length);
SpawnIt(allObjsToSpawnFrom[ind]);
}
void SpawnIt(GameObject objToSpawn) {
Vector2 spawnPos =
Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.7f));
Instantiate(objToSpawn, spawnPos, Quaternion.identity, groupTransform);
}
}