I have several scripts I use that have cooldowns on them, I now have a script in C# that I need to behave in the same way but I’m having trouble adding the cooldown to my script:
Here is an example of my working script:
#pragma strict
var isPlaying = false;
var coolDown = 1.5;
function Update() {
if (!isPlaying && Input.GetButtonDown("CreepingDeath")) {
PlayPS();
}
}
function PlayPS() {
isPlaying = true;
particleSystem.Play();
yield WaitForSeconds(6.0);
particleSystem.Stop();
yield WaitForSeconds(coolDown);
isPlaying = false;
}
Here is what I’ve come up with for my C# script, but I just can’t get it to work:
using UnityEngine;
using System;
using System.Collections;
bool isPlaying = false;
bool coolDown = 1.5f;
public class TriggerWwiseEvent : MonoBehaviour {
void Update() {
if (!isPlaying && Input.GetButtonDown("CreepingDeath")){
PlayPS();
}
}
void PlayPS() {
isPlaying = true;
GetComponent<AkTriggerOnKeyPress>().Keypress();
yield return new WaitForSeconds(coolDown);
isPlaying = false;
}
I’m way more comfortable in Js so any help would be very much appreciated here.
There are a few things wrong with you C# conversion. I recommend you look into the basics of OOP and bear in mind that ALL methods and variables MUST belong to a class.
Not sure whether you wanted you PlayPS() method to more closely resemble the one in the js script, I’ve created a second method called PlayPSAlt() which follows the same structure as the js version. The normal version mirrors the one in your attempted C# conversion.
This solution makes use of Coroutines, which you may want to read into.
using UnityEngine;
using System;
using System.Collections;
public class TriggerWwiseEvent : MonoBehaviour {
private float coolDown = 1.5f;
private bool isPlaying = false;
void Update() {
if (isPlaying && Input.GetButtonDown("CreepingDeath")){
StartCoroutine("PlayPS");
}
}
IEnumerator PlayPS() {
GetComponent<AkTriggerOnKeyPress>().Keypress();
isPlaying = true;
yield return new WaitForSeconds(coolDown);
isPlaying = false;
}
IEnumerator PlayPSAlt()
//Closer to function in original javascript
particleSystem.Play();
isPlaying = true;
yield return new WaitForSeconds(6.0f);
particleSystem.Stop();
yield return new WaitForSeconds(coolDown);
isPlaying = false;
}
}
using UnityEngine;
using System;
using System.Collections;
public class TriggerWwiseEvent : MonoBehaviour {
bool isPlaying = false;
bool coolDown = 1.5f;
void Update() {
if (!isPlaying && Input.GetButtonDown("CreepingDeath")){
StartCoroutine(PlayPS());
}
}
IEnumerator PlayPS() {
isPlaying = true;
GetComponent<AkTriggerOnKeyPress>().Keypress();
yield return new WaitForSeconds(coolDown);
isPlaying = false;
}
With C# you need to use StartCoroutine and IEnumerator when creating functions that use yield. The above script should fix your problem and show you how it all works 