创建一个胶囊体(Capsule)改名为Player 作为主角
创建一个文件夹命名Prefabs
再创建一个Sphere作为子弹,添加上Bullet.cs脚本后拉到Prefabs文件夹内作为预制体
1. 新建Fire.cs 类 加载到Player 上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fire : MonoBehaviour
{
[Header("把子弹预制体拉到这")]
public GameObject _bullet; //子弹预制体
void Update ()
{
if (UIController.Instance.Count > 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(_bullet);
UIController.Instance.AutoAdd();
}
}
}
}
2.
建Bullet.cs脚本,加载到子弹预制体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//子弹必须先添加Rigidbody组件
public class Bullet : MonoBehaviour
{
private float speed = 100.0f;//子弹速度
void Awake()
{
GetComponent<Rigidbody>().velocity = Vector3.forward * speed;//添加刚体,向前(Z轴)运动
}
void Update ()
{
Destroy(this.gameObject,1.0f);//1秒后子弹销毁
}
}
3.
添加计数功能
新建一个Canvas ,创建子节点Panel
再创建子节点text
节点Panel是为了使计数的方块可以适应屏幕,我们选中Panel 点击Inspector里面的方块
4.。新建UIController.cs脚本
sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIController : MonoBehaviour
{
private static UIController _instance;
public static UIController Instance
{
get
{
if (_instance != null)
{
return _instance;
}
else
{
return null;
}
}
}
[Header("把Canvas/Panel/Text预制体拉到这")]
public Text CountText;
[Header("子弹总数")]
public int Count;
void Awake()
{
_instance = this;
Count = 30;
}
public void AutoAdd()
{
CountText.text = "弹药:" + --Count;
}
}
别忘了把UIController绑定到 Canves上就行