跳到主要内容

武器改装与策略模式,装饰器,组件模式

1. 枪身类(GunBody)

using UnityEngine;

public class GunBody : MonoBehaviour
{
// 枪身的相关属性和方法
public string gunName;
public float weight;

// 可以在这里添加一些枪身的行为
public void ShowGunBodyInfo()
{
Debug.Log($"Gun Name: {gunName}, Weight: {weight}");
}
}

2. 枪口类(GunMuzzle)

using UnityEngine;

public class GunMuzzle : MonoBehaviour
{
public AudioClip fireSound;
private AudioSource audioSource;

void Start()
{
audioSource = GetComponent<AudioSource>();
}

// 发射声音的方法
public void PlayFireSound()
{
if (fireSound != null && audioSource != null)
{
audioSource.PlayOneShot(fireSound);
}
else
{
Debug.LogWarning("Fire sound or audio source is missing.");
}
}
}

3. 弹夹类(GunMagazine)

using UnityEngine;

public class GunMagazine : MonoBehaviour
{
public int ammoCount;
public int maxAmmo;

// 装弹的方法
public void Reload()
{
ammoCount = maxAmmo;
Debug.Log("Reloaded!");
}

// 发射一发子弹的方法
public bool FireBullet()
{
if (ammoCount > 0)
{
ammoCount--;
return true;
}
else
{
Debug.LogWarning("Out of ammo!");
return false;
}
}
}

4. 枪类(Weapon)

using UnityEngine;

public class Weapon : MonoBehaviour
{
public GunBody gunBody;
public GunMuzzle gunMuzzle;
public GunMagazine gunMagazine;

void Start()
{
// 初始化各组件
if (gunBody == null || gunMuzzle == null || gunMagazine == null)
{
Debug.LogError("Weapon components are not assigned!");
}
}

// 开火的方法
public void Fire()
{
if (gunMagazine.FireBullet())
{
gunMuzzle.PlayFireSound();
Debug.Log($"{gunBody.gunName} fired!");
}
}
}

5. 武器控制类(WeaponCon)

using UnityEngine;

public class WeaponCon : MonoBehaviour
{
public Weapon weapon;

void Update()
{
// 假设按下鼠标左键开火
if (Input.GetMouseButtonDown(0))
{
weapon.Fire();
}
}
}