- Home /
Else if not working | C#
Hi all,
Im having problems with my C# Script, I want it so when a Key is held down, a sound and Gameobject are enabled. When the key is let go they both stop - Getting error "Unexpected Symbol 'Else'" (Sorry for the script going messy at the end)
using UnityEngine;
using System.Collections;
public class Hose : MonoBehaviour {
public GameObject SprayParticles;
public AudioSource HoseSound;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
if( Input.GetKeyDown( KeyCode.Z) ) {
SprayParticles.SetActive(true);
HoseSound.Play();
}
{
else if ( Input.GetKeyDown( KeyCode.Z) )
{
SprayParticles.SetActive(false);
HoseSound.Stop();
}
}
}
Answer by Joyrider · Feb 09, 2015 at 10:43 AM
You have a backet line 22 that should not be there. And same goes for line 29.
Hence your error.
Cheers, I get rid of 22 and keep 29 and I get no errors, if I get rid of 29 I get a parsing error.
Even without the errors the script isn't working though. Pressing Z only enables the Game object and Sound, but when I let go it doesn't disable it.
EDIT:- I got rid of the Bracket on line 22 then changed the Input.Get$$anonymous$$eyDown in the Else if function to Input.Get$$anonymous$$eyUp. Works fine.
It is because it will only turn it on, you have to set the "else if" to be different than the "if" otherwise it will only do the "if" so your new code would be if( Input.Get$$anonymous$$eyDown( $$anonymous$$eyCode.Z) && !SprayParticles.enabled) { SprayParticles.SetActive(true); HoseSound.Play(); } { else if ( Input.Get$$anonymous$$eyDown( $$anonymous$$eyCode.Z) )&& SprayParticles.enabled { SprayParticles.SetActive(false); HoseSound.Stop(); } }
Cheers, I used this method to do it (Changing Get$$anonymous$$eyDown to Get$$anonymous$$eyUp on the Else if section (Changed to Button control now))
using UnityEngine;
using System.Collections;
public class Hose : $$anonymous$$onoBehaviour {
public ParticleEmitter SprayParticles;
public AudioSource HoseSound;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
if (Input.GetButtonDown ("Fire1")) {
HoseSound.Play();
SprayParticles.emit = true;
}
else if (Input.GetButtonUp ("Fire1"))
{
HoseSound.Stop();
SprayParticles.emit = false;
}
}
}
Your answer
Follow this Question
Related Questions
merry fragmas part 2 PlayerNetworkMover Script errors 1 Answer
Add script to created gameobject via script 0 Answers
[RPC] identifier expected 1 Answer
GetComponent won't work 1 Answer
Script open help? 1 Answer