今天用unity写一个石头剪刀布,界面如下:
代码如下,简单实现了剪刀的按键功能
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class xindx : MonoBehaviour
{
Image coumputerImg, playerImg;
Text result;
Button jiandao, shito, bu;
public Image[] imgs;
void Start()
{
coumputerImg = transform.GetChild(1).GetComponent<Image>();
playerImg = transform.GetChild(3).GetComponent<Image>();
result = transform.GetChild(4).GetComponent<Text>();
jiandao = transform.GetChild(5).GetComponent<Button>();
shito = transform.GetChild(6).GetComponent<Button>();
bu = transform.GetChild(7).GetComponent<Button>();
//GetChild(0)这个是获取组件位置,第0个组件,
//GetComponent<Image>()这个是获取组件的类型
//按钮事件
jiandao.onClick.AddListener(Jiandao);
shito.onClick.AddListener(Shito);
bu.onClick.AddListener(Bu);
//onClick这个是为按键添加对应的方法,就不需要去按键中拖放,括号中是要添加的方法名
}
void Jiandao()
{
playerImg.sprite = imgs[0].sprite;
int i = Random.Range(0,3);
coumputerImg.sprite = imgs[i].sprite;
//sprite这个是图片显示
}
void Shito()
{
print("shito");
}
void Bu()
{
print("bu");
}
}