【发布时间】:2021-07-08 14:17:44
【问题描述】:
更新:正在交换的是按钮本身,而不是 tempRefId。虽然问题仍然存在。
我正在尝试为 Unity 游戏编写模组,但我不确定这是与 Unity 相关的问题。
在游戏中玩家可以打开一张地图,这段代码所做的就是在地图中的一些对象旁边添加一个按钮。我遇到的问题是每次打开地图时都会交换与每个按钮关联的整数值tempRefId。它一开始是正确的,然后设置为不正确的值,然后换回等等。我确定下面的代码只运行一次,第一次打开地图时。
// 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";
}
据我了解,int 是按值传递的,所以我不明白 tempRefId 的值在分配后会如何变化,这可能意味着我没有正确理解我的 lambda 表达式。如果问题在代码中不明显,可能是什么原因造成的?
此问题不会影响已创建按钮的所有实例,似乎只影响循环中创建的第一个和最后一个。这两个的值是每次打开地图时交换的值。
【问题讨论】:
-
在
UIButton uiButton1 =上设置断点并检查tempRefId是否已更改?我有一种感觉,因为您正在创建一个新的GameObject,其父级为child,它会更改tempRefId。 -
@Codexer 我无法设置断点,但通过记录值我可以确认它没有改变。
-
ToggleVeinHeighlight是什么样的?如果是这种情况,它在那里没有改变,那么也许这个例程正在用它做点什么? -
很遗憾没有,该值仅用作该方法中的数组索引。
-
也许不是
tempRefId被交换,而是按钮?否则,ref是为了什么?
标签: c# unity3d lambda variable-assignment