Errors Unity Keycode etc - c#

Errors: Invalid token If, UnityEngine.KeyCode is a 'method' but is used like a 'type', UnityEngine.KeyCode.Equals is a 'type' but is used like a 'Variable'
private void Update()
{
if (Input.GetKeyDown(KeyCode.I));
{
hideCheatGUI = true;
}
}
if (Input.GetKeyDown(KeyCode.Equals));
I need help fixing it. (I'm new so understand if I ask "noob" questions).

Simply remove the semicolons after your if statements. There you are not able to enter in any of those conditions.
Also, put your second if statement in your Update function. There, you put it outside.
private void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
hideCheatGUI = true;
}
if (Input.GetKeyDown(KeyCode.Equals))
{
// Your code
}
}

Related

Member 'Enemy_health.enemiesKilled' cannot be accessed with an instance reference; qualify it with a type name instead

probably a problem of static usage, i searched for the solution but didn't find it, i have this as parameter "private Enemy_health killcount ;"
and this in start function "killcount = GetComponent<Enemy_health>() ;"
also "public static float enemiesKilled ;" in enemy_health script
private void OnTriggerEnter2D (Collider2D collision)
{
if (!alrdySpawned)
{
if(collision.gameObject.name == "Player 1")
{
killcount.enemiesKilled = 0 ;
startTimer = true ;
StartCorou = true ;
alrdySpawned = true ;
if(StartCorou)
{
StartCoroutine(SpawnMonsters()) ;
}
}
}
}
Because the instance name does not match the first object name, which is usually written this way. This code only works for the primary object.
I suggest you to replace the part of code with tag comparison to fix this problem.
if(collision.gameObject.CompareTag("Player"))
If you are not already familiar with it, go to the guide to using tags in Unity:
https://docs.unity3d.com/Manual/Tags.html

C# Put multiple methods and call them into the main method

Sample code below is just a short one, my real code for one if statement is more than 1000 lines of code and those need to be called multiple times. So, to save lines I plan on putting it into a method and just calling that method, which is only around 1 line?
I was wondering if there is a possible way of putting multiple if else statements into MULTIPLE methods, and then calling those methods in the main method. If Method SuperSignalQ1 is true, then it will check method SuperSignalQ2, and so on.
I need this because without the method, my current code is more than 900k, which crashes my PC. This is the only way I could think of shortening my code, by putting it into a method and calling it in the main method as needed, rather than typing those 100s of lines everytime I need those.
So basically my question is:
How to call a method in the main method
How to check if that method is true so that it can then proceed to the next method. I receive error when doing the code in the MainCalculation
Cannot convert method group 'SuperSignalQ1' to non-delegate type 'bool'. Did you intend to invoke the method?
public void SuperSignalQ1()
{
if(RSI > RSI2)
{
if(CCI > CCI2) //There are actually more than 20 if else here which is around 1000 lines
{
return;
}
}
}
public void SuperSignalQ2()
{
if(RSI2 > RSI3)
{
if(CCI2 > CCI3) //There are actually more than 20 if else here which is around 1000 lines
{
return;
}
}
}
public void SuperSignalQ3()
{
if(RSI3 > RSI4)
{
if(CCI3 > CCI4) //There are actually more than 20 if else here which is around 1000 lines
{
return;
}
}
}
public void MainCalculation()
{
if (SuperSignalQ1 = True)
{
if(SuperSignalQ2 = True)
{
if SuperSignalQ3 = True)
{
SetColor(Color.White);
}
}
}
}
So basically, put multiple nested if statement into multiple methods, and then do an boolean check of those methods in the main method
You have
public void SuperSignalQ1()
and later on you have
if (SuperSignalQ1 = True)
This if statement is broken.
In c#, you test with the double equals:
if (someVariable == true)
What you've got is an assignment statement, because there's one equals sign.
You're also missing some brackets, so C# thinks you are referring to it as a variable instead of a method.
So it thinks you are trying to assign a value of True to the method pointer. Which it quite rightly complains about.
It looks like you actually want those methods to return a boolean value, and you could do something like this:
public bool SuperSignalQ1()
{
if(RSI > RSI2)
{
if(CCI > CCI2) //There are actually more than 20 if else here which is around 1000 lines
{
return true;
}
}
return false; // if none of the conditions are valid
}
public bool SuperSignalQ2()
{
if(RSI2 > RSI3)
{
if(CCI2 > CCI3) //There are actually more than 20 if else here which is around 1000 lines
{
return true;
}
}
return false; // if none of the conditions are valid
}
public bool SuperSignalQ3()
{
if(RSI3 > RSI4)
{
if(CCI3 > CCI4) //There are actually more than 20 if else here which is around 1000 lines
{
return true;
}
}
}
public void MainCalculation()
{
if (SuperSignalQ1() == true)
{
if(SuperSignalQ2() == true)
{
if (SuperSignalQ3() == true)
{
SetColor(Color.White);
}
}
}
}
BUT
For boolean, you don't usually use the == format, you'd just go if (SuperSignalQ1())
As #aether643 suggested, you might want to refactor your code so you don't have such a long chunk of code without mental breaks
In C#, you can actually do assignments in if tests. Don't do that.

C# loop over bool values

Is there a concise way to loop over true/false in C#?
I have ~20 lines of code in a unit test I'd rather not duplicate to toggle one boolean true/false.
I could break it off into a function and call it twice, but meh. This code feels more like I'm iterating over possible values than performing a distinct action with different parameters. Even if I had a function, I'd prefer the syntax of looping over the possible values rather than just calling it twice.
I could write a for loop like so...
bool toggle;
for (int i = 0; i < 2; i++)
{
toggle = i == 1;
}
But that doesn't seem very clean.
I like this syntax:
for (bool b : { false, true }) { /* ... */ }
But it doesn't look like that will compile in C#.
Edit:
Following Jeroen's suggestion about local functions and Dmitry's answer, this is the route I went:
[TestMethod]
public void GetAndSetValue()
{
foreach (bool toggle in new [] { false, true })
{
GetAndSetValue(toggle);
}
void GetAndSetValue(bool toggle)
{
// details not important
}
}
Reasonable coders can debate whether the loop reads more easily than two function calls:
GetAndSetValue(false);
GetAndSetValue(true);
I like the loop better, so I'll roll with it until someone complains. Cheers!
Correct syntax will be foreach, not for:
foreach (bool b in new [] { false, true }) {
/* ... */
}
While I think simply writing a parametrized function is definitely the correct approach, the closest to that C++11 syntax that you can get in C# would be:
foreach (bool value in new [] { false, true })
{
// ...
}
I would probably just do it this way, either with a local function:
[TestMethod]
public void GetAndSetValue()
{
GetAndSetValue(false);
void GetAndSetValue(bool toggle)
{
// details not important
if (!toggle)
GetAndSetValue(true);
}
}
Or "old" school with a private method.
[TestMethod]
public void GetAndSetValue()
{
GetAndSetValue(false);
}
private void GetAndSetValue(bool toggle)
{
// details not important
if (!toggle)
GetAndSetValue(true);
}

Passing line of code as argument into function

I am looking to pass a line of code into a function I am calling in c# with the intention to optimise my code and attempt to learn something new. I am familiar with using strings, ints, floats, booleans as I have shown in my code.
The idea is to call a function on a button click that stops a script and begins a script again. Without the function this code is working:
public void PlayOnClick()
{
if(count != 1)
{
m_animator.GetComponent<Animator>().Play("Scale");
d_animator.GetComponent<Animator>().Play("CloseUp");
((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play();
Dialyser.GetComponent<RotationByMouseDrag>().enabled = false;
count = 1;
}
else
{
m_animator.GetComponent<Animator>().Play("Scale");
d_animator.GetComponent<Animator>().Play("ScaleDown");
((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Stop();
Dialyser.GetComponent<RotationByMouseDrag>().enabled = true;
count = 0;
}
}
However I believe this can be shortened. I have got this so far:
void Lock(string A, string B, ? C, bool D, int E)
{
m_animator.GetComponent<Animator>().Play(A);
d_animator.GetComponent<Animator>().Play(B);
C;
Dialyser.GetComponent<RotationByMouseDrag>().enabled = D;
count = E;
}
In function C I would want to pass the following line when pressed once:
((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Stop();
And have it change to this when pressed again:
((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play();
I have come across eval - but I believe that is just for javascript and could be quite processor intensive. I have looked into parsing the line as a string.
I am currently coming up trumps on searches and on attempts. Could anyone shed some light on this for me?
What you are looking for is called delegates, or function pointers in c++ terms.
You can find more on delegates here.
Actions might feel more quicker to code with.
Basically, you can pass a reference to a method you want to execute. The signature of the method should be exactly the same as parameter type declared in the method. So if you expect to pass and run a piece of code that does not return any value, you could use Action type, without any type parameters. For example
class A {
void printAndExecute(String textToPrint, Action voidMethodToExecute) {
Debug.Log(textToPrint);
voidMethodToExecute();
}
}
class B : MonoBehaviour {
void Start() {
new A().printAndExecute("SAY", sayHello);
}
void sayHello() {
Debug.Log("Hello!");
}
}
Hope it helps
You have to pass an Action type or a custom delegate :
void Lock(string A, string B, System.Action C, bool D, int E)
{
m_animator.GetComponent<Animator>().Play(A);
d_animator.GetComponent<Animator>().Play(B);
C();
Dialyser.GetComponent<RotationByMouseDrag>().enabled = D;
count = E;
}
// ...
Lock("Scale", "CloseUp", ((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play, false, 1 ) ;

Can the ErrorProvider be queried to see if it has set any errors?

I have this code to do some basic sanity checking before posting a record:
if (string.IsNullOrWhiteSpace(textBoxFirstName.Text))
{
errorProvider.SetError(textBoxFirstName, "Enter a first name");
}
if (string.IsNullOrWhiteSpace(textBoxLastName.Text))
{
errorProvider.SetError(textBoxLastName, "Enter a last name");
}
...but I want to then do something like this to exit the handler if either of those conditions has been met:
if (errorProvider.SetErrorCount > 0) then return;
...but I see no way to do that. I don't want to have to write an "OR" statement to see if either of the textBoxes I'm checking are empty and then short circuit the handler that way.
Is there a way to tell whether the errorProvider is "dirty" to avoid cluttery code?
Write a method and pass it the error message and the control. Have a counter variable and increase the counter within the method. Here is some pseudocode:
private int errorCount;
SetError(Control c, string message)
{
errorProvider.SetError(c, message);
errorCount++;
}
One option would be to use the GetError method off of the ErrorProvider.
// possibly use a backing field for all controls to evaluate
private readonly Control[] textBoxes = new[] { textBoxFirstName, textBoxLastName };
// helper property to evaluate the controls
private bool HasErrors
{
get { return textBoxes.Any(x => !string.IsNullOrEmpty(errorProvider.GetError(x)); }
}

Categories

Resources