您的位置:首页 > 其它

U3D 点击按钮控制物体上下左右移动,并变化按钮文本

2019-07-17 20:26 387 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_42872122/article/details/96357524

1、创建控制物体上下左右移动的C#脚本:“move”

[code]using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class move : MonoBehaviour           //调用“move”脚本
{
bool start = false;                     //布尔函数判断是否两种状态
// Use this for initialization
void Start ()
{
start = false;                      //将开始点击状态赋值为否
}

// Update is called once per frame
void Update ()
{
if (start == true)                   //检测到点击按键
if (Input.GetKey(KeyCode.UpArrow))        //上键
{
transform.eulerAngles = new Vector3(0, 0, 0);        //欧拉角:确定定点转动刚体位置的3个一组独立角参量
//vector3代表三维空间
transform.position += transform.forward * 10;        //进给量:10
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.eulerAngles = new Vector3(0, 270, 0);
transform.position += transform.forward * 10;
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.eulerAngles = new Vector3(0, 180, 0);
transform.position += transform.forward * 10;
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.eulerAngles = new Vector3(0, 90, 0);
transform.position += transform.forward * 10;
}
}

public void OnButtonClick()
{
start = !start;                     //赋予点击”开始“按钮时的状态是否变化(点击”开始“按钮可以移动,再点击不能移动)
}
}

 

2、创建控制点击按钮文本发生变化的C#脚本:”BText“

[code]using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//调用UI

public class BText : MonoBehaviour
{
public Text Bt;

//以下为原来的代码不用管
// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{

}

//简单的条件语句判断
public void OnButtonClick()
{
if (Bt.text == "开始")
{
Bt.text = "结束";
}
else
{
Bt.text = "开始";
}
}

}

 

3、操作具体步骤:

3.1、“move”控制cube的移动,将其添加到cube上;

        “BText”控制Button的变化,将其添加到Button上。

 3.2、添加Button里的点击事件:

第一步将cube托进对象里,选择上面脚本里调用的函数。即实现点击按钮cube可以移动,再次点击按钮cube不能移动。

第二步将Button托进对象里,选择上面脚本里调用的函数。即实现点击按钮Button的文本发生变化,为“开始”和“结束”。

3.3、运行即可看到效果 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: