using UnityEngine; using System.Collections.Generic; using System; public class…
- User
using UnityEngine; using System.Collections.Generic; using System;
public class CircuitManager : MonoBehaviour { private readonly Dictionary<string, CircuitNode> _nodes = new();
public static Action OnConnectionChanged { get; internal set; } public static CircuitManager Instance { get; private set; } private void Awake() { if (Instance == null) Instance = this; else Destroy(gameObject); } public void RegisterNode(CircuitNode node) { if (!_nodes.ContainsKey(node.NodeId)) { _nodes.Add(node.NodeId, node); } else { Debug.LogWarning($"Duplicate node ID: {node.NodeId}"); } } // Добавление нового подключения public void AddConnection(string sourceId, string targetId, WireType type) { Debug.Log("AddConection called"); if (_nodes.TryGetValue(sourceId, out var source) && _nodes.TryGetValue(targetId, out var target)) { Debug.Log("AddConection called if called"); var connection = new CircuitConnection(source, target, type); source.Connections.Add(connection); target.Connections.Add(connection); } else { Debug.Log("Else in if addconnection entered"); // Debug.Log(sourceId); // Debug.Log(targetId); } OnConnectionChanged?.Invoke(); foreach (var connection in GetConnections(sourceId)) { connection.Source.GetComponent<Visual>().UpdateConnections(); Debug.Log(sourceId); Debug.Log(connection.Target.NodeId); } } // Получение всех подключений к узлу public List<CircuitConnection> GetConnections(string nodeId) { return _nodes.TryGetValue(nodeId, out var node) ? node.Connections : new List<CircuitConnection>(); } // Проверка правильности подключений // public bool ValidateConnections(string nodeId) // { // if (!_nodes.TryGetValue(nodeId, out var node)) return false; // int phaseACount = 0; // int phaseBCount = 0; // int phaseCCount = 0; // int neutralCount = 0; // int groundCount = 0; // foreach (var conn in node.Connections) // { // switch (conn.Type) // { // case WireType.PhaseA: phaseACount++; break; // case WireType.PhaseB: phaseBCount++; break; // case WireType.PhaseC: phaseCCount++; break; // case WireType.Neutral: neutralCount++; break; // case WireType.Ground: groundCount++; break; // } // } // // // Правила валидации (пример для клеммной колодки) // // return phaseCount <= 3 && // // neutralCount == 1 && // // groundCount == 1; // }}
почему if в addconnection не проходит?
Assistant
Условие
ifв методеAddConnectionне проходит, потому что один или оба узла с переданными ID (sourceIdилиtargetId) не найдены в словаре_nodes.Проблема в том, что
TryGetValueвозвращаетfalseдля одного из ID, что означает, что узел не зарегистрирован вCircuitManager.Для диагностики проблемы добавьте отладочную информацию:
public void AddConnection(string sourceId, string targetId, WireType type) { Debug.Log($"AddConnection called: sourceId='{sourceId}', targetId='{targetId}'"); // Проверим, что у нас есть в словаре Debug.Log($"Registered nodes: {string.Join(", ", _nodes.Keys)}"); bool sourceExists = _nodes.TryGetValue(sourceId, out var source); bool targetExists = _nodes.TryGetValue(targetId, out var target); Debug.Log($"Source exists: {sourceExists}, Target exists: {targetExists}"); if (sourceExists && targetExists) { Debug.Log("Creating connection..."); var connection = new CircuitConnection(source, target, type); source.Connections.Add(connection); target.Connections.Add(connection); } else { Debug.LogError($"Node not found - Source: {sourceId} ({sourceExists}), Target: {targetId} ({targetExists})"); } OnConnectionChanged?.Invoke(); // ... остальной код }Наиболее вероятные причины:
- Узлы не зарегистрированы -
RegisterNodeне был вызван для одного из узлов - Неправильные ID - переданные
sourceId/targetIdне соответствуют реальным NodeId - Порядок выполнения -
AddConnectionвызывается до регистрации узлов - Пробелы или невидимые символы в строках ID
Проверьте, что все узлы корректно регистрируются через
RegisterNodeперед вызовомAddConnection.- Узлы не зарегистрированы -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.