Question by
Rinsige · Mar 19, 2019 at 05:34 AM ·
c#scripting problemarray
How to spawn sprites in a row randomly from a single array without double-ups
I'm very new to coding and am only just starting to get the hang of it and I'm making a game that requires you to fly through 5 different colour blocks that gradually increase in speed.
A problem I've hit is I can get the 5 blocks to spawn a row in a way that randomizes the colours/positions for each block for each row but I'm constantly getting double-ups that creates holes in the row and puts two blocks on each other.
Help would be very much appreciated.
Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class WallSpawner : MonoBehaviour
{
public GameObject[] walls;
public GameObject[] spawnPoints;
public Vector2 movementDirection;
public float spawnTime = 2f;
private int colourIndex;
// Start is called before the first frame update
void Start()
{
movementDirection = new Vector2(0,-1);
colourIndex = walls.Length -1;
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Spawn()
{
while(colourIndex >= 0)
{
int rand = Random.Range(0, spawnPoints.Length);
GameObject wall = Instantiate(walls[colourIndex], spawnPoints[rand].transform.position, Quaternion.identity);
wall.GetComponent<Rigidbody2D>().velocity = movementDirection * 2.0f;
Destroy(wall, 10.0f);
colourIndex--;
}
colourIndex = walls.Length -1;
}
}
Comment
use a list, copy all the array objetcs to that list and remove from the list the object that has spawned