实例一:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FireCtrl : MonoBehaviour
{
//预制体
public GameObject bullet;
//子弹发射位置
public Transform firePos;
//发射周期
private float fireRate = 5.0f;//等待5秒后发射
private float nextFire = 0.0f;//一开始发射时间
void Start ()
{
}
void Update ()
{
if (Input.GetMouseButtonDown(0) && Time.time >nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(bullet,firePos.position,firePos.rotation);
}
}
}
实例二:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FireCannon : MonoBehaviour
{
//炮弹预设
public GameObject cannon = null;
//炮弹发射初始点
public Transform firePos;
//发射周期
private float fireRate = 5.0f;//等待5秒后发射
private float nextFire = 0.0f;//一开始发射时间
void Start ()
{
//在Resources文件夹载入弹药预制体
cannon =(GameObject)Resources.Load("Cannon");
}
void Update ()
{
//按键盘 Speed 发射弹药 && 下一次发射弹药时间
if (Input.GetKeyDown(KeyCode.Space) && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Fire();
}
}
void Fire()
{
//生成弹药
Instantiate(cannon,firePos.position,firePos.rotation);
}
}