Code Line Not Executing

The code snippet below is on a script attached to a GameObject in the Canvas that has a Button on it. It populates that Button’s OnClick listener. The code is executed when the button is clicked. The problem is the final line of code never executes. The GameObject is never turned off. The IF statement that encapsulates that line does indeed return true (as I’ve tested it thoroughly through debugging). The method “TransferEnhancementToUnit” returns a boolean value obviously. Any ideas on why the GameObject can’t be turned off?

public void OnClick()
{
    if (Game.instance.selectedUnit != null)
    {
        if (Game.instance.localPlayer.TransferEnhancementToUnit(Game.instance.localPlayer.Enhancements[enhancementIndex], Game.instance.selectedUnit))
            gameObject.SetActive(false);
    }
}

I can’t reason about 200-character lines like 5, but if you say it is executing, then put proper open/close brackets around the SetActive() call and also put a Debug.Log() statement in there and prove that it is running.

If it really is running, then something else is turning this gameObject back on. Remember once this gameObject is OFF, then most things in this script will never get called again.

In general, 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 are the values of the variables involved? Are they initialized?

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

“Proper” open/close brackets aren’t required for a single IF statement line. However, adding them doesn’t change anything. I know this because I did have Debug.Log items sprinked throughout (which required me to have the brackets around gameObject.SetActive(false). I mentioned that when I said: [quote=“DRRosen3, post:1, topic: 834481, username:DRRosen3”]
The IF statement that encapsulates that line does indeed return true (as I’ve tested it thoroughly through debugging).
[/quote]

I’ve also ruled this out as an issue already, by adding an OnDisable method to the class, and Debug.Log’ing inside that method. That Debug.Log is never printed to the console, which means OnDisable is never called, meaning the GameObject was never turned off (and thus never back on).

This too doesn’t hold any weight to the issue because as I mentioned I know for a fact that Game.instance.localPlayer.TransferEnhancementToUnit() is returning true, because I’ve put a Debug.Log inside that method as well.

Is there a reason you haven’t done this yet?

if (Game.instance.localPlayer.TransferEnhancementToUnit(Game.instance.localPlayer.Enhancements[enhancementIndex], Game.instance.selectedUnit)) {
    Debug.Log($"Deactivating {gameObject.name}. Current state: {gameObject.activeInHierarchy} ", gameObject);
    gameObject.SetActive(false);
    Debug.Log($"Finished deactivating {gameObject.name}. Current state: {gameObject.activeInHierarchy} ", gameObject);
}

Basically one of your assumptions about what’s happening is wrong (as is the case with any bug). Either this code isn’t running, your condition is returning false, or it’s working and running, but something else is re-activating the object shortly after this code.

One other possibility is that if you are running this code somewhere other than the main thread, it may unceremoniously die without any errors when you try to deactivate the object.

1 Like

I’ll give your Debug suggestion a shot. However, I’m not making any assumptions here. I’m 100% sure that the condition is returning true (because I have it set to Debug what it returns). So… Unless Unity hasn’t properly documented the OnDisable method…as I’ve stated that I have a Debug message inside of OnDisable…it’s never being deactivated. If the GameObject was truly being deactivated (at any point) that OnDisable Debug message would print to the console. It never does.

Assuming:

  • this script is ON the gameObject in question

  • the OnClick is actually correctly connected to the button

  • the GameObject was enabled to begin with

  • this script was enabled to begin with (otherwise it wouldn’t get OnDisable())

etc. etc.

These are just 15 seconds off the top of the latte foam floating on my brain.

There’s probably 50 other possible reasons, ZERO of which have to do with Unity having a bug.

Why do people always recommend debug logs when you can just use the debugger and set a breakpoint at the if, then you can step over it to see if the condition is true/false, if it is false you can hover the conditions with the mouse to check why it is false (or drag the variables in the watch window if you need more information), much faster and easier than putting debug logs everywhere

Honestly I recommend Debug.Log a lot around here because it’s easier than teaching beginners how to use the debugger.

That being said log statements have some advantages and are easier to use in certain circumstances. They are different tools with pros and cons.

For example log statements are great when you want quick feedback while maintaining interactivity of the application.

2 Likes

Because Unity doesn’t freeze. With interactive game software it may be necessary to do the same thing 57 times to get the problem to show up, or to get it to show up enough for you to reason about what is going on.

If every single time Unity froze solid while you looked in the debugger and decided this was NOT the time that it was interesting to you, it gets extremely tedious.

It’s further complicated by if the error condition you are investigating is only triggered by continuous user input, such as moving right or thrusting your spacecraft: When you return to running, you have physically let go of the key but Unity still thinks it is down (because it never saw the key up message), and now you have lost control of the game and probably die.

And now you have to get to that level and that situation again.

And as Praetor says, it’s just easier. I can explain to my grandmother how to put Debug.Log() statements into code. I can’t explain to her how to attach a debugger, start the game, put a breakpoint in (“how come it’s a red hollow circle honey?”). etc.

Not only that, but Debug.Log will ALWAYS work on EVERY platform, debugger or not.

Sure it’s easier to explain how to add a debug log to a beginner, but you don’t have to teach them how to use a debugger, because there are already tutorials, but atleast mention it, so they can look it up.

If the debugger breaks at a time “it was not interesting to you” then you did not setup your breakpoints (conditions) correctly.

As Praetor said they are tools for different cases and yes debug log is better in certain circumstances, but im talking about OPs code where the question is why the code doesn’t run and in that case the debugger is the better choice, because like I already said above you can set a breakpoint at the if statement and step over it to see if the condition was met and if not you can check state of the conditions to see why it wasn’t true.

True, though it’s rather common that people are going to ask for detailed instructions. Sure, you can keep redirecting them to tutorials or just leave the thread alone. But usually one replies in order to actually get things resolved.
It’s simply more straightforward to go with console logging.

I usually recommend both, hoping that the one or other takes note of that information and has enough ambitions to search for it on the internet in order to learn something new. But when you deal with individuals who do not search by themselves, it’s more-likely turning into a back and forth - most of the people are here to help on actual problems (bugs, architecture, engine details, specific behaviours) rather than finding up-to-date and easy-to-understand tutorials for IDE xyz - that’d be a good sticky thread though, like the one about code tags.

1 Like

If “there are already tutorials” was actually a thing, people wouldn’t be in the forums asking questions.

Yes there are tutorials for the debugger. But have you even tried to pretend you’re a new user and work through one? Anyone who has used Unity for a few years on a few different versions and installations and operating systems know that getting a debugger to attach is anything but simple.

Yet if you can correctly type the syntax for Debug.Log(), I have NEVER seen that fail.

I’m not saying DON’T attach the debugger. I’m saying if I’m typing one sentence to a new user of Unity on the forum, that sentence is going to be “sprinkle some Debug.Log() calls in, see what’s going on.” It will never be “attach the debugger.” That’s just not going to get the results you imagine it will.

Learning to debug (by debug logs and attaching the debugger) is as important as programming itself, so it’s worth the few minutes of research to learn how to do it, it’s not as hard as you make it sound. So a sticky that explains both would be a good idea.

Sorry OP for dragging your post so offtopic, this is my last comment about the debugger topic, let me know if you still need help with your code.

1 Like

So I’m only posting this for anyone that was interested, or may come across this in the future. I used PraetorBlue’s suggested debugging, but didn’t really find out anything new. The reason for that is that we decided to go a different design route, and moved away from using a Button.

When I did use the suggested debug method above, both debug lines printed to the console; and the state of the second line was true. Hope this helps anyone else that may run into this problem get a head-start on figuring out Unity UI Button’s and turning them (their GameObject) off via code when pressed.