механики

This commit is contained in:
lapich committed 2026-10-19 20:14:24 +03:00
1 parent dd5a95a4d3
commit 11d57bec19
129 files changed
+21889 -62

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
using UnityEngine;
using UnityEngine.InputSystem;
public class AmmoPickup : MonoBehaviour
{
[Header("Настройки")]
public int ammoAmount = 14; // Сколько патронов дает коробка
public bool pickupOnTouch = true; // Подбирать автоматически при касании
public float interactionDistance = 2.5f; // Дистанция для подбора по клавише E
public AudioClip pickupSound; // Звук подбора
[Header("Анимация парения")]
public bool animateBobbing = true;
public float rotationSpeed = 45f;
public float bobSpeed = 2f;
public float bobHeight = 0.1f;
private Vector3 startPos;
private bool isCollected = false;
void Start()
{
startPos = transform.position;
}
void Update()
{
if (isCollected) return;
// Анимация вращения и легкого покачивания
if (animateBobbing)
{
transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime, Space.World);
float newY = startPos.y + Mathf.Sin(Time.time * bobSpeed) * bobHeight;
transform.position = new Vector3(startPos.x, newY, startPos.z);
}
// Если не автоматический подбор, проверяем дистанцию до игрока и нажатие клавиши E
if (!pickupOnTouch && Keyboard.current != null && Keyboard.current.eKey.wasPressedThisFrame)
{
var playerGun = FindAnyObjectByType<PlayerGun>();
if (playerGun != null)
{
float dist = Vector3.Distance(transform.position, playerGun.transform.position);
if (dist <= interactionDistance)
{
TryPickup(playerGun);
}
}
}
}
private void OnTriggerEnter(Collider other)
{
if (isCollected || !pickupOnTouch) return;
PlayerGun playerGun = other.GetComponentInParent<PlayerGun>();
if (playerGun != null)
{
TryPickup(playerGun);
}
}
private void TryPickup(PlayerGun playerGun)
{
if (playerGun == null) return;
bool added = playerGun.AddAmmo(ammoAmount);
if (added)
{
isCollected = true;
if (pickupSound != null)
{
AudioSource.PlayClipAtPoint(pickupSound, transform.position, 1.0f);
}
Debug.Log($"<color=green>[Подбор] Взята коробка патронов (+{ammoAmount})!</color>");
Destroy(gameObject);
}
else
{
Debug.Log("[Подбор] Боезапас уже полон!");
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 50d7aaf3e2e7a95468a0e6163e600f31
+165 -11
View File
@@ -1,28 +1,127 @@
using UnityEngine;
using UnityEngine.AI;
using UnityEngine;
using UnityEngine.AI;
public class BlindMutantAI : MonoBehaviour
{
private NavMeshAgent agent;
[Header("Настройки скорости")]
public float walkSpeed = 2f;
public float runSpeed = 5f;
[Header("Патрулирование")]
public Transform[] patrolPoints;
public Transform[] patrolPoints;
private int currentPatrolIndex;
private bool isInvestigating = false;
private bool isInvestigating = false;
[Header("Обнаружение игрока")]
public float detectionRadius = 3.5f; // Радиус обостренных чувств (слух/запах в упор)
public float losePlayerDistance = 14f; // Дистанция потери цели
private Transform targetPlayer;
private PlayerHealth targetPlayerHealth;
[Header("Настройки атаки")]
public float attackRange = 1.8f; // Дистанция ближнего боя
public float attackDamage = 20f; // Урон за один удар
public float attackCooldown = 1.2f; // Кулдаун между ударами
private float nextAttackTime = 0f;
void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.speed = walkSpeed;
if (patrolPoints.Length > 0) GoToNextPatrolPoint();
// Автоматически находим игрока на сцене
var playerObj = FindAnyObjectByType<PlayerHealth>();
if (playerObj != null)
{
targetPlayerHealth = playerObj;
}
if (patrolPoints != null && patrolPoints.Length > 0)
{
GoToNextPatrolPoint();
}
}
void Update()
{
// 1. Поведение при активном преследовании игрока
if (targetPlayer != null)
{
HandlePlayerChaseAndAttack();
return;
}
// 2. Проверка близости игрока (если подошел слишком близко — чует даже слепой)
CheckProximityDetection();
// 3. Патрулирование и расследование звуков
HandlePatrolAndInvestigation();
}
private void HandlePlayerChaseAndAttack()
{
if (targetPlayerHealth != null && targetPlayerHealth.IsDead)
{
LosePlayerTarget();
return;
}
float distanceToPlayer = Vector3.Distance(transform.position, targetPlayer.position);
// Игрок убежал слишком далеко
if (distanceToPlayer > losePlayerDistance)
{
LosePlayerTarget();
return;
}
// Игрок в зоне удара
if (distanceToPlayer <= attackRange)
{
agent.isStopped = true;
// Разворачиваемся к игроку
Vector3 lookDirection = targetPlayer.position - transform.position;
lookDirection.y = 0f;
if (lookDirection.sqrMagnitude > 0.001f)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookDirection), Time.deltaTime * 10f);
}
// Наносим урон по кулдауну
if (Time.time >= nextAttackTime)
{
nextAttackTime = Time.time + attackCooldown;
if (targetPlayerHealth != null)
{
targetPlayerHealth.TakeDamage(attackDamage);
Debug.Log($"Мутант нанес удар игроку! Урон: {attackDamage}");
}
}
}
else
{
// Бежим к игроку
agent.isStopped = false;
agent.speed = runSpeed;
agent.SetDestination(targetPlayer.position);
}
}
private void CheckProximityDetection()
{
if (targetPlayerHealth == null || targetPlayerHealth.IsDead) return;
float distance = Vector3.Distance(transform.position, targetPlayerHealth.transform.position);
if (distance <= detectionRadius)
{
EngagePlayer(targetPlayerHealth.transform);
}
}
private void HandlePatrolAndInvestigation()
{
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
@@ -30,26 +129,81 @@ public class BlindMutantAI : MonoBehaviour
{
isInvestigating = false;
agent.speed = walkSpeed;
if (patrolPoints.Length > 0) GoToNextPatrolPoint();
if (patrolPoints != null && patrolPoints.Length > 0)
{
GoToNextPatrolPoint();
}
}
else if (patrolPoints.Length > 0)
else if (patrolPoints != null && patrolPoints.Length > 0)
{
GoToNextPatrolPoint();
}
}
}
private void EngagePlayer(Transform playerTransform)
{
targetPlayer = playerTransform;
if (targetPlayerHealth == null)
{
targetPlayerHealth = playerTransform.GetComponent<PlayerHealth>();
}
isInvestigating = false;
agent.isStopped = false;
agent.speed = runSpeed;
agent.SetDestination(targetPlayer.position);
Debug.Log("Мутант обнаружил игрока и начинает атаку!");
}
private void LosePlayerTarget()
{
targetPlayer = null;
agent.isStopped = false;
agent.speed = walkSpeed;
isInvestigating = false;
if (patrolPoints != null && patrolPoints.Length > 0)
{
GoToNextPatrolPoint();
}
Debug.Log("Мутант потерял игрока и возвращается к патрулированию.");
}
private void GoToNextPatrolPoint()
{
if (patrolPoints.Length == 0) return;
if (patrolPoints == null || patrolPoints.Length == 0) return;
agent.destination = patrolPoints[currentPatrolIndex].position;
currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length;
}
public void HearSound(Vector3 soundPosition)
{
// Если уже бьем игрока в упор, не отвлекаемся на случайный шум вдалеке
if (targetPlayer != null && Vector3.Distance(transform.position, targetPlayer.position) <= attackRange)
{
return;
}
isInvestigating = true;
agent.speed = runSpeed;
agent.SetDestination(soundPosition);
agent.isStopped = false;
agent.speed = runSpeed;
agent.SetDestination(soundPosition);
}
public void OnDamagedByPlayer(Transform player)
{
EngagePlayer(player);
}
private void OnDrawGizmosSelected()
{
// Радиус ближнего обнаружения
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, detectionRadius);
// Радиус атаки
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
+4 -3
View File
@@ -1,4 +1,4 @@
using UnityEngine;
using UnityEngine;
using UnityEngine.InputSystem;
public class CameraFollow : MonoBehaviour
@@ -31,8 +31,9 @@ public class CameraFollow : MonoBehaviour
// Читаем дельту мыши (смещение курсора за один кадр)
Vector2 mouseDelta = mouse.delta.ReadValue();
yaw += mouseDelta.x * mouseSensitivity * Time.deltaTime;
pitch -= mouseDelta.y * mouseSensitivity * Time.deltaTime;
float sens = mouseSensitivity * GameSettings.GetMouseSensitivity();
yaw += mouseDelta.x * sens * Time.deltaTime;
pitch -= mouseDelta.y * sens * Time.deltaTime;
// Ограничиваем угол наклона камеры
pitch = Mathf.Clamp(pitch, -40f, 60f);
+52
View File
@@ -0,0 +1,52 @@
using UnityEngine;
using UnityEngine.UI;
public class CrosshairUI : MonoBehaviour
{
[Header("Элементы прицела")]
public Image dotImage;
public Image outlineImage;
[Header("Цвета курсора")]
public Color normalColor = new Color(1f, 1f, 1f, 0.9f);
public Color enemyTargetColor = new Color(1f, 0.25f, 0.25f, 1f); // Красный при наведении на врага
public Color interactTargetColor = new Color(0.3f, 0.85f, 1f, 1f); // Голубой при наведении на интерактивный предмет
[Header("Дистанция проверки")]
public float detectRange = 25f;
private Camera mainCamera;
void Start()
{
mainCamera = Camera.main;
if (dotImage != null) dotImage.color = normalColor;
}
void Update()
{
if (dotImage == null) return;
if (mainCamera == null)
{
mainCamera = Camera.main;
if (mainCamera == null) return;
}
Ray ray = new Ray(mainCamera.transform.position, mainCamera.transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit, detectRange))
{
if (hit.collider.GetComponentInParent<MutantHealth>() != null)
{
dotImage.color = enemyTargetColor;
return;
}
if (hit.collider.CompareTag("Throwable"))
{
dotImage.color = interactTargetColor;
return;
}
}
dotImage.color = normalColor;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b1bc6be5f3547e542b645c64c104d61b
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a24655b00a5156c469f760c3b17157d1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,787 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.AI;
using Unity.AI.Navigation;
public static class LaboratoryLevelGenerator
{
private const float WALL_HEIGHT = 4.25f;
private const float WALL_THICKNESS = 0.35f;
[MenuItem("Tools/Generate Full Laboratory Location")]
public static void Generate()
{
Debug.Log("<color=cyan>=== GENERATING LABORATORY LOCATION ===</color>");
// 1. Remove previous Laboratory_Complex or old maze if present
var oldLab = GameObject.Find("Laboratory_Complex");
if (oldLab != null)
{
Undo.DestroyObjectImmediate(oldLab);
}
var oldMaze = GameObject.Find("Maze");
if (oldMaze != null)
{
oldMaze.SetActive(false);
}
// Disable or cleanup old planes
for (int i = 0; i <= 4; i++)
{
string pName = i == 0 ? "Plane" : $"Plane ({i})";
var pl = GameObject.Find(pName);
if (pl != null)
{
pl.SetActive(false);
}
}
// Load assets and materials
Material echoMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/EchoCloudMat.mat");
if (echoMat == null)
{
echoMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/EchoMat.mat");
}
Material woodMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Wood_BaseMap.mat");
Material otherMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Others_BaseMap.mat");
Material glassMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/3D Laboratory Environment with Appratus/Materials/Laboratory03_Glass_BaseMap 1.mat");
GameObject tablePrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/table with drawers.prefab");
GameObject shelfShowcasePrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/shelf showcase.prefab");
GameObject shelf2Prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/shelf (2).prefab");
GameObject rackPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/rack.prefab");
GameObject chairPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/chair.prefab");
GameObject pillarPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/pillar.prefab");
GameObject boxPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/Box.prefab");
GameObject beakerPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/Beaker.prefab");
GameObject flaskPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/Erlenmeyer_flask.prefab");
GameObject testTubePrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/Glass_Lab_test_tube.prefab");
GameObject instPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/analytical_lab_instruments.prefab");
GameObject tapPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/3D Laboratory Environment with Appratus/Prefabs/tap.prefab");
// Root object
GameObject labRoot = new GameObject("Laboratory_Complex");
Undo.RegisterCreatedObjectUndo(labRoot, "Create Laboratory_Complex");
GameObject floorsParent = new GameObject("Floors");
floorsParent.transform.SetParent(labRoot.transform);
GameObject wallsParent = new GameObject("Walls");
wallsParent.transform.SetParent(labRoot.transform);
GameObject roomsParent = new GameObject("Rooms_Props");
roomsParent.transform.SetParent(labRoot.transform);
GameObject lightsParent = new GameObject("Atmospheric_Lighting");
lightsParent.transform.SetParent(labRoot.transform);
GameObject pickupsParent = new GameObject("Throwable_Distractions");
pickupsParent.transform.SetParent(labRoot.transform);
// 2. Build Floor Grid (64m x 64m, from -32 to +32 in X and Z)
CreateFloorGrid(floorsParent.transform, echoMat, -32f, 32f, -32f, 32f);
// 3. Build Perimeter Exterior Walls
CreateWall(wallsParent.transform, echoMat, new Vector3(0, WALL_HEIGHT / 2f, -32f), new Vector3(64f, WALL_HEIGHT, WALL_THICKNESS), "Wall_Perimeter_South");
CreateWall(wallsParent.transform, echoMat, new Vector3(0, WALL_HEIGHT / 2f, 32f), new Vector3(64f, WALL_HEIGHT, WALL_THICKNESS), "Wall_Perimeter_North");
CreateWall(wallsParent.transform, echoMat, new Vector3(-32f, WALL_HEIGHT / 2f, 0), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 64f), "Wall_Perimeter_West");
CreateWall(wallsParent.transform, echoMat, new Vector3(32f, WALL_HEIGHT / 2f, 0), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 64f), "Wall_Perimeter_East");
// 4. Build Rooms Walls with Doorways
// We define rooms as bounding boxes [minX, maxX, minZ, maxZ] and doors on specific sides with cutout [doorMin, doorMax]
// Room 1: Entrance / Decontamination (X: -6 to +6, Z: -32 to -22)
BuildRoomWalls(wallsParent.transform, echoMat, -6f, 6f, -32f, -22f,
southDoor: null, // sealed
northDoor: new Vector2(-1.8f, 1.8f),
westDoor: null,
eastDoor: null,
roomName: "Decontamination");
// Room 4: Cryo Archive (X: -30 to -14, Z: -32 to -20)
BuildRoomWalls(wallsParent.transform, echoMat, -30f, -14f, -32f, -20f,
southDoor: null,
northDoor: new Vector2(-24f, -20f),
westDoor: null,
eastDoor: new Vector2(-27f, -23f),
roomName: "CryoArchive");
// Room 8: Security & Surveillance (X: 14 to 30, Z: -32 to -20)
BuildRoomWalls(wallsParent.transform, echoMat, 14f, 30f, -32f, -20f,
southDoor: null,
northDoor: new Vector2(20f, 24f),
westDoor: new Vector2(-27f, -23f),
eastDoor: null,
roomName: "SecurityOffice");
// Room 2: Biochemistry Research Lab (X: -30 to -14, Z: -14 to 2)
BuildRoomWalls(wallsParent.transform, echoMat, -30f, -14f, -14f, 2f,
southDoor: new Vector2(-24f, -20f),
northDoor: new Vector2(-24f, -20f),
westDoor: null,
eastDoor: new Vector2(-8f, -4f),
roomName: "BiochemLab");
// Room 6: Surgical Theatre & Medical Bay (X: 14 to 30, Z: -14 to 2)
BuildRoomWalls(wallsParent.transform, echoMat, 14f, 30f, -14f, 2f,
southDoor: new Vector2(20f, 24f),
northDoor: new Vector2(20f, 24f),
westDoor: new Vector2(-8f, -4f),
eastDoor: null,
roomName: "SurgicalBay");
// Room 3: Bio-Hazard Containment Vault (X: -30 to -12, Z: 8 to 26)
BuildRoomWalls(wallsParent.transform, echoMat, -30f, -12f, 8f, 26f,
southDoor: new Vector2(-23f, -19f),
northDoor: new Vector2(-23f, -19f), // leads to North Maintenance bypass
westDoor: null,
eastDoor: new Vector2(15f, 19f),
roomName: "BioContainment");
// Room 5: Central Bio-Dome & Core Reactor (X: -7 to 7, Z: 8 to 26)
BuildRoomWalls(wallsParent.transform, echoMat, -7f, 7f, 8f, 26f,
southDoor: new Vector2(-2f, 2f),
northDoor: new Vector2(-2f, 2f), // leads to North Maintenance bypass
westDoor: new Vector2(15f, 19f),
eastDoor: new Vector2(15f, 19f),
roomName: "CentralCore");
// Room 7: Genetics Sequencing Lab (X: 12 to 30, Z: 6 to 18)
BuildRoomWalls(wallsParent.transform, echoMat, 12f, 30f, 6f, 18f,
southDoor: new Vector2(19f, 23f),
northDoor: new Vector2(19f, 23f),
westDoor: new Vector2(10f, 14f),
eastDoor: null,
roomName: "GeneticsLab");
// Room 9: Generator Substation (X: 12 to 30, Z: 20 to 30)
BuildRoomWalls(wallsParent.transform, echoMat, 12f, 30f, 20f, 30f,
southDoor: new Vector2(19f, 23f),
northDoor: null,
westDoor: new Vector2(23f, 27f), // leads to North Maintenance bypass
eastDoor: null,
roomName: "GeneratorRoom");
// 5. Build Tangled Corridor Internal Walls & Partitions (Maze structure)
BuildCorridorMaze(wallsParent.transform, echoMat);
// 6. Populate Rooms with Furniture & Props
PopulateDecontamination(roomsParent.transform, pillarPrefab, rackPrefab, chairPrefab, echoMat);
PopulateBiochemLab(roomsParent.transform, tablePrefab, shelfShowcasePrefab, shelf2Prefab, tapPrefab, instPrefab, beakerPrefab, flaskPrefab, testTubePrefab, pickupsParent.transform);
PopulateBioContainment(roomsParent.transform, pillarPrefab, tablePrefab, boxPrefab, beakerPrefab, instPrefab, pickupsParent.transform);
PopulateCryoArchive(roomsParent.transform, rackPrefab, shelf2Prefab, boxPrefab, beakerPrefab, pickupsParent.transform);
PopulateCentralCore(roomsParent.transform, pillarPrefab, tablePrefab, instPrefab, boxPrefab, beakerPrefab, pickupsParent.transform);
PopulateSurgicalBay(roomsParent.transform, tablePrefab, shelfShowcasePrefab, chairPrefab, beakerPrefab, pickupsParent.transform);
PopulateGeneticsLab(roomsParent.transform, tablePrefab, shelfShowcasePrefab, instPrefab, chairPrefab, beakerPrefab, pickupsParent.transform);
PopulateGeneratorRoom(roomsParent.transform, pillarPrefab, boxPrefab, beakerPrefab, pickupsParent.transform);
PopulateCorridorNiches(roomsParent.transform, pillarPrefab, boxPrefab, rackPrefab);
// 7. Atmospheric Lighting setup
CreateLighting(lightsParent.transform);
// 8. Reconfigure Player Position
var player = GameObject.Find("Capsule");
if (player != null)
{
player.transform.position = new Vector3(0f, 1.05f, -28f);
player.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
Debug.Log("Moved Player to Entrance Airlock (0, 1.05, -28)");
}
// 9. Reconfigure Enemy (BlindMutantAI) & Patrol Waypoints
var enemy = GameObject.Find("enemy");
SetupPatrolWaypoints(labRoot.transform, enemy);
// 10. Re-bake NavMesh Surface
var navMeshSurface = Object.FindAnyObjectByType<NavMeshSurface>();
if (navMeshSurface != null)
{
navMeshSurface.transform.position = Vector3.zero;
navMeshSurface.collectObjects = CollectObjects.All;
navMeshSurface.BuildNavMesh();
Debug.Log("<color=green>NavMesh successfully baked for the entire laboratory complex!</color>");
}
// Mark scene dirty
EditorUtility.SetDirty(labRoot);
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
Debug.Log("<color=green>=== LABORATORY COMPLEX GENERATION COMPLETE! ===</color>");
}
private static void CreateFloorGrid(Transform parent, Material mat, float minX, float maxX, float minZ, float maxZ)
{
// 4 large floor quadrants for clean rendering and collision
float midX = (minX + maxX) / 2f;
float midZ = (minZ + maxZ) / 2f;
float sizeX = (maxX - minX) / 2f;
float sizeZ = (maxZ - minZ) / 2f;
Vector2[] quads = new Vector2[]
{
new Vector2((minX + midX) / 2f, (minZ + midZ) / 2f),
new Vector2((midX + maxX) / 2f, (minZ + midZ) / 2f),
new Vector2((minX + midX) / 2f, (midZ + maxZ) / 2f),
new Vector2((midX + maxX) / 2f, (midZ + maxZ) / 2f)
};
for (int i = 0; i < quads.Length; i++)
{
var floorGo = GameObject.CreatePrimitive(PrimitiveType.Cube);
floorGo.name = $"Floor_Quadrant_{i + 1}";
floorGo.transform.SetParent(parent);
floorGo.transform.position = new Vector3(quads[i].x, -0.25f, quads[i].y);
floorGo.transform.localScale = new Vector3(sizeX, 0.5f, sizeZ);
if (mat != null) floorGo.GetComponent<Renderer>().sharedMaterial = mat;
}
}
private static void BuildRoomWalls(Transform parent, Material mat, float minX, float maxX, float minZ, float maxZ,
Vector2? southDoor, Vector2? northDoor, Vector2? westDoor, Vector2? eastDoor, string roomName)
{
GameObject roomWalls = new GameObject($"Walls_{roomName}");
roomWalls.transform.SetParent(parent);
// South Wall (along X at Z = minZ)
CreateWallWithDoor(roomWalls.transform, mat, minX, maxX, minZ, true, southDoor, $"{roomName}_South");
// North Wall (along X at Z = maxZ)
CreateWallWithDoor(roomWalls.transform, mat, minX, maxX, maxZ, true, northDoor, $"{roomName}_North");
// West Wall (along Z at X = minX)
CreateWallWithDoor(roomWalls.transform, mat, minZ, maxZ, minX, false, westDoor, $"{roomName}_West");
// East Wall (along Z at X = maxX)
CreateWallWithDoor(roomWalls.transform, mat, minZ, maxZ, maxX, false, eastDoor, $"{roomName}_East");
}
private static void CreateWallWithDoor(Transform parent, Material mat, float startCoord, float endCoord, float fixedCoord,
bool isHorizontal, Vector2? doorRange, string wallName)
{
if (startCoord > endCoord)
{
float t = startCoord; startCoord = endCoord; endCoord = t;
}
if (!doorRange.HasValue)
{
// Full solid wall
float length = endCoord - startCoord;
float mid = (startCoord + endCoord) / 2f;
Vector3 pos = isHorizontal ? new Vector3(mid, WALL_HEIGHT / 2f, fixedCoord) : new Vector3(fixedCoord, WALL_HEIGHT / 2f, mid);
Vector3 scale = isHorizontal ? new Vector3(length, WALL_HEIGHT, WALL_THICKNESS) : new Vector3(WALL_THICKNESS, WALL_HEIGHT, length);
CreateWall(parent, mat, pos, scale, wallName);
return;
}
float dMin = Mathf.Clamp(doorRange.Value.x, startCoord, endCoord);
float dMax = Mathf.Clamp(doorRange.Value.y, startCoord, endCoord);
// Left / Start section
if (dMin > startCoord + 0.2f)
{
float len1 = dMin - startCoord;
float mid1 = (startCoord + dMin) / 2f;
Vector3 pos1 = isHorizontal ? new Vector3(mid1, WALL_HEIGHT / 2f, fixedCoord) : new Vector3(fixedCoord, WALL_HEIGHT / 2f, mid1);
Vector3 scale1 = isHorizontal ? new Vector3(len1, WALL_HEIGHT, WALL_THICKNESS) : new Vector3(WALL_THICKNESS, WALL_HEIGHT, len1);
CreateWall(parent, mat, pos1, scale1, $"{wallName}_PartA");
}
// Right / End section
if (endCoord > dMax + 0.2f)
{
float len2 = endCoord - dMax;
float mid2 = (dMax + endCoord) / 2f;
Vector3 pos2 = isHorizontal ? new Vector3(mid2, WALL_HEIGHT / 2f, fixedCoord) : new Vector3(fixedCoord, WALL_HEIGHT / 2f, mid2);
Vector3 scale2 = isHorizontal ? new Vector3(len2, WALL_HEIGHT, WALL_THICKNESS) : new Vector3(WALL_THICKNESS, WALL_HEIGHT, len2);
CreateWall(parent, mat, pos2, scale2, $"{wallName}_PartB");
}
// Over-door Lintel (bulkhead arch)
float doorLen = dMax - dMin;
float doorMid = (dMin + dMax) / 2f;
float lintelHeight = WALL_HEIGHT - 2.5f;
float lintelPosY = 2.5f + (lintelHeight / 2f);
Vector3 lintelPos = isHorizontal ? new Vector3(doorMid, lintelPosY, fixedCoord) : new Vector3(fixedCoord, lintelPosY, doorMid);
Vector3 lintelScale = isHorizontal ? new Vector3(doorLen, lintelHeight, WALL_THICKNESS) : new Vector3(WALL_THICKNESS, lintelHeight, doorLen);
CreateWall(parent, mat, lintelPos, lintelScale, $"{wallName}_Lintel");
}
private static GameObject CreateWall(Transform parent, Material mat, Vector3 pos, Vector3 scale, string name)
{
var wall = GameObject.CreatePrimitive(PrimitiveType.Cube);
wall.name = name;
wall.transform.SetParent(parent);
wall.transform.position = pos;
wall.transform.localScale = scale;
if (mat != null) wall.GetComponent<Renderer>().sharedMaterial = mat;
return wall;
}
private static void BuildCorridorMaze(Transform parent, Material mat)
{
GameObject mazeGo = new GameObject("Tangled_Corridors_Maze");
mazeGo.transform.SetParent(parent);
// 1. Central Core Elevator Shaft / Ventilation Pillar divider (splits Central Hallway into two paths)
// Position: X: -3 to +3, Z: -6 to 2
CreateWall(mazeGo.transform, mat, new Vector3(0f, WALL_HEIGHT / 2f, -2f), new Vector3(5f, WALL_HEIGHT, 6f), "Central_Ventilation_Core");
// 2. West Serpentine Hallway Dividers (creating zig-zags between X: -14 and -6)
// Horizontal baffle at Z = -17 (X from -14 to -9)
CreateWall(mazeGo.transform, mat, new Vector3(-11.5f, WALL_HEIGHT / 2f, -17f), new Vector3(5f, WALL_HEIGHT, WALL_THICKNESS), "Baffle_West_1");
// Vertical wall at X = -9 (Z from -17 to -12) with opening
CreateWall(mazeGo.transform, mat, new Vector3(-9f, WALL_HEIGHT / 2f, -14.5f), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 5f), "Baffle_West_2");
// Horizontal baffle at Z = -11 (X from -11 to -7)
CreateWall(mazeGo.transform, mat, new Vector3(-9f, WALL_HEIGHT / 2f, -11f), new Vector3(4f, WALL_HEIGHT, WALL_THICKNESS), "Baffle_West_3");
// Vertical wall at X = -10 (Z from -4 to 3)
CreateWall(mazeGo.transform, mat, new Vector3(-10f, WALL_HEIGHT / 2f, -0.5f), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 7f), "Baffle_West_4");
// Alcove cover at X = -7 (Z = 5)
CreateWall(mazeGo.transform, mat, new Vector3(-8.5f, WALL_HEIGHT / 2f, 5f), new Vector3(3f, WALL_HEIGHT, WALL_THICKNESS), "Baffle_West_Alcove");
// 3. East Serpentine Hallway Dividers (creating zig-zags between X: +6 and +14)
// Horizontal baffle at Z = -17 (X from 9 to 14)
CreateWall(mazeGo.transform, mat, new Vector3(11.5f, WALL_HEIGHT / 2f, -17f), new Vector3(5f, WALL_HEIGHT, WALL_THICKNESS), "Baffle_East_1");
// Vertical wall at X = 9 (Z from -17 to -12)
CreateWall(mazeGo.transform, mat, new Vector3(9f, WALL_HEIGHT / 2f, -14.5f), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 5f), "Baffle_East_2");
// Horizontal baffle at Z = -11 (X from 7 to 11)
CreateWall(mazeGo.transform, mat, new Vector3(9f, WALL_HEIGHT / 2f, -11f), new Vector3(4f, WALL_HEIGHT, WALL_THICKNESS), "Baffle_East_3");
// Vertical wall at X = 10 (Z from -4 to 3)
CreateWall(mazeGo.transform, mat, new Vector3(10f, WALL_HEIGHT / 2f, -0.5f), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 7f), "Baffle_East_4");
// Alcove cover at X = 7 (Z = 5)
CreateWall(mazeGo.transform, mat, new Vector3(8.5f, WALL_HEIGHT / 2f, 5f), new Vector3(3f, WALL_HEIGHT, WALL_THICKNESS), "Baffle_East_Alcove");
// 4. North Maintenance Crawlway / Bypass (Long narrow bypass at Z: 28 to 31, spanning X: -27 to +27)
// Southern guide wall of the crawlway:
// Section A (X: -30 to -9 at Z = 28.5) with door into BioContainment at X: -21
CreateWallWithDoor(mazeGo.transform, mat, -30f, -9f, 28.5f, true, new Vector2(-23f, -19f), "NorthCrawl_WestGuide");
// Section B (X: -5 to +5 at Z = 28.5) behind Central Core with center access door
CreateWallWithDoor(mazeGo.transform, mat, -7f, 7f, 28.5f, true, new Vector2(-2f, 2f), "NorthCrawl_MidGuide");
// Section C (X: 9 to 30 at Z = 28.5) leading to Generator room with door at X: 21
CreateWallWithDoor(mazeGo.transform, mat, 9f, 30f, 28.5f, true, new Vector2(19f, 23f), "NorthCrawl_EastGuide");
// 5. South Crossroads Corridor Dividers (between Decontamination and Wings)
// Partition at X = -6, Z = -18 (creating blind corner from Decon to Cryo)
CreateWall(mazeGo.transform, mat, new Vector3(-6f, WALL_HEIGHT / 2f, -18f), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 4f), "Crossroad_West_Corner");
// Partition at X = +6, Z = -18 (creating blind corner from Decon to Security)
CreateWall(mazeGo.transform, mat, new Vector3(6f, WALL_HEIGHT / 2f, -18f), new Vector3(WALL_THICKNESS, WALL_HEIGHT, 4f), "Crossroad_East_Corner");
}
private static void PopulateDecontamination(Transform parent, GameObject pillarPrefab, GameObject rackPrefab, GameObject chairPrefab, Material echoMat)
{
GameObject room = new GameObject("Decontamination_Props");
room.transform.SetParent(parent);
// Decontamination Frame (two pillars with lintel)
SpawnProp(pillarPrefab, room.transform, new Vector3(-2f, 0f, -25f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(2f, 0f, -25f), Quaternion.identity);
// Lockers / Racks along West wall
SpawnProp(rackPrefab, room.transform, new Vector3(-4.8f, 0f, -29f), Quaternion.Euler(0f, 90f, 0f));
SpawnProp(rackPrefab, room.transform, new Vector3(-4.8f, 0f, -27f), Quaternion.Euler(0f, 90f, 0f));
// Benches along East wall
SpawnProp(chairPrefab, room.transform, new Vector3(4.5f, 0f, -29f), Quaternion.Euler(0f, -90f, 0f));
SpawnProp(chairPrefab, room.transform, new Vector3(4.5f, 0f, -27f), Quaternion.Euler(0f, -90f, 0f));
}
private static void PopulateBiochemLab(Transform parent, GameObject tablePrefab, GameObject showcasePrefab, GameObject shelfPrefab,
GameObject tapPrefab, GameObject instPrefab, GameObject beakerPrefab, GameObject flaskPrefab, GameObject tubePrefab, Transform pickupsParent)
{
GameObject room = new GameObject("BiochemLab_Props");
room.transform.SetParent(parent);
// Central Lab Island 1
SpawnProp(tablePrefab, room.transform, new Vector3(-24f, 0f, -8f), Quaternion.identity);
SpawnProp(tablePrefab, room.transform, new Vector3(-20f, 0f, -8f), Quaternion.identity);
SpawnProp(instPrefab, room.transform, new Vector3(-24f, 1.07f, -8f), Quaternion.identity);
SpawnProp(tapPrefab, room.transform, new Vector3(-20f, 1.07f, -8f), Quaternion.identity);
// Central Lab Island 2
SpawnProp(tablePrefab, room.transform, new Vector3(-24f, 0f, -4f), Quaternion.identity);
SpawnProp(tablePrefab, room.transform, new Vector3(-20f, 0f, -4f), Quaternion.identity);
SpawnProp(tubePrefab, room.transform, new Vector3(-23.5f, 1.07f, -4f), Quaternion.identity);
SpawnProp(flaskPrefab, room.transform, new Vector3(-20.5f, 1.07f, -4f), Quaternion.identity);
// Shelves along West Wall
SpawnProp(showcasePrefab, room.transform, new Vector3(-29f, 0f, -10f), Quaternion.Euler(0f, 90f, 0f));
SpawnProp(showcasePrefab, room.transform, new Vector3(-29f, 0f, -2f), Quaternion.Euler(0f, 90f, 0f));
SpawnProp(shelfPrefab, room.transform, new Vector3(-29f, 0f, -6f), Quaternion.Euler(0f, 90f, 0f));
// Throwable Beaker distraction on bench
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(-19.5f, 1.15f, -8f), "Throwable_Beaker_Biochem1");
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(-24.5f, 1.15f, -4f), "Throwable_Beaker_Biochem2");
}
private static void PopulateBioContainment(Transform parent, GameObject pillarPrefab, GameObject tablePrefab, GameObject boxPrefab,
GameObject beakerPrefab, GameObject instPrefab, Transform pickupsParent)
{
GameObject room = new GameObject("BioContainment_Props");
room.transform.SetParent(parent);
// 4 massive containment corner pillars
SpawnProp(pillarPrefab, room.transform, new Vector3(-26f, 0f, 12f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(-15f, 0f, 12f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(-26f, 0f, 22f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(-15f, 0f, 22f), Quaternion.identity);
// Broken containment center vat/chamber
var vatBase = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
vatBase.name = "Containment_Vat_Broken";
vatBase.transform.SetParent(room.transform);
vatBase.transform.position = new Vector3(-20.5f, 1.5f, 17f);
vatBase.transform.localScale = new Vector3(3.5f, 1.5f, 3.5f);
// Observation console desk
SpawnProp(tablePrefab, room.transform, new Vector3(-20.5f, 0f, 10.5f), Quaternion.identity);
SpawnProp(instPrefab, room.transform, new Vector3(-20.5f, 1.07f, 10.5f), Quaternion.identity);
// Overturned boxes and cover
SpawnProp(boxPrefab, room.transform, new Vector3(-24f, 0f, 15f), Quaternion.Euler(0f, 35f, 0f));
SpawnProp(boxPrefab, room.transform, new Vector3(-24f, 0f, 16.5f), Quaternion.Euler(0f, 15f, 0f));
SpawnProp(boxPrefab, room.transform, new Vector3(-16f, 0f, 20f), Quaternion.Euler(0f, 60f, 0f));
// Throwable distraction beaker
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(-20f, 1.15f, 10.5f), "Throwable_Beaker_Containment");
}
private static void PopulateCryoArchive(Transform parent, GameObject rackPrefab, GameObject shelfPrefab, GameObject boxPrefab,
GameObject beakerPrefab, Transform pickupsParent)
{
GameObject room = new GameObject("CryoArchive_Props");
room.transform.SetParent(parent);
// Rows of storage racks creating narrow aisles
SpawnProp(rackPrefab, room.transform, new Vector3(-26f, 0f, -28f), Quaternion.identity);
SpawnProp(rackPrefab, room.transform, new Vector3(-26f, 0f, -24f), Quaternion.identity);
SpawnProp(rackPrefab, room.transform, new Vector3(-21f, 0f, -28f), Quaternion.identity);
SpawnProp(rackPrefab, room.transform, new Vector3(-21f, 0f, -24f), Quaternion.identity);
SpawnProp(rackPrefab, room.transform, new Vector3(-16f, 0f, -28f), Quaternion.identity);
// Storage boxes stacked for cover
SpawnProp(boxPrefab, room.transform, new Vector3(-28.5f, 0f, -22f), Quaternion.identity);
SpawnProp(boxPrefab, room.transform, new Vector3(-28.5f, 1.08f, -22f), Quaternion.identity);
SpawnProp(boxPrefab, room.transform, new Vector3(-17f, 0f, -22f), Quaternion.identity);
// Shelves along back wall
SpawnProp(shelfPrefab, room.transform, new Vector3(-23f, 0f, -31f), Quaternion.identity);
// Throwable distraction beaker in storage
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(-26f, 1.15f, -28f), "Throwable_Beaker_Cryo");
}
private static void PopulateCentralCore(Transform parent, GameObject pillarPrefab, GameObject tablePrefab, GameObject instPrefab,
GameObject boxPrefab, GameObject beakerPrefab, Transform pickupsParent)
{
GameObject room = new GameObject("CentralCore_Props");
room.transform.SetParent(parent);
// 4 massive observation pillars
SpawnProp(pillarPrefab, room.transform, new Vector3(-5.5f, 0f, 10.5f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(5.5f, 0f, 10.5f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(-5.5f, 0f, 23.5f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(5.5f, 0f, 23.5f), Quaternion.identity);
// Central Specimen Reactor Vat
var coreCylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
coreCylinder.name = "Central_Mutant_Reactor_Core";
coreCylinder.transform.SetParent(room.transform);
coreCylinder.transform.position = new Vector3(0f, 2.0f, 17f);
coreCylinder.transform.localScale = new Vector3(4.5f, 2.0f, 4.5f);
// Observation console desks
SpawnProp(tablePrefab, room.transform, new Vector3(-3f, 0f, 13f), Quaternion.Euler(0f, 45f, 0f));
SpawnProp(instPrefab, room.transform, new Vector3(-3f, 1.07f, 13f), Quaternion.Euler(0f, 45f, 0f));
SpawnProp(tablePrefab, room.transform, new Vector3(3f, 0f, 13f), Quaternion.Euler(0f, -45f, 0f));
SpawnProp(instPrefab, room.transform, new Vector3(3f, 1.07f, 13f), Quaternion.Euler(0f, -45f, 0f));
// Cover crates in corners
SpawnProp(boxPrefab, room.transform, new Vector3(-5.5f, 0f, 17f), Quaternion.identity);
SpawnProp(boxPrefab, room.transform, new Vector3(5.5f, 0f, 17f), Quaternion.identity);
// Throwable distraction beaker on console
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(-2.8f, 1.15f, 13.2f), "Throwable_Beaker_Core");
}
private static void PopulateSurgicalBay(Transform parent, GameObject tablePrefab, GameObject showcasePrefab, GameObject chairPrefab,
GameObject beakerPrefab, Transform pickupsParent)
{
GameObject room = new GameObject("SurgicalBay_Props");
room.transform.SetParent(parent);
// Dual operating / dissection tables
SpawnProp(tablePrefab, room.transform, new Vector3(18f, 0f, -6f), Quaternion.identity);
SpawnProp(tablePrefab, room.transform, new Vector3(24f, 0f, -6f), Quaternion.identity);
// Surgeon stools
SpawnProp(chairPrefab, room.transform, new Vector3(18f, 0f, -4.5f), Quaternion.Euler(0f, 180f, 0f));
SpawnProp(chairPrefab, room.transform, new Vector3(24f, 0f, -4.5f), Quaternion.Euler(0f, 180f, 0f));
// Medical supply showcases along East Wall
SpawnProp(showcasePrefab, room.transform, new Vector3(29f, 0f, -10f), Quaternion.Euler(0f, -90f, 0f));
SpawnProp(showcasePrefab, room.transform, new Vector3(29f, 0f, -2f), Quaternion.Euler(0f, -90f, 0f));
// Throwable beaker
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(23.5f, 1.15f, -6f), "Throwable_Beaker_Surgery");
}
private static void PopulateGeneticsLab(Transform parent, GameObject tablePrefab, GameObject showcasePrefab, GameObject instPrefab,
GameObject chairPrefab, GameObject beakerPrefab, Transform pickupsParent)
{
GameObject room = new GameObject("GeneticsLab_Props");
room.transform.SetParent(parent);
// Genetic sequencer workstations
SpawnProp(tablePrefab, room.transform, new Vector3(18f, 0f, 12f), Quaternion.identity);
SpawnProp(instPrefab, room.transform, new Vector3(18f, 1.07f, 12f), Quaternion.identity);
SpawnProp(chairPrefab, room.transform, new Vector3(18f, 0f, 10.5f), Quaternion.identity);
SpawnProp(tablePrefab, room.transform, new Vector3(24f, 0f, 12f), Quaternion.identity);
SpawnProp(instPrefab, room.transform, new Vector3(24f, 1.07f, 12f), Quaternion.identity);
SpawnProp(chairPrefab, room.transform, new Vector3(24f, 0f, 10.5f), Quaternion.identity);
// Showcases along East Wall
SpawnProp(showcasePrefab, room.transform, new Vector3(29f, 0f, 12f), Quaternion.Euler(0f, -90f, 0f));
// Throwable beaker
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(24.5f, 1.15f, 12f), "Throwable_Beaker_Genetics");
}
private static void PopulateGeneratorRoom(Transform parent, GameObject pillarPrefab, GameObject boxPrefab, GameObject beakerPrefab, Transform pickupsParent)
{
GameObject room = new GameObject("GeneratorRoom_Props");
room.transform.SetParent(parent);
// 2 Massive Transformer Generator Blocks
var gen1 = GameObject.CreatePrimitive(PrimitiveType.Cube);
gen1.name = "Generator_Core_1";
gen1.transform.SetParent(room.transform);
gen1.transform.position = new Vector3(18f, 2.0f, 25f);
gen1.transform.localScale = new Vector3(3f, 4f, 4f);
var gen2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
gen2.name = "Generator_Core_2";
gen2.transform.SetParent(room.transform);
gen2.transform.position = new Vector3(25f, 2.0f, 25f);
gen2.transform.localScale = new Vector3(3f, 4f, 4f);
// Support pillars
SpawnProp(pillarPrefab, room.transform, new Vector3(14f, 0f, 28f), Quaternion.identity);
SpawnProp(pillarPrefab, room.transform, new Vector3(28f, 0f, 28f), Quaternion.identity);
// Power supply crates
SpawnProp(boxPrefab, room.transform, new Vector3(21.5f, 0f, 27.5f), Quaternion.identity);
SpawnProp(boxPrefab, room.transform, new Vector3(21.5f, 1.08f, 27.5f), Quaternion.identity);
// Throwable distraction
SpawnThrowableBeaker(beakerPrefab, pickupsParent, new Vector3(21.5f, 1.15f, 22f), "Throwable_Beaker_Generator");
}
private static void PopulateCorridorNiches(Transform parent, GameObject pillarPrefab, GameObject boxPrefab, GameObject rackPrefab)
{
GameObject niches = new GameObject("Corridor_Niches_Cover");
niches.transform.SetParent(parent);
// South Concourse pillars & crates
SpawnProp(pillarPrefab, niches.transform, new Vector3(-3f, 0f, -18f), Quaternion.identity);
SpawnProp(pillarPrefab, niches.transform, new Vector3(3f, 0f, -18f), Quaternion.identity);
SpawnProp(boxPrefab, niches.transform, new Vector3(0f, 0f, -17f), Quaternion.identity);
// West corridor alcove hiding spot
SpawnProp(boxPrefab, niches.transform, new Vector3(-8.5f, 0f, 6.5f), Quaternion.identity);
SpawnProp(rackPrefab, niches.transform, new Vector3(-8.5f, 0f, -12.5f), Quaternion.Euler(0f, 90f, 0f));
// East corridor alcove hiding spot
SpawnProp(boxPrefab, niches.transform, new Vector3(8.5f, 0f, 6.5f), Quaternion.identity);
SpawnProp(rackPrefab, niches.transform, new Vector3(8.5f, 0f, -12.5f), Quaternion.Euler(0f, -90f, 0f));
// North Crawlway mid-point cover
SpawnProp(boxPrefab, niches.transform, new Vector3(-8f, 0f, 30f), Quaternion.identity);
SpawnProp(boxPrefab, niches.transform, new Vector3(8f, 0f, 30f), Quaternion.identity);
}
private static void SpawnProp(GameObject prefab, Transform parent, Vector3 pos, Quaternion rot)
{
if (prefab == null) return;
GameObject instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab, parent);
if (instance != null)
{
instance.transform.position = pos;
instance.transform.rotation = rot;
}
}
private static void SpawnThrowableBeaker(GameObject beakerPrefab, Transform parent, Vector3 pos, string name)
{
GameObject beaker;
if (beakerPrefab != null)
{
beaker = (GameObject)PrefabUtility.InstantiatePrefab(beakerPrefab, parent);
}
else
{
beaker = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
beaker.transform.localScale = new Vector3(0.3f, 0.5f, 0.3f);
}
beaker.name = name;
beaker.transform.position = pos;
// Ensure collider
var col = beaker.GetComponent<Collider>();
if (col == null)
{
col = beaker.AddComponent<CapsuleCollider>();
}
// Rigidbody for throwing physics
var rb = beaker.GetComponent<Rigidbody>();
if (rb == null)
{
rb = beaker.AddComponent<Rigidbody>();
}
rb.mass = 1.0f;
rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
// ImpactWave component so it triggers echolocation wave and mutant alert when landing!
var wave = beaker.GetComponent<ImpactWave>();
if (wave == null)
{
wave = beaker.AddComponent<ImpactWave>();
}
wave.soundRadius = 18f;
wave.minImpactForce = 1.5f;
// Load EchoPulse prefab if available
var pulsePrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/EchoPulse.prefab");
if (pulsePrefab != null)
{
wave.wavePrefab = pulsePrefab;
}
}
private static void CreateLighting(Transform parent)
{
// Entrance Airlock - Warning Red emergency light
CreatePointLight(parent, "Light_Decon_Red", new Vector3(0f, 3.8f, -27f), new Color(1f, 0.2f, 0.15f), 2.5f, 12f);
// South Concourse - Dim Amber light
CreatePointLight(parent, "Light_SouthConcourse", new Vector3(0f, 3.8f, -18f), new Color(1f, 0.75f, 0.4f), 1.8f, 14f);
// Cryo Archive - Cold Cyan/Blue
CreatePointLight(parent, "Light_Cryo_Cyan", new Vector3(-20f, 3.8f, -26f), new Color(0.2f, 0.7f, 1f), 1.6f, 16f);
// Security Office - Amber Terminal light
CreatePointLight(parent, "Light_Security_Amber", new Vector3(20f, 3.8f, -26f), new Color(1f, 0.65f, 0.2f), 1.8f, 16f);
// Biochem Lab - Toxic Pale Green
CreatePointLight(parent, "Light_Biochem_Green", new Vector3(-20f, 3.8f, -6f), new Color(0.35f, 0.95f, 0.5f), 2.0f, 18f);
// Surgical Theatre - Clinical Cold White
CreatePointLight(parent, "Light_Surgery_White", new Vector3(20f, 3.8f, -6f), new Color(0.85f, 0.92f, 1f), 2.2f, 18f);
// Bio-Containment Vault - Deep Pulsing Red
CreatePointLight(parent, "Light_BioContainment_Alarm", new Vector3(-20f, 3.8f, 17f), new Color(1f, 0.1f, 0.1f), 2.5f, 20f);
// Central Core Bio-Reactor - Eerie Glowing Cyan/Emerald Spotlight from above
CreatePointLight(parent, "Light_CentralReactor_Glow", new Vector3(0f, 3.8f, 17f), new Color(0.2f, 1f, 0.85f), 3.0f, 22f);
// Genetics Lab - Blue / Violet
CreatePointLight(parent, "Light_Genetics_Violet", new Vector3(20f, 3.8f, 12f), new Color(0.6f, 0.4f, 1f), 1.8f, 16f);
// Generator Room - Warning Amber
CreatePointLight(parent, "Light_Generator_Amber", new Vector3(20f, 3.8f, 25f), new Color(1f, 0.5f, 0.1f), 2.0f, 16f);
// North Crawlway Corridor lights
CreatePointLight(parent, "Light_NorthCrawl_West", new Vector3(-15f, 3.2f, 29.5f), new Color(1f, 0.7f, 0.3f), 1.2f, 10f);
CreatePointLight(parent, "Light_NorthCrawl_Mid", new Vector3(0f, 3.2f, 29.5f), new Color(1f, 0.7f, 0.3f), 1.2f, 10f);
CreatePointLight(parent, "Light_NorthCrawl_East", new Vector3(15f, 3.2f, 29.5f), new Color(1f, 0.7f, 0.3f), 1.2f, 10f);
// Serpentine Corridor Waypoint lights
CreatePointLight(parent, "Light_WestSerpentine", new Vector3(-10f, 3.5f, -8f), new Color(0.5f, 0.6f, 0.7f), 1.0f, 10f);
CreatePointLight(parent, "Light_EastSerpentine", new Vector3(10f, 3.5f, -8f), new Color(0.5f, 0.6f, 0.7f), 1.0f, 10f);
}
private static void CreatePointLight(Transform parent, string name, Vector3 pos, Color color, float intensity, float range)
{
GameObject lightGo = new GameObject(name);
lightGo.transform.SetParent(parent);
lightGo.transform.position = pos;
var light = lightGo.AddComponent<Light>();
light.type = LightType.Point;
light.color = color;
light.intensity = intensity;
light.range = range;
light.shadows = LightShadows.Soft;
}
private static void SetupPatrolWaypoints(Transform parent, GameObject enemy)
{
// Clean up any old patrol points
var oldPatrol = GameObject.Find("PatrolWaypoints");
if (oldPatrol != null)
{
Undo.DestroyObjectImmediate(oldPatrol);
}
// Also disable old 1 .. 1 (13) if present in scene root
for (int i = 0; i <= 15; i++)
{
string oldName = i == 0 ? "1" : $"1 ({i})";
var oldGo = GameObject.Find(oldName);
if (oldGo != null)
{
oldGo.SetActive(false);
}
}
GameObject patrolParent = new GameObject("PatrolWaypoints");
patrolParent.transform.SetParent(parent);
// 20 Waypoints looping smoothly through all sections of the lab!
Vector3[] waypoints = new Vector3[]
{
new Vector3(0f, 0f, -20f), // WP0: South Concourse
new Vector3(-10f, 0f, -20f), // WP1: West Concourse
new Vector3(-20f, 0f, -26f), // WP2: Cryo Archive
new Vector3(-10f, 0f, -14f), // WP3: West Serpentine South
new Vector3(-20f, 0f, -10f), // WP4: Biochem Lab South
new Vector3(-20f, 0f, -2f), // WP5: Biochem Lab North
new Vector3(-10f, 0f, 4f), // WP6: West Serpentine North
new Vector3(-20f, 0f, 12f), // WP7: Bio-Containment South
new Vector3(-20f, 0f, 22f), // WP8: Bio-Containment North
new Vector3(-15f, 0f, 29.5f), // WP9: North Crawlway West
new Vector3(0f, 0f, 29.5f), // WP10: North Crawlway Center
new Vector3(15f, 0f, 29.5f), // WP11: North Crawlway East
new Vector3(20f, 0f, 25f), // WP12: Generator Room
new Vector3(20f, 0f, 12f), // WP13: Genetics Lab
new Vector3(0f, 0f, 21f), // WP14: Central Core North
new Vector3(0f, 0f, 13f), // WP15: Central Core South
new Vector3(10f, 0f, 4f), // WP16: East Serpentine North
new Vector3(20f, 0f, -6f), // WP17: Surgical Theatre
new Vector3(10f, 0f, -14f), // WP18: East Serpentine South
new Vector3(20f, 0f, -26f) // WP19: Security Office
};
Transform[] transforms = new Transform[waypoints.Length];
for (int i = 0; i < waypoints.Length; i++)
{
var wpGo = new GameObject($"Waypoint_{i}");
wpGo.transform.SetParent(patrolParent.transform);
wpGo.transform.position = waypoints[i];
transforms[i] = wpGo.transform;
}
if (enemy != null)
{
enemy.transform.position = new Vector3(0f, 0.5f, 17f); // Start mutant in Central Core
var ai = enemy.GetComponent<BlindMutantAI>();
if (ai != null)
{
ai.patrolPoints = transforms;
Debug.Log($"Configured {transforms.Length} patrol points on BlindMutantAI.");
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a3c64d1d83957dd4098c862118aabf51
@@ -0,0 +1,579 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;
using UnityEngine.Rendering.Universal;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
public static class MainMenuSceneBuilder
{
private static DefaultControls.Resources uiResources;
private static Font standardFont;
[MenuItem("Tools/Build Main Menu Scene")]
public static string BuildScene()
{
standardFont = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
uiResources = new DefaultControls.Resources
{
standard = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd"),
background = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Background.psd"),
knob = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd"),
checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Checkmark.psd"),
dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/DropdownArrow.psd"),
mask = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UIMask.psd")
};
// Создаем новую пустую сцену
Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
// 1. Камера
GameObject camGo = new GameObject("Main Camera");
Camera cam = camGo.AddComponent<Camera>();
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = new Color(0.035f, 0.05f, 0.075f, 1f);
camGo.AddComponent<UniversalAdditionalCameraData>();
camGo.AddComponent<AudioListener>();
camGo.tag = "MainCamera";
camGo.transform.position = new Vector3(0, 0, -10);
// 2. EventSystem
GameObject eventSysGo = new GameObject("EventSystem");
eventSysGo.AddComponent<EventSystem>();
eventSysGo.AddComponent<InputSystemUIInputModule>();
// 3. Canvas
GameObject canvasGo = new GameObject("Canvas");
Canvas canvas = canvasGo.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.pixelPerfect = true;
CanvasScaler scaler = canvasGo.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
scaler.matchWidthOrHeight = 0.5f;
canvasGo.AddComponent<GraphicRaycaster>();
// 4. Менеджер Главного Меню
GameObject managerGo = new GameObject("MainMenuManager");
MainMenuManager manager = managerGo.AddComponent<MainMenuManager>();
// 5. Задний фон Canvas
CreateImage("Background_Dark", canvasGo.transform,
new Color(0.025f, 0.04f, 0.065f, 1f),
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
// Декоративная подложка с мягким сине-зеленым свечением
CreateImage("Decor_Tint", canvasGo.transform,
new Color(0.00f, 0.45f, 0.60f, 0.06f),
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
// Декоративная неоновая полоса слева
CreateImage("AccentLine_Left", canvasGo.transform,
new Color(0.00f, 0.85f, 0.95f, 0.70f),
new Vector2(0f, 0f), new Vector2(0f, 1f),
new Vector2(6f, 0f), new Vector2(3f, 0f));
// Копирайт / версия в правом нижнем углу
CreateText("Version_Text", canvasGo.transform,
"Версия 1.0.0 | Лаборатория 'Эхо'",
14, FontStyle.Normal, TextAnchor.MiddleRight,
new Color(0.40f, 0.52f, 0.62f, 0.75f),
new Vector2(0.70f, 0.02f), new Vector2(0.98f, 0.06f), Vector2.zero, Vector2.zero);
// 6. Заголовок игры (Логотип и подзаголовок)
GameObject headerContainer = CreateEmptyRect("Header_Container", canvasGo.transform,
new Vector2(0.08f, 0.64f), new Vector2(0.55f, 0.90f), Vector2.zero, Vector2.zero);
CreateText("Title_Text", headerContainer.transform,
"ECHO // PROTOCOL",
48, FontStyle.Bold, TextAnchor.MiddleLeft,
new Color(0.92f, 0.97f, 1f, 1f),
new Vector2(0f, 0.40f), new Vector2(1f, 1f), Vector2.zero, Vector2.zero);
CreateText("Subtitle_Text", headerContainer.transform,
"ТАКТИЧЕСКИЙ СТЕЛС-ЭКШЕН • СЕКРЕТНЫЙ ОБЪЕКТ",
16, FontStyle.Normal, TextAnchor.MiddleLeft,
new Color(0.00f, 0.85f, 0.95f, 0.85f),
new Vector2(0f, 0.12f), new Vector2(1f, 0.40f), Vector2.zero, Vector2.zero);
CreateImage("Header_Divider", headerContainer.transform,
new Color(0.00f, 0.85f, 0.95f, 0.45f),
new Vector2(0f, 0.02f), new Vector2(0.85f, 0.05f), Vector2.zero, Vector2.zero);
// 7. Основная панель кнопок меню (MainMenuPanel)
GameObject mainMenuPanel = CreateEmptyRect("MainMenuPanel", canvasGo.transform,
new Vector2(0.08f, 0.18f), new Vector2(0.38f, 0.60f), Vector2.zero, Vector2.zero);
VerticalLayoutGroup menuLayout = mainMenuPanel.AddComponent<VerticalLayoutGroup>();
menuLayout.childAlignment = TextAnchor.UpperLeft;
menuLayout.spacing = 18f;
menuLayout.childControlWidth = true;
menuLayout.childControlHeight = false;
menuLayout.childForceExpandWidth = true;
menuLayout.childForceExpandHeight = false;
// Кнопка "ИГРАТЬ"
Button playBtn = CreateStyledButton("Button_Play", mainMenuPanel.transform,
"► ИГРАТЬ",
new Color(0.08f, 0.22f, 0.32f, 0.95f),
new Color(0.00f, 0.65f, 0.85f, 1.0f),
new Color(0.04f, 0.14f, 0.22f, 1.0f),
new Color(0.90f, 0.98f, 1.0f, 1.0f),
66f, 24);
// Кнопка "НАСТРОЙКИ"
Button settingsBtn = CreateStyledButton("Button_Settings", mainMenuPanel.transform,
"⚙ НАСТРОЙКИ",
new Color(0.07f, 0.12f, 0.18f, 0.90f),
new Color(0.18f, 0.38f, 0.52f, 1.0f),
new Color(0.04f, 0.08f, 0.12f, 1.0f),
new Color(0.85f, 0.92f, 0.98f, 1.0f),
62f, 22);
// Кнопка "ВЫХОД"
Button quitBtn = CreateStyledButton("Button_Quit", mainMenuPanel.transform,
"✖ ВЫХОД ИЗ ИГРЫ",
new Color(0.18f, 0.08f, 0.10f, 0.90f),
new Color(0.55f, 0.16f, 0.22f, 1.0f),
new Color(0.10f, 0.04f, 0.06f, 1.0f),
new Color(0.95f, 0.85f, 0.85f, 1.0f),
62f, 22);
// ==========================================
// 8. Панель настроек (SettingsPanel)
// ==========================================
GameObject settingsPanel = CreateEmptyRect("SettingsPanel", canvasGo.transform,
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
// Затемняющий фон
CreateImage("Backdrop_Dim", settingsPanel.transform,
new Color(0.01f, 0.02f, 0.03f, 0.78f),
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
// Модальное окно
GameObject settingsCard = CreateImage("Settings_Card", settingsPanel.transform,
new Color(0.05f, 0.08f, 0.12f, 0.98f),
new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f),
new Vector2(920f, 720f), Vector2.zero);
Outline panelOutline = settingsCard.AddComponent<Outline>();
panelOutline.effectColor = new Color(0.00f, 0.85f, 0.95f, 0.50f);
panelOutline.effectDistance = new Vector2(2f, -2f);
// Заголовок панели настроек
CreateText("Settings_Header", settingsCard.transform,
"НАСТРОЙКИ СИСТЕМЫ",
28, FontStyle.Bold, TextAnchor.MiddleCenter,
new Color(0.90f, 0.97f, 1.0f, 1.0f),
new Vector2(0.05f, 0.90f), new Vector2(0.95f, 0.98f), Vector2.zero, Vector2.zero);
CreateImage("Settings_Divider", settingsCard.transform,
new Color(0.00f, 0.85f, 0.95f, 0.35f),
new Vector2(0.05f, 0.89f), new Vector2(0.95f, 0.895f), Vector2.zero, Vector2.zero);
// Контейнер списка настроек
GameObject settingsList = CreateEmptyRect("Settings_List", settingsCard.transform,
new Vector2(0.06f, 0.14f), new Vector2(0.94f, 0.87f), Vector2.zero, Vector2.zero);
VerticalLayoutGroup settingsLayout = settingsList.AddComponent<VerticalLayoutGroup>();
settingsLayout.spacing = 16f;
settingsLayout.childAlignment = TextAnchor.UpperCenter;
settingsLayout.childControlWidth = true;
settingsLayout.childControlHeight = false;
settingsLayout.childForceExpandWidth = true;
settingsLayout.childForceExpandHeight = false;
// --- Раздел: Звук ---
CreateCategoryHeader("HEADER_AUDIO", settingsList.transform, "— АУДИО И ЗВУК —");
var volumeRow = CreateSliderRow("Row_Volume", settingsList.transform, "Общая громкость", 0f, 1f, 1f, "%");
Slider volSlider = volumeRow.slider;
Text volText = volumeRow.valueText;
Toggle muteToggle = CreateToggleRow("Row_Mute", settingsList.transform, "Отключить звук (Mute)");
// --- Раздел: Графика ---
CreateCategoryHeader("HEADER_GRAPHICS", settingsList.transform, "— ГРАФИКА И ДИСПЛЕЙ —");
Dropdown qualityDropdown = CreateDropdownRow("Row_Quality", settingsList.transform, "Качество графики");
Toggle fullscreenToggle = CreateToggleRow("Row_Fullscreen", settingsList.transform, "Полноэкранный режим");
Dropdown resolutionDropdown = CreateDropdownRow("Row_Resolution", settingsList.transform, "Разрешение экрана");
// --- Раздел: Управление ---
CreateCategoryHeader("HEADER_CONTROLS", settingsList.transform, "— УПРАВЛЕНИЕ —");
var sensRow = CreateSliderRow("Row_Sensitivity", settingsList.transform, "Чувствительность мыши", 0.2f, 3.0f, 1.0f, "x");
Slider sensSlider = sensRow.slider;
Text sensText = sensRow.valueText;
// Нижняя строка кнопок в панели настроек
GameObject bottomButtonsRow = CreateEmptyRect("Settings_BottomButtons", settingsCard.transform,
new Vector2(0.06f, 0.03f), new Vector2(0.94f, 0.12f), Vector2.zero, Vector2.zero);
HorizontalLayoutGroup bottomLayout = bottomButtonsRow.AddComponent<HorizontalLayoutGroup>();
bottomLayout.spacing = 30f;
bottomLayout.childAlignment = TextAnchor.MiddleCenter;
bottomLayout.childControlWidth = true;
bottomLayout.childControlHeight = true;
bottomLayout.childForceExpandWidth = true;
bottomLayout.childForceExpandHeight = true;
Button resetBtn = CreateStyledButton("Button_ResetDefaults", bottomButtonsRow.transform,
"Сбросить настройки",
new Color(0.18f, 0.12f, 0.14f, 0.95f),
new Color(0.35f, 0.18f, 0.22f, 1.0f),
new Color(0.12f, 0.06f, 0.08f, 1.0f),
new Color(0.95f, 0.85f, 0.85f, 1.0f),
50f, 18);
Button backBtn = CreateStyledButton("Button_Back", bottomButtonsRow.transform,
"✔ НАЗАД В МЕНЮ",
new Color(0.08f, 0.22f, 0.30f, 0.95f),
new Color(0.00f, 0.65f, 0.85f, 1.0f),
new Color(0.05f, 0.14f, 0.20f, 1.0f),
new Color(0.90f, 0.98f, 1.0f, 1.0f),
50f, 20);
// ==========================================
// 9. Панель загрузки (LoadingPanel)
// ==========================================
GameObject loadingPanel = CreateImage("LoadingPanel", canvasGo.transform,
new Color(0.02f, 0.03f, 0.05f, 0.97f),
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
GameObject loadingContainer = CreateEmptyRect("Loading_Container", loadingPanel.transform,
new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f),
new Vector2(600f, 200f), Vector2.zero);
CreateText("Loading_Title", loadingContainer.transform,
"ЗАГРУЗКА МИССИИ...",
28, FontStyle.Bold, TextAnchor.MiddleCenter,
new Color(0.00f, 0.85f, 0.95f, 1.0f),
new Vector2(0f, 0.60f), new Vector2(1f, 1f), Vector2.zero, Vector2.zero);
GameObject sliderObj = DefaultControls.CreateSlider(uiResources);
sliderObj.name = "Loading_ProgressBar";
sliderObj.transform.SetParent(loadingContainer.transform, false);
RectTransform sliderRt = sliderObj.GetComponent<RectTransform>();
sliderRt.anchorMin = new Vector2(0.05f, 0.35f);
sliderRt.anchorMax = new Vector2(0.95f, 0.55f);
sliderRt.offsetMin = Vector2.zero;
sliderRt.offsetMax = Vector2.zero;
Slider loadingSlider = sliderObj.GetComponent<Slider>();
loadingSlider.interactable = false;
Transform fillTransform = sliderObj.transform.Find("Fill Area/Fill");
if (fillTransform != null)
{
Image fillImg = fillTransform.GetComponent<Image>();
if (fillImg != null) fillImg.color = new Color(0.00f, 0.85f, 0.95f, 1f);
}
GameObject loadingPercent = CreateText("Loading_Text", loadingContainer.transform,
"0%",
18, FontStyle.Normal, TextAnchor.MiddleCenter,
new Color(0.80f, 0.90f, 1.0f, 0.9f),
new Vector2(0f, 0f), new Vector2(1f, 0.30f), Vector2.zero, Vector2.zero);
Text loadingText = loadingPercent.GetComponent<Text>();
// ==========================================
// 10. Привязка ссылок к MainMenuManager
// ==========================================
manager.headerContainer = headerContainer;
manager.mainMenuPanel = mainMenuPanel;
manager.settingsPanel = settingsPanel;
manager.loadingPanel = loadingPanel;
manager.gameSceneName = "SampleScene";
manager.loadingSlider = loadingSlider;
manager.loadingText = loadingText;
manager.volumeSlider = volSlider;
manager.volumeValueText = volText;
manager.muteToggle = muteToggle;
manager.qualityDropdown = qualityDropdown;
manager.fullscreenToggle = fullscreenToggle;
manager.resolutionDropdown = resolutionDropdown;
manager.sensitivitySlider = sensSlider;
manager.sensitivityValueText = sensText;
UnityEditor.Events.UnityEventTools.AddPersistentListener(playBtn.onClick, manager.PlayGame);
UnityEditor.Events.UnityEventTools.AddPersistentListener(settingsBtn.onClick, manager.OpenSettings);
UnityEditor.Events.UnityEventTools.AddPersistentListener(quitBtn.onClick, manager.QuitGame);
UnityEditor.Events.UnityEventTools.AddPersistentListener(backBtn.onClick, manager.CloseSettings);
UnityEditor.Events.UnityEventTools.AddPersistentListener(resetBtn.onClick, manager.ResetToDefaults);
// Изначальная видимость панелей
headerContainer.SetActive(true);
mainMenuPanel.SetActive(true);
settingsPanel.SetActive(false);
loadingPanel.SetActive(false);
// 11. Сохранение сцены и Build Settings
string scenePath = "Assets/Scenes/MainMenu.unity";
EditorSceneManager.SaveScene(newScene, scenePath);
Debug.Log("[MainMenuSceneBuilder] Сцена создана: " + scenePath);
List<EditorBuildSettingsScene> buildScenes = new List<EditorBuildSettingsScene>();
buildScenes.Add(new EditorBuildSettingsScene(scenePath, true));
buildScenes.Add(new EditorBuildSettingsScene("Assets/Scenes/SampleScene.unity", true));
EditorBuildSettings.scenes = buildScenes.ToArray();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return "SUCCESS: MainMenu created and configured!";
}
#region Хелперы создания UI элементов
private static GameObject CreateEmptyRect(string name, Transform parent, Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta, Vector2 anchoredPosition)
{
GameObject go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
RectTransform rt = go.GetComponent<RectTransform>();
rt.anchorMin = anchorMin;
rt.anchorMax = anchorMax;
rt.sizeDelta = sizeDelta;
rt.anchoredPosition = anchoredPosition;
return go;
}
private static GameObject CreateImage(string name, Transform parent, Color color, Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta, Vector2 anchoredPosition)
{
GameObject go = CreateEmptyRect(name, parent, anchorMin, anchorMax, sizeDelta, anchoredPosition);
Image img = go.AddComponent<Image>();
img.color = color;
img.sprite = uiResources.background;
img.type = Image.Type.Sliced;
return go;
}
private static GameObject CreateText(string name, Transform parent, string text, int fontSize, FontStyle style, TextAnchor alignment, Color color, Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta, Vector2 anchoredPosition)
{
GameObject go = CreateEmptyRect(name, parent, anchorMin, anchorMax, sizeDelta, anchoredPosition);
Text t = go.AddComponent<Text>();
t.font = standardFont;
t.text = text;
t.fontSize = fontSize;
t.fontStyle = style;
t.alignment = alignment;
t.color = color;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
return go;
}
private static Button CreateStyledButton(string name, Transform parent, string label, Color normalColor, Color highlightedColor, Color pressedColor, Color textColor, float height, int fontSize)
{
GameObject btnObj = DefaultControls.CreateButton(uiResources);
btnObj.name = name;
btnObj.transform.SetParent(parent, false);
LayoutElement layout = btnObj.AddComponent<LayoutElement>();
layout.minHeight = height;
layout.preferredHeight = height;
Image img = btnObj.GetComponent<Image>();
img.color = normalColor;
img.type = Image.Type.Sliced;
Button btn = btnObj.GetComponent<Button>();
ColorBlock colors = btn.colors;
colors.normalColor = normalColor;
colors.highlightedColor = highlightedColor;
colors.pressedColor = pressedColor;
colors.selectedColor = highlightedColor;
colors.colorMultiplier = 1f;
colors.fadeDuration = 0.12f;
btn.colors = colors;
Text text = btnObj.GetComponentInChildren<Text>();
if (text != null)
{
text.font = standardFont;
text.text = label;
text.fontSize = fontSize;
text.fontStyle = FontStyle.Bold;
text.color = textColor;
text.alignment = TextAnchor.MiddleCenter;
}
return btn;
}
private static void CreateCategoryHeader(string name, Transform parent, string text)
{
GameObject go = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 32f), Vector2.zero);
LayoutElement layout = go.AddComponent<LayoutElement>();
layout.minHeight = 32f;
layout.preferredHeight = 32f;
Text t = go.AddComponent<Text>();
t.font = standardFont;
t.text = text;
t.fontSize = 17;
t.fontStyle = FontStyle.Bold;
t.alignment = TextAnchor.MiddleLeft;
t.color = new Color(0.00f, 0.85f, 0.95f, 0.95f);
}
private struct SliderRow
{
public Slider slider;
public Text valueText;
}
private static SliderRow CreateSliderRow(string name, Transform parent, string label, float min, float max, float def, string unit)
{
GameObject row = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 42f), Vector2.zero);
LayoutElement layout = row.AddComponent<LayoutElement>();
layout.minHeight = 42f;
layout.preferredHeight = 42f;
HorizontalLayoutGroup hLayout = row.AddComponent<HorizontalLayoutGroup>();
hLayout.spacing = 18f;
hLayout.childAlignment = TextAnchor.MiddleLeft;
hLayout.childControlWidth = false;
hLayout.childControlHeight = true;
hLayout.childForceExpandWidth = false;
hLayout.childForceExpandHeight = true;
// Метка названия
GameObject lblGo = CreateEmptyRect("Label", row.transform, Vector2.zero, Vector2.one, new Vector2(280f, 42f), Vector2.zero);
LayoutElement lblLayout = lblGo.AddComponent<LayoutElement>();
lblLayout.minWidth = 280f;
lblLayout.preferredWidth = 280f;
Text lbl = lblGo.AddComponent<Text>();
lbl.font = standardFont;
lbl.text = label;
lbl.fontSize = 18;
lbl.alignment = TextAnchor.MiddleLeft;
lbl.color = new Color(0.85f, 0.92f, 0.98f, 1f);
// Slider
GameObject sliderObj = DefaultControls.CreateSlider(uiResources);
sliderObj.name = "Slider";
sliderObj.transform.SetParent(row.transform, false);
LayoutElement sliderLayout = sliderObj.AddComponent<LayoutElement>();
sliderLayout.minWidth = 360f;
sliderLayout.preferredWidth = 360f;
Slider slider = sliderObj.GetComponent<Slider>();
slider.minValue = min;
slider.maxValue = max;
slider.value = def;
// Значение текстом
GameObject valGo = CreateEmptyRect("ValueText", row.transform, Vector2.zero, Vector2.one, new Vector2(90f, 42f), Vector2.zero);
LayoutElement valLayout = valGo.AddComponent<LayoutElement>();
valLayout.minWidth = 90f;
valLayout.preferredWidth = 90f;
Text valText = valGo.AddComponent<Text>();
valText.font = standardFont;
valText.text = unit == "%" ? $"{Mathf.RoundToInt(def * 100)}%" : $"{def:F1}{unit}";
valText.fontSize = 18;
valText.fontStyle = FontStyle.Bold;
valText.alignment = TextAnchor.MiddleCenter;
valText.color = new Color(0.00f, 0.85f, 0.95f, 1f);
return new SliderRow { slider = slider, valueText = valText };
}
private static Toggle CreateToggleRow(string name, Transform parent, string label)
{
GameObject row = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 40f), Vector2.zero);
LayoutElement layout = row.AddComponent<LayoutElement>();
layout.minHeight = 40f;
layout.preferredHeight = 40f;
HorizontalLayoutGroup hLayout = row.AddComponent<HorizontalLayoutGroup>();
hLayout.spacing = 18f;
hLayout.childAlignment = TextAnchor.MiddleLeft;
hLayout.childControlWidth = false;
hLayout.childControlHeight = true;
hLayout.childForceExpandWidth = false;
hLayout.childForceExpandHeight = true;
// Метка названия
GameObject lblGo = CreateEmptyRect("Label", row.transform, Vector2.zero, Vector2.one, new Vector2(280f, 40f), Vector2.zero);
LayoutElement lblLayout = lblGo.AddComponent<LayoutElement>();
lblLayout.minWidth = 280f;
lblLayout.preferredWidth = 280f;
Text lbl = lblGo.AddComponent<Text>();
lbl.font = standardFont;
lbl.text = label;
lbl.fontSize = 18;
lbl.alignment = TextAnchor.MiddleLeft;
lbl.color = new Color(0.85f, 0.92f, 0.98f, 1f);
// Toggle
GameObject toggleObj = DefaultControls.CreateToggle(uiResources);
toggleObj.name = "Toggle";
toggleObj.transform.SetParent(row.transform, false);
LayoutElement toggleLayout = toggleObj.AddComponent<LayoutElement>();
toggleLayout.minWidth = 50f;
toggleLayout.preferredWidth = 50f;
Text toggleLabel = toggleObj.GetComponentInChildren<Text>();
if (toggleLabel != null) toggleLabel.text = "";
Toggle toggle = toggleObj.GetComponent<Toggle>();
return toggle;
}
private static Dropdown CreateDropdownRow(string name, Transform parent, string label)
{
GameObject row = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 44f), Vector2.zero);
LayoutElement layout = row.AddComponent<LayoutElement>();
layout.minHeight = 44f;
layout.preferredHeight = 44f;
HorizontalLayoutGroup hLayout = row.AddComponent<HorizontalLayoutGroup>();
hLayout.spacing = 18f;
hLayout.childAlignment = TextAnchor.MiddleLeft;
hLayout.childControlWidth = false;
hLayout.childControlHeight = true;
hLayout.childForceExpandWidth = false;
hLayout.childForceExpandHeight = true;
// Метка названия
GameObject lblGo = CreateEmptyRect("Label", row.transform, Vector2.zero, Vector2.one, new Vector2(280f, 44f), Vector2.zero);
LayoutElement lblLayout = lblGo.AddComponent<LayoutElement>();
lblLayout.minWidth = 280f;
lblLayout.preferredWidth = 280f;
Text lbl = lblGo.AddComponent<Text>();
lbl.font = standardFont;
lbl.text = label;
lbl.fontSize = 18;
lbl.alignment = TextAnchor.MiddleLeft;
lbl.color = new Color(0.85f, 0.92f, 0.98f, 1f);
// Dropdown
GameObject dropdownObj = DefaultControls.CreateDropdown(uiResources);
dropdownObj.name = "Dropdown";
dropdownObj.transform.SetParent(row.transform, false);
LayoutElement ddLayout = dropdownObj.AddComponent<LayoutElement>();
ddLayout.minWidth = 420f;
ddLayout.preferredWidth = 420f;
Dropdown dropdown = dropdownObj.GetComponent<Dropdown>();
Text caption = dropdown.captionText;
if (caption != null) caption.font = standardFont;
Text item = dropdown.itemText;
if (item != null) item.font = standardFont;
return dropdown;
}
#endregion
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1f74c7b4416e74b48a61ff45e7b3c88e
+462
View File
@@ -0,0 +1,462 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
public static class PauseMenuBuilder
{
private static DefaultControls.Resources uiResources;
private static Font standardFont;
[MenuItem("Tools/Add Pause Menu to SampleScene")]
public static string Build()
{
standardFont = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
uiResources = new DefaultControls.Resources
{
standard = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd"),
background = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Background.psd"),
knob = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd"),
checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Checkmark.psd"),
dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/DropdownArrow.psd"),
mask = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UIMask.psd")
};
// Открываем сцену геймплея
Scene gameplayScene = EditorSceneManager.OpenScene("Assets/Scenes/SampleScene.unity", OpenSceneMode.Single);
// Проверяем, есть ли уже EventSystem
if (Object.FindAnyObjectByType<EventSystem>() == null)
{
GameObject esGo = new GameObject("EventSystem");
esGo.AddComponent<EventSystem>();
esGo.AddComponent<InputSystemUIInputModule>();
}
// Удаляем старый PauseMenu, если был
var old = GameObject.Find("PauseCanvas");
if (old != null) Object.DestroyImmediate(old);
// Создаем Canvas паузы
GameObject canvasGo = new GameObject("PauseCanvas");
Canvas canvas = canvasGo.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 100; // Поверх всего
CanvasScaler scaler = canvasGo.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
scaler.matchWidthOrHeight = 0.5f;
canvasGo.AddComponent<GraphicRaycaster>();
PauseMenu pauseMenu = canvasGo.AddComponent<PauseMenu>();
// 1. Панель паузы (PauseMenuPanel)
GameObject pausePanel = CreateImage("PauseMenuPanel", canvasGo.transform,
new Color(0.02f, 0.035f, 0.055f, 0.88f),
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
GameObject card = CreateImage("Pause_Card", pausePanel.transform,
new Color(0.06f, 0.09f, 0.14f, 0.98f),
new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f),
new Vector2(460f, 520f), Vector2.zero);
Outline outline = card.AddComponent<Outline>();
outline.effectColor = new Color(0.00f, 0.85f, 0.95f, 0.45f);
outline.effectDistance = new Vector2(2f, -2f);
CreateText("Pause_Title", card.transform,
"ПАУЗА",
34, FontStyle.Bold, TextAnchor.MiddleCenter,
new Color(0.92f, 0.97f, 1f, 1f),
new Vector2(0.05f, 0.84f), new Vector2(0.95f, 0.96f), Vector2.zero, Vector2.zero);
CreateImage("Pause_Divider", card.transform,
new Color(0.00f, 0.85f, 0.95f, 0.40f),
new Vector2(0.10f, 0.82f), new Vector2(0.90f, 0.825f), Vector2.zero, Vector2.zero);
GameObject btnContainer = CreateEmptyRect("Buttons_Container", card.transform,
new Vector2(0.08f, 0.06f), new Vector2(0.92f, 0.78f), Vector2.zero, Vector2.zero);
VerticalLayoutGroup vLayout = btnContainer.AddComponent<VerticalLayoutGroup>();
vLayout.spacing = 16f;
vLayout.childAlignment = TextAnchor.MiddleCenter;
vLayout.childControlWidth = true;
vLayout.childControlHeight = false;
vLayout.childForceExpandWidth = true;
vLayout.childForceExpandHeight = false;
Button resumeBtn = CreateStyledButton("Btn_Resume", btnContainer.transform,
"► ПРОДОЛЖИТЬ",
new Color(0.08f, 0.22f, 0.32f, 0.95f),
new Color(0.00f, 0.65f, 0.85f, 1.0f),
new Color(0.04f, 0.14f, 0.22f, 1.0f),
new Color(0.90f, 0.98f, 1.0f, 1.0f),
60f, 22);
Button settingsBtn = CreateStyledButton("Btn_Settings", btnContainer.transform,
"⚙ НАСТРОЙКИ",
new Color(0.07f, 0.12f, 0.18f, 0.90f),
new Color(0.18f, 0.38f, 0.52f, 1.0f),
new Color(0.04f, 0.08f, 0.12f, 1.0f),
new Color(0.85f, 0.92f, 0.98f, 1.0f),
56f, 20);
Button menuBtn = CreateStyledButton("Btn_MainMenu", btnContainer.transform,
"⌂ ГЛАВНОЕ МЕНЮ",
new Color(0.07f, 0.12f, 0.18f, 0.90f),
new Color(0.18f, 0.38f, 0.52f, 1.0f),
new Color(0.04f, 0.08f, 0.12f, 1.0f),
new Color(0.85f, 0.92f, 0.98f, 1.0f),
56f, 20);
Button quitBtn = CreateStyledButton("Btn_Quit", btnContainer.transform,
"✖ ВЫХОД ИЗ ИГРЫ",
new Color(0.18f, 0.08f, 0.10f, 0.90f),
new Color(0.55f, 0.16f, 0.22f, 1.0f),
new Color(0.10f, 0.04f, 0.06f, 1.0f),
new Color(0.95f, 0.85f, 0.85f, 1.0f),
56f, 20);
// 2. Панель настроек (SettingsPanel)
GameObject settingsPanel = CreateEmptyRect("SettingsPanel", canvasGo.transform,
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
CreateImage("Backdrop_Dim", settingsPanel.transform,
new Color(0.01f, 0.02f, 0.03f, 0.80f),
Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
GameObject settingsCard = CreateImage("Settings_Card", settingsPanel.transform,
new Color(0.05f, 0.08f, 0.12f, 0.98f),
new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f),
new Vector2(880f, 680f), Vector2.zero);
Outline setOutline = settingsCard.AddComponent<Outline>();
setOutline.effectColor = new Color(0.00f, 0.85f, 0.95f, 0.50f);
setOutline.effectDistance = new Vector2(2f, -2f);
CreateText("Settings_Header", settingsCard.transform,
"НАСТРОЙКИ",
28, FontStyle.Bold, TextAnchor.MiddleCenter,
new Color(0.90f, 0.97f, 1.0f, 1.0f),
new Vector2(0.05f, 0.90f), new Vector2(0.95f, 0.98f), Vector2.zero, Vector2.zero);
CreateImage("Settings_Divider", settingsCard.transform,
new Color(0.00f, 0.85f, 0.95f, 0.35f),
new Vector2(0.05f, 0.89f), new Vector2(0.95f, 0.895f), Vector2.zero, Vector2.zero);
GameObject settingsList = CreateEmptyRect("Settings_List", settingsCard.transform,
new Vector2(0.06f, 0.14f), new Vector2(0.94f, 0.87f), Vector2.zero, Vector2.zero);
VerticalLayoutGroup sLayout = settingsList.AddComponent<VerticalLayoutGroup>();
sLayout.spacing = 16f;
sLayout.childAlignment = TextAnchor.UpperCenter;
sLayout.childControlWidth = true;
sLayout.childControlHeight = false;
sLayout.childForceExpandWidth = true;
sLayout.childForceExpandHeight = false;
// Разделы
CreateCategoryHeader("HEADER_AUDIO", settingsList.transform, "— АУДИО —");
var volumeRow = CreateSliderRow("Row_Volume", settingsList.transform, "Общая громкость", 0f, 1f, 1f, "%");
Toggle muteToggle = CreateToggleRow("Row_Mute", settingsList.transform, "Отключить звук");
CreateCategoryHeader("HEADER_GRAPHICS", settingsList.transform, "— ГРАФИКА —");
Dropdown qualityDropdown = CreateDropdownRow("Row_Quality", settingsList.transform, "Качество графики");
Toggle fullscreenToggle = CreateToggleRow("Row_Fullscreen", settingsList.transform, "Полноэкранный режим");
CreateCategoryHeader("HEADER_CONTROLS", settingsList.transform, "— УПРАВЛЕНИЕ —");
var sensRow = CreateSliderRow("Row_Sensitivity", settingsList.transform, "Чувствительность мыши", 0.2f, 3.0f, 1.0f, "x");
GameObject botRow = CreateEmptyRect("Settings_BottomButtons", settingsCard.transform,
new Vector2(0.06f, 0.03f), new Vector2(0.94f, 0.12f), Vector2.zero, Vector2.zero);
HorizontalLayoutGroup bLayout = botRow.AddComponent<HorizontalLayoutGroup>();
bLayout.spacing = 30f;
bLayout.childAlignment = TextAnchor.MiddleCenter;
bLayout.childControlWidth = true;
bLayout.childControlHeight = true;
Button backBtn = CreateStyledButton("Button_Back", botRow.transform,
"✔ НАЗАД В ПАУЗУ",
new Color(0.08f, 0.22f, 0.30f, 0.95f),
new Color(0.00f, 0.65f, 0.85f, 1.0f),
new Color(0.05f, 0.14f, 0.20f, 1.0f),
new Color(0.90f, 0.98f, 1.0f, 1.0f),
48f, 18);
// Привязываем ссылки
pauseMenu.pauseMenuPanel = pausePanel;
pauseMenu.settingsPanel = settingsPanel;
pauseMenu.volumeSlider = volumeRow.slider;
pauseMenu.volumeValueText = volumeRow.valueText;
pauseMenu.muteToggle = muteToggle;
pauseMenu.qualityDropdown = qualityDropdown;
pauseMenu.fullscreenToggle = fullscreenToggle;
pauseMenu.sensitivitySlider = sensRow.slider;
pauseMenu.sensitivityValueText = sensRow.valueText;
UnityEditor.Events.UnityEventTools.AddPersistentListener(resumeBtn.onClick, pauseMenu.ResumeGame);
UnityEditor.Events.UnityEventTools.AddPersistentListener(settingsBtn.onClick, pauseMenu.OpenSettings);
UnityEditor.Events.UnityEventTools.AddPersistentListener(menuBtn.onClick, pauseMenu.ReturnToMainMenu);
UnityEditor.Events.UnityEventTools.AddPersistentListener(quitBtn.onClick, pauseMenu.QuitGame);
UnityEditor.Events.UnityEventTools.AddPersistentListener(backBtn.onClick, pauseMenu.CloseSettings);
pausePanel.SetActive(false);
settingsPanel.SetActive(false);
// Сохраняем сцену геймплея
EditorSceneManager.SaveScene(gameplayScene);
Debug.Log("[PauseMenuBuilder] PauseMenu успешно добавлен в SampleScene.unity");
// Открываем обратно сцену MainMenu
EditorSceneManager.OpenScene("Assets/Scenes/MainMenu.unity", OpenSceneMode.Single);
return "SUCCESS: PauseMenu added to SampleScene and MainMenu restored!";
}
#region Хелперы UI
private static GameObject CreateEmptyRect(string name, Transform parent, Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta, Vector2 anchoredPosition)
{
GameObject go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
RectTransform rt = go.GetComponent<RectTransform>();
rt.anchorMin = anchorMin;
rt.anchorMax = anchorMax;
rt.sizeDelta = sizeDelta;
rt.anchoredPosition = anchoredPosition;
return go;
}
private static GameObject CreateImage(string name, Transform parent, Color color, Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta, Vector2 anchoredPosition)
{
GameObject go = CreateEmptyRect(name, parent, anchorMin, anchorMax, sizeDelta, anchoredPosition);
Image img = go.AddComponent<Image>();
img.color = color;
img.sprite = uiResources.background;
img.type = Image.Type.Sliced;
return go;
}
private static GameObject CreateText(string name, Transform parent, string text, int fontSize, FontStyle style, TextAnchor alignment, Color color, Vector2 anchorMin, Vector2 anchorMax, Vector2 sizeDelta, Vector2 anchoredPosition)
{
GameObject go = CreateEmptyRect(name, parent, anchorMin, anchorMax, sizeDelta, anchoredPosition);
Text t = go.AddComponent<Text>();
t.font = standardFont;
t.text = text;
t.fontSize = fontSize;
t.fontStyle = style;
t.alignment = alignment;
t.color = color;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
return go;
}
private static Button CreateStyledButton(string name, Transform parent, string label, Color normalColor, Color highlightedColor, Color pressedColor, Color textColor, float height, int fontSize)
{
GameObject btnObj = DefaultControls.CreateButton(uiResources);
btnObj.name = name;
btnObj.transform.SetParent(parent, false);
LayoutElement layout = btnObj.AddComponent<LayoutElement>();
layout.minHeight = height;
layout.preferredHeight = height;
Image img = btnObj.GetComponent<Image>();
img.color = normalColor;
img.type = Image.Type.Sliced;
Button btn = btnObj.GetComponent<Button>();
ColorBlock colors = btn.colors;
colors.normalColor = normalColor;
colors.highlightedColor = highlightedColor;
colors.pressedColor = pressedColor;
colors.selectedColor = highlightedColor;
colors.colorMultiplier = 1f;
colors.fadeDuration = 0.12f;
btn.colors = colors;
Text text = btnObj.GetComponentInChildren<Text>();
if (text != null)
{
text.font = standardFont;
text.text = label;
text.fontSize = fontSize;
text.fontStyle = FontStyle.Bold;
text.color = textColor;
text.alignment = TextAnchor.MiddleCenter;
}
return btn;
}
private static void CreateCategoryHeader(string name, Transform parent, string text)
{
GameObject go = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 30f), Vector2.zero);
LayoutElement layout = go.AddComponent<LayoutElement>();
layout.minHeight = 30f;
layout.preferredHeight = 30f;
Text t = go.AddComponent<Text>();
t.font = standardFont;
t.text = text;
t.fontSize = 16;
t.fontStyle = FontStyle.Bold;
t.alignment = TextAnchor.MiddleLeft;
t.color = new Color(0.00f, 0.85f, 0.95f, 0.95f);
}
private struct SliderRow
{
public Slider slider;
public Text valueText;
}
private static SliderRow CreateSliderRow(string name, Transform parent, string label, float min, float max, float def, string unit)
{
GameObject row = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 40f), Vector2.zero);
LayoutElement layout = row.AddComponent<LayoutElement>();
layout.minHeight = 40f;
layout.preferredHeight = 40f;
HorizontalLayoutGroup hLayout = row.AddComponent<HorizontalLayoutGroup>();
hLayout.spacing = 18f;
hLayout.childAlignment = TextAnchor.MiddleLeft;
hLayout.childControlWidth = false;
hLayout.childControlHeight = true;
hLayout.childForceExpandWidth = false;
hLayout.childForceExpandHeight = true;
GameObject lblGo = CreateEmptyRect("Label", row.transform, Vector2.zero, Vector2.one, new Vector2(260f, 40f), Vector2.zero);
LayoutElement lblLayout = lblGo.AddComponent<LayoutElement>();
lblLayout.minWidth = 260f;
lblLayout.preferredWidth = 260f;
Text lbl = lblGo.AddComponent<Text>();
lbl.font = standardFont;
lbl.text = label;
lbl.fontSize = 17;
lbl.alignment = TextAnchor.MiddleLeft;
lbl.color = new Color(0.85f, 0.92f, 0.98f, 1f);
GameObject sliderObj = DefaultControls.CreateSlider(uiResources);
sliderObj.name = "Slider";
sliderObj.transform.SetParent(row.transform, false);
LayoutElement sliderLayout = sliderObj.AddComponent<LayoutElement>();
sliderLayout.minWidth = 360f;
sliderLayout.preferredWidth = 360f;
Slider slider = sliderObj.GetComponent<Slider>();
slider.minValue = min;
slider.maxValue = max;
slider.value = def;
GameObject valGo = CreateEmptyRect("ValueText", row.transform, Vector2.zero, Vector2.one, new Vector2(80f, 40f), Vector2.zero);
LayoutElement valLayout = valGo.AddComponent<LayoutElement>();
valLayout.minWidth = 80f;
valLayout.preferredWidth = 80f;
Text valText = valGo.AddComponent<Text>();
valText.font = standardFont;
valText.text = unit == "%" ? $"{Mathf.RoundToInt(def * 100)}%" : $"{def:F1}{unit}";
valText.fontSize = 17;
valText.fontStyle = FontStyle.Bold;
valText.alignment = TextAnchor.MiddleCenter;
valText.color = new Color(0.00f, 0.85f, 0.95f, 1f);
return new SliderRow { slider = slider, valueText = valText };
}
private static Toggle CreateToggleRow(string name, Transform parent, string label)
{
GameObject row = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 38f), Vector2.zero);
LayoutElement layout = row.AddComponent<LayoutElement>();
layout.minHeight = 38f;
layout.preferredHeight = 38f;
HorizontalLayoutGroup hLayout = row.AddComponent<HorizontalLayoutGroup>();
hLayout.spacing = 18f;
hLayout.childAlignment = TextAnchor.MiddleLeft;
hLayout.childControlWidth = false;
hLayout.childControlHeight = true;
hLayout.childForceExpandWidth = false;
hLayout.childForceExpandHeight = true;
GameObject lblGo = CreateEmptyRect("Label", row.transform, Vector2.zero, Vector2.one, new Vector2(260f, 38f), Vector2.zero);
LayoutElement lblLayout = lblGo.AddComponent<LayoutElement>();
lblLayout.minWidth = 260f;
lblLayout.preferredWidth = 260f;
Text lbl = lblGo.AddComponent<Text>();
lbl.font = standardFont;
lbl.text = label;
lbl.fontSize = 17;
lbl.alignment = TextAnchor.MiddleLeft;
lbl.color = new Color(0.85f, 0.92f, 0.98f, 1f);
GameObject toggleObj = DefaultControls.CreateToggle(uiResources);
toggleObj.name = "Toggle";
toggleObj.transform.SetParent(row.transform, false);
LayoutElement toggleLayout = toggleObj.AddComponent<LayoutElement>();
toggleLayout.minWidth = 50f;
toggleLayout.preferredWidth = 50f;
Text toggleLabel = toggleObj.GetComponentInChildren<Text>();
if (toggleLabel != null) toggleLabel.text = "";
return toggleObj.GetComponent<Toggle>();
}
private static Dropdown CreateDropdownRow(string name, Transform parent, string label)
{
GameObject row = CreateEmptyRect(name, parent, Vector2.zero, Vector2.one, new Vector2(0f, 42f), Vector2.zero);
LayoutElement layout = row.AddComponent<LayoutElement>();
layout.minHeight = 42f;
layout.preferredHeight = 42f;
HorizontalLayoutGroup hLayout = row.AddComponent<HorizontalLayoutGroup>();
hLayout.spacing = 18f;
hLayout.childAlignment = TextAnchor.MiddleLeft;
hLayout.childControlWidth = false;
hLayout.childControlHeight = true;
hLayout.childForceExpandWidth = false;
hLayout.childForceExpandHeight = true;
GameObject lblGo = CreateEmptyRect("Label", row.transform, Vector2.zero, Vector2.one, new Vector2(260f, 42f), Vector2.zero);
LayoutElement lblLayout = lblGo.AddComponent<LayoutElement>();
lblLayout.minWidth = 260f;
lblLayout.preferredWidth = 260f;
Text lbl = lblGo.AddComponent<Text>();
lbl.font = standardFont;
lbl.text = label;
lbl.fontSize = 17;
lbl.alignment = TextAnchor.MiddleLeft;
lbl.color = new Color(0.85f, 0.92f, 0.98f, 1f);
GameObject dropdownObj = DefaultControls.CreateDropdown(uiResources);
dropdownObj.name = "Dropdown";
dropdownObj.transform.SetParent(row.transform, false);
LayoutElement ddLayout = dropdownObj.AddComponent<LayoutElement>();
ddLayout.minWidth = 380f;
ddLayout.preferredWidth = 380f;
Dropdown dropdown = dropdownObj.GetComponent<Dropdown>();
Text caption = dropdown.captionText;
if (caption != null) caption.font = standardFont;
Text item = dropdown.itemText;
if (item != null) item.font = standardFont;
return dropdown;
}
#endregion
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b79d9f06926eeac4e9bbcdc7b7ca7bba
+140
View File
@@ -0,0 +1,140 @@
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public static class SetupHealthBarHUD
{
[MenuItem("Tools/Setup Health Bar HUD")]
public static void Setup()
{
var existingCanvas = GameObject.Find("HUD_Canvas");
if (existingCanvas != null)
{
Object.DestroyImmediate(existingCanvas);
}
// Canvas
GameObject canvasGo = new GameObject("HUD_Canvas");
Canvas canvas = canvasGo.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
CanvasScaler scaler = canvasGo.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.matchWidthOrHeight = 0.5f;
canvasGo.AddComponent<GraphicRaycaster>();
// EventSystem
if (Object.FindAnyObjectByType<EventSystem>() == null)
{
GameObject esGo = new GameObject("EventSystem");
esGo.AddComponent<EventSystem>();
esGo.AddComponent<UnityEngine.InputSystem.UI.InputSystemUIInputModule>();
Undo.RegisterCreatedObjectUndo(esGo, "Create EventSystem");
}
// HealthBar Root Container (Top-Right)
GameObject hbContainer = new GameObject("HealthBar", typeof(RectTransform));
hbContainer.transform.SetParent(canvasGo.transform, false);
RectTransform hbRect = hbContainer.GetComponent<RectTransform>();
hbRect.anchorMin = new Vector2(1f, 1f);
hbRect.anchorMax = new Vector2(1f, 1f);
hbRect.pivot = new Vector2(1f, 1f);
hbRect.anchoredPosition = new Vector2(-40f, -40f);
hbRect.sizeDelta = new Vector2(280f, 36f);
// Background
GameObject bgGo = new GameObject("Background", typeof(RectTransform), typeof(Image));
bgGo.transform.SetParent(hbContainer.transform, false);
RectTransform bgRect = bgGo.GetComponent<RectTransform>();
bgRect.anchorMin = Vector2.zero;
bgRect.anchorMax = Vector2.one;
bgRect.offsetMin = Vector2.zero;
bgRect.offsetMax = Vector2.zero;
Image bgImg = bgGo.GetComponent<Image>();
bgImg.color = new Color(0.08f, 0.08f, 0.08f, 0.85f);
// Health Fill (Filled Image)
GameObject fillGo = new GameObject("HealthFill", typeof(RectTransform), typeof(Image));
fillGo.transform.SetParent(hbContainer.transform, false);
RectTransform fillRect = fillGo.GetComponent<RectTransform>();
fillRect.anchorMin = Vector2.zero;
fillRect.anchorMax = Vector2.one;
fillRect.offsetMin = new Vector2(4f, 4f);
fillRect.offsetMax = new Vector2(-4f, -4f);
Image fillImg = fillGo.GetComponent<Image>();
fillImg.type = Image.Type.Filled;
fillImg.fillMethod = Image.FillMethod.Horizontal;
fillImg.fillOrigin = (int)Image.OriginHorizontal.Left;
fillImg.fillAmount = 1f;
fillImg.color = new Color(0.2f, 0.85f, 0.3f, 1f);
// Text (Current / Max HP)
GameObject textGo = new GameObject("Text_HP", typeof(RectTransform), typeof(Text));
textGo.transform.SetParent(hbContainer.transform, false);
RectTransform textRect = textGo.GetComponent<RectTransform>();
textRect.anchorMin = Vector2.zero;
textRect.anchorMax = Vector2.one;
textRect.offsetMin = Vector2.zero;
textRect.offsetMax = Vector2.zero;
Text hpText = textGo.GetComponent<Text>();
hpText.text = "100 / 100";
hpText.alignment = TextAnchor.MiddleCenter;
hpText.fontSize = 20;
hpText.fontStyle = FontStyle.Bold;
hpText.color = Color.white;
Font defaultFont = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
if (defaultFont == null) defaultFont = Resources.GetBuiltinResource<Font>("Arial.ttf");
hpText.font = defaultFont;
// PlayerHealthUI
PlayerHealthUI uiComp = hbContainer.AddComponent<PlayerHealthUI>();
uiComp.healthFillImage = fillImg;
uiComp.healthText = hpText;
uiComp.playerHealth = Object.FindAnyObjectByType<PlayerHealth>();
// Crosshair / Center Cursor (Center of Screen)
GameObject crosshairGo = new GameObject("Crosshair", typeof(RectTransform));
crosshairGo.transform.SetParent(canvasGo.transform, false);
RectTransform crosshairRect = crosshairGo.GetComponent<RectTransform>();
crosshairRect.anchorMin = new Vector2(0.5f, 0.5f);
crosshairRect.anchorMax = new Vector2(0.5f, 0.5f);
crosshairRect.pivot = new Vector2(0.5f, 0.5f);
crosshairRect.anchoredPosition = Vector2.zero;
crosshairRect.sizeDelta = new Vector2(8f, 8f);
// Outline
GameObject chOutlineGo = new GameObject("Outline", typeof(RectTransform), typeof(Image));
chOutlineGo.transform.SetParent(crosshairGo.transform, false);
RectTransform chOutlineRect = chOutlineGo.GetComponent<RectTransform>();
chOutlineRect.anchorMin = Vector2.zero;
chOutlineRect.anchorMax = Vector2.one;
chOutlineRect.offsetMin = new Vector2(-1f, -1f);
chOutlineRect.offsetMax = new Vector2(1f, 1f);
Image chOutlineImg = chOutlineGo.GetComponent<Image>();
chOutlineImg.color = new Color(0f, 0f, 0f, 0.7f);
// Center Dot
GameObject chDotGo = new GameObject("Dot", typeof(RectTransform), typeof(Image));
chDotGo.transform.SetParent(crosshairGo.transform, false);
RectTransform chDotRect = chDotGo.GetComponent<RectTransform>();
chDotRect.anchorMin = Vector2.zero;
chDotRect.anchorMax = Vector2.one;
chDotRect.offsetMin = Vector2.zero;
chDotRect.offsetMax = Vector2.zero;
Image chDotImg = chDotGo.GetComponent<Image>();
chDotImg.color = new Color(1f, 1f, 1f, 0.95f);
// CrosshairUI component
CrosshairUI chScript = crosshairGo.AddComponent<CrosshairUI>();
chScript.dotImage = chDotImg;
chScript.outlineImage = chOutlineImg;
Undo.RegisterCreatedObjectUndo(canvasGo, "Create HUD_Canvas with HealthBar and Crosshair");
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(canvasGo.scene);
Debug.Log("HUD HealthBar и прицел в центре экрана успешно созданы!");
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4495f70ce2eb87d478a3ba7d4fd3f906
@@ -0,0 +1,233 @@
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
public static class SetupShootingAndAmmo
{
[MenuItem("Tools/Setup Shooting & Ammo System")]
public static void Setup()
{
// 1. Находим игрока (PlayerMovement)
PlayerMovement playerMovement = Object.FindAnyObjectByType<PlayerMovement>();
if (playerMovement == null)
{
Debug.LogError("[Setup] Не найден объект игрока с компонентом PlayerMovement!");
return;
}
GameObject playerGo = playerMovement.gameObject;
Undo.RegisterFullObjectHierarchyUndo(playerGo, "Setup Shooting");
// 2. Добавляем / настраиваем PlayerGun на игроке
PlayerGun playerGun = playerGo.GetComponent<PlayerGun>();
if (playerGun == null)
{
playerGun = playerGo.AddComponent<PlayerGun>();
}
// 3. Создаем плейсхолдер модель оружия (GunHolder), если еще нет
Transform existingGun = playerGo.transform.Find("GunHolder");
if (existingGun != null)
{
Object.DestroyImmediate(existingGun.gameObject);
}
GameObject gunHolder = new GameObject("GunHolder");
gunHolder.transform.SetParent(playerGo.transform, false);
// Позиционируем справа на уровне пояса / руки
gunHolder.transform.localPosition = new Vector3(0.35f, 1.0f, 0.45f);
gunHolder.transform.localRotation = Quaternion.identity;
// Создаем детали пистолета-заглушки
// А. Затвор / Ствол
GameObject slide = GameObject.CreatePrimitive(PrimitiveType.Cube);
slide.name = "Pistol_Slide";
slide.transform.SetParent(gunHolder.transform, false);
slide.transform.localPosition = new Vector3(0f, 0.05f, 0.1f);
slide.transform.localScale = new Vector3(0.08f, 0.08f, 0.3f);
Object.DestroyImmediate(slide.GetComponent<Collider>());
// Б. Рукоятка
GameObject grip = GameObject.CreatePrimitive(PrimitiveType.Cube);
grip.name = "Pistol_Grip";
grip.transform.SetParent(gunHolder.transform, false);
grip.transform.localPosition = new Vector3(0f, -0.05f, 0.02f);
grip.transform.localRotation = Quaternion.Euler(15f, 0f, 0f);
grip.transform.localScale = new Vector3(0.07f, 0.16f, 0.08f);
Object.DestroyImmediate(grip.GetComponent<Collider>());
// В. Ствол на конце
GameObject barrel = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
barrel.name = "Pistol_Barrel";
barrel.transform.SetParent(gunHolder.transform, false);
barrel.transform.localPosition = new Vector3(0f, 0.05f, 0.26f);
barrel.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
barrel.transform.localScale = new Vector3(0.04f, 0.04f, 0.04f);
Object.DestroyImmediate(barrel.GetComponent<Collider>());
// Точка вылета пули
GameObject muzzleGo = new GameObject("MuzzlePoint");
muzzleGo.transform.SetParent(gunHolder.transform, false);
muzzleGo.transform.localPosition = new Vector3(0f, 0.05f, 0.32f);
// Вспышка (свет)
GameObject flashGo = new GameObject("MuzzleFlashLight");
flashGo.transform.SetParent(muzzleGo.transform, false);
flashGo.transform.localPosition = Vector3.zero;
Light flashLight = flashGo.AddComponent<Light>();
flashLight.type = LightType.Point;
flashLight.color = new Color(1f, 0.85f, 0.4f);
flashLight.range = 5f;
flashLight.intensity = 3f;
flashLight.enabled = false;
// Назначаем ссылки в PlayerGun
playerGun.gunModelTransform = gunHolder.transform;
playerGun.muzzlePoint = muzzleGo.transform;
playerGun.muzzleFlashLight = flashLight;
playerGun.isGunEquipped = false;
playerGun.UpdateGunVisibility();
// Покрасим пистолет в стильный темный цвет
Material gunMat = new Material(Shader.Find("Universal Render Pipeline/Lit"));
if (gunMat.shader == null || !gunMat.shader.isSupported)
{
gunMat = new Material(Shader.Find("Standard"));
}
gunMat.color = new Color(0.15f, 0.16f, 0.18f, 1f);
slide.GetComponent<Renderer>().material = gunMat;
grip.GetComponent<Renderer>().material = gunMat;
barrel.GetComponent<Renderer>().material = gunMat;
// 4. Настраиваем UI патронов на HUD_Canvas
GameObject canvasGo = GameObject.Find("HUD_Canvas");
if (canvasGo == null)
{
SetupHealthBarHUD.Setup();
canvasGo = GameObject.Find("HUD_Canvas");
}
Transform existingAmmoUI = canvasGo.transform.Find("AmmoPanel");
if (existingAmmoUI != null)
{
Object.DestroyImmediate(existingAmmoUI.gameObject);
}
// Ammo Root Container (под полоской здоровья)
GameObject ammoContainer = new GameObject("AmmoPanel", typeof(RectTransform));
ammoContainer.transform.SetParent(canvasGo.transform, false);
RectTransform ammoRect = ammoContainer.GetComponent<RectTransform>();
ammoRect.anchorMin = new Vector2(1f, 1f);
ammoRect.anchorMax = new Vector2(1f, 1f);
ammoRect.pivot = new Vector2(1f, 1f);
ammoRect.anchoredPosition = new Vector2(-40f, -84f);
ammoRect.sizeDelta = new Vector2(280f, 40f);
// Background
GameObject bgGo = new GameObject("Background", typeof(RectTransform), typeof(Image));
bgGo.transform.SetParent(ammoContainer.transform, false);
RectTransform bgRect = bgGo.GetComponent<RectTransform>();
bgRect.anchorMin = Vector2.zero;
bgRect.anchorMax = Vector2.one;
bgRect.offsetMin = Vector2.zero;
bgRect.offsetMax = Vector2.zero;
Image bgImg = bgGo.GetComponent<Image>();
bgImg.color = new Color(0.08f, 0.08f, 0.08f, 0.85f);
Font defaultFont = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
if (defaultFont == null) defaultFont = Resources.GetBuiltinResource<Font>("Arial.ttf");
// Иконка / Лейбл "AMMO"
GameObject labelGo = new GameObject("Text_Label", typeof(RectTransform), typeof(Text));
labelGo.transform.SetParent(ammoContainer.transform, false);
RectTransform labelRect = labelGo.GetComponent<RectTransform>();
labelRect.anchorMin = new Vector2(0f, 0f);
labelRect.anchorMax = new Vector2(0.4f, 1f);
labelRect.offsetMin = new Vector2(12f, 0f);
labelRect.offsetMax = Vector2.zero;
Text labelText = labelGo.GetComponent<Text>();
labelText.text = "ПАТРОНЫ";
labelText.font = defaultFont;
labelText.fontSize = 14;
labelText.fontStyle = FontStyle.Bold;
labelText.alignment = TextAnchor.MiddleLeft;
labelText.color = new Color(0.7f, 0.7f, 0.7f, 0.9f);
// Текст патронов (7 / 21)
GameObject countGo = new GameObject("Text_Count", typeof(RectTransform), typeof(Text));
countGo.transform.SetParent(ammoContainer.transform, false);
RectTransform countRect = countGo.GetComponent<RectTransform>();
countRect.anchorMin = new Vector2(0.4f, 0f);
countRect.anchorMax = new Vector2(1f, 1f);
countRect.offsetMin = Vector2.zero;
countRect.offsetMax = new Vector2(-12f, 0f);
Text countText = countGo.GetComponent<Text>();
countText.text = "7 / 21";
countText.font = defaultFont;
countText.fontSize = 20;
countText.fontStyle = FontStyle.Bold;
countText.alignment = TextAnchor.MiddleRight;
countText.color = Color.white;
// Текст статуса / подсказки под панелью
GameObject statusGo = new GameObject("Text_Status", typeof(RectTransform), typeof(Text));
statusGo.transform.SetParent(ammoContainer.transform, false);
RectTransform statusRect = statusGo.GetComponent<RectTransform>();
statusRect.anchorMin = new Vector2(0f, 0f);
statusRect.anchorMax = new Vector2(1f, 0f);
statusRect.pivot = new Vector2(0.5f, 1f);
statusRect.anchoredPosition = new Vector2(0f, -4f);
statusRect.sizeDelta = new Vector2(280f, 22f);
Text statusText = statusGo.GetComponent<Text>();
statusText.text = "";
statusText.font = defaultFont;
statusText.fontSize = 13;
statusText.fontStyle = FontStyle.Bold;
statusText.alignment = TextAnchor.MiddleRight;
statusText.color = new Color(1f, 0.85f, 0.2f, 1f);
// PlayerAmmoUI компонент
PlayerAmmoUI ammoUI = ammoContainer.AddComponent<PlayerAmmoUI>();
ammoUI.playerGun = playerGun;
ammoUI.ammoText = countText;
ammoUI.statusText = statusText;
// 5. Создаем 2 коробки с патронами на уровне рядом с игроком
CreateAmmoBox(playerGo.transform.position + playerGo.transform.forward * 3f + playerGo.transform.right * 1.5f, 14);
CreateAmmoBox(playerGo.transform.position + playerGo.transform.forward * 6f - playerGo.transform.right * 2f, 21);
Undo.RegisterCreatedObjectUndo(gunHolder, "Create Gun Holder");
Undo.RegisterCreatedObjectUndo(ammoContainer, "Create Ammo HUD");
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(playerGo.scene);
Debug.Log("<color=green>[Setup] Механика стрельбы, пистолет, патроны и UI успешно настроены!</color>");
}
private static void CreateAmmoBox(Vector3 position, int ammoCount)
{
GameObject boxGo = GameObject.CreatePrimitive(PrimitiveType.Cube);
boxGo.name = $"AmmoBox_({ammoCount})";
boxGo.transform.position = position + Vector3.up * 0.25f;
boxGo.transform.localScale = new Vector3(0.4f, 0.3f, 0.3f);
// Коллайдер делаем триггером
Collider col = boxGo.GetComponent<Collider>();
col.isTrigger = true;
// Скрипт подбора
AmmoPickup pickup = boxGo.AddComponent<AmmoPickup>();
pickup.ammoAmount = ammoCount;
pickup.pickupOnTouch = true;
// Военный зеленый / оранжевый материал
Material boxMat = new Material(Shader.Find("Universal Render Pipeline/Lit"));
if (boxMat.shader == null || !boxMat.shader.isSupported)
{
boxMat = new Material(Shader.Find("Standard"));
}
boxMat.color = new Color(0.2f, 0.45f, 0.25f, 1f); // Темно-зеленый армейский ящик
boxGo.GetComponent<Renderer>().material = boxMat;
Undo.RegisterCreatedObjectUndo(boxGo, "Create Ammo Box");
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 41488dce66056594a89389df1a6bc9cb
+51
View File
@@ -0,0 +1,51 @@
using UnityEngine;
public static class GameSettings
{
public const string KeyMasterVolume = "Settings_MasterVolume";
public const string KeyIsMuted = "Settings_IsMuted";
public const string KeyQualityLevel = "Settings_QualityLevel";
public const string KeyFullscreen = "Settings_Fullscreen";
public const string KeyResolutionWidth = "Settings_ResolutionWidth";
public const string KeyResolutionHeight = "Settings_ResolutionHeight";
public const string KeyResolutionRefresh = "Settings_ResolutionRefresh";
public const string KeyMouseSensitivity = "Settings_MouseSensitivity";
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void ApplyAllSettings()
{
// 1. Звук
float volume = PlayerPrefs.GetFloat(KeyMasterVolume, 1.0f);
bool isMuted = PlayerPrefs.GetInt(KeyIsMuted, 0) == 1;
AudioListener.volume = isMuted ? 0f : Mathf.Clamp01(volume);
// 2. Качество графики
if (PlayerPrefs.HasKey(KeyQualityLevel))
{
int quality = PlayerPrefs.GetInt(KeyQualityLevel);
if (quality >= 0 && quality < QualitySettings.names.Length)
{
QualitySettings.SetQualityLevel(quality, true);
}
}
// 3. Полноэкранный режим и разрешение
bool isFullscreen = PlayerPrefs.GetInt(KeyFullscreen, Screen.fullScreen ? 1 : 0) == 1;
int width = PlayerPrefs.GetInt(KeyResolutionWidth, Screen.currentResolution.width);
int height = PlayerPrefs.GetInt(KeyResolutionHeight, Screen.currentResolution.height);
if (width > 0 && height > 0)
{
Screen.SetResolution(width, height, isFullscreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed);
}
else
{
Screen.fullScreen = isFullscreen;
}
}
public static float GetMouseSensitivity()
{
return PlayerPrefs.GetFloat(KeyMouseSensitivity, 1.0f);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a358f3fa58ca3c47a4d73e748ef4bd8
+430
View File
@@ -0,0 +1,430 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MainMenuManager : MonoBehaviour
{
[Header("Панели")]
public GameObject mainMenuPanel;
public GameObject headerContainer;
public GameObject settingsPanel;
public GameObject loadingPanel;
[Header("Загрузка")]
public string gameSceneName = "SampleScene";
public Slider loadingSlider;
public Text loadingText;
[Header("Настройки: Звук")]
public Slider volumeSlider;
public Text volumeValueText;
public Toggle muteToggle;
[Header("Настройки: Графика")]
public Dropdown qualityDropdown;
public Toggle fullscreenToggle;
public Dropdown resolutionDropdown;
[Header("Настройки: Управление")]
public Slider sensitivitySlider;
public Text sensitivityValueText;
private Resolution[] availableResolutions;
private List<Resolution> filteredResolutions = new List<Resolution>();
private bool isInitializing = false;
private void Awake()
{
// Разблокируем курсор и гарантируем нормальный ход времени
Time.timeScale = 1f;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
private void Start()
{
isInitializing = true;
if (mainMenuPanel != null) mainMenuPanel.SetActive(true);
if (settingsPanel != null) settingsPanel.SetActive(false);
if (loadingPanel != null) loadingPanel.SetActive(false);
InitializeSettingsUI();
isInitializing = false;
}
#region Основное меню
public void PlayGame()
{
if (!string.IsNullOrEmpty(gameSceneName))
{
StartCoroutine(LoadSceneRoutine(gameSceneName));
}
else
{
SceneManager.LoadScene(1);
}
}
public void OpenSettings()
{
if (mainMenuPanel != null) mainMenuPanel.SetActive(false);
if (headerContainer != null) headerContainer.SetActive(false);
if (settingsPanel != null) settingsPanel.SetActive(true);
}
public void CloseSettings()
{
PlayerPrefs.Save();
if (settingsPanel != null) settingsPanel.SetActive(false);
if (headerContainer != null) headerContainer.SetActive(true);
if (mainMenuPanel != null) mainMenuPanel.SetActive(true);
}
public void QuitGame()
{
PlayerPrefs.Save();
Debug.Log("[MainMenu] Выход из игры вызван.");
Application.Quit();
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
private IEnumerator LoadSceneRoutine(string sceneName)
{
if (loadingPanel != null)
{
loadingPanel.SetActive(true);
if (mainMenuPanel != null) mainMenuPanel.SetActive(false);
if (settingsPanel != null) settingsPanel.SetActive(false);
}
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
if (asyncLoad == null)
{
Debug.LogError($"[MainMenu] Не удалось запустить загрузку сцены '{sceneName}'.");
yield break;
}
asyncLoad.allowSceneActivation = false;
while (!asyncLoad.isDone)
{
float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f);
if (loadingSlider != null)
{
loadingSlider.value = progress;
}
if (loadingText != null)
{
loadingText.text = $"Загрузка операции... {Mathf.RoundToInt(progress * 100)}%";
}
// Когда загрузка завершена на 90% (внутренний предел Unity до активации)
if (asyncLoad.progress >= 0.9f)
{
if (loadingText != null)
{
loadingText.text = "Инициализация локации...";
}
yield return new WaitForSecondsRealtime(0.35f);
asyncLoad.allowSceneActivation = true;
}
yield return null;
}
}
#endregion
#region Настройки
private void InitializeSettingsUI()
{
// 1. Громкость и Mute
float savedVolume = PlayerPrefs.GetFloat(GameSettings.KeyMasterVolume, 1.0f);
bool savedMute = PlayerPrefs.GetInt(GameSettings.KeyIsMuted, 0) == 1;
if (volumeSlider != null)
{
volumeSlider.minValue = 0f;
volumeSlider.maxValue = 1f;
volumeSlider.value = savedVolume;
volumeSlider.onValueChanged.AddListener(OnVolumeChanged);
}
if (muteToggle != null)
{
muteToggle.isOn = savedMute;
muteToggle.onValueChanged.AddListener(OnMuteChanged);
}
UpdateVolumeLabel(savedVolume, savedMute);
AudioListener.volume = savedMute ? 0f : savedVolume;
// 2. Качество графики
if (qualityDropdown != null)
{
qualityDropdown.ClearOptions();
List<string> qualityOptions = new List<string>();
string[] names = QualitySettings.names;
// Локализованные названия или имена из проекта
for (int i = 0; i < names.Length; i++)
{
qualityOptions.Add(TranslateQualityName(names[i]));
}
qualityDropdown.AddOptions(qualityOptions);
int currentQuality = PlayerPrefs.GetInt(GameSettings.KeyQualityLevel, QualitySettings.GetQualityLevel());
currentQuality = Mathf.Clamp(currentQuality, 0, names.Length - 1);
qualityDropdown.value = currentQuality;
qualityDropdown.RefreshShownValue();
qualityDropdown.onValueChanged.AddListener(OnQualityChanged);
}
// 3. Полноэкранный режим
bool isFullscreen = PlayerPrefs.GetInt(GameSettings.KeyFullscreen, Screen.fullScreen ? 1 : 0) == 1;
if (fullscreenToggle != null)
{
fullscreenToggle.isOn = isFullscreen;
fullscreenToggle.onValueChanged.AddListener(OnFullscreenChanged);
}
// 4. Разрешения экрана
PopulateResolutions();
// 5. Чувствительность мыши
float savedSens = PlayerPrefs.GetFloat(GameSettings.KeyMouseSensitivity, 1.0f);
if (sensitivitySlider != null)
{
sensitivitySlider.minValue = 0.2f;
sensitivitySlider.maxValue = 3.0f;
sensitivitySlider.value = savedSens;
sensitivitySlider.onValueChanged.AddListener(OnSensitivityChanged);
}
UpdateSensitivityLabel(savedSens);
}
private void PopulateResolutions()
{
if (resolutionDropdown == null) return;
resolutionDropdown.ClearOptions();
availableResolutions = Screen.resolutions;
filteredResolutions.Clear();
List<string> options = new List<string>();
int currentResolutionIndex = 0;
int currentWidth = Screen.currentResolution.width;
int currentHeight = Screen.currentResolution.height;
int savedWidth = PlayerPrefs.GetInt(GameSettings.KeyResolutionWidth, currentWidth);
int savedHeight = PlayerPrefs.GetInt(GameSettings.KeyResolutionHeight, currentHeight);
// Фильтруем дубликаты разрешений (с разной частотой обновления)
HashSet<string> seen = new HashSet<string>();
for (int i = availableResolutions.Length - 1; i >= 0; i--)
{
var res = availableResolutions[i];
string key = $"{res.width}x{res.height}";
if (!seen.Contains(key))
{
seen.Add(key);
filteredResolutions.Insert(0, res);
}
}
// Если разрешений нет (например в некоторых режимах редактора), добавляем стандартные
if (filteredResolutions.Count == 0)
{
Resolution fallback = new Resolution { width = 1920, height = 1080 };
filteredResolutions.Add(fallback);
}
for (int i = 0; i < filteredResolutions.Count; i++)
{
var res = filteredResolutions[i];
string option = $"{res.width} × {res.height}";
options.Add(option);
if (res.width == savedWidth && res.height == savedHeight)
{
currentResolutionIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
resolutionDropdown.onValueChanged.AddListener(OnResolutionChanged);
}
public void OnVolumeChanged(float val)
{
if (isInitializing) return;
PlayerPrefs.SetFloat(GameSettings.KeyMasterVolume, val);
bool isMuted = muteToggle != null && muteToggle.isOn;
if (!isMuted)
{
AudioListener.volume = val;
}
UpdateVolumeLabel(val, isMuted);
}
public void OnMuteChanged(bool isMuted)
{
if (isInitializing) return;
PlayerPrefs.SetInt(GameSettings.KeyIsMuted, isMuted ? 1 : 0);
float currentVol = volumeSlider != null ? volumeSlider.value : 1.0f;
AudioListener.volume = isMuted ? 0f : currentVol;
UpdateVolumeLabel(currentVol, isMuted);
}
private void UpdateVolumeLabel(float volume, bool isMuted)
{
if (volumeValueText != null)
{
if (isMuted)
{
volumeValueText.text = "ВЫКЛ";
}
else
{
volumeValueText.text = $"{Mathf.RoundToInt(volume * 100)}%";
}
}
}
public void OnQualityChanged(int index)
{
if (isInitializing) return;
QualitySettings.SetQualityLevel(index, true);
PlayerPrefs.SetInt(GameSettings.KeyQualityLevel, index);
}
public void OnFullscreenChanged(bool isFullscreen)
{
if (isInitializing) return;
Screen.fullScreen = isFullscreen;
PlayerPrefs.SetInt(GameSettings.KeyFullscreen, isFullscreen ? 1 : 0);
}
public void OnResolutionChanged(int index)
{
if (isInitializing) return;
if (index < 0 || index >= filteredResolutions.Count) return;
Resolution res = filteredResolutions[index];
bool isFullscreen = fullscreenToggle != null ? fullscreenToggle.isOn : Screen.fullScreen;
Screen.SetResolution(res.width, res.height, isFullscreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed);
PlayerPrefs.SetInt(GameSettings.KeyResolutionWidth, res.width);
PlayerPrefs.SetInt(GameSettings.KeyResolutionHeight, res.height);
}
public void OnSensitivityChanged(float val)
{
if (isInitializing) return;
PlayerPrefs.SetFloat(GameSettings.KeyMouseSensitivity, val);
UpdateSensitivityLabel(val);
}
private void UpdateSensitivityLabel(float val)
{
if (sensitivityValueText != null)
{
sensitivityValueText.text = $"{val:F1}x";
}
}
public void ResetToDefaults()
{
isInitializing = true;
// Сброс звука
if (volumeSlider != null) volumeSlider.value = 1.0f;
if (muteToggle != null) muteToggle.isOn = false;
AudioListener.volume = 1.0f;
PlayerPrefs.SetFloat(GameSettings.KeyMasterVolume, 1.0f);
PlayerPrefs.SetInt(GameSettings.KeyIsMuted, 0);
UpdateVolumeLabel(1.0f, false);
// Сброс графики (максимальное качество)
int highestQuality = QualitySettings.names.Length - 1;
if (qualityDropdown != null)
{
qualityDropdown.value = highestQuality;
qualityDropdown.RefreshShownValue();
}
QualitySettings.SetQualityLevel(highestQuality, true);
PlayerPrefs.SetInt(GameSettings.KeyQualityLevel, highestQuality);
// Сброс полного экрана
if (fullscreenToggle != null)
{
fullscreenToggle.isOn = true;
}
Screen.fullScreen = true;
PlayerPrefs.SetInt(GameSettings.KeyFullscreen, 1);
// Сброс разрешения (родное)
if (resolutionDropdown != null && filteredResolutions.Count > 0)
{
int lastIndex = filteredResolutions.Count - 1;
resolutionDropdown.value = lastIndex;
resolutionDropdown.RefreshShownValue();
var res = filteredResolutions[lastIndex];
Screen.SetResolution(res.width, res.height, FullScreenMode.FullScreenWindow);
PlayerPrefs.SetInt(GameSettings.KeyResolutionWidth, res.width);
PlayerPrefs.SetInt(GameSettings.KeyResolutionHeight, res.height);
}
// Сброс чувствительности
if (sensitivitySlider != null)
{
sensitivitySlider.value = 1.0f;
}
PlayerPrefs.SetFloat(GameSettings.KeyMouseSensitivity, 1.0f);
UpdateSensitivityLabel(1.0f);
PlayerPrefs.Save();
isInitializing = false;
}
private string TranslateQualityName(string unityName)
{
switch (unityName.ToLower())
{
case "very low": return "Очень низкое";
case "low": return "Низкое";
case "medium": return "Среднее";
case "high": return "Высокое";
case "very high": return "Очень высокое";
case "ultra": return "Ультра";
default: return unityName;
}
}
#endregion
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 184bffc58f97dd54b96740a6289afda6
+22 -6
View File
@@ -1,21 +1,37 @@
using UnityEngine;
using UnityEngine;
public class MutantHealth : MonoBehaviour
{
public float maxHealth = 50f;
private float currentHealth;
void Start() { currentHealth = maxHealth; }
public bool IsDead => currentHealth <= 0;
public float CurrentHealth => currentHealth;
public void TakeDamage(float damage)
private BlindMutantAI mutantAI;
void Awake()
{
currentHealth = maxHealth;
mutantAI = GetComponent<BlindMutantAI>();
}
public void TakeDamage(float damage, Transform attacker = null)
{
if (IsDead) return;
currentHealth -= damage;
Debug.Log("Мутант получил урон! Осталось: " + currentHealth);
Debug.Log($"Мутант получил урон: {damage}! Осталось: {currentHealth}");
if (mutantAI != null && attacker != null)
{
mutantAI.OnDamagedByPlayer(attacker);
}
if (currentHealth <= 0)
{
Debug.Log("МУТАНТ УМЕР!");
Destroy(gameObject); // Уничтожаем модельку мутанта
Destroy(gameObject);
}
}
}
+243
View File
@@ -0,0 +1,243 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;
public class PauseMenu : MonoBehaviour
{
[Header("Панели")]
public GameObject pauseMenuPanel;
public GameObject settingsPanel;
[Header("Настройки: Звук")]
public Slider volumeSlider;
public Text volumeValueText;
public Toggle muteToggle;
[Header("Настройки: Графика")]
public Dropdown qualityDropdown;
public Toggle fullscreenToggle;
[Header("Настройки: Управление")]
public Slider sensitivitySlider;
public Text sensitivityValueText;
private bool isPaused = false;
private bool isInitializing = false;
public bool IsPaused => isPaused;
private void Start()
{
if (pauseMenuPanel != null) pauseMenuPanel.SetActive(false);
if (settingsPanel != null) settingsPanel.SetActive(false);
InitializeSettingsUI();
}
private void Update()
{
var keyboard = Keyboard.current;
if (keyboard != null && keyboard.escapeKey.wasPressedThisFrame)
{
if (isPaused)
{
if (settingsPanel != null && settingsPanel.activeSelf)
{
CloseSettings();
}
else
{
ResumeGame();
}
}
else
{
PauseGame();
}
}
}
public void PauseGame()
{
isPaused = true;
Time.timeScale = 0f;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
if (pauseMenuPanel != null) pauseMenuPanel.SetActive(true);
if (settingsPanel != null) settingsPanel.SetActive(false);
}
public void ResumeGame()
{
isPaused = false;
Time.timeScale = 1f;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
if (pauseMenuPanel != null) pauseMenuPanel.SetActive(false);
if (settingsPanel != null) settingsPanel.SetActive(false);
}
public void OpenSettings()
{
if (pauseMenuPanel != null) pauseMenuPanel.SetActive(false);
if (settingsPanel != null) settingsPanel.SetActive(true);
}
public void CloseSettings()
{
PlayerPrefs.Save();
if (settingsPanel != null) settingsPanel.SetActive(false);
if (pauseMenuPanel != null) pauseMenuPanel.SetActive(true);
}
public void ReturnToMainMenu()
{
Time.timeScale = 1f;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
SceneManager.LoadScene("MainMenu");
}
public void QuitGame()
{
PlayerPrefs.Save();
Application.Quit();
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
private void InitializeSettingsUI()
{
isInitializing = true;
// Звук
float savedVolume = PlayerPrefs.GetFloat(GameSettings.KeyMasterVolume, 1.0f);
bool savedMute = PlayerPrefs.GetInt(GameSettings.KeyIsMuted, 0) == 1;
if (volumeSlider != null)
{
volumeSlider.minValue = 0f;
volumeSlider.maxValue = 1f;
volumeSlider.value = savedVolume;
volumeSlider.onValueChanged.AddListener(OnVolumeChanged);
}
if (muteToggle != null)
{
muteToggle.isOn = savedMute;
muteToggle.onValueChanged.AddListener(OnMuteChanged);
}
UpdateVolumeLabel(savedVolume, savedMute);
// Качество графики
if (qualityDropdown != null)
{
qualityDropdown.ClearOptions();
List<string> options = new List<string>();
foreach (var q in QualitySettings.names)
{
options.Add(TranslateQuality(q));
}
qualityDropdown.AddOptions(options);
qualityDropdown.value = PlayerPrefs.GetInt(GameSettings.KeyQualityLevel, QualitySettings.GetQualityLevel());
qualityDropdown.RefreshShownValue();
qualityDropdown.onValueChanged.AddListener(OnQualityChanged);
}
// Полноэкранный режим
if (fullscreenToggle != null)
{
fullscreenToggle.isOn = PlayerPrefs.GetInt(GameSettings.KeyFullscreen, Screen.fullScreen ? 1 : 0) == 1;
fullscreenToggle.onValueChanged.AddListener(OnFullscreenChanged);
}
// Чувствительность
float savedSens = PlayerPrefs.GetFloat(GameSettings.KeyMouseSensitivity, 1.0f);
if (sensitivitySlider != null)
{
sensitivitySlider.minValue = 0.2f;
sensitivitySlider.maxValue = 3.0f;
sensitivitySlider.value = savedSens;
sensitivitySlider.onValueChanged.AddListener(OnSensitivityChanged);
}
UpdateSensitivityLabel(savedSens);
isInitializing = false;
}
private void OnVolumeChanged(float val)
{
if (isInitializing) return;
PlayerPrefs.SetFloat(GameSettings.KeyMasterVolume, val);
bool isMuted = muteToggle != null && muteToggle.isOn;
if (!isMuted) AudioListener.volume = val;
UpdateVolumeLabel(val, isMuted);
}
private void OnMuteChanged(bool isMuted)
{
if (isInitializing) return;
PlayerPrefs.SetInt(GameSettings.KeyIsMuted, isMuted ? 1 : 0);
float currentVol = volumeSlider != null ? volumeSlider.value : 1.0f;
AudioListener.volume = isMuted ? 0f : currentVol;
UpdateVolumeLabel(currentVol, isMuted);
}
private void UpdateVolumeLabel(float vol, bool muted)
{
if (volumeValueText != null)
{
volumeValueText.text = muted ? "ВЫКЛ" : $"{Mathf.RoundToInt(vol * 100)}%";
}
}
private void OnQualityChanged(int index)
{
if (isInitializing) return;
QualitySettings.SetQualityLevel(index, true);
PlayerPrefs.SetInt(GameSettings.KeyQualityLevel, index);
}
private void OnFullscreenChanged(bool isFullscreen)
{
if (isInitializing) return;
Screen.fullScreen = isFullscreen;
PlayerPrefs.SetInt(GameSettings.KeyFullscreen, isFullscreen ? 1 : 0);
}
private void OnSensitivityChanged(float val)
{
if (isInitializing) return;
PlayerPrefs.SetFloat(GameSettings.KeyMouseSensitivity, val);
UpdateSensitivityLabel(val);
}
private void UpdateSensitivityLabel(float val)
{
if (sensitivityValueText != null)
{
sensitivityValueText.text = $"{val:F1}x";
}
}
private string TranslateQuality(string q)
{
switch (q.ToLower())
{
case "very low": return "Очень низкое";
case "low": return "Низкое";
case "medium": return "Среднее";
case "high": return "Высокое";
case "very high": return "Очень высокое";
case "ultra": return "Ультра";
default: return q;
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c414c251468433948a0f88741b8366df
+127
View File
@@ -0,0 +1,127 @@
using UnityEngine;
using UnityEngine.UI;
public class PlayerAmmoUI : MonoBehaviour
{
[Header("Ссылки")]
public PlayerGun playerGun;
public Text ammoText;
public Text statusText;
public Image ammoIcon;
[Header("Цвета")]
public Color normalColor = Color.white;
public Color lowAmmoColor = new Color(1f, 0.6f, 0.1f, 1f); // Оранжевый при малом запасе
public Color noAmmoColor = new Color(0.95f, 0.2f, 0.2f, 1f); // Красный когда пусто
public Color reloadingColor = new Color(1f, 0.85f, 0.2f, 1f); // Желтый при перезарядке
void Start()
{
if (playerGun == null)
{
playerGun = FindAnyObjectByType<PlayerGun>();
}
UpdateAmmoUI();
}
void Update()
{
UpdateAmmoUI();
}
private void UpdateAmmoUI()
{
if (playerGun == null)
{
playerGun = FindAnyObjectByType<PlayerGun>();
if (playerGun == null) return;
}
bool isEquipped = playerGun.IsEquipped;
int current = playerGun.CurrentAmmo;
int reserve = playerGun.ReserveAmmo;
bool reloading = playerGun.IsReloading;
// Если оружие убрано (в руках кулаки)
if (!isEquipped)
{
if (ammoIcon != null)
{
ammoIcon.color = new Color(1f, 1f, 1f, 0.35f);
}
if (ammoText != null)
{
ammoText.text = "КУЛАКИ";
ammoText.color = normalColor;
}
if (statusText != null)
{
statusText.gameObject.SetActive(true);
statusText.text = "[2] ВЗЯТЬ ОРУЖИЕ";
statusText.color = normalColor;
}
return;
}
// Оружие в руках (огнестрел активен)
if (ammoIcon != null)
{
ammoIcon.color = Color.white;
}
// Обновление основного текста
if (ammoText != null)
{
ammoText.text = $"{current} / {reserve}";
if (reloading)
{
ammoText.color = reloadingColor;
}
else if (current == 0)
{
ammoText.color = noAmmoColor;
}
else if (current <= 2)
{
ammoText.color = lowAmmoColor;
}
else
{
ammoText.color = normalColor;
}
}
// Обновление статуса (перезарядка / подсказка / убрать в кобуру)
if (statusText != null)
{
if (reloading)
{
statusText.gameObject.SetActive(true);
statusText.text = "ПЕРЕЗАРЯДКА...";
statusText.color = reloadingColor;
}
else if (current == 0 && reserve > 0)
{
statusText.gameObject.SetActive(true);
statusText.text = "[R] ПЕРЕЗАРЯДИТЬ";
statusText.color = noAmmoColor;
}
else if (current == 0 && reserve == 0)
{
statusText.gameObject.SetActive(true);
statusText.text = "НЕТ ПАТРОНОВ!";
statusText.color = noAmmoColor;
}
else
{
statusText.gameObject.SetActive(true);
statusText.text = "[1] УБРАТЬ ОРУЖИЕ";
statusText.color = new Color(0.85f, 0.85f, 0.85f, 0.75f);
}
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 67d173000fb7d294f9d356f4b015e2e5
+203
View File
@@ -0,0 +1,203 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerAttack : MonoBehaviour
{
[Header("Параметры атаки")]
public float attackDamage = 25f;
public float attackCooldown = 0.8f;
public float attackRange = 2.8f; // Достаточная дистанция, превышающая атаку мутанта (1.8м)
public float attackRadius = 1.4f; // Радиус зоны поражения удара
public float attackNoiseRadius = 10f;
[Header("Эффекты (опционально)")]
public GameObject hitEffectPrefab;
[Header("Аудио")]
public AudioSource audioSource;
public AudioClip punchSound;
public AudioClip hitSound;
[Header("Управление")]
public bool allowLeftClick = true; // Разрешить ЛКМ для удара кулаком, когда огнестрел убран
private float nextAttackTime = 0f;
private Camera mainCamera;
void Start()
{
mainCamera = Camera.main;
if (audioSource == null)
{
audioSource = GetComponent<AudioSource>();
}
}
void Update()
{
bool attackPressed = false;
// 1. Быстрый рукопашный удар на клавишу F (доступен всегда)
if (Keyboard.current != null && Keyboard.current.fKey.wasPressedThisFrame)
{
attackPressed = true;
}
// 2. Рукопашный удар на ЛКМ (когда огнестрел убран в кобуру или отсутствует)
else if (allowLeftClick && Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame)
{
PlayerGun gun = GetComponent<PlayerGun>();
if (gun == null || !gun.IsEquipped)
{
attackPressed = true;
}
}
if (attackPressed && Time.time >= nextAttackTime)
{
PerformAttack();
}
}
private void PerformAttack()
{
nextAttackTime = Time.time + attackCooldown;
if (mainCamera == null) mainCamera = Camera.main;
// 1. Определяем направление атаки по прицелу камеры
Vector3 attackDir = transform.forward;
if (mainCamera != null)
{
Vector3 camFwd = mainCamera.transform.forward;
camFwd.y = 0f;
if (camFwd.sqrMagnitude > 0.001f)
{
attackDir = camFwd.normalized;
// Поворачиваем персонажа лицом к направлению атаки (прицелу)
transform.rotation = Quaternion.LookRotation(attackDir);
}
}
if (audioSource != null && punchSound != null)
{
audioSource.PlayOneShot(punchSound);
}
Debug.Log("Игрок наносит рукопашный удар!");
HashSet<MutantHealth> damagedEnemies = new HashSet<MutantHealth>();
// 2. Метод А: Проверка по лучу прицела (SphereCast из камеры)
if (mainCamera != null)
{
Ray aimRay = new Ray(mainCamera.transform.position, mainCamera.transform.forward);
float maxCamDist = 12f; // дистанция луча от камеры (камера позади игрока на ~4м)
RaycastHit[] aimHits = Physics.SphereCastAll(aimRay, 0.4f, maxCamDist);
foreach (var hit in aimHits)
{
if (hit.collider.gameObject == gameObject) continue;
MutantHealth target = hit.collider.GetComponentInParent<MutantHealth>();
if (target != null && !damagedEnemies.Contains(target))
{
// Проверяем, что мутант находится в пределах досягаемости игрока
float distFromPlayer = Vector3.Distance(transform.position, target.transform.position);
if (distFromPlayer <= attackRange + 0.5f)
{
damagedEnemies.Add(target);
ApplyDamage(target, hit.point);
}
}
}
}
// 3. Метод Б: Зона поражения перед персонажем (OverlapSphere)
Vector3 attackCenter = transform.position + attackDir * (attackRange * 0.5f) + Vector3.up * 1.0f;
Collider[] hits = Physics.OverlapSphere(attackCenter, attackRadius);
foreach (Collider hit in hits)
{
if (hit.gameObject == gameObject) continue;
MutantHealth mutantHealth = hit.GetComponentInParent<MutantHealth>();
if (mutantHealth != null && !damagedEnemies.Contains(mutantHealth))
{
damagedEnemies.Add(mutantHealth);
ApplyDamage(mutantHealth, hit.ClosestPoint(attackCenter));
}
}
// 4. Метод В: Прямая проверка расстояния в секторе обзора (если мутант в упор бьет игрока)
if (damagedEnemies.Count == 0)
{
var allMutants = FindObjectsByType<MutantHealth>(FindObjectsInactive.Exclude);
foreach (var mutant in allMutants)
{
if (mutant == null || mutant.IsDead) continue;
Vector3 toMutant = mutant.transform.position - transform.position;
float dist = toMutant.magnitude;
toMutant.y = 0f;
// Если мутант в радиусе ближнего боя и перед игроком (угол менее 80 градусов)
if (dist <= attackRange && Vector3.Dot(attackDir, toMutant.normalized) > 0.15f)
{
damagedEnemies.Add(mutant);
ApplyDamage(mutant, mutant.transform.position + Vector3.up);
}
}
}
if (damagedEnemies.Count == 0)
{
Debug.Log("Удар промахнулся (врагов в зоне досягаемости нет).");
}
// Шум от рукопашного боя привлекает ближайших мутантов
MakeAttackNoise();
}
private void ApplyDamage(MutantHealth target, Vector3 hitPoint)
{
target.TakeDamage(attackDamage, transform);
Debug.Log($"<color=green>Удар попал по мутанту: {target.name}! Нанесено {attackDamage} урона.</color>");
if (audioSource != null && hitSound != null)
{
audioSource.PlayOneShot(hitSound);
}
if (hitEffectPrefab != null)
{
Instantiate(hitEffectPrefab, hitPoint, Quaternion.identity);
}
}
private void MakeAttackNoise()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, attackNoiseRadius);
foreach (Collider col in colliders)
{
BlindMutantAI mutant = col.GetComponentInParent<BlindMutantAI>();
if (mutant != null)
{
mutant.HearSound(transform.position);
}
}
}
private void OnDrawGizmosSelected()
{
Vector3 dir = transform.forward;
if (mainCamera != null)
{
Vector3 camFwd = mainCamera.transform.forward;
camFwd.y = 0f;
if (camFwd.sqrMagnitude > 0.001f) dir = camFwd.normalized;
}
Vector3 attackCenter = transform.position + dir * (attackRange * 0.5f) + Vector3.up * 1.0f;
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackCenter, attackRadius);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ba64df0da8dea44478d9017fd08874b3
+399
View File
@@ -0,0 +1,399 @@
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerGun : MonoBehaviour
{
[Header("Параметры стрельбы")]
public float damage = 35f; // Урон за одно попадание
public float fireRate = 0.25f; // Минимальная задержка между выстрелами (сек)
public float maxRange = 60f; // Максимальная дистанция поражения
public float noiseRadius = 30f; // Радиус шума выстрела (слепые мутанты услышат)
public bool isAutomatic = false; // Одиночный или автоматический огонь
[Header("Боезапас")]
public int currentAmmo = 7; // Патронов в магазине сейчас
public int magSize = 7; // Вместимость одного магазина
public int reserveAmmo = 21; // Патронов в резерве
public int maxReserveAmmo = 56; // Максимум патронов в резерве
public float reloadDuration = 1.6f; // Длительность перезарядки (сек)
[Header("Ссылки на точки и визуал")]
public Transform muzzlePoint; // Точка вылета пули / вспышки
public GameObject hitEffectPrefab; // Префаб искр / пыли при попадании
public Light muzzleFlashLight; // Свет вспышки (мигает при выстреле)
public Transform gunModelTransform; // Модель оружия (для анимации отдачи)
[Header("Экипировка оружия")]
[Tooltip("Находится ли оружие сейчас в руках")]
public bool isGunEquipped = false; // По умолчанию убрано в кобуру (в руках кулаки)
public bool hasGun = true; // Есть ли у игрока огнестрел
public AudioClip equipSound; // Звук доставания оружия
public AudioClip holsterSound; // Звук убирания оружия
[Header("Аудио")]
public AudioSource audioSource;
public AudioClip shootSound;
public AudioClip reloadSound;
public AudioClip emptyClickSound;
[Header("Состояние")]
private bool isReloading = false;
private float nextFireTime = 0f;
private Camera mainCamera;
private Vector3 originalGunLocalPos;
// Свойства для UI и других скриптов
public int CurrentAmmo => currentAmmo;
public int ReserveAmmo => reserveAmmo;
public int MagSize => magSize;
public bool IsReloading => isReloading;
public bool IsEquipped => isGunEquipped;
public bool HasGun => hasGun;
void Start()
{
mainCamera = Camera.main;
if (audioSource == null)
{
audioSource = GetComponent<AudioSource>();
if (audioSource == null)
{
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
audioSource.spatialBlend = 0.3f;
}
}
if (gunModelTransform != null)
{
originalGunLocalPos = gunModelTransform.localPosition;
}
if (muzzleFlashLight != null)
{
muzzleFlashLight.enabled = false;
}
// Применяем начальную видимость оружия (убрано или в руках)
UpdateGunVisibility();
}
void Update()
{
if (mainCamera == null) mainCamera = Camera.main;
HandleInput();
}
private void HandleInput()
{
if (Keyboard.current == null || Mouse.current == null) return;
// 1. Клавиша [1] - Убрать огнестрел (перейти на кулаки / рукопашный бой)
if (Keyboard.current.digit1Key.wasPressedThisFrame)
{
SetEquipped(false);
}
// 2. Клавиша [2] - Достать огнестрел (если уже в руках — убрать как переключатель)
if (Keyboard.current.digit2Key.wasPressedThisFrame)
{
if (hasGun)
{
SetEquipped(!isGunEquipped);
}
else
{
Debug.Log("[Оружие] Огнестрельное оружие еще не найдено!");
}
}
// 3. Клавиша [X] - Быстро убрать / достать оружие (Toggle)
if (Keyboard.current.xKey.wasPressedThisFrame)
{
if (hasGun)
{
ToggleEquip();
}
}
// Если оружие не в руках (убрано), огонь и перезарядка блокируются!
// (ЛКМ в этом случае используется скриптом PlayerAttack для рукопашного удара)
if (!isGunEquipped) return;
// 4. Выстрел (ЛКМ)
bool shootInput = isAutomatic
? Mouse.current.leftButton.isPressed
: Mouse.current.leftButton.wasPressedThisFrame;
if (shootInput)
{
TryShoot();
}
// 5. Перезарядка (Клавиша R)
if (Keyboard.current.rKey.wasPressedThisFrame)
{
TryStartReload();
}
}
/// <summary>
/// Переключение взятия/убирания оружия
/// </summary>
public void ToggleEquip()
{
SetEquipped(!isGunEquipped);
}
/// <summary>
/// Взять огнестрел в руки или убрать в кобуру
/// </summary>
public void SetEquipped(bool equip)
{
if (!hasGun && equip)
{
Debug.Log("[Оружие] Огнестрел недоступен!");
return;
}
if (isGunEquipped == equip) return;
// Если шла перезарядка и мы убираем оружие — прерываем перезарядку
if (!equip && isReloading)
{
StopAllCoroutines();
isReloading = false;
if (muzzleFlashLight != null) muzzleFlashLight.enabled = false;
if (gunModelTransform != null) gunModelTransform.localPosition = originalGunLocalPos;
}
isGunEquipped = equip;
UpdateGunVisibility();
// Проигрываем звук экипировки/убирания, если назначен
if (audioSource != null)
{
if (isGunEquipped && equipSound != null)
audioSource.PlayOneShot(equipSound);
else if (!isGunEquipped && holsterSound != null)
audioSource.PlayOneShot(holsterSound);
}
Debug.Log(isGunEquipped
? "<color=green>[Оружие] Огнестрел взят в руки! (ЛКМ - огонь, R - перезарядка, [1]/[X] - убрать)</color>"
: "<color=cyan>[Оружие] Огнестрел убран в кобуру. В руках кулаки (ЛКМ / F - рукопашный бой, [2] - достать оружие)</color>");
}
/// <summary>
/// Включение/выключение визуала модели оружия
/// </summary>
public void UpdateGunVisibility()
{
if (gunModelTransform != null)
{
gunModelTransform.gameObject.SetActive(isGunEquipped);
}
}
public void TryShoot()
{
if (!isGunEquipped) return;
if (isReloading) return;
if (Time.time < nextFireTime) return;
// Если магазин пуст
if (currentAmmo <= 0)
{
PlayEmptySound();
nextFireTime = Time.time + 0.3f;
// Автоматически предложить перезарядку, если есть патроны в запасе
if (reserveAmmo > 0)
{
TryStartReload();
}
return;
}
// Производим выстрел
nextFireTime = Time.time + fireRate;
currentAmmo--;
ExecuteShot();
}
private void ExecuteShot()
{
// Звук выстрела
if (audioSource != null && shootSound != null)
{
audioSource.PlayOneShot(shootSound);
}
// Вспышка и отдача
StartCoroutine(MuzzleFlashRoutine());
StartCoroutine(RecoilRoutine());
// Луч выстрела из камеры вперед через перекрестие
Vector3 rayOrigin = mainCamera != null ? mainCamera.transform.position : transform.position + Vector3.up * 1.5f;
Vector3 rayDir = mainCamera != null ? mainCamera.transform.forward : transform.forward;
Vector3 hitPoint = rayOrigin + rayDir * maxRange;
if (Physics.Raycast(rayOrigin, rayDir, out RaycastHit hit, maxRange))
{
hitPoint = hit.point;
// Нанесение урона врагу
MutantHealth mutant = hit.collider.GetComponentInParent<MutantHealth>();
if (mutant != null)
{
mutant.TakeDamage(damage, transform);
Debug.Log($"<color=orange>[Оружие] Попадание по {mutant.name}! Нанесено {damage} урона.</color>");
}
// Эффект попадания
if (hitEffectPrefab != null)
{
Instantiate(hitEffectPrefab, hit.point, Quaternion.LookRotation(hit.normal));
}
}
// Отрисовка трассера выстрела
DrawTracer(muzzlePoint != null ? muzzlePoint.position : transform.position + transform.forward * 0.5f + Vector3.up * 1.2f, hitPoint);
// Шум выстрела привлекает всех ближайших мутантов!
AlertMutants(noiseRadius);
// Также порождаем эхо-волну (если на игроке есть EchoTrigger / визуализатор звука)
TriggerEchoWave();
}
private void AlertMutants(float radius)
{
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider col in colliders)
{
BlindMutantAI mutant = col.GetComponentInParent<BlindMutantAI>();
if (mutant != null)
{
mutant.HearSound(transform.position);
}
}
}
private void TriggerEchoWave()
{
EchoTrigger echo = GetComponent<EchoTrigger>();
if (echo != null)
{
// Вызов генерации волны эхолокации при громком выстреле
echo.TriggerExternalWave(transform.position, noiseRadius, 2.5f);
}
}
public void TryStartReload()
{
if (!isGunEquipped) return; // Нельзя перезаряжать убранное оружие
if (isReloading) return;
if (currentAmmo >= magSize) return; // Магазин уже полон
if (reserveAmmo <= 0)
{
Debug.Log("[Оружие] Нет запасных патронов!");
return;
}
StartCoroutine(ReloadRoutine());
}
private IEnumerator ReloadRoutine()
{
isReloading = true;
Debug.Log("[Оружие] Перезарядка...");
if (audioSource != null && reloadSound != null)
{
audioSource.PlayOneShot(reloadSound);
}
yield return new WaitForSeconds(reloadDuration);
int needed = magSize - currentAmmo;
int toLoad = Mathf.Min(needed, reserveAmmo);
currentAmmo += toLoad;
reserveAmmo -= toLoad;
isReloading = false;
Debug.Log($"[Оружие] Перезарядка завершена! Патроны: {currentAmmo}/{reserveAmmo}");
}
public bool AddAmmo(int amount)
{
if (amount <= 0) return false;
if (reserveAmmo >= maxReserveAmmo) return false;
reserveAmmo = Mathf.Min(reserveAmmo + amount, maxReserveAmmo);
Debug.Log($"<color=cyan>[Патроны] Подобрано {amount} патронов. Всего в запасе: {reserveAmmo}</color>");
return true;
}
private void PlayEmptySound()
{
if (audioSource != null && emptyClickSound != null)
{
audioSource.PlayOneShot(emptyClickSound);
}
else
{
Debug.Log("[Оружие] *Сухой щелчок* Магазин пуст!");
}
}
private IEnumerator MuzzleFlashRoutine()
{
if (muzzleFlashLight != null)
{
muzzleFlashLight.enabled = true;
yield return new WaitForSeconds(0.04f);
muzzleFlashLight.enabled = false;
}
}
private IEnumerator RecoilRoutine()
{
if (gunModelTransform != null)
{
gunModelTransform.localPosition = originalGunLocalPos - Vector3.forward * 0.08f + Vector3.up * 0.02f;
float elapsed = 0f;
float duration = 0.12f;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
gunModelTransform.localPosition = Vector3.Lerp(gunModelTransform.localPosition, originalGunLocalPos, elapsed / duration);
yield return null;
}
gunModelTransform.localPosition = originalGunLocalPos;
}
}
private void DrawTracer(Vector3 start, Vector3 end)
{
GameObject tracer = new GameObject("BulletTracer");
LineRenderer lr = tracer.AddComponent<LineRenderer>();
lr.startWidth = 0.035f;
lr.endWidth = 0.01f;
lr.positionCount = 2;
lr.SetPosition(0, start);
lr.SetPosition(1, end);
Material mat = new Material(Shader.Find("Sprites/Default"));
mat.color = new Color(1f, 0.9f, 0.4f, 0.9f);
lr.material = mat;
Destroy(tracer, 0.06f);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fffe9fba59eaaf7468e9b00e9146d7cf
+11 -3
View File
@@ -1,16 +1,24 @@
using UnityEngine;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public float maxHealth = 100f;
private float currentHealth;
void Start() { currentHealth = maxHealth; }
public bool IsDead => currentHealth <= 0;
public float CurrentHealth => currentHealth;
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(float damage)
{
if (IsDead) return;
currentHealth -= damage;
Debug.Log("Игрок получил урон! Осталось здоровья: " + currentHealth);
Debug.Log($"Игрок получил урон! Осталось здоровья: {currentHealth}");
if (currentHealth <= 0)
{
+73
View File
@@ -0,0 +1,73 @@
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealthUI : MonoBehaviour
{
[Header("Ссылки")]
public PlayerHealth playerHealth;
public Slider healthSlider;
public Image healthFillImage;
public Text healthText;
[Header("Настройки визуала")]
public bool smoothTransition = true;
public float smoothSpeed = 5f;
public bool changeColorWithHealth = true;
public Color highHealthColor = new Color(0.2f, 0.85f, 0.3f, 1f); // Зеленый
public Color lowHealthColor = new Color(0.9f, 0.2f, 0.2f, 1f); // Красный
private float currentFill = 1f;
void Start()
{
if (playerHealth == null)
{
playerHealth = FindAnyObjectByType<PlayerHealth>();
}
UpdateHealthUI(true);
}
void Update()
{
UpdateHealthUI(false);
}
private void UpdateHealthUI(bool immediate)
{
if (playerHealth == null) return;
float maxHp = playerHealth.maxHealth;
float currentHp = Mathf.Max(0f, playerHealth.CurrentHealth);
float targetFill = maxHp > 0f ? currentHp / maxHp : 0f;
if (immediate || !smoothTransition)
{
currentFill = targetFill;
}
else
{
currentFill = Mathf.MoveTowards(currentFill, targetFill, smoothSpeed * Time.deltaTime);
}
if (healthSlider != null)
{
healthSlider.value = currentFill;
}
if (healthFillImage != null)
{
healthFillImage.fillAmount = currentFill;
if (changeColorWithHealth)
{
healthFillImage.color = Color.Lerp(lowHealthColor, highHealthColor, currentFill);
}
}
if (healthText != null)
{
healthText.text = $"{Mathf.CeilToInt(currentHp)} / {Mathf.CeilToInt(maxHp)}";
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a3b8d2acc69084a4aa7546ddbfbb3b9d
+1 -1
View File
@@ -1,4 +1,4 @@
using UnityEngine;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]