先新建一个Weapon,在里面存放各种武器,武器由Anchor和States构成,Anchor里存放设计(外观)以及一些Resources,States保存武器的状态,Hip表示默认状态,Ads表示瞄准状态。
先来看一下Weapon脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
#region Variables
public Gun[] loadOut; // 利用Gun脚本加载好prefab
public Transform weaponParent;
private int currentIndex;
private GameObject currentWeapon;
#endregion
// Start is called before the first frame update
#region Monobehaviour Callbacks
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Alpha1))
{
Equip(0);
}
if(Input.GetKeyDown(KeyCode.Alpha2))
{
Equip(1);
}
// 一直按着右键
if (currentWeapon != null)
{
Aim(Input.GetMouseButton(1));
}
}
#endregion
#region Private Methods
void Equip(int idx)
{
if (currentWeapon != null) Destroy(currentWeapon);
currentIndex = idx;
GameObject newWeapon = Instantiate(loadOut[idx].prefab, weaponParent.position, weaponParent.rotation, weaponParent) as GameObject;
newWeapon.transform.localPosition = Vector3.zero; //相对于父坐标的位移
newWeapon.transform.localEulerAngles = Vector3.zero; // 相对于父坐标的旋转
currentWeapon = newWeapon;
}
void Aim(bool isAiming)
{
// Gameobject.transform.find 返回子gameobjct的transform
Transform anchor = currentWeapon.transform.Find("Anchor");
Transform ads = currentWeapon.transform.Find("States/Ads");