I'm attempting to add 1 to the variable levelname everytime the LevelChange function is called. However, everytime its called it resets the value to 1 like its originally set in the beginning of the code. I'm used to c++ and very confused. This code is a bit sloppy because ive tried a ton of ways to solve this. Any help would be appreciated.
Theres a bracket missing because for some reason i cant get this line to go in the code block.
public class NextLevel : MonoBehaviour {
int levelname = 1;
int newlevelname;
string levelnameS;
void LevelChange()
{
levelname++;
newlevelname = levelname;
string levelnameS = newlevelname.ToString(); //Converts newlevelname which is an int value to a string
Debug.Log(levelnameS); //prints to the console
SceneManager.LoadScene(levelnameS); //changes scene based on the level name. In this case its a number because thats what the levels are named.
Debug.Log(levelname);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
LevelChange(); //calls the level change function
}
}
}
levelname is a instance property. Each instance of class NextLevel has own value of this. So if you every time create new instance of NextLevel and call Update count always start from 1.
You can switch levelname to static property or always use one instance of class NextLevel.
use public static int levelname = 1;
instead of int levelname=1
Related
I'm creating a calculator in Unity and faced with a problem.So I need to change bool value to write second number of my calculator.
My script attached to all the buttons(GameObjects) in the scene.
I need to change this value to true to write second number of calculator.
private bool input_second_num;
public void Input(){
if (calculate_label.text.Length < 15 && !input_second_num)
{
calculate_label.text += btnNumber;
first_num = long.Parse(calculate_label.text);
}
esle if (calculate_label.text.Length < 15 && input_second_num)
{
calculate_label.text += btnNumber;
second_num = long.Parse(calculate_label.text);
}
}
//Calls when clicking on action button
public void Action()
{
input_second_num = true;
calculate_label.text = " ";
}
At first input_second_num is false to write first number at first.When I'm changing input_second_num to true in another function clicking on action button and then trying to input second num, input_second_num is anyways false and I'm typing number for first_number.
Why is it so happening?
It's difficult to answer with the code posted and my initial observations require more than will fit into a comment.
You have posted two functions with the same signature public void Input(). I can't see how this code builds without issues; I must therefore assume that they are declared in different class types.
This function is incorrect:
public void Input()
{
else if (calculate_label.text.Length < 15 && input_second_num)
{
calculate_label.text += btnNumber;
second_num = long.Parse(calculate_label.text);
print("Second: " + second_num);
}
}
You're starting an if block statement with an else - is there code missing?
You state that you declared input_second_num as
private static input_second_num;
There is no data type assigned again I can't see how your code builds without issues.
Please revisit your question and show us more of your class code.
I'm trying to create a Calculator with a Class. However using references from the internet particularly from this website (https://www.sourcecodester.com/tutorials/c/7548/simple-calculator-using-class-c.html)
It did not mention to declare "Information" or whatsoever.
When I typed in the code, the error list return with Information does not exist in current context.
Is there a way to modify the code below? Thank you so much.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
}
public void RadioButton_Click(object sender, System.EventArgs e)
{
//call a constructor method and return to cal as an instance of a class
calculate cal = new calculate();
//declaring the string variable represent as a textbox
string txtnum1 = TextBox1.Text;
string txtnum2 = TextBox2.Text;
//declaring the double variable
double dbl_val1 = default(double);
double dbl_val2 = default(double);
if (**Information**.IsNumeric(txtnum1) && **Information**.IsNumeric(txtnum2)) //check if the textbox has a numeric value
{
//convert the string to double
dbl_val1 = double.Parse(txtnum1);
dbl_val2 = double.Parse(txtnum2);
//get the value of the converted variable
//to pass it into the variable in the class
cal.num1 = dbl_val1;
cal.num2 = dbl_val2;
//the condition is, if the radiobutton is clicked,
//the operation of MDAS executes.
if (Radio_Multiplication.Checked)
{
//result:
cal.multiply(); //call a subname in a class for multiplying
}
else if (Radio_Addition.Checked)
{
//result:
cal.add(); //call a subname in a class for adding
}
else if (Radio_Subtraction.Checked)
{
//result:
cal.subtract(); //call a subname in a class for subtracting
}
}
else
{
//the result is:
//if the textbox is empty or has a string value
TextBox3.Text = "Enter a number";
return;
}
//put the result of the MDAS to a textbox.
TextBox3.Text = cal.total.ToString();
}
}
I had a quick look at the link and they don't appear to have declared Information anywhere nor have they indicated that they've overridden anything so...I don't know.
That line, however, is just validating that the information entered into the two text boxes are actually numbers and not anything else that can't be calculated.
There are lots of methods you could use to check those numbers. Options would include, but are not limited to:
if(Int32.TryParse(txtNum1, out int temp1) && Int32.TryParse(txtNum2, out int temp2))
{
do stuff;
}
or
if(txtNum1.All(char.IsDigit) && txtNum2.All(char.IsDigit))
{
do stuff;
}
There are other options, but those two might be worth looking into.
Downloading the sample project, I had a look at what Information refers to. Turns out, it's a class from the Microsoft.VisualBasic namespace, presumably for exposing certain aspects of the VB core library to all .NET languages. You can use it in your program by adding a reference to Microsoft.VisualBasic to your project and adding:
using Microsoft.VisualBasic;
to the top of your code file.
(Personally, I can't imagine that this approach is terribly efficient. It's supposed to take an object and determine if it can be evaluated as a number, and I have no idea what approaches it uses to make that deduction based on any random object. You would probably be better off using one of the alternatives that Benny O'Neill suggests.)
In my code I have a method with the two parameters.
One parameter takes in an int value and the other an array.
e.g
public void NextSong(int i, TagLib.File[] queue)
{
i++;
SONG_URL = queue[i].Name;
Stop();
Play();
}
My problem here is every time this variable is called like so:
NextSong(0, SongQueue);
It reverts back to the amount placed in the parameter field. How do I stop this?
Two ways:
public int NextSong(int i, TagLib.File[] queue)
{
i++;
SONG_URL = queue[i].Name;
Stop();
Play();
return i;
}
int i = 0;
i= NextSong(i, SongQueue);
Here we are passing a variable of i to the method, during the method we increment that variable and then pass it back via the return. We now have reference to that variable.
OR
public void NextSong(TagLib.File[] queue, out int i)
{
i++;
SONG_URL = queue[i].Name;
Stop();
Play();
}
int i = 0;
NextSong(SongQueue, out i);
This uses the out functionality, which enforces someone to pass a variable that will be returned. It passes the variable by reference (You could also use ref, but since int can't be null, it doesn't change much in this case).
That is working as expected, as long as 0 it will keep on being passed, the variable will always reset.
What you can do it to change the signature of the NextSong method to yield back the value of i:
public int NextSong(int i, TagLib.File[] queue)
{
i++;
SONG_URL = queue[i].Name;
Stop();
Play();
return i;
}
Then in your code you initialize some global value to 0 and call the method as follows: globalVariable = NextSong(globalVariable, SongQueue).
I need to use some variables defined in a script but when I call them their values are 0. I don't know what I am doing wrong.
Example:
Script1.cs
public int cont;
public void Method() { cont++; }
void Update() { Method(); }
Script2.cs
public Script1 usingScript1;
void MethodX()
{
usingScript1.GetComponent<Script1>();
Debug.Log(usingScript1.cont);
}
void Update() { MethodX(); }
This script should be showing the "cont" variable increasing since it's being called from Update(), but that's not happening. When I call it, it's 0 and don't increase.
Also, I refer the object which contains Script1.cs in the Ispector. It must be a simple thing that I'm missing. I even tried calling Method().
Just to add to what everyone mentioned, have you tried initializing "cont" ?
This
public int cont;
becomes
public int cont = 0;
Also try initializing it in the Start() function if this doesn't work.
The function called Method() is never called anywhere in this code. Since it's the only thing that modifies the value of the variable called cont, if it is never called, cont will never change from its default value of zero.
EDIT: Whoops!
Okay, the actual problem here is that you need to change
usingScript1.GetComponent<Script1>();
to
usingScript1 = GetComponent<Script1>();
The latter line of code sets the variable usingScript1 so that you can use it in your code. The former simply calls a function without doing anything with the information it returns.
EDIT: GetComponent() will only work is the two scripts are attatched to the same gameobject. Otherwise, you can use FindObjectOfType().
I managed to solve it and never thought about it. As simple as it. Instad of creating an object, I just made the variables static and call 'em using the class.
Script1.cs
public static cont;
Script2.cs
Script1.cont;
And it works.
I'm making a program that estimates energy usage. I have a list of appliances and have created a class for them:
List<Appliances> appliancesList = new List<Appliances>
{
new Appliances("Toaster",6000, durationInput),
new Appliances("Washing Machine",7000,durationInput),
};
class Appliances
{
public String name;
public int energy_rating;
public int duration;
public Appliances(String nameInput, int energy_ratingInput, int durationInput)
{
name = nameInput;
energy_rating = energy_ratingInput;
duration = durationInput;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
durationInput = int.Parse(textBox1.Text);
}
As you can see in the class, I have tried to create a variable that allows the user to enter the duration and then assign that value to the appropriate appliance in the list. I get a red line under 'durationInput' in the list section and the error says 'The name durationInput does not exist in the current context'
Any ideas?
You should be referencing duration. Durationinput is your parameter. The only thing you should be doing with durationinput is setting the variable duration equal to durationinput. Everything else should be referencing duration.
change
durationInput = int.Parse(textBox1.Text);
to
this.duration = int.Parse(textBox1.Text);
Your constructor accepts 3 parameters.
public Appliances(String nameInput, int energy_ratingInput, int durationInput)
In your list statement, you only pass two variables.
new Appliances("Washing Machine",durationInput)
You need to either pass three variables
new Appliances("Washing Machine",0,durationInput)
or overload your constructor.