Update: It's the buttons themselves, not tempRefId, that are being swapped. Though the issue still persists.
I'm trying to write a mod for a Unity game, but I'm not sure this is a Unity related issue.
In the game the player can open a map, and what this code does is add a button next to a few objects in the map. The issue I'm having is that the integer value associated with each button, tempRefId
, is swapped every time the map is opened. It starts off correct, then is set to an incorrect value, then swaps back etc.. I am certain the code below is only run once, the first time the map is opened.
// Loop through a set of gameobjects in code above
if (child.gameObject.name.Contains("res-entry") && child.GetComponent<UIResAmountEntry>().refId != 0 && child.GetComponent<UIResAmountEntry>().valueString.Trim() != "0" && !child.Find("unique-string"))
{
int tempRefId = child.GetComponent<UIResAmountEntry>().refId; // ID of resource
Transform iconTransform = child.Find("icon");
GameObject toggleHighlightButton = GameObject.Instantiate<GameObject>(
original: iconTransform.gameObject,
position: new Vector3(child.position.x+1f, child.position.y-0.02f, child.position.z),
rotation: Quaternion.identity,
parent: child);
UIButton uiButton1 = toggleHighlightButton.GetComponent<UIButton>();
uiButton1.onClick += (id) => { ToggleVeinHeighlight(tempRefId, ref toggleHighlightButton); };
uiButton1.onRightClick += (id) => { DebugStuff(tempRefId); }; // Why is this value inconsistant?
toggleHighlightButton.name = "unique-string";
}
From my understanding an int
is passed by value, so I don't understand how the value of tempRefId
can change after assigning it, which probably means I don't understand my lambda expressions properly. If the issue isn't apparent from the code, what could be causing the issue?
The issue does not affect all instances of the created buttons, seemingly only the first and last ones created in the loop. The values of these two are the ones that swap each time the map is opened.