- Home /
Random array issue C#
I think the code is good, i just cannot figure out how to make it work?
Can anyone walk me through this?
I have attached it to an empty game object with no child objects and then made 3 empty game objects and used those for spawn locations. and it did not work. so then i made the 3 spawn points if you will (the empty game objects) a child of the empty game object that has the script attached. and that did not work. Than i attached the script to player, to another object in the game, and to the spawn points, all of those did not work.
so...? What do i attach it to? how to i get it to work?
i would really appreciate some help with this.
Thank you.
here is the code for you guys to take a look at, Maybe it isn't correct....idk.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewSpawnS: MonoBehaviour
{
public GameObject[] objectsToSpawn;
public Transform[] spawnPoints;
public List<GameObject> spawnedObjects;
public int spawnCount;
private int objectIndex;
private int spawnIndex;
private void start ()
{
for (int i = 0; i < spawnCount; i++)
{
objectIndex = Random.Range(0, objectsToSpawn.Length);
spawnIndex = Random.Range(0, spawnPoints.Length);
GameObject go = Instantiate(objectsToSpawn[objectIndex], spawnPoints[spawnIndex].position, Quaternion.identity);
spawnedObjects.Add(go);
}
}
}
Thank you for any help you can offer.
Assign the spawnPoints in the inspector and the objectsToSpawn aswel.
Answer by DarkToadster · Mar 17, 2018 at 03:52 PM
Here is a GIF showing you how i set up the code.
It is the code i have shown in your other ask with an little addition to prevent the first error when attaching the script
void OnDrawGizmos()
{
if(spawnPoints != null)
{
Gizmos.color = Color.red;
for (int i = 0; i < spawnPoints.Length; i++)
{
Gizmos.DrawSphere(spawnPoints[i].position, 0.5f);
}
}
}
Answer by cvid · Mar 17, 2018 at 03:41 PM
First of all you shoud change this line
private void start ()
to
private void Start ()
After it you should create empty object on scene and attach this script. An lastly you need to fill script fields in the Editor.
objectsToSpawn - here should be your prefabs (objects that you want to spawn)
spawnPoints - spawn points (empty objects from your scene)
spawnCount - count of objects that will be spawn