using System; using Unity.Collections; using UnityEngine; using UnityEngine.UIElements; namespace BoostComponents { public class BoostBar : VisualElement { // Need this uxml traits and factory for it to show up in editor public new class UxmlTraits : VisualElement.UxmlTraits { UxmlDoubleAttributeDescription m_ProgressAttribute = new UxmlDoubleAttributeDescription() { name = "progress" }; UxmlIntAttributeDescription m_ChargesAttribute = new UxmlIntAttributeDescription() { name = "charges" }; public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); (ve as BoostBar).progress = m_ProgressAttribute.GetValueFromBag(bag, cc); (ve as BoostBar).charges = m_ChargesAttribute.GetValueFromBag(bag, cc); } } public new class UxmlFactory : UxmlFactory { } public static readonly string ussClassName = "boostBar"; public static readonly string ussLabelClassName = "boostBar"; double m_Progress = 0f; int m_Charges = 2; Color strokeColor = Color.white; public double progress { get => m_Progress; set { m_Progress = value; MarkDirtyRepaint(); } } public int charges { get => m_Charges; set { m_Charges = value; MarkDirtyRepaint(); } } public BoostBar() { AddToClassList(ussClassName); RegisterCallback(evt => CustomStylesResolved(evt)); generateVisualContent += GenerateVisualContent; } static void CustomStylesResolved(CustomStyleResolvedEvent evt) { BoostBar element = (BoostBar)evt.currentTarget; element.UpdateCustomStyles(); } void UpdateCustomStyles() { MarkDirtyRepaint(); } void GenerateVisualContent(MeshGenerationContext context) { float width = contentRect.width; float height = contentRect.height; double length = width * m_Progress; Vector2 left = new Vector2(0f, height / 2); Vector2 end = new Vector2((float)length, height / 2); var painter = context.painter2D; painter.lineWidth = 4.0f; painter.lineCap = LineCap.Butt; painter.strokeColor = strokeColor; painter.BeginPath(); painter.MoveTo(left); painter.LineTo(end); painter.Stroke(); float chevGap = width / charges; for (int i = 0; i < charges + 1; i++) { painter.BeginPath(); painter.MoveTo(new Vector2(i * chevGap, height)); painter.LineTo(new Vector2(i * chevGap, 0f)); painter.Stroke(); } } } }