короче есть такая система поэтапной сборки блюпринта, давай сделай так чтобы в ui еще отображалось сколько этапов, какой сейчас этап, сколько деталей на этом этапе выполнено и осталось. и типо это все включалось по туглу этот ui вот тут SubscribeAllBlueprints(List droneParts) будет еще булл надо ли отображать этот ui . вот код using System.Collections.Generic;
using AYellowpaper.SerializedCollections;
using UnityEngine;
using UnityEngine.Events;
public class BlueprintManager : StaticInstance
{
public List blueprints;
public UnityEvent onAllBlueprintsFilled;
code
Assistant
public int currentStageIndex = 0;
public SerializedDictionary<int, List<Blueprint>> blueprintsByStage = new SerializedDictionary<int, List<Blueprint>>();
public void SubscribeAllBlueprints(List<DronePart> droneParts)
{
blueprints.Clear();
blueprintsByStage.Clear();
// Подписываемся на события заполнения каждого блюпринта
foreach (var dronePart in droneParts)
{
if (dronePart.TryGetComponent(out Blueprint blueprint))
{
if (!blueprintsByStage.ContainsKey(blueprint.stageIndex))
{
blueprintsByStage[blueprint.stageIndex] = new List<Blueprint>();
}
blueprintsByStage[blueprint.stageIndex].Add(blueprint);
// Подписываемся на событие заполнения блюпринта
blueprint.OnBlueprintFilled += OnBlueprintFilled;
// Устанавливаем видимость блюпринта в зависимости от текущего этапа
if (blueprint.stageIndex == currentStageIndex)
{
blueprint.gameObject.SetActive(true);
}
else
{
blueprint.gameObject.SetActive(false);
}
blueprints.Add(blueprint);
}
}
}
private void OnBlueprintFilled(Blueprint bp)
{
NotifyExamManager();
// Проверяем, заполнены ли все блюпринты текущего этапа
bool stageCompleted = true;
foreach (Blueprint blueprint in blueprintsByStage[currentStageIndex])
{
if (!blueprint.IsFilled)
{
stageCompleted = false;
break;
}
}
if (stageCompleted)
{
ProceedToNextStage();
}
}
private void ProceedToNextStage()
{
// Скрываем блюпринты предыдущего этапа
foreach (Blueprint bp in blueprintsByStage[currentStageIndex])
{
bp.gameObject.SetActive(false);
}
currentStageIndex++;
// Проверяем, есть ли следующий этап
if (blueprintsByStage.ContainsKey(currentStageIndex))
{
// Показываем блюпринты нового этапа
foreach (Blueprint bp in blueprintsByStage[currentStageIndex])
{
bp.gameObject.SetActive(true);
}
}
else
{
Debug.Log("Сборка завершена!");
onAllBlueprintsFilled.Invoke();
}
}
private void NotifyExamManager()
{
ExamManager.Instance?.IncrementDetailCount();
}
private void Start()
{
onAllBlueprintsFilled.AddListener(OnAllBlueprintsFilled);
}
private void OnAllBlueprintsFilled()
{
ExamManager.Instance?.EndExam();
}
}using EasyButtons;
using UnityEngine;
[RequireComponent(typeof(DronePart))]
public class Blueprint : MonoBehaviour
{
[HideInInspector] public DronePart dronePart;
public bool IsFilled { get; private set; }
code
public int stageIndex; // Этап, к которому относится блюпринт
public delegate void BlueprintFilledHandler(Blueprint blueprint);
public event BlueprintFilledHandler OnBlueprintFilled;
public void Fill()
{
if (!IsFilled)
{
IsFilled = true;
OnBlueprintFilled?.Invoke(this); // Передаем ссылку на себя для использования в обработчике
}
}
void Start()
{
dronePart = GetComponent<DronePart>();
}
}
Конечно, давайте расширим вашу систему поэтапной сборки блюпринта, добавив отображение информации о стадиях и деталях в UI. Вот пошаговое руководство с примерами кода, чтобы реализовать требуемый функционал.
Шаг 1: Создание UI в Unity
Создайте Canvas:
В иерархии Unity, правой кнопкой мыши выберите UI -> Canvas, если он еще не создан.
Добавьте необходимые UI элементы:
Text для общего количества этапов:
Правой кнопкой на Canvas выберите UI -> Text и назовите его, например, TotalStagesText.
Text для текущего этапа:
Создайте еще один UI -> Text и назовите его CurrentStageText.
Text для выполненных и оставшихся деталей:
Создайте UI -> Text и назовите его DetailsStatusText.
Родительский объект UI (для удобства включения/выключения):
Создайте пустой UI -> Panel и поместите все вышеуказанные текстовые элементы внутрь него. Назовите его, например, BlueprintUI.
Настройте позиционирование и стиль текстов по вашему усмотрению.
Шаг 2: Скрипт управления UI
Создайте новый скрипт, например, BlueprintUIManager, который будет управлять отображением информации.
csharp
using UnityEngine;
using UnityEngine.UI;
public class BlueprintUIManager : MonoBehaviour
{
[Header("UI Elements")]
public GameObject blueprintUIPanel; // Родительский объект UI
public Text totalStagesText;
public Text currentStageText;
public Text detailsStatusText;
// Метод для обновления UI
public void UpdateUI(int totalStages, int currentStage, int completedDetails, int totalDetails)
{
totalStagesText.text = $"Этапов: {totalStages}";
currentStageText.text = $"Текущий этап: {currentStage}";
detailsStatusText.text = $"Деталей: {completedDetails} из {totalDetails}";
}
// Метод для включения/выключения UI
public void SetUIActive(bool isActive)
{
blueprintUIPanel.SetActive(isActive);
}
}
Настройка в Unity:
Добавьте BlueprintUIManager на Canvas или другой подходящий объект.
Присвойте ссылки на UI элементы в инспекторе:
Blueprint UIPanel → Панель BlueprintUI.
Total Stages Text → Текстовый объект TotalStagesText.
Current Stage Text → Текстовый объект CurrentStageText.
Details Status Text → Текстовый объект DetailsStatusText.
Шаг 3: Изменение BlueprintManager
Теперь модифицируем ваш BlueprintManager, чтобы взаимодействовать с BlueprintUIManager.
Обновленный BlueprintManager:
csharp
Объяснение изменений:
Добавили ссылку на BlueprintUIManager через SerializeField.
Добавлен параметр bool showUI в метод SubscribeAllBlueprints, который определяет, показывать ли UI.
Добавлены методы для обновления UI при инициализации и при изменении этапов.
Метод GetCompletedDetailsInCurrentStage подсчитывает количество завершенных деталей на текущем этапе.
Настройка в Unity:
Перейдите к объекту, на который прикреплен BlueprintManager.
В инспекторе присвойте ссылку на BlueprintUIManager в поле UI Manager.
Шаг 4: Модификация вызова SubscribeAllBlueprints
Теперь, при вызове метода SubscribeAllBlueprints, вы можете передавать булевский параметр для включения или выключения UI.
Убедитесь, что при вызове метода Fill в Blueprint, событие OnBlueprintFilled корректно инициирует обновление UI через BlueprintManager. В уже предоставленном коде это реализовано.
Дополнительные улучшения
Анимации и визуальные эффекты:
Можно добавить анимации при переключении этапов или заполнении деталей для улучшения пользовательского опыта.
Обработка ошибок:
Добавьте проверки на null для ссылок на UI элементы, чтобы избежать ошибок во время выполнения.
Локализация:
Если планируется поддержка нескольких языков, рассмотрите возможность использования системы локализации для текстовых элементов UI.
Оптимизация:
Если количество блюпринтов или этапов велико, подумайте о более эффективных способах подсчета и отображения информации.
Заключение
Следуя этому руководству, вы сможете добавить в вашу систему отображение информации о стадиях и деталях сборки блюпринта. Это улучшит взаимодействие пользователя с вашей системой и сделает процесс сборки более понятным и интуитивным.
Если у вас возникнут дополнительные вопросы или потребуется помощь с реализацией, не стесняйтесь обращаться!
Not yet included in a published release.
using System.Collections.Generic;
using AYellowpaper.SerializedCollections;
using UnityEngine;
using UnityEngine.Events;
public class BlueprintManager : StaticInstance<BlueprintManager>
{
public List<Blueprint> blueprints;
public UnityEvent onAllBlueprintsFilled;
public int currentStageIndex = 0;
public SerializedDictionary<int, List<Blueprint>> blueprintsByStage = new SerializedDictionary<int, List<Blueprint>>();
// Добавляем ссылку на BlueprintUIManager
[SerializeField] private BlueprintUIManager uiManager;
private int totalStages = 0;
public void SubscribeAllBlueprints(List<DronePart> droneParts, bool showUI)
{
blueprints.Clear();
blueprintsByStage.Clear();
// Подписываемся на события заполнения каждого блюпринта
foreach (var dronePart in droneParts)
{
if (dronePart.TryGetComponent(out Blueprint blueprint))
{
if (!blueprintsByStage.ContainsKey(blueprint.stageIndex))
{
blueprintsByStage[blueprint.stageIndex] = new List<Blueprint>();
}
blueprintsByStage[blueprint.stageIndex].Add(blueprint);
// Подписываемся на событие заполнения блюпринта
blueprint.OnBlueprintFilled += OnBlueprintFilled;
// Устанавливаем видимость блюпринта в зависимости от текущего этапа
if (blueprint.stageIndex == currentStageIndex)
{
blueprint.gameObject.SetActive(true);
}
else
{
blueprint.gameObject.SetActive(false);
}
blueprints.Add(blueprint);
}
}
// Определяем общее количество этапов
totalStages = blueprintsByStage.Keys.Count;
// Обновляем UI при старте
if (showUI && uiManager != null)
{
uiManager.SetUIActive(true);
UpdateUI();
}
else if (uiManager != null)
{
uiManager.SetUIActive(false);
}
}
private void OnBlueprintFilled(Blueprint bp)
{
NotifyExamManager();
// Проверяем, заполнены ли все блюпринты текущего этапа
bool stageCompleted = true;
foreach (Blueprint blueprint in blueprintsByStage[currentStageIndex])
{
if (!blueprint.IsFilled)
{
stageCompleted = false;
break;
}
}
// Обновляем UI, если он активен
if (uiManager != null && uiManager.gameObject.activeInHierarchy)
{
int completedDetails = GetCompletedDetailsInCurrentStage();
int totalDetails = blueprintsByStage[currentStageIndex].Count;
uiManager.UpdateUI(totalStages, currentStageIndex + 1, completedDetails, totalDetails);
}
if (stageCompleted)
{
ProceedToNextStage();
}
}
private void ProceedToNextStage()
{
// Скрываем блюпринты предыдущего этапа
foreach (Blueprint bp in blueprintsByStage[currentStageIndex])
{
bp.gameObject.SetActive(false);
}
currentStageIndex++;
// Проверяем, есть ли следующий этап
if (blueprintsByStage.ContainsKey(currentStageIndex))
{
// Показываем блюпринты нового этапа
foreach (Blueprint bp in blueprintsByStage[currentStageIndex])
{
bp.gameObject.SetActive(true);
}
// Обновляем UI
if (uiManager != null && uiManager.gameObject.activeInHierarchy)
{
int completedDetails = GetCompletedDetailsInCurrentStage();
int totalDetails = blueprintsByStage[currentStageIndex].Count;
uiManager.UpdateUI(totalStages, currentStageIndex + 1, completedDetails, totalDetails);
}
}
else
{
Debug.Log("Сборка завершена!");
onAllBlueprintsFilled.Invoke();
// Скрываем UI после завершения сборки
if (uiManager != null)
{
uiManager.SetUIActive(false);
}
}
}
private void NotifyExamManager()
{
ExamManager.Instance?.IncrementDetailCount();
}
private void Start()
{
onAllBlueprintsFilled.AddListener(OnAllBlueprintsFilled);
}
private void OnAllBlueprintsFilled()
{
ExamManager.Instance?.EndExam();
}
// Метод для обновления UI при инициализации
private void UpdateUI()
{
if (uiManager != null)
{
int completedDetails = GetCompletedDetailsInCurrentStage();
int totalDetails = blueprintsByStage[currentStageIndex].Count;
uiManager.UpdateUI(totalStages, currentStageIndex + 1, completedDetails, totalDetails);
}
}
// Метод для получения количества заполненных деталей на текущем этапе
private int GetCompletedDetailsInCurrentStage()
{
int count = 0;
foreach (Blueprint bp in blueprintsByStage[currentStageIndex])
{
if (bp.IsFilled)
count++;
}
return count;
}
}