I’m struggling to figure out a way to determine the total sum of variables in my game:
Each of the circles is a button with UI text on it. What would be the best method of being able to swap the positions of the circles by clicking on them, then checking what the total sum of the circles are that are connected via the black line?
I’m not claiming this to be the best method, but it is a method to go about.
When you click one button, remember that as the button that was clicked. When you click another button, swap value with the previouly clicked button and the most recently clicked button. Additionally you can perform an animation to give more feedback if you want. I did not include that in my example.
Number.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class Number : MonoBehaviour
{
[Serializable]
public class NumberEvent : UnityEvent<int> { }
public Text text;
public NumberEvent onValueChanged;
public int Value
{
get { return value; }
set
{
if (this.value == value)
return;
this.value = value;
Refresh();
onValueChanged.Invoke(value);
}
}
[SerializeField]
private int value;
private static Number selected;
void Awake()
{
Refresh();
}
void Refresh()
{
text.text = value.ToString();
}
// Bind button to call this during On Click
public void OnClick()
{
if (!selected)
{
selected = this;
}
else
{
Swap(selected, this);
Deselect();
}
}
public static void Swap(Number a, Number b)
{
int tmp = a.Value;
a.Value = b.Value;
b.Value = tmp;
}
public static int Sum(IEnumerable<Number> numbers)
{
int sum = 0;
foreach (var number in numbers)
sum += number.Value;
return sum;
}
// Could be useful to call if you pause the game or enter other menues etc.
public static void Deselect()
{
selected = null;
}
}
To calculate score, just loop through all the connected numbers and add their values together.
ConnectedNumbers.cs
using UnityEngine;
using UnityEngine.UI;
public class ConnectedNumbers : MonoBehaviour
{
public Number[] connected;
public Text text;
void Awake()
{
foreach (var number in connected)
number.onValueChanged.AddListener(ConnectedValueChanged);
Refresh();
}
void ConnectedValueChanged(int unused)
{
Refresh();
}
void Refresh()
{
text.text = Number.Sum(connected).ToString();
}
}