This question was
closed Nov 29, 2016 at 02:26 PM by
Nova-1504 for the following reason:
The question is answered, right answer was accepted
Question by
Nova-1504 · Nov 29, 2016 at 01:46 PM ·
c#errorif statementcompiler errordeclaration
CS1023 An embedded statement may not be a declaration or labeled statement help
I'm getting CS1023 using this code;
using UnityEngine;
using System.Collections;
public class ThrowObject : MonoBehaviour {
public GameObject bullet;
public AudioClip shootSound;
public GameObject vehicularToThrow;
private float throwSpeed = 2200f;
private AudioSource source;
private float volLowRange = .5f;
private float volHighRange = 1.0f;
void Awake () {
source = GetComponent<AudioSource>();
}
void Update () {
if (Input.GetButtonDown("Fire1"))
{
float vol = Random.Range (volLowRange, volHighRange);
source.PlayOneShot(shootSound,vol);
GameObject throwThis = Instantiate (bullet, transform.position, transform.rotation) as GameObject;
throwThis.GetComponent<Rigidbody>().AddRelativeForce (new Vector3(0,0,throwSpeed));
if (Input.GetButtonDown("Fire2"))
GameObject shootCar = Instantiate (vehicularToThrow, transform.position, transform.rotation) as GameObject;
shootCar.GetComponent<Rigidbody>().AddRelativeForce (new Vector3(0,0,throwSpeed));
}
}
}
Why? I tried moving the declaration outside of the if statement and nothing changed, same error. Help! It's at 26, 131, by the way.
Comment
Best Answer
Answer by Landern · Nov 29, 2016 at 02:16 PM
wrap your if statement in curly braces, this does at least one thing you want to do and that is not lose the scope of the shootCar GameObject you just instantiated, currently the way it's written without a code block(curly braces) shootCar is out of scope on line 27.
Should look like:
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
float vol = Random.Range(volLowRange, volHighRange);
source.PlayOneShot(shootSound, vol);
GameObject throwThis = Instantiate(bullet, transform.position, transform.rotation) as GameObject;
throwThis.GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0, 0, throwSpeed));
if (Input.GetButtonDown("Fire2"))
{ // add code block start curly
GameObject shootCar = Instantiate(vehicularToThrow, transform.position, transform.rotation) as GameObject;
shootCar.GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0, 0, throwSpeed));
} // add code block end curly
}
}
Basically you got it, I just figured it out before finding your reply. $$anonymous$$y if statement was inside an if statement.