Made code to randomly spawn packages. How not spawn in the same place once?

Soooo… this is my code. All the spawn points are in the “public Vector3 Vectors;” list. But how do i get the spawner not to spawn at the same place twice. I still want it to be random but never random in the same place twice. As is right now, the spawner can spawn packages on top of each other which will confuse player since when the package is destroyed there is still a package there.

Had a problem when Package was destroyed when i ran over the reference package, this was fixed by making the Package a prefab.

You may of course use my code if you want to!

class SpawnerPackage : MonoBehaviour

{

bool hasPackage;          
public GameObject[] packagePickup;
public Vector3[] Vectors;

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Package" && !hasPackage)
    {
        Debug.Log("Spawning!");

        InvokeRepeating("SpawnRandomPackage", 2, 1.5f);
        hasPackage = true;
    }
    if (other.tag == "Customer" && hasPackage)
    {
        CancelInvoke();
        hasPackage = false;
    }
}

void SpawnRandomPackage()
{
    int spawnPoint = 0;
    spawnPoint = Random.Range(0, Vectors.Length);

    int packageIndex = Random.Range(0, packagePickup.Length);


    Instantiate(packagePickup[packageIndex], Vectors[spawnPoint], packagePickup[packageIndex].transform.rotation);
}

}

Hi,

What do you mean by “not twice”? “Definitely only once” or “not again as long as there is still a package on that position”.

If the former, you could create a List with your indices, and use Random.Range on that List. You pick an integer from that list and remove it from the list. And you use the integer to access your “Vectors” array.

If you meant “only once”, you could copy your positions to a List and remove the used positions from the List.

Did this help?


See also:

Not again as long as there is still a package on that position.

In that case, you could test a dictionary where the key is your Vector3 position and the value the reference to the package. If the package gets destroyed, the value in the dictionary automatically becomes null.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms