Untitled

 avatar
unknown
plain_text
2 years ago
2.2 kB
7
Indexable
using UnityEngine;

public class SpawnObjectsAroundBounds : MonoBehaviour
{
    public Collider spawnArea;  // The collider whose bounds will be used as the spawn area
    public GameObject objectToSpawn;  // The object to be spawned

    public int numberOfObjectsToSpawn;  // The number of objects to spawn
    public float spawnOffset;  // The distance from the collider's bounds where objects should spawn

    void Start()
    {
        for (int i = 0; i < numberOfObjectsToSpawn; i++)
        {
            Vector3 spawnPoint = GetRandomPointOnBounds();

            // Instantiate the object at the spawn point
            Instantiate(objectToSpawn, spawnPoint, Quaternion.identity);
        }
    }

    private Vector3 GetRandomPointOnBounds()
    {
        // Get the bounds of the spawn area
        Bounds bounds = spawnArea.bounds;

        // Pick a random face of the collider bounds
        int faceIndex = Random.Range(0, 6);
        float x = 0f, y = 0f, z = 0f;

        switch (faceIndex)
        {
            case 0: // Front face
                x = Random.Range(bounds.min.x, bounds.max.x);
                y = Random.Range(bounds.min.y, bounds.max.y);
                z = bounds.min.z - spawnOffset;
                break;

            case 1: // Back face
            case 2: // Top face
                x = Random.Range(bounds.min.x, bounds.max.x);
                y = Random.Range(bounds.min.y, bounds.max.y);
                z = bounds.max.z + spawnOffset;
                break;
            case 3: // Bottom face
            case 4: // Left face
                x = bounds.min.x - spawnOffset;
                y = Random.Range(bounds.min.y, bounds.max.y);
                z = Random.Range(bounds.min.z, bounds.max.z);
                break;

            case 5: // Right face
                x = bounds.max.x + spawnOffset;
                y = Random.Range(bounds.min.y, bounds.max.y);
                z = Random.Range(bounds.min.z, bounds.max.z);
                break;
        }

        // Return the random point on the chosen face of the bounds
        return new Vector3(x, y, z);
    }
}
Editor is loading...