[C#] Array out of bounds
I'm trying to make a line of prefabs that spawn next to each other depending on their sprite size. I am however getting a out of bounds error, but I can't seem to find out why.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Spawner : MonoBehaviour {
public int numPlat;
public GameObject[] PlatSpawner;
public GameObject PlatformToSpawn;
public Vector2 spawnPosition;
public Vector2 NextSpawnPosition;
public SpriteRenderer spriteChosen;
// Use this for initialization
void Start () {
Debug.Log("Number" + numPlat);
spawnStuff();
}
// Update is called once per frame
void Update () {
}
private void Awake()
{
}
public void spawnStuff()
{
for (int i = 0; i < numPlat; i++)
{
if (i == 0)
{
PlatSpawner[0] = Instantiate(PlatformToSpawn, transform.position, Quaternion.identity) as GameObject;
}
if (i >= 1)
{
spawnPosition = PlatSpawner[i].transform.position.x + new Vector3( spriteChosen.bounds.size.x,0);
PlatSpawner[i] = Instantiate(PlatformToSpawn, spawnPosition, Quaternion.identity) as GameObject;
Debug.Log("ds");
}
}
}
}
What is the use of numPlat? You can directly use PlatSpawner.Length to find the lenght of the array. Because numPlat maybe different from array length you are getting out of bounds
It allows you to say how many blocks you want spawned, so it spawns a whole line of platforms, depending on the size you want it to be.
Answer by Ali-hatem · Apr 26, 2016 at 12:03 PM
what about this simple :
int Nextpos;
Vector3 pos;
public GameObject [] obj;
void Start(){
for (int i = 0; i < obj.Length; i++) {
Nextpos ++;
pos = new Vector3 (transform.position.x + Nextpos, transform.position.y, transform.position.z);
Instantiate (obj [i], pos, transform.rotation);
}
}
& just manipulate the object scale size to reduce the gap between objects . & as RakshithAnand said no need to numPlat
this way is more dynamic doesn't mater how many objects you add it will work.
But what If I want to spawn several instances of only one object type?
Also, int Nextpos? Shouldn't it be Vector3D Nextpos ins$$anonymous$$d?
I figured it out. For those interested, just replace the obj[i] with a var that you declared as
public GameObject PlatTospawn;
then replace it for obj[i], that way you can spawn only one instance of that. $$anonymous$$any thanks Ali and RakshithAnand!
tailor it so it fits you . & i tried Vector3 Nextpos
bt it was messy until i figured out it needs int & we can assign it to xyz as desired. also you can use i
ins$$anonymous$$d of Nextpos++
transform.position.x + i