using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour {
private Animator ani;
public AudioClip fireClip;//开火声音
public AudioClip reloadClip;//装子弹声音
public AudioClip readyClip;//准备声音
public GameObject muzzleFlash;//火花特效
public GameObject bullet;//预设体
private Transform firePoint;//发射点
void Awake(){
ani = GetComponent ();
firePoint = transform.Find ("FirePoint");
}
public void Fire(){
//如果当前动画状态信息为Normal
if (ani.GetCurrentAnimatorStateInfo (0).IsName ("Normal")) {
//播放Fire动画
ani.SetTrigger ("Fire");
//播放Fire声音在当前位置
AudioSource.PlayClipAtPoint(fireClip,transform.position);
//显示火花特效
muzzleFlash.SetActive(true);
}
}
public void Reload(){
//如果当前动画状态信息为Normal
if (ani.GetCurrentAnimatorStateInfo (0).IsName ("Normal")) {
//播放动画
ani.SetTrigger("Reload");
//播放声音
AudioSource.PlayClipAtPoint(reloadClip,transform.position);
}
}
///
/// 生成子弹
///
void InitBullet(){
//生成子弹
GameObject currentblt=Instantiate(bullet,firePoint.position,firePoint.rotation)as GameObject;
//给子弹添加速度
currentblt.GetComponent ().velocity = firePoint.forward * 10f;
}
}
using UnityEngine;
using System.Collections;
public class GunManager : MonoBehaviour {
private int currentGunIndex = 0;//当前枪支序号
private Gun currentGun;//当前枪支脚本
void Start(){
//找到默认枪支
currentGun = transform.GetChild(currentGunIndex).GetComponent ();
}
void Update(){
if (Input.GetMouseButtonDown(0)) {
currentGun.Fire ();
}
if (Input.GetKeyDown(KeyCode.R)) {
currentGun.Reload ();
}
if (Input.GetKeyDown(KeyCode.Q)) {
GunSwitch ();
}
}
///
/// 换枪
///
void GunSwitch(){
//隐藏当前使用的枪支
transform.GetChild (currentGunIndex).gameObject.SetActive (false);
//换下一把枪
currentGunIndex++;
//Low
// if (currentGunIndex==transform.childCount) {
// currentGunIndex = 0;
// }
//防止子对象越界
//当序号大于枪支个数,取余后序号归零。
currentGunIndex=currentGunIndex%transform.childCount;
//显示新的枪支
transform.GetChild (currentGunIndex).gameObject.SetActive (true);
//更新枪支
Start();
}
}
using UnityEngine;
using System.Collections;
public class MuzzleFlash : MonoBehaviour {
//火花显示时间
public float interval = 0.1f;
///
/// 在可用状态时执行
///
void OnEnable(){
//每隔一段时间执行方法
Invoke("Hide",interval);
}
///
/// 隐藏当前游戏对象
///
void Hide(){
gameObject.SetActive (false);
}
}