- Home /
The question is answered, right answer was accepted
Error CS0023: The '!' operator cannot be applied to operand of type 'void'
Hello,
Here is part of my script:
void Update ()
{
if (!GoRight () || !GoLeft())
{
CharacterMover.Instance.LeftRight = 0;
}
}
public void GoRight ()
{
CharacterMover.Instance.LeftRight = 1;
}
public void GoLeft ()
{
CharacterMover.Instance.LeftRight = -1;
}
My error is at line 3 inside the IF statement. The two methods "GoLeft" and "GoRight" are connected to a button via OnPointerDown on the Eventsystem. All I want is whenever none of those two functions are being called, the LeftRight float from another script goes to 0. Any ideas on how to fix this error? Thank you
Answer by JathOsh · Oct 09, 2016 at 02:45 AM
void means they do not return something if you were to do ! it would need to return true like:
void Update ()
{
if (!GoRight () || !GoLeft())
{
CharacterMover.Instance.LeftRight = 0;
}
}
public bool GoRight ()
{
CharacterMover.Instance.LeftRight = 1;
return true;
}
public bool GoLeft ()
{
CharacterMover.Instance.LeftRight = -1;
return true;
}
These will both always return true so you might want an if statement deciding weather or not they should return true or false
I've been struggling with how to answer this one. I'm afraid your answer isn't it and will only make things worse.
Your code fixes the compilation problem, but it won't achieve what the OP is trying to do, nor will it help with their lack of understanding of the concepts of functions, variables, and program flow.
Note that, as they have said, the GoLeft() and GoRight() functions are called by button events. They should not be calling those functions explictly in the Update() function at all.
What they really need to do is go back to basics and learn some program$$anonymous$$g fundamentals.
The simplest way to do it might be just to replace the whole Update() function with a LateUpdate() that sets the LeftRight variable to zero. That way it will start every frame as zero and only be changed to something else in frames where one of those buttons sends a "down" event.
Another, probably better, solution would be to add a function to hook up to the equivalent PointerUp() events, and have that function set the LeftRight variable back to zero.
It depends on what they're trying to achieve. But the Update() function definitely needs to be removed, as opposed to mangling the rest of the code in order to allow the Update function to compile.
Follow this Question
Related Questions
Weird Error c# 1 Answer
Please Help 1 Answer
Multiple Cars not working 1 Answer
C# Error help ( error CS0023 The `!’ operator cannot be applied to operand of type `string’ ) ??? 1 Answer
Distribute terrain in zones 3 Answers