My code works, but why?

Ok, so here’s my code: (in fixed update)

if (DPscroll - scroll != 0.0f)
{
    scroll += (DPscroll - scroll) / 2.0f * Time.fixedDeltaTime;
}

DPscroll is a value that sets itself immediately, and the function above smooths it out to the scroll variable.
DPscroll - scroll is sometimes 0, but that shouldn’t matter, as 1.0f / 0.0f returns NaN
But why does 0.0f / 1.0f return NaN? Shouldn’t is return 0?

0.0f / 1.0f does not return NaN.

I’m guessing you’re dividing by zero somewhere.

Try guarding that expression coming out of Time.fixedDeltaTime. That’s only professional when getting data from another subsystem.

Go back and check your work over carefully. Here’s how:

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

1 Like

I’m not sure what you want to claim here. What you said there is simply not true. First of all 1.0f/0.0f is not NaN but +infinity. Also 0.0f/1.0f is indeed 0f. However 0.0f/0.0f is actually NaN. Since you divide by 2, I don’t see any reason for this code to break.

Your title said that your code works but you don’t know why. I don’t know why you think it shouldn’t work…

Maybe you got a NaN value somewhere and you didn’t know where it came from? It certainly didn’t come from this part :slight_smile:

What you’re actually doing is what a lot people are doing, that is using Lerp as a non linear smoothing function. This is all the same:

float dt = 1f/2f * Time.fixedDeltaTime;
scroll += (DPscroll - scroll) * dt;

scroll = scroll + (DPscroll - scroll) * dt
scroll = scroll + DPscroll * dt - scroll * dt
scroll = scroll*(1 - dt) + DPscroll * dt

scroll = Mathf.Lerp(scroll, DOScroll, dt);
scroll = Mathf.Lerp(scroll, DOScroll, 0.5f * Time.fixedDeltaTime);

ps: There’s almost never a need to use fixedDeltaTime manually. When you read Time.deltaTime inside FixedUpdate, it returns the value of fixedDeltaTime.

There’s also almost no reason to do any “scroll” or camera movement in FixedUpdate, since the only time a camera’s position matters is once after LateUpdate.

Ah yes, I see. I delete the safe guard and it just returns zero. I don’t know what changed since but it works :eyes:
But know I have a problem where the scroll variable changes randomly. The code shown is the only place where scroll is changed

I am using it for the position of an object.

Well, that’s not really possible. So either you’re missing where you may change your scroll variable, or your “target” DPscroll suddenly makes large temporary jumps which of course affects your smoothed variable as well. Use Debug.Log to find out what it is.

A neat trick to solve issues of figuring out who is changing a certain variable is simply replacing it with a property. That way you can actually Debug.Log every get or set access to the variable and you get a stacktrace so you know who is manipulating it.

So you would replace

float scroll;

with

private float _scroll;
float scroll
{
    get {
        Debug.Log("scroll get: " + _scroll, gameObject);
        return _scroll;
    }
    set {
        Debug.Log("scroll set to : " + value + " old value was: " + _scroll, gameObject);
        _scroll = value;
    }
}

Now you get a log every time scroll is read somewhere or when it is set to a new value. Each log has a stacktrace so you can see which method and which line of code actually did cause that read or write. The second argument to Debug.Log allows to pass a context object. This object will be “pinged” / highlighted when you click on the log message in the console. This helps to identify which object this variable actually belongs to. Common errors are that you try to manipulate or read values from a different object like a prefab.

Of course once you’re done with debugging, you should remove the property and go back to your normal field. Keep the number of Debug.Log calls to a minimum or you get lost in the mass of log messages.

I’ve added that code and there’s no places where it shouldn’t be set. The issue only happens when it reaches 0, and it is being set in the script that it should be, but to values of 7~8 when 0.

Is it possible that you misinterpret very small values wrongly? Very small numbers are written in scientific notation like 8.12345E-10 which is actually 0.000000000812345.

Since your smoothing function theoretically will NEVER reach 0 as it just gets closer and closer to 0. Practically due to precision limitations the number may eventually actually round to 0 but that can take some time. Though it’s also possible that you get “stuck” at a very low number.

ah yes, I am then mis-reading the number. Thanks!

Best question ever! :smile:

3 Likes

I spent about 5 hours writing a bunch of code over the weekend without running it. I grabbed a coffee then ran it expecting the usual problems here and there but it worked, perfectly. It still does. I still think it’s a trap, something is not correct. :wink:

3 Likes

Oh yes! This happens once every other year and it’s terrifyingly suspicious, for all I know, it may create a tiny black hole if I run it again! :wink:

1 Like

It’s why I have trust issues! :smile:

(sorry for the derail)

Thread closed. :smile:

1 Like