using UnityEngine;
public class ClickRandomizer : MonoBehaviour
{
// Пул компонентов, которые могут быть добавлены при клике
// (укажите в инспекторе нужные типы или оставьте пустым — тогда добавится случайный из встроенных)
public MonoBehaviour[] componentPool;
void OnMouseDown()
{
// 1. С шансом 50% добавляем случайный компонент из пула (если его ещё нет)
if (componentPool != null && componentPool.Length > 0 && Random.value < 0.5f)
{
MonoBehaviour template = componentPool[Random.Range(0, componentPool.Length)];
System.Type type = template.GetType();
if (GetComponent(type) == null)
{
gameObject.AddComponent(type);
Debug.Log($"Добавлен компонент: {type.Name}");
}
}
// 2. Изменяем случайные свойства у всех компонентов на объекте
foreach (var comp in GetComponents<Component>())
{
RandomizeComponent(comp);
}
}
// Меняет случайное публичное свойство/поле у компонента
void RandomizeComponent(Component comp)
{
if (comp == null) return;
// Для Renderer — меняем цвет материала (самый наглядный эффект)
if (comp is Renderer rend)
{
rend.material.color = Random.ColorHSV();
return;
}
// Для Transform — случайный поворот и масштаб
if (comp is Transform t)
{
t.localRotation = Random.rotation;
t.localScale = Vector3.one * Random.Range(0.5f, 2f);
return;
}
// Для Rigidbody — случайная масса и импульс
if (comp is Rigidbody rb)
{
rb.mass = Random.Range(0.5f, 10f);
rb.AddForce(Random.insideUnitSphere * 5f, ForceMode.Impulse);
return;
}
// Универсальный вариант: перебираем публичные поля и свойства через рефлексию
var type = comp.GetType();
var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (var field in fields)
{
// Пропускаем то, что нельзя рандомизировать
if (field.IsInitOnly || field.IsLiteral) continue;
object randomValue = GetRandomValue(field.FieldType);
if (randomValue != null)
{
field.SetValue(comp, randomValue);
}
}
}
// Генерирует случайное значение для поддерживаемых типов
object GetRandomValue(System.Type type)
{
if (type == typeof(float)) return Random.Range(0f, 10f);
if (type == typeof(int)) return Random.Range(0, 100);
if (type == typeof(bool)) return Random.value > 0.5f;
if (type == typeof(Vector3)) return Random.insideUnitSphere * 5f;
if (type == typeof(Vector2)) return Random.insideUnitCircle * 5f;
if (type == typeof(Color)) return Random.ColorHSV();
if (type == typeof(string)) return "rand_" + Random.Range(0, 9999);
return null; // тип не поддерживается — пропускаем
}
}