(后续会出UGUI+Json的版本,敬请期待!)
游戏开发中经常会出现药品商店,实际操作与武器商店类似,甚至根据实际情况可以简化设置,废话不多说,直接上代码:
药品商店的源码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShopDrug : MonoBehaviour
{
public static ShopDrug _instance;
private TweenPosition tween;
private TweenPosition tween2;
private bool isShow = false;
//关联关闭按钮
public UIButton uIButton;
public GameObject numberDialog;
public UIInput numberInput;
public UIButton btn1001;
public UIButton btn1002;
public UIButton btn1003;
public UIButton btnOk;
public UISprite sprTip;
//关联上面的文字
public UILabel spriceTipText;
private int buy_id = 0;
Vector3 sprTrs;
private void Awake()
{
_instance = this;
tween = this.GetComponent<TweenPosition>();
tween2 = sprTip.GetComponent<TweenPosition>();
}
public void Start()
{
sprTrs = new Vector3(2.4f,-8,0);
uIButton.onClick.Add(new EventDelegate(() =>
{
TransformState();
}));
btn1001.onClick.Add(new EventDelegate(() =>
{
Buy(1001);
}));
btn1002.onClick.Add(new EventDelegate(() =>
{
Buy(1002);
}));
btn1003.onClick.Add(new EventDelegate(() =>
{
Buy(1003);
}));
btnOk.onClick.Add(new EventDelegate(() =>
{
int count = int.Parse(numberInput.value);
ObjectInfo info = ObjectsInfo._instance.GetObjectInfoById(buy_id);
int price = info.price_buy;
int price_total = price * count;
bool success = Inventory._instance.GetCoin(price_total);
if(success)
{
//取款成功 可以购买
if(count>0)
{
Inventory._instance.GetId(buy_id, count);
spriceTipText.text = "购买成功";
sprTip.enabled=true;
spriceTipText.enabled=true;
tween2.PlayForward();
Invoke("SprTipHide", 1);
}
}
else
{
//金币不足
spriceTipText.text = "金币不足";
sprTip.enabled = true;
spriceTipText.enabled = true;
tween2.PlayForward();
Invoke("SprTipHide", 1);
}
numberDialog.SetActive(false);
}));
}
void ShowNumberDialog()
{
numberDialog.SetActive(true);
numberInput.value = "0";
}
void Buy(int id)
{
ShowNumberDialog();
buy_id= id;
}
public void TransformState()
{
if(isShow==false)
{
tween.PlayForward();
isShow = true;
}
else
{
tween.PlayReverse();
isShow = false;
}
}
void SprTipHide()
{
sprTip.enabled=false;
spriceTipText.enabled=false;
tween2.PlayReverse();
}
}
药品商人的源码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShopDrugNPC :NPC
{
public void OnMouseOver()
{
//鼠标在这个上面一直调用方法
if(Input.GetMouseButtonDown(0)&&UICamera.isOverUI == false)
{
GetComponent<AudioSource>().Play();
ShopDrug._instance.TransformState();
}
}
}
其中使用了UICamera.isOverUI主要是用于判断点击的是不是在UI上面,防止UI点击穿透(可能会点击到UI下面的NPC。其它的代码几乎不需要过多的解释,如果对于代码不明白的欢迎私聊问我。其中有一些代码可能关联了其它系统,直接复制使用可能会有些问题,可以直接删除修改即可,或者查看我的其它系统笔记补充该系统。
主要核心逻辑已经给出,(适用于21版Unity)希望我的笔记对你有些帮助,喜欢就点赞收藏吧!