Spawn object in certain zone (2d)

Hello,
I’ve got question about spawn area. I would like to spawn objects only in certain zone (marked on the picture), but always above player. I’ve got only spawn in camera boundary, but because of that some of the object spawn out of level.
Is there any simple way to do that?

Thanks in advance :slight_smile:

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

public class deploySquare : MonoBehaviour
{
    public GameObject squarePrefab;
    public float respawnTime = 0.01f;
    private Vector2 screenBounds;

    // Start is called before the first frame update
    void Start()
    {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        StartCoroutine(squareWave());
    }
    private void spawnSquare ()
    {
        GameObject a = Instantiate(squarePrefab) as GameObject;
        a.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));

    }

   IEnumerator squareWave()
    {
        while(true)
        {
            yield return new WaitForSeconds(respawnTime);
            spawnSquare();
        }
     
    }
}

Please use code tags: Using code tags properly

The best way to spawn things in a pre-made level is to put GameObjects (invisible with nothing on them) where you want the spawn to happen, then drag that gameObject into your script to use as a position.

You can also add gizmos to these invisible gameObjects so they show up in scene when you’re working and editing your level, or even write your own custom gizmos with OnDrawGizmos() or OnDrawGizmosSelected().

1 Like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Helper class to spawn 2D objects inside an Polygon Collider 2D area for forum.unity.com by Zer0Cool
/// - create an empty GameObject
/// - add a "Polygon Collider 2D" component
/// - edit the vertices of the polygon collider to match your spawning zone (see https://docs.unity3d.com/Manual/class-PolygonCollider2D.html)
/// </summary>
public class Collider2dPolygonRangeSpawner : MonoBehaviour
{
    public PolygonCollider2D polygonCollider;
    public int numberRandomPositions = 10;

    void Start()
    {
        if (polygonCollider == null) GetComponent<PolygonCollider2D>();
        if (polygonCollider == null) Debug.Log("Please assign PolygonCollider2D component.");

        int i = 0;
        while ( i < numberRandomPositions)
        {
            Vector3 rndPoint3D = RandomPointInBounds(polygonCollider.bounds, 1f);
            Vector2 rndPoint2D = new Vector2(rndPoint3D.x, rndPoint3D.y);
            Vector2 rndPointInside = polygonCollider.ClosestPoint(new Vector2(rndPoint2D.x, rndPoint2D.y));
            if (rndPointInside.x == rndPoint2D.x && rndPointInside.y == rndPoint2D.y)
            {
                GameObject rndCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                rndCube.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
                rndCube.transform.position = rndPoint2D;
                i++;
            }
        }
    }

    private Vector3 RandomPointInBounds(Bounds bounds, float scale)
    {
        return new Vector3(
            Random.Range(bounds.min.x * scale, bounds.max.x * scale),
            Random.Range(bounds.min.y * scale, bounds.max.y * scale),
            Random.Range(bounds.min.z * scale, bounds.max.z * scale)
        );
    }
}
7 Likes

thank you so much bro, it works with me :3

but how do i instantiate game objects with these random boundaries? Help me plzz

Steps to success:

  1. carefully read the explicit steps that @Zer0Cool posted above. If you don’t understand, go google.

  2. study the lines 21 to 34 of his code, which actually DO exactly what he says in his steps.

  3. please don’t post to old thread: start your own fresh thread and post a clear question about what you’re having difficulties with.