Home > Software design >  Calling a float from the same script isn't working in my Unity C# script
Calling a float from the same script isn't working in my Unity C# script

Time:04-25

I am brand new to Unity and C# so this question might be a bit silly. I created a public float to store the value 5f but when I call it later on within the same script it doesn't work, however if I input the float value directly it does work. I'm not sure if theres a certain way to call it that I missed? Thanks.

This is when I declared the float. This is the line of code that uses it. Replacing jumpForce with 5f makes the function work.

CodePudding user response:

Since you're new to unity, I will go ahead and assume you're probably also new to C#. Since you haven't produced any code for us to look at, it's very difficult for us to suggest what the problem might be in your use-case, as there are thousands of possible things you could be doing wrong.

In the first instance, general troubleshooting begins with syntax though. So, look at how you're writing the code. The declaration of a variable prior to its use is very important. Generally, a good practice way of declaring variables could look something like:

public float MyFloat { get; set; } = 5f;

This should be placed outside of your functions, within your class. Breaking this down, 'public' means that any part of your code should be able to call this variable once it is initialised, but it won't exist unless the class has been initialised because it is not declared 'static'. 'float' is self explanatory, you are declaring that the variable is of float in type. MyFloat is the name of the variable, and how you will refer back to it elsewhere in your code. '{ get; set; }' tells C# that you want a private property to be exposed by a public field, which is done for you by the compiler. And lastly, '= 5f;' sets the initial value of the private property to 5 as a floating point number, before ending the line of code with a semicolon (your C# full-stop/period).

If your class has been initialised, you will now be able to retrieve and operate on this variable using its name 'MyFloat' elsewhere (EDIT: Within the same class). You should use it within a method or a function now, which might look something like:

void Update()
{
   //Increment your float by 1 on each update.
   MyFloat = MyFloat   1f;
}

Once you have verified that your syntax is correct and appropriate for the situation, you should then troubleshoot your logic, how you do this will very much depend on your use-case, but a common way to do this for a simple situation like a single-float is to debug your code and 'watch' the value. Or even do your calculations on paper, never hurts!

Please do update your question with more elaboration on the problem though, it will be less stressful for us and you.

  • Related