Spawning Regime (4 to 1)

Hi all, I need some help with something.

So I have been working on a spawn system for my 2D game, I am currently trying to spawn objects in a fixed order. The fixed order is “For every 4 enemies that spawn, a pick up item will then spawn.”

I have 5 spawn points set up and it randomly generated both enemies and pick up items but I would like some help narrowing down how to set a fixed order of 4 enemies, then 1 pick up item.

Many thanks.

Start with spawning tutorials. This is extremely well-understood territory, as a LOT of games spawn stuff.

Besides, nobody is going to retype an entire tutorial in this little box!

Generally one queues up the things to spawn in some sort of collection, perhaps a List or Queue. Again though, choices of data structures are fundamentally tied to how this is all engineered.

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

I’d like to clarify the current situation.

  • Do you have five spawn points, and each one operates independently, meaning it randomly spawns either an enemy or an item at its discretion?

  • You have five spawn points, but they are controlled by a single manager who decides from which point an enemy or item will spawn at any given moment?

  • Are you looking to make the spawns always alternate, like four enemies/item, then four enemies/item, and so on?

  • Or are you not controlling what can spawn at any given moment, but if, by chance, there were four enemies in a row, the fifth spawn must definitely contain an item?

So. we do have a working spawner that spawns in the objects and one that spawns the pick up item after every 4 enemies.

There are five spawn points that are parented to an empty game object that has the script attached. The idea is for one enemies and pick ups to spawn from each point at random, I just need to figure out how to set that

        // shuffle the spawn positions:
        for (int i=0;i<transform.childCount;i++)
        {
            int r=Random.Range(0,transform.childCount);
            Vector3 p1=transform.GetChild(i).transform.position;
            Vector3 p2=transform.GetChild(r).transform.position;
            transform.GetChild(i).transform.position=p2;
            transform.GetChild(r).transform.position=p1;
        }
        // now spawn 4 enemy and 1 pickup at the above positions

IronDan21, To be honest, I still don’t understand what’s going on with your spawns, specifically the system of connections between them, and who or what controls it. Perhaps you should have shown your code from the very beginning; it might have clarified the situation. I still haven’t grasped what the task is - is it about creating every fifth spawn as an item, or something else?

If you have a bunch of things (like spawnpoints) and you have a coherent set of things you want to happen among them (eg, a sequence of spawned items), make a manager that:

  • knows about all the spawnpoints
  • knows about the collection of things to spawn
  • iterates the collection
  • chooses an unused spawnpoint
  • does what you need

Random.Range() is used to generate random numbers.

It can generate the same one multiple times.

If this is unsuitable then put your targets into another collection and shuffle that collection.

Now iterate that shuffled collection in order, like a deck of cards.

Be sure to handle insufficient spawnpoints for the number of spawned items!

I’ll post the code tomorrow

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    bool isspawning = false;
    public float mintime = 5.0f;
    public float maxtime = 15.0f;
    public GameObject[] enemies;


    private float startSize;

    [SerializeField]
    private float numberOfIllusions = 0;

    public GameObject fortunes;

    IEnumerator spawnobject(int index, float seconds)
    {
        yield return new WaitForSeconds(3f);
        var scale = new Vector3(Random.Range(3f, 3f), 1.0f, Random.Range(3f, 3f));
        GameObject obj = Instantiate(enemies[index], transform.position, transform.rotation);
        obj.transform.localScale = Vector3.one * Random.Range(0.5f, 1f);
        numberOfIllusions = numberOfIllusions + 1;

        isspawning = false;
    }

    private void Start()
    {
       
    }

    void Update()
    {
        SpawningFortunesPattern();
        if (!isspawning)
        {
            isspawning = true;
            int enemyindex = Random.Range(0, enemies.Length);
            StartCoroutine(spawnobject(enemyindex, Random.Range(mintime, maxtime)));
        }
       
    }

    private void SpawningFortunesPattern()
    {
        if (numberOfIllusions >= 4)
        {
            Debug.Log("Four illusions have spawned");
            GameObject objct = Instantiate(fortunes, transform.position, transform.rotation);
            objct.transform.localScale = Vector3.one * Random.Range(0.25f, 0.25f);
            numberOfIllusions = 0;
        }
    }
}
[CODE]

As was suggested above, you need a controller that will oversee everything that’s happening. I’ve made some changes to your script, and it has become more visually understandable. This is a spawn controller. In its inspector, you need to fill in arrays of enemies as well as arrays of objects representing spawn points (these can be empty objects in the scene). The variable “_fortuneCycle” means that every fifth spawn will be an item spawn.
This script is only for one object; you don’t need to add it to each spawn point as it was before. Just one script that controls everything.

using System.Collections;
using UnityEngine;

public class MainSpawner : MonoBehaviour
{
    public GameObject[] EnemyPrefabs;
    public GameObject FortunePrefab;
    [Space]
    public Transform[] SpawnPoints;
    [Space]
    public float MinTime = 5.0f;
    public float MaxTime = 15.0f;
    [Space]
    [SerializeField] private int _fortuneCycle = 4;

    private int _spawnCounter = 0;

    private void Start()
    {
        EnableSpawn();
    }

    public void EnableSpawn()
    {
        StartCoroutine(SpawnCoroutine());
    }


    public void DisableSpawn()
    {
        StopAllCoroutines();
    }

    private IEnumerator SpawnCoroutine()
    {
        while (true)
        {
            float waitTime = Random.Range(MinTime, MaxTime);
            yield return new WaitForSeconds(waitTime);

            if (_spawnCounter == _fortuneCycle)
            {
                SpawnFortunes();
                _spawnCounter = 0;
            }
            else
            {
                SpawnEnemy();
                _spawnCounter++;
            }

        }
    }

    private void SpawnEnemy()
    {
        int enemyIndex = Random.Range(0, EnemyPrefabs.Length);
        Transform point = GetRandSpawnPoint();

        GameObject newEnemy = Instantiate(EnemyPrefabs[enemyIndex], point.position, point.rotation);
        newEnemy.transform.localScale = Vector3.one * Random.Range(0.5f, 1f);
    }

    private void SpawnFortunes()
    {
        Debug.Log("Four illusions have spawned");

        Transform point = GetRandSpawnPoint();

        GameObject newFortune = Instantiate(FortunePrefab, point.position, point.rotation);
        newFortune.transform.localScale = Vector3.one * Random.Range(0.25f, 0.25f);
    }

    private Transform GetRandSpawnPoint()
    {
        return SpawnPoints[Random.Range(0, SpawnPoints.Length)];
    }
}

I’ve sorted it out. Thanks a lot for the help! :slight_smile: