C# 从虚拟空间传递值
我对C#非常陌生,在我正在开发的一个游戏中,对这段代码有一些问题 我正在使用一个脚本来处理弹药,我想在一个片段中武器发射最后一轮时播放一个声音(M1加兰德)。问题是“ammo”变量似乎是静态的,并且只有在虚拟空间中才会发生变化。我不知道如何将更改后的值从空中传递出去。我需要以某种方式检测剪辑中何时还剩下一个镜头,并向“受保护的虚拟空间”发送某种指示器以获得镜头声音效果,然后激发镜头声音和剪辑弹出声音。以下是我到目前为止所做的(我只是尝试粘贴代码的相关部分,如果您在这里遗漏了一些上下文,请原谅):C# 从虚拟空间传递值,c#,unity3d,C#,Unity3d,我对C#非常陌生,在我正在开发的一个游戏中,对这段代码有一些问题 我正在使用一个脚本来处理弹药,我想在一个片段中武器发射最后一轮时播放一个声音(M1加兰德)。问题是“ammo”变量似乎是静态的,并且只有在虚拟空间中才会发生变化。我不知道如何将更改后的值从空中传递出去。我需要以某种方式检测剪辑中何时还剩下一个镜头,并向“受保护的虚拟空间”发送某种指示器以获得镜头声音效果,然后激发镜头声音和剪辑弹出声音。以下是我到目前为止所做的(我只是尝试粘贴代码的相关部分,如果您在这里遗漏了一些上下文,请原谅):
公共虚拟空间使用弹药(int count=1)
{
如果(弹药最好的解决方法是使用事件
在UseAmmo函数中,您需要进行检查:
public virtual void UseAmmo(int count =1)
{
if (ammo <= 0) return;
//store old ammo
oldAmmo = ammo;
ammo -= count;
//Need to make sure ammo actually changed, and is now down to 1
if (ammo != oldAmmo && ammo == 1) {
ClipIsLow();
}
if (ammo <= 0) ammo =0;
}
然后你会有一门枪战课:
public static class GunEvents {
delegate void ClipIsLowEvent();
public static event ClipIsLowEvent OnClipIsLow;
//this is how we fire the event
public static void ClipIsLow(){
OnClipIsLow?.Invoke();
}
}
然后,在音频脚本中(MonoBehavior)
如果您不想学习事件,您可以简单地将以下内容添加到与UseAmmo
方法相同的类中,尽管这肯定是不好的,因为它会将您的弹药脚本与音频播放相结合,这绝不是一个好主意。您的弹药脚本不应该关心游戏中播放的声音
但既然你说你是新来的,反正就在这里
void ClipIsLow() {
audioSource.Play();
}
请在声明弹药的地方共享代码。这是一个公共int:public int ammon;无效射击效果()
是否允许更改为无效射击效果(out int ammon)
?将弹药设置为静态不是一个理想的选择。想象一下玩家是否可以双持枪或在玩家的库存中有两支相同的枪。
public static class GunEvents {
delegate void ClipIsLowEvent();
public static event ClipIsLowEvent OnClipIsLow;
//this is how we fire the event
public static void ClipIsLow(){
OnClipIsLow?.Invoke();
}
}
void OnEnable() {
//listen to event, if event occurs call PlayLowClipSound
GunEvents.OnClipIsLow += PlayLowClipSound;
}
void OnDisable() {
//Stop listening to event. Important to avoid memory leak.
GunEvents.OnClipIsLow -= PlayLowClipSound;
}
//Method that is called when event fires. Actually plays the sound.
void PlayLowClipSound() {
lowClipAudioSource.Play()
}
void ClipIsLow() {
audioSource.Play();
}