ObjectPlacer.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace JTSystems
  5. {
  6. [ExecuteInEditMode]
  7. public class ObjectPlacer : MonoBehaviour
  8. {
  9. public enum PlacementType { Grid, Circle }
  10. [SerializeField] private PlacementType placementType;
  11. [Header(" Grid Placement ")]
  12. [SerializeField] private int rows;
  13. [SerializeField] private int columns;
  14. [SerializeField] private Vector2 spacing;
  15. [Header(" Circle Placement ")]
  16. [SerializeField] private int amount;
  17. [SerializeField] private float radius;
  18. [Header(" Settings ")]
  19. [SerializeField] private GameObject objectToPlace;
  20. private void Awake()
  21. {
  22. }
  23. // Start is called before the first frame update
  24. void Start()
  25. {
  26. if(Application.isPlaying)
  27. enabled = false;
  28. }
  29. // Update is called once per frame
  30. void Update()
  31. {
  32. ClearOldObjects();
  33. PlaceObjects();
  34. }
  35. private void ClearOldObjects()
  36. {
  37. transform.Clear();
  38. }
  39. private void PlaceObjects()
  40. {
  41. switch(placementType)
  42. {
  43. case PlacementType.Grid:
  44. PlaceOnGrid();
  45. break;
  46. case PlacementType.Circle:
  47. PlaceOnCircle();
  48. break;
  49. }
  50. }
  51. private void PlaceOnGrid()
  52. {
  53. float startXOffset = spacing.x / 2f + (float)(rows - 2) / 2f * spacing.x;
  54. float startZOffset = spacing.y / 2f + (float)(columns - 2) / 2f * spacing.y;
  55. Vector3 startPosition = transform.position + Vector3.left * startXOffset + Vector3.back * startZOffset;
  56. float xStep = spacing.x;
  57. float yStep = spacing.y;
  58. for (int y = 0; y < columns; y++)
  59. {
  60. for (int x = 0; x < rows; x++)
  61. {
  62. Vector3 spawnPosition = startPosition + xStep * x * Vector3.right + Vector3.forward * y * yStep;
  63. Instantiate(objectToPlace, spawnPosition, Quaternion.identity, transform);
  64. }
  65. }
  66. }
  67. private void PlaceOnCircle()
  68. {
  69. float angleStep = 360f / amount;
  70. for (int i = 0; i < amount; i++)
  71. {
  72. float x = radius * Mathf.Cos(i * angleStep * Mathf.Deg2Rad);
  73. float z = radius * Mathf.Sin(i * angleStep * Mathf.Deg2Rad);
  74. Vector3 spawnPosition = transform.position + new Vector3(x, 0, z);
  75. Instantiate(objectToPlace, spawnPosition, Quaternion.identity, transform);
  76. }
  77. }
  78. }
  79. }