当我切换武器时,旧武器不会被破坏,所以你最终会在屏幕上显示2个功能正常的枪支。我试图使用Destroy(currentWeapon)摧毁游戏对象,但没有运气。此外,我使用一个空的游戏对象附加到播放器预制件,这是枪被实例化的地方。问题是我需要2个不同的游戏对象,所以不同的枪可以坐在不同的位置。我制作了两个空的游戏对象,但我需要帮助让它们在切换枪时切换。
非常感谢任何帮助!
using UnityEngine;
using UnityEngine.Networking;
public class WeaponManager : NetworkBehaviour {
[SerializeField]
private string weaponLayerName = "Weapon";
[SerializeField]
private Transform tecweaponHolder;
[SerializeField]
private Transform awpweaponHolder;
[SerializeField]
private PlayerWeapon primaryWeapon;
[SerializeField]
private PlayerWeapon secondaryWeapon;
private PlayerWeapon currentWeapon;
private WeaponGraphics currentGraphics;
void Start ()
{
EquipWeapon(primaryWeapon);
}
void Update()
{
if(Input.GetAxis("WeaponSwitch") >0f)
{
EquipWeapon(secondaryWeapon);
Debug.Log("switched weapon");
}
else if (Input.GetAxis("WeaponSwitch")<0f)
{
EquipWeapon(primaryWeapon);
Debug.Log("switched weapon back");
}
}
public PlayerWeapon GetCurrentWeapon ()
{
return currentWeapon;
}
public WeaponGraphics GetCurrentGraphics()
{
return currentGraphics;
}
void EquipWeapon (PlayerWeapon _weapon)
{
currentWeapon = _weapon;
GameObject _weaponIns = (GameObject)Instantiate(_weapon.graphics, tecweaponHolder.position, tecweaponHolder.rotation);
_weaponIns.transform.SetParent(tecweaponHolder);
currentGraphics = _weaponIns.GetComponent<WeaponGraphics>();
if (currentGraphics == null)
Debug.LogError("No WeaponGraphics component on the weapon object: " + _weaponIns.name);
if (isLocalPlayer)
Util.SetLayerRecursively(_weaponIns, LayerMask.NameToLayer(weaponLayerName));
}
}
更新:
private Transform currentHolder;
void Start ()
{
currentHolder = awpweaponHolder;
EquipWeapon(primaryWeapon);
}
void Update()
{
if(Input.GetAxis("WeaponSwitch") >0f)
{
currentHolder = tecweaponHolder;
EquipWeapon(secondaryWeapon);
Debug.Log("switched weapon");
}
else if (Input.GetAxis("WeaponSwitch")<0f)
{
currentHolder = awpweaponHolder;
EquipWeapon(primaryWeapon);
Debug.Log("switched weapon back");
}
}
答案 0 :(得分:3)
你的代码中没有任何地方可以摧毁旧的(当前的)武器。
void EquipWeapon(PlayerWeapon _weapon) {
foreach (Transform child in tecweaponHolder) {
Destroy(child.gameObject);
}
currentWeapon = _weapon;
// ...
}