Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [CanEditMultipleObjects]
- public class ObjectSpawner : MonoBehaviour
- {
- [SerializeField] private GameObject[] objects;
- [Space]
- [SerializeField] private Color gizmoColor = new Color(193, 96, 36, 185);
- private float averangeSize;
- private void Awake()
- {
- Instantiate(objects[Random.Range(0, objects.Length - 1)], transform);
- CalculateAverageSize();
- }
- private void OnDrawGizmos()
- {
- if (objects != null && objects.Length > 0) CalculateAverageSize();
- DrawGizmo();
- }
- private void OnDrawGizmosSelected()
- {
- if (objects != null && objects.Length > 0) DrawGizmo();
- }
- private void DrawGizmo()
- {
- float averageHeight = CalculateAverageSizeY();
- Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0);
- Gizmos.matrix = transform.localToWorldMatrix;
- Gizmos.color = gizmoColor;
- Gizmos.DrawCube(gizmoPositionLocal, DrawAverageSizeGizmo());
- Gizmos.color = gizmoColor * 2;
- Gizmos.DrawWireCube(gizmoPositionLocal, DrawAverageSizeGizmo());
- }
- public float CalculateAverageSize()
- {
- float volumeSum = 0f;
- foreach (GameObject obj in objects)
- {
- Vector3 objSize = obj.transform.lossyScale;
- float objVolume = objSize.x * objSize.y * objSize.z;
- volumeSum += objVolume;
- }
- averangeSize = volumeSum / objects.Length;
- return averangeSize;
- }
- public Vector3 DrawAverageSizeGizmo()
- {
- float averageSizeX = CalculateAverageSizeX();
- float averageSizeY = CalculateAverageSizeY();
- float averageSizeZ = CalculateAverageSizeZ();
- // Create a new Vector3 with the average size as the length of the vector
- return new Vector3(averageSizeX, averageSizeY, averageSizeZ);
- }
- private float CalculateAverageSizeX()
- {
- float sum = 0f;
- foreach (GameObject obj in objects)
- {
- Bounds bounds = obj.GetComponent<Renderer>().bounds;
- sum += bounds.extents.x * 2; // Get the width of the bounding box
- }
- return sum / objects.Length;
- }
- private float CalculateAverageSizeY()
- {
- float sum = 0f;
- foreach (GameObject obj in objects)
- {
- Bounds bounds = obj.GetComponent<Renderer>().bounds;
- sum += bounds.extents.y * 2; // Get the height of the bounding box
- }
- return sum / objects.Length;
- }
- private float CalculateAverageSizeZ()
- {
- float sum = 0f;
- foreach (GameObject obj in objects)
- {
- Bounds bounds = obj.GetComponent<Renderer>().bounds;
- sum += bounds.extents.z * 2; // Get the depth of the bounding box
- }
- return sum / objects.Length;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment