A
A
alexdurden2021-11-03 05:50:06
Unity
alexdurden, 2021-11-03 05:50:06

How to make infinite spawn with a condition?

Hello! I have points on the stage that the Player devours, thereby earning points.

Point spawning now occurs in the “for (int i = 1; i <= 10; i++)” loop. But the task is to make the spawn infinite, while at the same time, so that there are no more than 10 points on the stage at a time.

I have already been told that for this you need to use a “while” loop, but I don’t know how to write a condition.

Please help.

PS code in the spoiler.

spoiler


[SerializeField]
    private Point _pointPrefab;
    
    [SerializeField][Range(0.1f, 100f)]
    private float delayTime = 5.0f;

    void Start()
    {
        StartCoroutine(SpawnPointsRoutine());
    }

    private IEnumerator SpawnPointsRoutine()
    {
        for(int i = 1; i <= 10; i++)
        {
            Instantiate(_pointPrefab, new Vector3(Random.Range(-9.8f, 6.5f), 0.5f, Random.Range(6.9f, 43.1f)), Quaternion.identity);
            yield return new WaitForSeconds(delayTime);     
        }
    }


Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
LittleBob, 2021-11-03
@LittleBob

You can try to create these 10 points in advance right on the stage behind the camera and during the game just move them to the spawn location. This, by the way, will not be so resource-intensive, because destroy and instantiante are heavy functions.
I don't know how to implement your code yet, I have to think. But, in my opinion, the option that I suggested is not worse.

N
Nekit Medvedev, 2021-11-03
@NIKROTOS

Throw the function into update (than you don't have an infinite loop) and write down the condition, if there are less than 10 points, create a new one.
By the way, for optimization it is better not to create/destroy objects, but to create their pool. Pre-created 10 points that you will simply deactivate / activate.

K
KraGen.Developer, 2021-11-03
@KraGenDeveloper

In general, I had a similar situation. It was necessary to make sure that there were always 15 platforms on the stage, when the player touches them, the platforms are deleted and new ones are created. In general, here

private int pointCount = 0;

void Update(){
if(pointCount <= 10){
pointCount++;
//создаёшь точку 
}

And in the code where the contact between the player and the point is recorded, just make it so that when one point is gobbled up, then pointCount --; all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question