- Home /
How do I call defined variables within a function? (CS0103)
Hi All,
After bashing my head against a brick wall - and a lot of googling - I've decided it's time I swallow my pride and ask for help!!
I've written some code which will increase/decrease a variable if it's different from the "requested" variable, essentially like the accelerator on a car.
I wrote a function to do this - however, it relies on variables which are defined further up in the script. For whatever reason, I can't call this variables in my function - as unity/mono things they don't exist! (Which they probably don't..)
Code is written in C#
float RPMportOUT = 0.0f;
float total = 0.0f;
public float RPMPGAINP = 0.0f;
public int portRPMACT = 0;
float REQRPMP = 0.0f;
public Telegraph tele;
// Use this for initialization
void Start () {
tele = GameObject.Find("MainShip").GetComponent<Telegraph>();
}
// Update is called once per frame
void Update () {
}
void fixedupdate ()
{
}
void engineRPM()
{
if (portRPMACT = REQRPM)
{
total = portRPMACT;
}
else {
if (portRPMACT < REQRPM)
{
total = portRPMACT + RPMGAINP;
}
else {
if (portRPMACT > REQRPM)
{
total = portRPMACT - RPMGAINP;
}
return RPMportOUT = total;
}
}
}
}
Thanks in advance!
Answer by KellyThomas · Dec 22, 2013 at 04:05 AM
total = portRPMACT;
total
is not declared in the posted code?
return RPMportOUT = total;
but the function is marked void
Oops! Now I know why you shouldn't write code or post a question at half three in the morning!
What should I mark my function as? Float?
I've edited the code to include the deceleration for "total"
If a function has a return type specified then a return value must used for all code paths. In other words a value must be returned regardless of which code paths your condition statements result in.
Your current code returns a value only under these circumstances
void engineRP$$anonymous$$() {
if (portRP$$anonymous$$ACT = REQRP$$anonymous$$) { //if this is false (note this should almost certainly be a `==` equality sign!)
total = portRP$$anonymous$$ACT;
}
else {
if (portRP$$anonymous$$ACT < REQRP$$anonymous$$) { // and this is false
total = portRP$$anonymous$$ACT + RP$$anonymous$$GAINP;
}
else {
if (portRP$$anonymous$$ACT > REQRP$$anonymous$$) {
total = portRP$$anonymous$$ACT - RP$$anonymous$$GAINP;
}
return RP$$anonymous$$portOUT = total; // then this will be called
}
}
}
You may find that this behaves in the manner you expect:
float engineRP$$anonymous$$() {
float total;
if (portRP$$anonymous$$ACT == REQRP$$anonymous$$) {
total = portRP$$anonymous$$ACT;
}
else if (portRP$$anonymous$$ACT < REQRP$$anonymous$$) {
total = portRP$$anonymous$$ACT + RP$$anonymous$$GAINP;
}
else {
total = portRP$$anonymous$$ACT - RP$$anonymous$$GAINP;
}
RP$$anonymous$$portOUT = total;
return RP$$anonymous$$portOUT;
}
Answer by Vonni · Dec 22, 2013 at 01:58 PM
public float ThisFunctionReturnsAFloat () {
return 2134.0f;
}
fill in the blanks :)