Почему цвет не срабатывает? у меня все входы и выходы белые, хотя долдны быть разных цветов. При этом линия рисуется нормально(все цвета работают). На тестовой картинке все работает, а как дело доходил до объектов вглубине иерархии все ломается. вот мой код.#region
using System;
using TMPro;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
#endregion
public class NodeController : MonoBehaviour
{
[FormerlySerializedAs("_nodeInfo")] [SerializeField]
private NodesManager.NodeInfo nodeInfo;
code
[FormerlySerializedAs("_selection")] [Header("References")] [SerializeField]
private GameObject selection;
[FormerlySerializedAs("_background")] [SerializeField]
private PointerChecker background;
[FormerlySerializedAs("_inputsContainer")] [SerializeField]
private GameObject inputsContainer;
[FormerlySerializedAs("_outputsContainer")] [SerializeField]
private GameObject outputsContainer;
private Vector2 _dragOffset;
private bool _isConnected;
private bool _isDraggingNode;
private bool _isRegistered;
private bool _isSelected;
private void Awake()
{
if (!_isRegistered)
Init();
}
private void Update()
{
if (_isDraggingNode)
{
var newPosition = (Vector2)Input.mousePosition + _dragOffset;
transform.position = newPosition;
if (NodesController.Instance.copiedNode.Item1 == nodeInfo.functionName.Substring(2))
NodesController.Instance.copiedNode =
(nodeInfo.functionName.Substring(2), GetComponent<RectTransform>());
}
}
private void Copy()
{
if (!_isSelected || !nodeInfo.canBeCopied)
return;
NodesController.Instance.copiedNode = (nodeInfo.functionName.Substring(2), GetComponent<RectTransform>());
}
private void VariableDeleted(VariablesManager.Variable variable)
{
if (variable.name == nodeInfo.connectedVariableName)
{
_isSelected = true;
Delete();
}
}
public void Init(string savedId = "")
{
if (_isRegistered){
if (savedId != "")
{
NodesManager.Instance.UnregisterNode(nodeInfo);
nodeInfo.id = savedId;
NodesManager.Instance.RegisterNode(nodeInfo, this);
}
return;
}
_isRegistered = true;
if(savedId != "")
nodeInfo.id = savedId;
else if (nodeInfo.id == "")
nodeInfo.id = Guid.NewGuid().ToString("N").Substring(0, 20);
InputManager.Instance.onLeftMousePressed += OnMouseClicked;
InputManager.Instance.onLeftMouseReleased += OnMouseReleased;
InputManager.Instance.onDeletePressed += Delete;
InputManager.Instance.onCopyPressed += Copy;
VariablesManager.Instance.onVariableChanged += UpdateNode;
VariablesManager.Instance.onVariableDeleted += VariableDeleted;
NodesManager.Instance.RegisterNode(nodeInfo, this);
NodesManager.Instance.onNodeFieldConnected += UpdateNodeField;
SetVariablesColors();
}
private void UpdateNodeField(string id, int index, bool isConnected)
{
if (nodeInfo == null || inputsContainer == null || outputsContainer == null)
return;
if (id != nodeInfo.id || !nodeInfo.hasAlternativeInput || nodeInfo.inputsList == null ||
nodeInfo.inputsList.Count == 0)
return;
if (isConnected)
{
_isConnected = true;
if (index < nodeInfo.inputsList.Count)
{
nodeInfo.inputsList[index].inputField?.gameObject.SetActive(false);
nodeInfo.inputsList[index].inputBool?.gameObject.SetActive(false);
}
else
{
index -= nodeInfo.inputsList.Count;
nodeInfo.outputsList[index].inputField?.gameObject.SetActive(false);
nodeInfo.outputsList[index].inputBool?.gameObject.SetActive(false);
}
return;
}
_isConnected = false;
if (index < nodeInfo.inputsList.Count)
{
if (nodeInfo.inputsList[index].variableType == NodesManager.NodeVariableType.Bool)
{
nodeInfo.inputsList[index].inputField?.gameObject.SetActive(false);
nodeInfo.inputsList[index].inputBool?.gameObject.SetActive(true);
}
else
{
nodeInfo.inputsList[index].inputField?.gameObject.SetActive(true);
nodeInfo.inputsList[index].inputBool?.gameObject.SetActive(false);
}
}
else
{
index -= nodeInfo.inputsList.Count;
if (nodeInfo.outputsList[index].variableType == NodesManager.NodeVariableType.Bool)
{
nodeInfo.outputsList[index].inputField?.gameObject.SetActive(false);
nodeInfo.outputsList[index].inputBool?.gameObject.SetActive(true);
}
else
{
nodeInfo.outputsList[index].inputField?.gameObject.SetActive(true);
nodeInfo.outputsList[index].inputBool?.gameObject.SetActive(false);
}
}
}
private void UpdateNode(VariablesManager.Variable oldVar, VariablesManager.Variable newVar)
{
if (nodeInfo.connectedVariableName != oldVar.name) return;
var index = 0;
foreach (var variable in nodeInfo.inputsList)
{
if (variable.variableType != NodesManager.NodeVariableType.Signal)
{
variable.variableType =
VariablesManager.Instance.ConvertToNodeVariableType(newVar.type);
inputsContainer.transform.GetChild(index).Find("Name").GetComponent<TextMeshProUGUI>().text =
newVar.name;
UpdateNodeField(nodeInfo.id, index, _isConnected);
break;
}
index++;
}
index = 0;
foreach (var variable in nodeInfo.outputsList)
{
if (variable.variableType != NodesManager.NodeVariableType.Signal)
{
variable.variableType =
VariablesManager.Instance.ConvertToNodeVariableType(newVar.type);
outputsContainer.transform.GetChild(index).Find("Name").GetComponent<TextMeshProUGUI>().text =
newVar.name;
UpdateNodeField(nodeInfo.id, index, _isConnected);
break;
}
index++;
}
nodeInfo.connectedVariableName = newVar.name;
nodeInfo.additionalInfo = newVar.name;
SetVariablesColors();
}
public void SetVariableFieldNameAndType(int index, string name, NodesManager.NodeVariableType type, string info)
{
if (!_isRegistered)
Init();
var field = NodesManager.Instance.GetFieldByIndex(nodeInfo, index);
field.variableType = type;
UpdateNodeField(nodeInfo.id, index, _isConnected);
if (index >= nodeInfo.inputsList.Count)
{
index -= nodeInfo.inputsList.Count;
outputsContainer.transform.GetChild(index).Find("Name").GetComponent<TextMeshProUGUI>().text = name;
}
else
{
inputsContainer.transform.GetChild(index).Find("Name").GetComponent<TextMeshProUGUI>().text = name;
}
nodeInfo.additionalInfo = info;
nodeInfo.connectedVariableName = name;
SetVariablesColors();
}
private void SetVariablesColors()
{
var index = 0;
foreach (Transform child in inputsContainer.transform)
{
ColorsController.Instance.SetColor(nodeInfo.inputsList[index].variableType.ToString(),
child.gameObject.GetComponentInChildren<Image>());;
index++;
}
index = 0;
foreach (Transform child in outputsContainer.transform)
{
ColorsController.Instance.SetColor(nodeInfo.outputsList[index].variableType.ToString(),
child.gameObject.GetComponentInChildren<Image>());;
index++;
}
}
public void SelectNode(bool isSelected)
{
_isSelected = isSelected;
selection.SetActive(_isSelected);
}
private void OnMouseClicked()
{
if (background.isPointerInside)
{
if (GetHighlightedChildIndex() == -1)
{
if (_isSelected)
{
_isDraggingNode = true;
_dragOffset = transform.position - Input.mousePosition;
}
if (_isDraggingNode) return;
_isSelected = !_isSelected;
selection.SetActive(_isSelected);
}
}
else if (transform.parent.parent.GetComponent<PointerChecker>().isPointerInside)
{
_isSelected = false;
selection.SetActive(false);
}
}
private void OnMouseReleased()
{
_isDraggingNode = false;
}
public int GetHighlightedChildIndex()
{
var index = 0;
var parent = inputsContainer.transform;
if (parent != null)
foreach (Transform child in parent)
{
if (child.gameObject.GetComponentInChildren<PointerChecker>().isPointerInside) return index;
index += 1;
}
parent = outputsContainer.transform;
if (parent != null)
foreach (Transform child in parent)
{
if (child.gameObject.GetComponentInChildren<PointerChecker>().isPointerInside) return index;
index += 1;
}
return -1;
}
public RectTransform GetChildRectTransformByIndex(int index)
{
if (index < nodeInfo.inputsList.Count)
return inputsContainer.transform.GetChild(index).Find("ConnectionPos").GetComponent<RectTransform>();
index -= nodeInfo.inputsList.Count;
return outputsContainer.transform.GetChild(index).Find("ConnectionPos").GetComponent<RectTransform>();
}
private GameObject GetFieldByIndex(int index)
{
if (index < nodeInfo.inputsList.Count) return inputsContainer.transform.GetChild(index).gameObject;
index -= nodeInfo.inputsList.Count;
return outputsContainer.transform.GetChild(index).gameObject;
}
public void Delete(bool force = false)
{
if (!force && (!_isSelected || !nodeInfo.canBeDeleted ||
!GameObject.Find("CodeSectionBG").GetComponent<PointerChecker>().isPointerInside))
return;
InputManager.Instance.onCopyPressed -= Copy;
InputManager.Instance.onLeftMousePressed -= OnMouseClicked;
InputManager.Instance.onLeftMouseReleased -= OnMouseReleased;
InputManager.Instance.onDeletePressed -= Delete;
VariablesManager.Instance.onVariableChanged -= UpdateNode;
NodesManager.Instance.onNodeFieldConnected -= UpdateNodeField;
VariablesManager.Instance.onVariableDeleted -= VariableDeleted;
NodesManager.Instance.UnregisterNode(nodeInfo);
StopAllCoroutines();
Destroy(gameObject);
}
private void Delete()
{
Delete(false);
}
}using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ColorsController : MonoBehaviour
{
private static ColorsController _instance;
public static ColorsController Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType();
}
return _instance;
}
}
code
public void SetColor(string type, Image image)
{
if (!VariableColors.ContainsKey(type))
{
Debug.LogWarning($"Color type {type} not found in dictionary");
image.color = Color.gray;
return;
}
var gradientColors = VariableColors[type];
int width = 256;
Texture2D gradientTexture = new Texture2D(width, 1);
gradientTexture.wrapMode = TextureWrapMode.Clamp;
Color[] colors = new Color[width];
for (int i = 0; i < width; i++)
{
float t = (float)i / (width - 1);
float scaledT = t * (gradientColors.Count - 1);
int colorIndex = Mathf.FloorToInt(scaledT);
float localT = scaledT - colorIndex;
colors[i] = Color.Lerp(gradientColors[colorIndex],
gradientColors[Mathf.Min(colorIndex + 1, gradientColors.Count - 1)], localT);
}
gradientTexture.SetPixels(colors);
gradientTexture.Apply();
Material gradientMaterial = new Material(Shader.Find("UI/Default"));
gradientMaterial.mainTexture = gradientTexture;
image.material = Instantiate(gradientMaterial);
}
public Dictionary<string, List<Color>> VariableColors = new Dictionary<string, List<Color>>()
{
{ "Bool", new List<Color>() { Color.red * .8f } },
{ "Int", new List<Color>() { Color.blue * .8f } },
{ "Float", new List<Color>() { Color.cyan * .8f } },
{ "String", new List<Color>() { Color.green * .8f } },
{ "Signal", new List<Color>() { Color.white * .9f } },
{
"All", new List<Color>()
{
Color.red * .8f,
Color.blue * .8f,
Color.cyan * .8f,
Color.green * .8f
}
},
{ "FloatAndInt", new List<Color>() { Color.cyan * .8f, Color.blue * .8f } }
};
}
Assistant
Проблема с цветами может быть вызвана несколькими факторами. Давайте проанализируем код и попробуем найти решение.
Проверьте словарь VariableColors: В классе ColorsController есть словарь VariableColors, который хранит цвета для каждого типа переменной. Проверьте, что в этом словаре есть все необходимые типы переменных и что цвета заданы правильно.
Проверьте метод SetColor: В методе SetColor класса ColorsController происходит установка цвета для элемента Image. Проверьте, что этот метод вызывается корректно и что передаваемые параметры (type и image) верны.
Проверьте вызовы метода SetColor: В классе NodeController метод SetColor вызывается в методе SetVariablesColors. Проверьте, что этот метод вызывается корректно и что передаваемые параметры (nodeInfo.inputsList[index].variableType.ToString() и child.gameObject.GetComponentInChildren<Image>()) верны.
Проверьте иерархию объектов: Поскольку проблема возникает только при работе с объектами в глубине иерархии, возможно, что проблема связана с тем, что элементы Image не находятся в правильной иерархии или не имеют правильных родителей.
Чтобы решить проблему, можно попробовать следующее:
Добавьте отладочные сообщения в метод SetColor, чтобы проверить, что он вызывается корректно и что передаваемые параметры верны.
Проверьте иерархию объектов в сцене, чтобы убедиться, что элементы Image находятся в правильной иерархии и имеют правильных родителей.
Попробуйте вызвать метод SetColor вручную для одного из элементов Image, чтобы проверить, что он работает корректно.
Если проблема все еще не решена, возможно, что проблема связана с другим кодом или настройками в вашем проекте. В этом случае можно попробовать создать минимальный пример, который демонстрирует проблему, и поделиться им с другими разработчиками для получения помощи.