S
S
SilNux2021-12-11 13:02:11
C++ / C#
SilNux, 2021-12-11 13:02:11

I can't spawn different objects in different positions, what could be the problem?

Tried different ways, but this one worked. At some point, it still breaks and throws an error:

IndexOutOfRangeException: Index was outside the bounds of the array.

Here is the code where the error is:

public class spawnEnemy : MonoBehaviour
{
    public Transform[] spawnPlace;

    public GameObject[] spriteEnemy; 

    void Start()
    {
        
    }

    void FixedUpdate()
    {
        WaitSpawn();
    }

    public void WaitSpawn()
    {

        Transform position = spawnPlace[Random.Range(0, spawnPlace.Length)];
        GameObject enemySquare = spriteEnemy[Random.Range(0, spriteEnemy.Length)];
        GameObject enemy = Instantiate(enemySquare, position.position, Quaternion.identity);
    }

}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
SilNux, 2021-12-25
@SilNux

I thought that the problem was in random, I checked it through Debug.log, it turned out that the array was not always filled with objects. Because of this, it gave an error. I checked for the presence of objects, everything works.

F
freeExec, 2021-12-11
@freeExec

Somewhere you forgot to add objects to the array, here it randomly gives you a zero element, but it is not there.

R
reLse, 2021-12-11
@reLse

Try checking != null to do

N
Nekit Medvedev, 2021-12-13
@NIKROTOS

Transform position = spawnPlace[Random.Range(0, spawnPlace.Length)];
It means that you choose a random position from pre-set ones, where do you set them?
By the way, Length gives the number of objects in the array. not the number of the last object (differ by 1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question