
Btn_Arr[i].onClick.AddListener(delegate { OnClick(i)})
}
这个循环实际上是通过委托进行了一次闭包 *** 作:delegate委托的内部变量i使用了外部循环的变量i,这就导致了i的实际作用域已经随外部变化而迁移。你端代码的实际效果就是所有的按钮最终添加的响应事件都指向了 OnClick(Btn_Arr.Length-1),因为这是i在这个循环内的最终值。
要实现你的要求其实也很简单,稍微改一下就好:
for (int i = 0i <Btn_Arr.Lengthi++) {
Button btn =Btn_Arr[i].
btn .onClick.AddListener(delegate { OnClick(btn )})
}
//.....
private void OnClick(Button btn)
{
int num= Array.IndexOf(Btn_Arr,btn)
switch (num)
{
//......
}
}
如果您想在Unity中,通过点击Button来移动ScrollView的内容,可以按照以下步骤进行:1. 在Unity UI中创建一个ScrollView和一些按钮Button,将它们排列在ScrollView的Content区域内。
2. 为每个按钮Button添加一个OnClick事件监听器,当点击该按钮时就会调用相应的方法。
3. 创建一个脚本,绑定到ScrollView的Content对象上,并在其中编写一个方法,使得当点击按钮时,ScrollView的Content向指定方向滚动一定距离。
4. 在方法中,获取ScrollView的RectTransform组件和Content对象的RectTransform组件,并根据需要计算出Content需要滚动的距离。
5. 调用ScrollView的ScrollTo方法,将Content滚动到指定位置即可。
以下是一份示例代码,仅供参考:
```csharp
using UnityEngine
using UnityEngine.UI
public class ScrollViewMove : MonoBehaviour
{
public ScrollRect scrollView
public float moveDistance = 100f
public void MoveLeft()
{
Vector2 pos = scrollView.content.anchoredPosition
pos.x += moveDistance
scrollView.content.anchoredPosition = pos
}
public void MoveRight()
{
Vector2 pos = scrollView.content.anchoredPosition
pos.x -= moveDistance
scrollView.content.anchoredPosition = pos
}
public void MoveUp()
{
Vector2 pos = scrollView.content.anchoredPosition
pos.y -= moveDistance
scrollView.content.anchoredPosition = pos
}
public void MoveDown()
{
Vector2 pos = scrollView.content.anchoredPosition
pos.y += moveDistance
scrollView.content.anchoredPosition = pos
}
}
```
在该示例代码中,我们通过定义四个移动方法 MoveLeft、MoveRight、MoveUp 和 MoveDown ,并为每个按钮添加一个 OnClick 事件监听器,当用户点击按钮时,将触发相应的方法,从而实现了通过点击按钮移动 ScrollView 内容的功能。
网页链接
先照着上面的是雨松大大的添加监听的方法 我的比较偷懒 代码如下: 把这个脚本挂载在按钮上……然后把对应 的需要移动的东西挂在gameObgect上 speed设置速度 命名是随便命的 自己改下 该方法 调用的是点击事件的接口 理论上说应该都能用
using UnityEngine
using UnityEngine.EventSystems
public class OnAnXiaBuSongShou : MonoBehaviour , IPointerUpHandler,IPointerDownHandler
{
public GameObject run_GameObject
public float speed=10f
private bool isRun
public void Move()
{
run_GameObject.transform.position += run_GameObject.transform.forward * speed*Time.deltaTime
}
// Update is called once per frame
void Update () {
if(isRun)
{
Move()
}
}
public void OnPointerUp(PointerEventData eventData)
{
isRun = false
}
public void OnPointerDown(PointerEventData eventData)
{
isRun = true
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)