- Home /
Java to C# conversion problem
Hey, I recently converted a script from Java to C#. I used to have a reload function which worked perfectly, but during the conversion I noticed that this function was not a void but an IEnumerator. Now the function doesn't work anymore. Anyone know why?
Script I am using (converted to C#):
IEnumerator Reload (){
//Play the Reload Audio
PlayReloadAudio();
//Determine the seconds it takes to Reload (var ReloadTime)
yield return new WaitForSeconds(ReloadTime);
//Tell Unity that the player is reloading
ReloadTimer ++;
//Only Reload if there are Clips left
if(Ammo > 0)
{
//Reset the amounts of Bullets to Default
BulletsLeft = BulletsPerClip;
//Subtract 1 clip
Ammo -= BulletsFired;
//Done Reloading
ReloadTimer --;
//Reset Bullets Fired
BulletsFired = 0;
}
}
Answer by aldonaletto · Jul 31, 2013 at 12:20 PM
I suspect that the problem may be in the caller code: in C# you must explicitly call a coroutine with StartCoroutine, and the coroutines must explicitly return IEnumerator. In your case, Reload should be called like this:
// start reload coroutine and return immediately:
StartCoroutine(Reload());
If the caller code is a coroutine that chains to Reload, then the code should be changed to this:
// start reload coroutine and wait for its completion:
yield return StartCoroutine(Reload());
But there's another possible issue to check! If you wait the reload time by disabling shots while ReloadTimer is > 0, the order is wrong: ReloadTimer should be incremented before WaitForSeconds, so that its value would become 1 when Reload is called and return magically to 0 after the delay specified - but before the if, or else you may enter an endless loop when Reload is called and there are no more clips:
IEnumerator Reload (){
//Play the Reload Audio
PlayReloadAudio();
//Tell Unity that the player is reloading
ReloadTimer ++;
//Determine the seconds it takes to Reload (var ReloadTime)
yield return new WaitForSeconds(ReloadTime);
//Delay is over
ReloadTimer --;
//Only actually Reload if there are Clips left
if(Ammo > 0){
//Reset the amounts of Bullets to Default
BulletsLeft = BulletsPerClip;
//Subtract 1 clip
Ammo -= BulletsFired;
//Reset Bullets Fired
BulletsFired = 0;
}
}
Hmm, maybe he's missing the actual class around his function?
Do you mean the script class? This would produce lots of compilation errors, and it seems that the code just doesn't do what the OP expects - but that's a valid point to check.
No I am not getting any compilation errors. Is this how you mean it:
if(BulletsLeft == 0)
{
//Automatic Reload if the Player is out of Ammo
StartCoroutine(Reload());
}
One more thing: you should start Reload only once in order to avoid multiple Reload coroutines running in parallel. Apparently you could do it with a $$anonymous$$or change in your code:
// don't call Reload if another Reload is running:
if (BulletsLeft == 0 && ReloadTimer == 0){
StartCoroutine(Reload());
}