V
V
vodimak2021-12-23 23:01:56
C++ / C#
vodimak, 2021-12-23 23:01:56

How to make random spawn of several objects in 1 script?

in short, I am a complete beginner and do not understand obvious things, I am making a game and meteorites should spawn from above, but in my script you can only put 1 object. if you throw several scripts, it will be unplayable. help refine the script so that 1 or several random meteorites spawn at a time (there are 9 types in total).
here is the code:

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

public class RandomSpawn : MonoBehaviour
{
    [SerializeField]
    private GameObject obj;
    float RandX;
    Vector2 whereToSpawn;
    [SerializeField]
    private float spawnRate = 2f;
    float nextSpawn = 0.0f;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
       if(Time.time > nextSpawn) 
       {
              nextSpawn = Time.time + spawnRate;
              RandX = Random.Range(-20f, 20f);
              whereToSpawn = new Vector2(RandX, transform.position.y);
              Instantiate(obj, whereToSpawn, Quaternion.identity);
       }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ente, 2021-12-24
@vodimak

Why unplayable? Create one prefab - this will be the main template for meteorites. Then create inherited prefabs from it and give them unique characteristics, like size, sprite, some script settings. Then create one MeteorSpawner script. Then you can draft several scripts and set unique values ​​for each, or separate them into different GameObjects.

[SerializeField] private GameObject prefab;
[SerializeField] private Vector2 minPos;
[SerializeField] private Vector2 maxPos;
[SerializeField] private Vector2 spawnRate;

private IEnumerator Start()
{
     while (true)
     {
          yield return new WaitForSeconds(Random.Range(spawnRate.x, spawnRate.y));
          var pos = new Vector2(Random.Range(min.x, max.x), Random.Range(min.y, max.y));
          Instantiate(prefab, pos, Quaternion.identity);
     }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question