title: How to develop RPG Damage Formulas?

text:
# Question
Title: How to develop RPG Damage Formulas?
I'm developing a classical 2d RPG (in a similar vein to final fantasy) and I was wondering if anyone had some advice on how to do damage formulas/links to resources/examples? I'll explain my current setup. Hopefully I'm not overdoing it with this question, and I apologize if my questions is too large/broad

My Characters stats are composed of the following:

```
enum Stat
{
    HP = 0,
    MP = 1,
    SP = 2,
    Strength = 3,
    Vitality = 4,
    Magic = 5,
    Spirit = 6,
    Skill = 7,
    Speed = 8, //Speed/Agility are the same thing
    Agility = 8,
    Evasion = 9,
    MgEvasion = 10,
    Accuracy = 11,
    Luck = 12,
};

```

Vitality is basically defense to physical attacks and spirit is defense to magic attacks.

All stats have fixed maximums (9999 for HP, 999 for MP/SP and 255 for the rest). With abilities, the maximums can be increased (99999 for HP, 9999 for HP/SP, 999 for the rest) with typical values (at level 100) before/after abilities+equipment+etc will be 8000/20,000 for HP, 800/2000 for SP/MP, 180/350 for other stats

Late game Enemy HP will typically be in the lower millions (with a super boss having the maximum of ~12 million).

I was wondering how do people actually develop proper damage formulas that scale correctly? For instance, based on this data, using the damage formulas for Final Fantasy X as a base looked very promising. A full reference here http://www.gamefaqs.com/ps2/197344-final-fantasy-x/faqs/31381 but as a quick example: Str = 127, 'Attack' command used, enemy Def = 34.

```
1. Physical Damage Calculation:
Step 1 ------------------------------------- [{(Stat^3 ÷ 32) + 32} x DmCon ÷16]
Step 2 ---------------------------------------- [{(127^3 ÷ 32) + 32} x 16 ÷ 16]
Step 3 -------------------------------------- [{(2048383 ÷ 32) + 32} x 16 ÷ 16]
Step 4 --------------------------------------------------- [{(64011) + 32} x 1]
Step 5 -------------------------------------------------------- [{(64043 x 1)}]
Step 6 ---------------------------------------------------- Base Damage = 64043
Step 7 ----------------------------------------- [{(Def - 280.4)^2} ÷ 110] + 16
Step 8 ------------------------------------------ [{(34 - 280.4)^2} ÷ 110] + 16
Step 9 ------------------------------------------------- [(-246)^2) ÷ 110] + 16
Step 10 ---------------------------------------------------- [60516 ÷ 110] + 16
Step 11 ------------------------------------------------------------ [550] + 16
Step 12 ---------------------------------------------------------- DefNum = 566
Step 13 ---------------------------------------------- [BaseDmg * DefNum ÷ 730]
Step 14 --------------------------------------------------- [64043 * 566 ÷ 730]
Step 15 ------------------------------------------------------ [36248338 ÷ 730]
Step 16 ------------------------------------------------- Base Damage 2 = 49655
Step 17 ------------ Base Damage 2 * {730 - (Def * 51 - Def^2 ÷ 11) ÷ 10} ÷ 730
Step 18 ---------------------- 49655 * {730 - (34 * 51 - 34^2 ÷ 11) ÷ 10} ÷ 730
Step 19 ------------------------- 49655 * {730 - (1734 - 1156 ÷ 11) ÷ 10} ÷ 730
Step 20 ------------------------------- 49655 * {730 - (1734 - 105) ÷ 10} ÷ 730
Step 21 ------------------------------------- 49655 * {730 - (1629) ÷ 10} ÷ 730
Step 22 --------------------------------------------- 49655 * {730 - 162} ÷ 730
Step 23 ----------------------------------------------------- 49655 * 568 ÷ 730
Step 24 -------------------------------------------------- Final Damage = 38635

```

I simply modified the dividers to include the attack rating of weapons and the armor rating of armor.

Magic Damage is calculated as follows: Mag = 255, Ultima is used, enemy MDef = 1

```
Step 1 ----------------------------------- [DmCon * ([Stat^2 ÷ 6] + DmCon) ÷ 4]
Step 2 ------------------------------------------ [70 * ([255^2 ÷ 6] + 70) ÷ 4]
Step 3 ------------------------------------------ [70 * ([65025 ÷ 6] + 70) ÷ 4]
Step 4 ------------------------------------------------ [70 * (10837 + 70) ÷ 4]
Step 5 ----------------------------------------------------- [70 * (10907) ÷ 4]
Step 6 ------------------------------------ Base Damage = 190872 [cut to 99999]
Step 7 ---------------------------------------- [{(MDef - 280.4)^2} ÷ 110] + 16
Step 8 ------------------------------------------- [{(1 - 280.4)^2} ÷ 110] + 16
Step 9 ---------------------------------------------- [{(-279.4)^2} ÷ 110] + 16
Step 10 -------------------------------------------------- [(78064) ÷ 110] + 16
Step 11 ------------------------------------------------------------ [709] + 16
Step 12 --------------------------------------------------------- MDefNum = 725
Step 13 --------------------------------------------- [BaseDmg * MDefNum ÷ 730]
Step 14 --------------------------------------------------- [99999 * 725 ÷ 730]
Step 15 ------------------------------------------------- Base Damage 2 = 99314
Step 16 ---------- Base Damage 2 * {730 - (MDef * 51 - MDef^2 ÷ 11) ÷ 10} ÷ 730
Step 17 ------------------------ 99314 * {730 - (1 * 51 - 1^2 ÷ 11) ÷ 10} ÷ 730
Step 18 ------------------------------ 99314 * {730 - (51 - 1 ÷ 11) ÷ 10} ÷ 730
Step 19 --------------------------------------- 99314 * {730 - (49) ÷ 10} ÷ 730
Step 20 ----------------------------------------------------- 99314 * 725 ÷ 730
Step 21 -------------------------------------------------- Final Damage = 98633

```

The problem is that the formulas completely fall apart once stats start going above 255. In particular Defense values over 300 or so start generating really strange behavior. High Strength + Defense stats lead to massive negative values for instance. While I might be able to modify the formulas to work correctly for my use case, it'd probably be easier just to use a completely new formula. How do people actually develop damage formulas? I was considering opening excel and trying to build the formula that way (mapping Attack Stats vs. Defense Stats for instance) but I was wondering if there's an easier way? While I can't convey the full game mechanics of my game here, might someone be able to suggest a good starting place for building a damage formula?

Thanks

# Answer
Creating formulas like this requires knowledge of elementary mathematical functions \- the things you learned about in Algebra and Pre-calculus class.

Once you have those mastered, just ask yourself *(replace "value" with "damage," or "health," or "speed" or whatever)*:

Then just tweak it *(add/multiply stuff, change the base-value, etc)* until it feels right. A graphing calculator will help you visualize how changes to the parameters will affect the function.

---

By the way, the problems you are experiencing are due to integer overflows.

Use variable-types that are large enough to hold the numbers you're working with. Sizes differ by platform in C++, but using the 32-bit Visual Studio compiler, `unsigned int` is 32-bit, while `unsigned __int64` *(MS-specific)* is 64-bit. Also consider using a `double`.

Additionally, try to reorganize your operations so that you don't encounter such large numbers in the first place *(for example, rather than `MDef * MDef / 110`, do `(int)((float)MDef / 110 * MDef)`)*.
> 154 votes

# Answer
> My Characters stats are composed of the following:

There's your real problem: you defined your stats *before* defining what those stats actually *mean*. You're putting the cart before the horse.

Look at how D&D (tabletop) works. "Strength" doesn't mean anything by itself; it only means something because there's a rule that says, "Add your strength bonus to your melee attack." That rule is part of D&D's combat rules. Without the combat rules, "Strength" is generally a meaningless quantity.

The first question you need to ask yourself is this: how much differentiation do I want between characters? Again, look at D&D. There, they have 6 basic stats. These stats define different dimensions of play for characters. A character with a high Dexterity will have different options from a character with low Dexterity.

But the reason for even that difference all comes back to rules. A high Dexterity means bonuses to ranged attacks; you can hit more often with ranged attacks. So just between Strength and Dexterity, you have two dimensions of play: ranged vs. melee.

Intelligence and Wisdom also form something of a pairing, but these interact more with specific classes. Int makes Wizards and other arcane spellcasters better (or *possible* under some rulesets), Wisdom is vital for Clerics and other divine spellcasters. Because divine and arcane spells have different spell lists, these two stats are involved in different dimensions of play.

You need to define the basic rules around stats *before* you can define growth progression functions and the like. You don't need specifics; you don't need to say that "each point of strength is added into the random roll to determine if a melee attack hits." What you need are meta-rules like "dexterity makes ranged attackers better." You can figure out exactly *how* it makes them better later on.

There are different ways to progress characters. A common old-school Final Fantasy trick was to simply use the character's level as part of their damage computations. This could be simply multiplying the level by the appropriate stat, or it could mean applying a function to the character's level. Say, a quadratic progression, so that the rate of a character's damage would increase per level.

However you want your combat functions to work, they need to take into account progression. Your functions need hooks for progression.

D&D has a funny way of progression. It is part class-based; every time you go up in level, you get new class features and a flat bonus to your to-hit, based on your character class. However, some class features got better by themselves. Spells in D&D would have progression built into them. A spell might do 1d4 damage per 2 levels of a spellcaster above the first. So every other wizard level makes that spell better.

D&D also used item-based progression heavily. Until 4th edition, item-based progression was mainly for fighting characters, but even in older editions, spellcasters had items that gave them stat buffs or other adjustments (or flat out gave them spells).

So items are another thing your combat functions need to take into account. Do items just buff one or more stats while equipped, or do they do other things as well? D&D was a bit odd, in that stats rarely changed; weapons simply did XdY damage, possibly with a bonus based on one of your stats. And that was that. So your only way to do more damage in battle was to find a better weapon. In many videogame RPGs, they take level into account in addition to a weapon.
> 39 votes

# Answer
Your formulas seem pretty complicated. I'm not sure how professional RPG developers handle this, but I'd recommend on focusing on simplicity. Try to find the simplest possible formula you can that still incorporates the range of stats you want to use. For instance, could you have stats modify each other prior to damage calculation, rather than modifying the damage during the calculation? Once you've got a formula in mind, I'd try graphing it for a wide range of possible values to see how it will behave as players level up. Obviously the fewer variables you have, them more feasible this will be.

Additionally, BlueRaja provided an important explanation of why you might be seeing unexpected values at higher stat levels. Using unsigned types and checking for overflows will be important.
> 23 votes

# Answer
> Late game Enemy HP will typically be in the lower millions (with a super boss having the maximum of ~12 million).

This I have a problem with. You should build your bosses around what you think your players should be able to handle. You're building your players and combat formula around what you want your bosses to be like.

Once you get your combat mechanics and roles built, then you can decide on how you want to design your bosses as it should be a good balance between the damage the players can deal/absorb vs what the boss can deal/absorb.
> 11 votes

# Answer
Those numbers you quoted are likely derived from a just tweaking a simulation, over thousands of runs.

So you should **write a simulation** create a level 20 character, and see how he fares through 200 battles or so against the enemy types he's supposed to be fighting at that point. Do it again for a level 30 character (in presumably the next section of the world).

It'll take a while to get right, but writing automated simulations will definitely make this much easier than just guessing and manually playing it out.
> 10 votes

# Answer
I think you make the mistake that you want to create a formula without having a proper design in mind.

First start with a design, then start thinking about representing the design in formulas. The clearer your design the easier it should be to find simple and/or precise formulas.

Try to implement "types" of enemies, e.g. "armored" =\> a player attack if it is of type physical is reduced by 50%. Do not make a battle flow to abstract, think about what is relevant and what is not.

If your design says "armored enemies" are weak against magic but strong against physical damage, represent that in code. But remember that you have do a lot of testing, because the values won't work magically the first time you write the code. Try to create a design, put the logic into code, always check whether this the technical representation of what you had in mind and if it isn't change the values until it is.
> 5 votes

# Answer
Although my design have not left Spreadsheet phase, I have came to one conclusion about designing math for RPG:

Keep them as simple as possible. In design that I'm working on, I used very simplistic formulas, that are adequate to semi class-less system. Ie. Fireball Spell have damage of 30. The forumal is:

```
BaseSpellDamage * Attribute (5 * 6)

```

We can also add modifiers like this:

```
Result = (BaseSpellDamage * Attribute) (5*6)
Result = Result + (Result * 50%) (30 = 30 + (30 * 50%))

```

So end result would be 45 damage. I found that using precentage multipliers is very easy, and very scalable solution to work with. Instead of coming with some odd numbers with complex math to figure out the result we want.

Now we can calulcate damage reseistance, that will just calcucate defense against set type of damage. There are two approaches and I honestly haven't decided which would suit better, but they both are simple and viable:

```
DamageResult = Resistance * Damage ( 50% * 45)

```

So the end result will be 22damage taken (I just cut the partial result).

Other formula:

```
DamageResult = Damage - Resistnace (45 - 22).

```

So end result will be 23. If it happen that resistance is bigger than damage taken then character just doesn't recieve any damage. Of course it's up to you to make sure that such situation have no place, except for when you want it be the case.

Although I must admit that precentage scaling is somewhat easier to balance and scale. But this also depends on your base numbers. Precentage scaling will work best if you start from 100 and up. If you are operating on small numbers (anything below 100 to be honest), it can get awkard as you will start getting floating point results, that will be hard to balance and actually do anything interesting with them.

Probably optimal solution in that case is to use both approaches when they see to fit. Or if you are fan of big numbers start from 1000.

And at the closing ends. I haven't come to this conclusions completly on my own. I have actually spend quite some time reading various RPG manuals (Hero, DnD). Especially DnD was helpful, as it operates on similiar principles but instead of attributes it's using levels for it's formulas, they can be sometime more complex. Than what I presented here.

In anycase, the best advice is: try to keep them as simple as possible. Do not use any advanced math, or long equations, as they are prone to errors, that are hard to spot, when you have to deal with 87234 other things at the same time.
> 5 votes

# Answer
As others have mentioned, the Final Fantasy X formula is pretty complex. Generally for that series the later the game, the more complicated the formula. It's probably easier to base your damage formula on another game entirely. But in general, I think it's worth discussing from a very general level what kind of damage formulas you can find in the world, and how you can make a game based around them. The first thing you need to decide is how much damage do you want to be able to do at the end of the game, and what kind of stats do you want the player to be able to have? Once you have that, you can pick a formula system, and then optimize the formula and weapon values to reflect those ranges over time.

## Purely Stat-Based

This is a good idea if you want your characters to be flexible in terms of what levels of enemies they can challenge. A formula like this is only going to depend on the player's stats, their equipment, and the stats of the enemies. These formulas are usually fairly simple. Final Fantasy Legend II (See http://www.shenafu.com/ffl2/weapon.php for instance, has weapons that do damage based on the simple formula:

```
(Stat+StatBonus)*WeaponStrength - Defense*4

```

A formula like this is good if you want a very simple method of estimating damage, or a quick jumping off point for modifying damage based on other factors like skills and elemental weaknesses.

To show how broad this kind of formula can truly go, consider the damage formula for Inflation RPG, an Android and IOS game (See http://inflation-rpg.wikia.com/wiki/Calculations). The formula is heavily both stat and equipment dependent. Each piece of equipment has two stats - a bonus to the ATK stat, and a multiplier value. Some pieces of equipment have low multipliers, but high bonuses, others have low bonuses but high multipliers. For a character with only 10 ATK, the Battle Axe with it's 5000 ATK Bonus but low 145% multiplier is a great choice. The total damage is `(10+5000)*1.45 = 7264`, but the Estoc, with 0 bonus and a multiplier of 300% is a poor choice - the damage is `(10+0)*3 = 30`. Later in the game, a character with 5000 attack would prefer switching weapons.

## Stat- and Level-Based:

A good example of this is Final Fantasy V, VI, and Final Fantasy XII (See http://www.gamefaqs.com/ps2/459841-final-fantasy-xii/faqs/45900, for example). The formula for swords in FFXII is:

```
DMG = [ATK x RANDOM(1~1.125) - DEF] x [1 + STR x (Lv+STR)/256]

```

and the damage formula for staves is:

```
DMG = [ATK x RANDOM(1~1.125) - DEF] x [1 + STR x (Lv+MAG)/256]

```

They're very similar, but notice that the sword formula only depends on the strength and level, while the staff formula depends on strength, *magic* and level. The advantage to this kind of formula is that it allows the player two avenues of growth - building their stats, or building their levels. The downside is that it also penalizes characters both ways as well. What this really ends up doing is allowing the player to level up to increase their damage output (for FFXII this amounts increasing their damage output by ~4% per level around level 50 when you factor in stat gains) to help customize the difficulty to their comfort level.

## Fixed Damage:

Fixed-damage formulas do not depend on the character's stats or level, they depend only on the internal damage formula of the weapon itself. They can still vary over a range, but they deal the same damage regardless of the user (barring any other special effects or character traits). They're best used if the weapon is going to do fixed-damage and the ability to equip the weapon depends on either stats and/or level. Diablo 2, for example, does this, as do many roguelikes which have weapons that depend on die rolls. That being said, 'fixed damage' does *not* imply "non-random" - and in fact there's usually some element of randomness to the damage done.

This is a good methodology if you want to have weapons that are easy to transfer between characters or to carefully control the damage output that characters at certain points in the game can do if you know what equipment they have access to (via drop tables, chests, and steal tables).

Another place you'll run into this is with certain types of equipment or items in Final Fantasy. 1000 Needles, for instance, always deals 1000 damage. In Final Fantasy Legend II, martial arts deal damage based on the formula:

```
Damage = WeaponStrength*(90-UsesLeft) - 4*Defense

```

Final Fantasy XII has somewhat fixed damage for guns as well, dealing damage according to the formula:

```
DMG = [ATK x RANDOM(1~1.125)]^2

```

Although the damage is somewhat random, it only varies by 26.5 percent over the total range, so you're guaranteed to do a certain level of damage on average over time. These types of attacks are useful for characters who have both low stats and low levels in games that normally account for those factors in dealing damage. Plus, they ignore the defense of the target (although the formula could be easily reworked to fit in defense if you so desired).
> 5 votes

# Answer
all games in the final fantasy series have had a stat cap of 255 because of the problem you are encountering. at level 100 stats would be 255.

you say about increasing stats with abilities and equipment and I remember seeing this in the games but the way this is done is in the formula. there is an extra step that checks for ability and equipment modifiers and applies them after the stats have been used.

in your case it would be step 21: apply ability modifiers step 22: apply equipment modifiers step23: final damage.

if you are interested google for final fantasy formulas, they are out there. I have copys of the actual battle mechanics including AI for final fantasy 4, 6, 7 and 9. people cracked them from the original games when they were creating roms for emulators. There not that hard to find if you look hard enough.

the biggest thing for creating formulas is testing. set up a script to run your battle wit ai on both side and run several hundred battles. vary the monsters and the stats and see if it works or if lv 40 kills everything, it is entirely possible that a boss is actually impossible to kill lol. a tip would be to turn off all animation as it is impressive how fast AI's can battle when no one is watching.
> 2 votes

# Answer
> I was wondering how do people actually develop proper damage formulas that scale correctly?

The first 2 things are:

* decide what you mean by 'correctly' - what is your idea of 'correct damage'?
* decide what you mean by 'scale' - what values are going to change, and what effect do you want those changes to have?

Once you know that, you have enough information to use the mathematical formulas that BlueRaja mentioned in his answer. Just remember there is no such thing as a 'proper' damage formula - just one that matches your design for the type of experience you want your players to have.
> 2 votes

# Answer
In essence, you need to figure out two things.

1. How to properly preform computation with large numbers.
2. How you want and expect attack damage to behave against weaker and strong opponents.

# 1

You can either use a `double` data-type or a big number library. Doing computations with large numbers (like in clicking / idle games often relies on such big number libraries). In your case, the numbers are relatively small so using 64-bit floating point will allow the needed flexibility.

# 2

How do you want the game to behave? some examples:

* One approach is to use `ATK` to decide if you hit or not and roll a die with a known damage rating depending on the weapon: for instance long sword 1d8, two handed sword 1d10, dagger 1d4. This will not scale amazingly well if the hp can grow on and on. If you use `ATK` to determine if the characters hit or miss, you can do another throw after a successful hit with `ATK * X%` to determine crits. This would mean game characters get more crits against weaker opponents but far less against stronger ones.
* If you want to use a damage formula, the damage formula can be as simple as `(ATK - DEF) +/- 20%` as it's done in World's End (an RPG strategy game). This will mean that attacks against an opponent with strong `DEF` could do no damage at all. For instace `ATK = 10`, `ENEMY DEF = 12`, `(ATK - DEF) = -2` and it also means that high attack vs slightly lower def, could do little damage, potentially making battles longer with increasing HP. For instance with `ATK = 1010`, `ENEMY DEF = 1005`, the damage would be 5. The damage will also increase dramatically now if the `ATK` is increased by a small percentage. For instance `ATK = 1055`, will do 900% more damage with only a %5 increase in `ATK` value.
* To avoid this, you can do something like `ATK / DEF * WEAPON_DAMAGE` This will scale more gradually when `ATK` or `DEF` are increased and allow a weak attacker to damage a creature with strong `DEF`.

tl;dr You need to treat your numbers responsibly and figure out how you want the game to behave in different situations. Some questions to ask yourself:

1. How many attacks (turns), should it take to defeat that boss / minion?
2. How should different skills, buffs, debuffs affect `x` battle? Should it be hopeless, should winning be `y%` less / more likely?
> 2 votes

# Answer
alternativly, if your looking for a very simple formula, Do the following:

(Note that this is my idea for a formula,)

First, for a simple attack formula, you will only need a few stats. THe player's Attack stat (this could be Strength, or Magic, depending on the type of move.)

Then, create a variable, called MovePower. This will depend on the move, and better moves would have a better MovePower. For my formula's, general "Attack" commands have a MovePower of 5.

Then, make the defence a percent based stat, (and, of course, make it inpossible to achieve 100% defence on damage)

Then, during the attack phase, simply multiply the attack stat by the move power, and remove damage based on the foes defence! simple!

You can also opt to have other modifyers, like if the move will hit (Accuracy), if the move has another added effect (Bio, inflicting poison,) and opt for that to hit, (Accuracy again,) have damage upgrading/downgrading moves that change stats, ect. Have fun with it!
> 1 votes

# Answer
that physical damage formula is the EXACT SAME as the one used in Final Fantasy 10. Those formulas were meant for stats UP TO 255, especially the defense stat. Here is the page on GameFAQs that explains the formulas: https://gamefaqs.gamespot.com/ps2/197344-final-fantasy-x/faqs/31381 Scroll down to the full damage calculation and you will see that those were pretty much copy and pasted. Tweak the formulas so that the defense will actually absorb damage like it is supposed to and so the damage does not increment so fast, because a 3 point strength increase will result in a massive increase of damage from my perspective from my playthrough of FF10 when I increased a party member 3 strength. Those formulas are meant for small increases of stats like how the sphere grid works. They are NOT meant for level ups where your stats increase quicker. Here is why you should cap your stats at 255 only if you are using those formulas: In FF10 once you are at 255 strength with the celestials, you will deal at least 99,999 damage, if not more since the cap is 99,999. Now try to find out how much damage it will be at 999 strength.
> -1 votes

---
Tags: game-design, mathematics, game-mechanics
---


# Question
Title: How to enable treat warnings as errors in Unreal Engine 4.24?
I've had little luck googling and it takes about an hour to build the engine (which I have to do if I'm to test if it works), so guessing is a bit time consuming.

I've seen advice to add the `'/WX'` flag to `*.target.cs`, as well to one of the functions in `VCToolChain.cs`, but I wasn't able to make it work.

Has anyone here enabled this and knows how it works? I don't think it matters, but I've been using VS2017.

# Answer
# Assumptions

* You're building the Unreal Engine from the github source.
* You're on Windows 10.
* Instructions from **Visual Studio 2019 Community Edition** are similar to those for **VS2017**.

# Solution

The advice you got regarding **/WX** option is correct, but I don't think the ***.target.cs** file was the proper place to put it. I see hints that there is a variable to append additional command-line options in that file, but nothing solid. Also, since there are multiple targets that you can build, I figured the following is the safest way to go.

## Steps

1. Open the solution, **UE4.sln**.
2. Right-click on the project **UE4 \> Properties**.
3. Go to **Configuration Properties \> NMake \> Additional Options**.
4. Append **/WX** to the list of options already there.
5. Press **Okay** and rerun your build.

Hope that solves your problem!

# Additional Notes

The solution here configures **msbuild** to build the Unreal Engine binaries. Once you have those binaries build, the **Unreal Build Tool (UBT)** binary is used to build your UE-specific code (instead of msbuild). The configured **UBT command** treats warnings-as-errors by default.

# References

MSVC Compiler Options \> Warning Levels

Understanding Unreal Build Tool
> 1 votes

---
Tags: unreal-4
---


title: .isGrounded is not working reliably

text:
# Question
Title: .isGrounded is not working reliably
New to Unity and C#, though, I got the code from the official doc page for Character Controller and thought that should work by default.

When pressing the Jump button here it doesn't always work. When checking if the player is grounded the variable `groundedPlayer` not always provides `true` when idle/not moving. Instead, the value is constantly changing between true and false.

Below is my current code which was modified a little:

```
public class PlayerController : MonoBehaviour
{
  private CharacterController controller;
  private Vector3 playerVelocity;
  private bool groundedPlayer;
  private float jumpHeight = 1.0f;
  private float gravityValue = -9.81f;

  private void Start()
  {
    controller = gameObject.AddComponent<CharacterController>();
  }

  void Update()
  {
    groundedPlayer = controller.isGrounded;
    //this will constantly return both false and true while idle
    print(groundedPlayer + ", " + playerVelocity + ", " + gameObject.transform.position.y.ToString("f8"));
    if (groundedPlayer && playerVelocity.y < 0)
    {
      playerVelocity.y = 0f;
    }

    if (Input.GetButtonDown("Jump") && groundedPlayer)
    {
      playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
    }

    playerVelocity.y += gravityValue * Time.deltaTime;

    controller.Move(playerVelocity * Time.deltaTime);
  }

}

```

It's just that I feel dumb since basic jumping is this difficult to implement for me. I feel like I'm missing something very obvious. I found 1 working solution for me which is implementing coyote time, but it looks like a workaround and might provide more glitches in the future. I also could try working on creating my own character controller, though that's a whole different field.

Anyone had this issue before? How did you fix it?

# Answer
Apparently the downforce vector was too small to make Unity recognize collision. I am not sure how big the vector has to be or if anything affects how big it has to be but in my case it is something around `-0.45f`. I've set the downforce vector to at least `-0.5f` when it first gets grounded and seems like it's working as intended now. The only issue is that I have to keep in mind that I have a fix of -0.5 now by default.

So `playerVelocity.y = 0f` changed to `playerVelocity.y = -0.5f;`:

```
  void Update()
  {
    // jumping mechanic
    groundedPlayer = controller.isGrounded;
    if (groundedPlayer && playerVelocity.y < 0)
    {
      playerVelocity.y = collisionFixForce;
    }

    if (Input.GetButtonDown("Jump") && groundedPlayer)
    {
      playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue + -collisionFixForce);
    }

    playerVelocity.y += gravityValue * Time.deltaTime;

    controller.Move(playerVelocity * Time.deltaTime);
  }

```
> 1 votes

---
Tags: unity, c#
---


# Question
Title: How to set the Y position of Camera to another object's y position, but only once, not continuously?
Essentially, I want to set the camera's Y position to another GameObject's Y position, but I only want to do this one. If you do

`cam.transform.position = new Vector3(0, thing.transform.position.y, 0)`,

it will continuously update to that object's y. Even if I store the Y float in a variable and set the camera's y to that it still continuously updates. It is only supposed to happen once.

# Answer
> 1 votes
You can set the camera's Y position once by setting it in one of the built-in functions that's executed only once. In Unity there's two such functions and they're called `Start` and `Awake`.

Some information about the two functions:

* The `Start` function gets called on the frame when a script is enabled, just before any Update function is called the first time.
* The `Start` function is called only once during the lifetime of the script instance.
* The `Awake` function gets called when a script instance is being loaded.
* Just like the `Start` function, the `Awake` function is also only called once during the lifetime of the script instance.
* The `Awake` function is always called before any `Start` functions.

Based on the above information, we can make sure that the other object, let's call it the `target object`, is fully initialized and correctly positioned before the position information is retrieved from it and the camera's position is set.

I'm not very familiar with Unity so the code example below is pseudo code and needs to be adapted/edited to work in Unity.

```
// Script attached to the camera object
public class CameraPositionScript : MonoBehaviour
{
    // The target object which the camera object should retrieve the position from
    private GameObject target;

    void Awake()
    {
        // The target object has been initialised at this point, so it's safe to reference it here
        target = GameObject.FindWithTag("TargetName");
    }

    void Start()
    {
        // Set the camera's Y position to the target object's Y position, this is done only once
        gameObject.transform.position.y = target.transform.position.y;
    }
}

```

# Answer
> 0 votes
If you have the cam target a `Transform` then you can use that so it just moves to whatever is in the selectedTarget field.

That way thing1 and thing2 ect could swap back and forth or whatever else you were selecting and all you would have to do is assign the transformTarget to a new transform.

To run only once in the update you can add a condition to check then you could do something like this.

```
public Transform selectedTarget;
string cachedTargetsName="";//set to cache the selections name
void Update()
{
   if(selectedTarget.gameObject.name != cachedTargetsName)
   MoveOnceToTargetsY();
}
void MoveOnceToTargetsY()
{
     cam.transform.position = new Vector3(0, selectedTarget.position.y, 0);
     cachedTargetName = selectedTarget.gameObject.name;
}

```

you can likely add a condition similar to `if(selectedTarget.gameObject.name != cachedTargetsName)MoveOnceToTarget()` various other ways to accomplish also like a OnChanged Event or something along those lines but this should get you on the right path.

# Answer
> 0 votes
If you want to this in the mid of your game, You can use "Flags". Syntax will be like below :

```
bool flag;  //It is False by default
fun()
{
   if (!flag)
   {
       flag = true; //set your flag
       //Your one time executable code
   }
 }

```

If you want to do it again, simply reset your "flag".

# Answer
> -1 votes
void Update() { if (parameterIsMet) { cam.transform.position = new Vector3(0, thing.transform.position.y, 0); } }

---
Tags: unity, c#
---


# Question
Title: How do I stop my skeleton from playing the walking animation?
I'm trying to get a Skeleton Model to go from its walking animation to its idle animation using a `bool` that checks for input. Currently, in-game, the skeleton doesn't leave its walking animation and stays in it even when not walking.

Here is the code I'm using:

```
public class SkeletonMove : MonoBehaviour
{
    private float velocity = 5f;
    public bool _isWalking = false;
    Vector2 input;

    void Update()
    {
        GetInput();

        if (Mathf.Abs(input.x) < 1 && Mathf.Abs(input.y) < 1)
            return;

        Rotate();
        Move();
    }

    void GetInput()
    {
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");
    }

    void Move()
    {
        _controller.Move(transform.forward * velocity * Time.deltaTime);
        _anim.SetBool("Walking", _isWalking);

        if (input.x != 0 || input.y != 0)
            _isWalking = true;

        if (input.x == 0 && input.y == 0)
            _isWalking = false;
    }

```

# Answer
> 1 votes
Welcome to the GameDev Stack Exchange.

As other users pointed out, GetAxisRaw returns values in the range of \[-1, 1\] which means if a user (or skeleton in your case) is not holding down both keyboard buttons or a joystick in the exact correct position, you will be returning values less that 1 or greater than -1. This will cause your animation code to return earlier than you probably planned. I believe this is the main source of your problem.

However I think there is another issue with your code. If you take a close look at your Move() function, you will see that you are actually updating your animators Bool before you update the value of \_isWalking. This means any update you send to your animator will be 1 update frame late, and if you are short circuiting (returning earlier to avoid running additional extra code) you may never pass the correct value into your animator.

These problems often pop up a lot and can be confusing to new game programmers, so I would suggest you look into adding code like `Debug.Log("My current input is: " + input.x + ", " + input.y);` in places you think might be going wrong. If your case `Debug.Log("Setting animation controller Walking bool to: " + _isWalking);` would help you know when and if you are sending your updates to the animation controller.

Here is slightly updated version of your script that I think will help fix your issues. It might have some compile errors (sorry I didn't test it) but I think you can probably get it working without too much trouble.

```
public class SkeletonMove : MonoBehaviour
{
    private float velocity = 5f;
    public bool _isWalking = false;
    public bool debugMode = false; // normally you don't want this kind of code here long term, this is just an example

    private void Update()
    {
        Vector2 input GetInput();

        if (Mathf.Abs(input.x) == 0 && Mathf.Abs(input.y) == 0)
        {
            StopMoving();
        }
        else
        {
            Rotate(input);
            Move(input);
        }
    }

    private Vector2 GetInput()
    {
        Vector2 input = Vector2.zero;
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");

        if (debugMode)
        {
            Debug.LogFormat("Skeleton {0} Input Update: {1}, {2}", gameObject.name, input.x, input.y);
        }

        return input;
    }

    private void Move(Vector2 input)
    {
        Vector3 movement = new Vector3(input.x, input.y, 0.0f);
        movement.Normalize();
        _controller.Move(movement * velocity * Time.deltaTime);

        _isWalking = input.x != 0 && input.y != 0;

        if (debugMode)
        {
            Debug.LogFormat("Skeleton {0} {1} Movement Update: {2}, {3}", gameObject.name, _isWalking ? "Walking" : "Sitting", movement.x, movement.y);
        }

        _anim.SetBool("Walking", _isWalking);
    }
}

```

Normally I wouldn't recommend this extra "debugMode" stuff, but I'm guessing you might be new to programming so it may be helpful for you to use this kind of style to help debug issues and keep track of how things work until you are more used to working with Unity and some of it's weird quirks. If you run into some really tough issues you may also want to look into using "breakpoints" so you can check your code line by line to see where parts may be failing or acting in seemingly unpredictable ways.

# Answer
> -1 votes
You are returning if the value is less than 1. That's why you can not enter into your Move() functions hence you can not enter into below code.

```
if (input.x == 0 && input.y == 0)
{
   _isWalking = false;
}

```

Try to debug your code.

---
Tags: unity, c#
---


# Question
Title: How do I apply Ambient Occlusion in Forward Rendering to the ambient term only?
I want to integrate Ambient Occlusion into my rendering which is a forward renderer.
How do I apply Ambient Occlusion to the ambient term only and thus not as a "post process" over the entire image (i.e. frambuffercolor * ambient occlusion)?

# Answer
You can do this with a technique called "depth pre-pass"

First you render the opaque geometry in your scene, drawing only the depth. No colour, texture, lighting.

Now you can run your ambient occlusion pass over this scene depth information, creating a texture containing your occlusion factor. You can run additional filter passes on this to smooth/de-noise it.

Now you render your scene again, with colour output as usual, doing all your material and lighting calculations. When it comes time to apply the ambient light, you sample the ambient occlusion texture you prepared earlier in the frame, use it to modulate the ambient term.

eg.

```
float ambientAmount = tex2D(ambientOcclusionTexture, screenSpaceUV);

float4 diffuse = ambientColour * ambientAmount;

// TODO: add contribution from each light
// into the diffuse lighting and specular terms.

float4 outputColour = albedo * diffuse + specular;

```

This might sound like a lot of extra work, but depth pre-pass is often applied as an optimization in forward renderers, as a way to get some of the benefits of deferred rendering without a full G-Buffer.

Because your first pass uses only depth, you can do it very quickly, in large batches with no material changes. Your later passes then benefit from early depth rejection, throwing out occluded fragments without doing expensive material and lighting calculations on them.

This helps especially if you have scenes with lots of overlapping/occluded geometry, expensive material effects, or lots of lights - using the cheap early depth pass to skip the costlier later passes on any occluded pixels.
> 4 votes

---
Tags: rendering
---


title: What does 'vertex splitting' mean?

text:
# Question
Title: What does 'vertex splitting' mean?
In the documentation of MeshUtility.SetPerTriangleUV2 it is said the following:

> Will insert per-triangle uv2 in mesh and handle vertex splitting etc.

What do they mean by 'vertex splitting' ?

# Answer
> 3 votes
As described in the two answers I linked in the comments, each vertex we send to the GPU is one unique combination of {position, normal, texture coordinate 1, texture coordinate 2, tangent, vertex color, etc...} (depending on which attributes we're using)

If you have a single vertex location on your mesh that needs two different texture coordinates (like on a texture seam), then that vertex location gets split into two vertices to send to the GPU - both with the same position, but one with texture coordinate A and one with texture coordinate B.

What this passage says is that this method does the splitting for you automatically if needed.

Let's say your mesh was a quad, something like...

```
0 --- 1     Vertex     Position       UV 0
| \   |        0       (0, 1, 0)     (0, 1)
|  \  |        1       (1, 1, 0)     (1, 1)
|   \ |        2       (0, 0, 0)     (0, 0)
2 --- 3        3       (1, 0, 0)     (1, 0)

```

With triangle indices `{0, 3, 1} {0, 2, 3}`

Now let's say we call `SetPerTriangleUV2` on this mesh, providing the UVs...

```
{(0, 0) (1, 0) (0.5, 0.5) (1, 0) (0.5, 0.5) (0, 0)}
    0      3        1        0        2        3

```

I labelled each UV coordinate here with the vertex it's going to apply to (in the order they're indexed by the mesh's triangles)

Notice that vertex 0 and 3 each get two different UVs assigned to them. So this method will make a copy of vertices 0 and 3 - one for the first triangle, with one set of UV2 coordinates, and one for the second triangle, with a different set of UV2 coordinates.

The vertex count after this operation will be 6, because we added two extra vertices to accommodate the split.

When the documentation says this method will "handle vertex splitting" it means that you don't need to check for this in your code and insert the extra vertex copies / update the indices yourself. The `SetPerTriangleUV2` will detect where vertices need to be split, split them, and update the triangle indices accordingly to accommodate the new splits.

---
Tags: unity, vertex
---


# Question
Title: Player Camera Shaking when Running Into Wall in Unity
I've been working on a 2D RPG game in Unity, and for some reason, whenever my character runs into a wall, the camera begins to shake violently. I have a RigidBody2D and a BoxCollider2D connected to him and a TilemapCollider connected to my Tilemap. The RigidBody component is Dynamic with a gravity scale of 0 (because it's a top-down game). Also, the camera is a child of the player. Here's the script to my character controller:

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerController : MonoBehaviour
{
    // Variable for the player speed and animation
    float speed = 2f;
    private Animator animator;
    private Vector3 change;

    // Called before the first frame is loaded
    void Start()
    {
        // Gets animator component
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        // Detects change in the player's coordinates
        change = Vector2.zero;
        change.x = Input.GetAxisRaw("Horizontal");
        change.y = Input.GetAxisRaw("Vertical");
        if (change != Vector3.zero)
        {
            // Detects whether the player's animation should play or not
            MoveCharacter();
            animator.SetFloat("moveX", change.x);
            animator.SetFloat("moveY", change.y);
            animator.SetBool("moving", true);
        }

        else
        {
            animator.SetBool("moving", false);
        }
    }

    void MoveCharacter()
    {
        //  Allows movement on the X axis and calculations to allow the player to move
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right * speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Translate(-Vector2.right * speed * Time.deltaTime);
        }

        // Allows movement on the Y axis
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            transform.Translate(Vector2.up * speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            transform.Translate(-Vector2.up * speed * Time.deltaTime);
        }
    }
}

```

# Answer
> 0 votes
Character controllers are difficult to write. You should use a kinetic rigidbody so you can control all the movement yourself. Your MoveCharacter() method should use raycasts or shapecasts to check to see if there's a wall, then only move up to the wall and not through it. The trick is to do this recursively when you hit a slope, sliding along the floor (project rest of movement vector onto slope) until you run out of movement or encounter an obstacle that would make you need to move backward to slide along.

If you just want a simple character controller without doing this yourself, you can use Unity's CharacterController class (though it's a bit dated). See CharacterController.Move.

---
Tags: unity, camera
---


title: Why the update function only call once

text:
# Question
Title: Why the update function only call once
I asked about this question How to efficiently implement a 7-segment display? in previous post. Now I just add an update function to the last part of the code to display the time(I don't bother the exact time at the moment just want to make sure the number change regularly). However,I'm not sure why the update only run once, I checked the answer in this website, mentioned the root cause is gameobject deactivated(Update function only running once) but this is not my case. I tried with `void OnMouseDown(){Display(DateTime.Now.Second)}`, the number does change according to my mouse button so I'm not sure what wrong with Update function. In addition, I assigned all the variable but it still pop out message unassigned reference exception, not sure where the problem.

```
using System;
using UnityEngine;

public class ClockDigit : MonoBehaviour
{
//  Assuming you number your segments as follows:
//   -- 0 --
//  |       |
//  5       1
//  |       |
//   -- 6 --
//  |       |
//  4       2
//  |       |
//   -- 3 --
// Store a lookup table for which segments
// should be active when displaying each digit.
static readonly bool[,] SEGMENT_IS_ACTIVE = new bool[,] {

    {true,  true,  true,  true,  true,  true,  false}, // 0
    {false, true,  true,  false, false, false, false}, // 1
    {true,  true,  false, true,  true,  false, true }, // 2
    {true,  true,  true,  true,  false, false, true }, // 3
    {false, true,  true,  false, false, true,  true }, // 4
    {true,  false, true,  true,  false, true,  true }, // 5
    {true,  false, true,  true,  true,  true,  true }, // 6
    {true,  true,  true,  false, false, false, false}, // 7
    {true,  true,  true,  true,  true,  true,  true }, // 8
    {true,  true,  true,  true,  false, true,  true }  // 9
};

public Color32 activeColour = Color.red;
public Color32 inactiveColour = Color.black;
public SpriteRenderer[] segments = new SpriteRenderer[7];

public void Display(int number)
{
    var digit = number % 10;
    if (digit < 0) digit *= -1;
    for (int i = 0; i < 7; i++)
    {
        if (SEGMENT_IS_ACTIVE[digit, i])
        {
            segments[i].color = activeColour;
        }
        else
        {
            segments[i].color = inactiveColour;
        }
    }
}

public void Update()
{
    Display(DateTime.Now.Second);

}
}

```

I tried this command also, the infinite loop freeze the Unity and FixedUpdate() command also update the frame only one time.

```
void Update()
    {while(true)
      Display(DateTime.Now.Second);
    }

```

# Answer
I found the problem already. I made a silly mistake by accidently added the script to main camera. When the Update function run, it encountered problem and stopped, so it only run once. Commenting out the Display(DateTime.Now.Second)and replace with a debug log, the debug log run indefinitely as no error encountered. I remove the script from main camera and it working as intended.
> 1 votes

---
Tags: unity, c#
---


# Question
Title: Is UDP still better than TCP for data-heavy realtime games?
I know that UDP is usually recommended for real-time multiplayer games with high data usage.

Most articles are serval years old, and since ~80% of all data transmitted on the internet is TCP, a lot of optimization must have been done for TCP.

This make me wonder: is UDP still superior in terms of speed and latency? Could recent TCP optimizations have made TCP perform better than UDP?

# Answer
> 125 votes
No, UDP is still superior in terms of ~~performance~~ latency, and will always be faster, because of the philosophy of the 2 protocols - assuming your communication data was designed with UDP or any other lossy communication in mind.

TCP creates an abstraction in which all network packets arrive, and they arrive in the exact order in which they were sent. To implement such an abstraction on a lossy channel, it must implement retransmissions and timeouts, which consume time. If you send 2 updates on TCP, and a packet of the first update gets lost, you will not see the second update until:

1. The loss of the first update is detected.
2. A retransmission of the first update is requested.
3. the retransmission has arrived and been processed.

It doesn't matter how fast this is done in TCP, because with UDP you simply discard the first update and use the second, newer one, right now. Unlike TCP, UDP does not guarantee that all packets arrive and it does not guarantee that they arrive in order.

This requires you to send the right kind of data, and design your communication in such a way that losing data is acceptable.

If you have data where every packet must arrive, and the packets must be processed by your game in the order they were sent, then UDP will not be faster. In fact using UDP in this case would likely be slower because you're reconstructing TCP and implementing it by means of UDP in which case you might as well use TCP.

EDIT - Adding some additional information to incorporate/address some of the comments:

Normally, the packet loss rate on Ethernet is very low, but it becomes much higher once WiFi is involved or if the user has an upload/download in progress. Let's assume we have a perfectly uniform packet loss of 0.01% (one way, not round-trip). On a first person shooter, clients should send updates whenever something happens, such as when the mouse cursor turns the player, which happens about 20 times per second. They could also send updates per frame or on a fixed interval, which would be 60-120 updates per second. Since these updates get sent at different times, they will/should be sent in one packet per update. On a 16 player game, all 16 players send these 20-120 packets per second to the server, resulting in a total of 320-1920 packets per second. With our packet loss rate of 0.01%, we expect to lose a packet every 5.2-31.25 seconds. In this example we ignore the packets sent from the server to the players for simplicity.

On every packet we receive after the lost packet, we'll send a DupAck, and after the 3rd DupAck the sender will retransmit the lost packet. So the time TCP requires to initiate the retransmit is 3 packets, plus the time it takes for the last DupAck to arrive at the sender. Then we need to wait for the retransmission to arrive, so in total we wait 3 packets + 1 roundtrip latency. The roundtrip latency is typically 0-1 ms on a local network and 50-200 ms on the internet. 3 packets will typically arrive in 25 ms if we send 120 packets per second, and in 150ms if we send 20 packets per second.

In contrast, with UDP we recover from a lost packet as soon as we get the next packet, so we lose 8.3 ms if we send 120 packets per second, and 50 ms if we send 20 packets per second.

With TCP things get messier if we also need to consider Nagle (if the developer forgets to turn off send coalescing, or can't disable delayed ACK), network congestion avoidance, or if packet loss is bad enough that we have to account for multiple packet losses (including lost Ack and DupAck). With UDP we can easily write faster code because we quite simply don't care about being a good network citizen like TCP does.

# Answer
> 19 votes
We agree upon both TCP and UDP being protocols built on top of IP, don't we? IP specifies how messages are delivered across the internet, but nothing is about the messages structure, format. Here come TCP and UDP protocols. They use IP properties, but let the programmer focus on the message exchange without worrying about the lower layers of net communication. And that's great, because dealing with analogic signals in wires directly would be kind of painful.

* TCP provides a set of functions to send and receive messages. It divides our data into small packets for ourselves and send them across the network. All we are asked is a *port* to use for the net socket, and the actual message we want to send. Also, it's reliable, meaning if some packets are lost along the network they are detected, then sent again taking care of sending them in the same order they were supposed to arrive.
* On the other hand, UDP is a protocol oriented toward user control. When using UDP to send our *datagrams*, we can't be sure if the datagram will ever arrive at destination or not (and we mean mathematical certainty here: when we send a packet it will probably arrive, but we can't be sure at 100%). Also, when a packet is lost it is neither going to be detected nor sent again.

At this point, TCP would look like the ideal solution to all our problems. It's reliable, it's fast, it solves connection latency for us by keeping track of what packets arrived and what packets we still need to send.

**BUT**, look beyond. The only advantage UDP gives us is its speed, and that's right the one thing we really want. A UDP packet is just crafted, sumchecked and sent without any particular controls, because that's how UDP protocol works. A TCP packet must be crafted, labeled, sumchecked, and when it arrives an ACK is sent back to tell the sender *"packet x is here, keep going"*, and when this signal is not sent then that means such packet *x* must be sent again.

> I know that UDP is usually recommended for real-time multiplayer games with high data usage.

Yes, but not only. UDP is largely preferred over TCP mainly because *its high speed* is idea to handle high data sending and management. This happens when, assuming such videogame runs on deterministic lockstep (what happens on the server is identically replicated on any client independently of network latency), an update packet is lost and never get to its destination. TCP would re-send such packet, and the following packets are dropped because arrive not in order, and are then re-sent after the lost one. UDP is much more tolerant in this scenario: it won't care about this packet, because newer updates are coming. The update lost is not rendered, instead game physics is interpolated upon integration method used and latest update received.

TCP causes jittering when latency is high enough, UDP does not:

```
<video style="min-width: 100% height: auto" autoplay="" preload="auto" loop="true"><source src="https://gafferongames.com/videos/deterministic_lockstep_tcp_250ms_5pc.mp4" type="video/mp4"><source src="http://173.255.195.190/cubes_deterministic_lockstep_tcp_250ms_5pc.webm" type="video/webm">Your browser does not support the video tag.</video>
```

> This make me wonder if UDP is still superior in terms of speed and latency.

Well, yes, it is and it will for a *long* time. You can read more about TCP vs UDP here.

# Answer
> 9 votes
TCP \<- Transmission **Control** Protocol. It's made to **control** transmission.

TCP was created to be a good and diplomatic network citizen. It focuses on making the networking a good experience for everyone, and willingly decreases it's throughput to achieve that. It **adjusts** to the environment by **adding latency**. Reasons are for example:

* Receiver detects a missing packet, tells the sender to slow down (halve the rate for a while).
* Receiver detects wrong incoming packet order (maybe they took different network paths), tells the sender to slow down - and btw, the receiver won't accept further packets until the missing one comes in. Dealing with this takes time.
* Sender detects network congestion (eg. slow roundtrip time), adds latency.
* Receiver cannot keep up with the speed (input buffer is getting too full), asks sender to add latency (flow control).
* There is a single slow receiver (high ping bastard, crybaby, what are they called) among receivers, latency (may be) added in the household.

Additionally

* Nagle's algorithm may keep the senders data on hold, until there s more to send (in order to utilise data frames more efficiently). Time critical data gets delayed.
* I believe ordinary home-routers with wlan may do smart things (slow down) to smooth the TCP throughput between multiple clients (the wlan interface being the bottleneck, even if the game doesn't use it). Relates to broadcasting/multicasting, ie. "other" data may decrease your TCP throughput.
* TCP **ACKnowledges** everything, which is not necessary for a gaming environment. There is no point in ACKing every single physics update. Enough to ackknowledge for example once per second, or similarly. If a client (or a server) is silent for a longer time, then it's time to react.

Despite these, TCP provides the **highest** figure for (overall transmitted data) / (overall consumed time). Just that it doesn't happen precisely when you want it to happen.

UDP does none of these. It fires upon **your** will, just that one cannot expect it to hit each time - insead the target must announce that "you haven't shot in a long time, why?". One can still create own custom ACK packets, put multiple records in a single packet, etc. And also important, control NAT traversal. UDP is most certainly suitable for games with low latency demand.

# Answer
> 3 votes
You may compare the first diagram of RFC 768 (UDP) to the first diagram of RFCP 793 (TCP) page 15.

Both show 16 bits for a “source port” followed by 16 bits for a “destination port”. Both show 16 bits for a “checksum”. According to RFC 768, UDP's “checksum procedure is the same as is used in TCP.”

Whereas UDP's Length wraps up the details of UDP's diagram, TCP's length is part of a “a 96 bit pseudo header” described on page 15 and 16.

Don't expect TCP to outperform UDP. That's simply not likely to happen, for multiple reasons. One is that TCP simply has more bits. So if equipment can effectively process a certain number of bits per second, that will permit more UDP packets than TCP packets.

The other reason is that TCP's “three way handshake” means that the sender must wait for a response. This requirement introduces additional overhead that UDP doesn't handle. There's a reason why most of your Internet communications start with some UDP communication. Basic DNS uses UDP because a request and a response can be completed in fewer steps than TCP's “three way handshake” process. TCP's feature of keeping track of lost packets is rather unexciting, because a computer could simply make a new request rather than trying to let a remote system know that there is an unfulfilled prior request.

# Answer
> 2 votes
Consider what's happening for a moment. To simplify the scenarios, you have two choices when trying to send a state change (like your player just changed direction, or shot a gun, or some other player just set off a bomb):

1. Keep a TCP session open, and when the bomb is to go off send a TCP message to all players (if possible, see below)
2. Keep a UDP port listening, and when the bomb is to go off send a UDP message to all players no matter their connection state

Assuming there wasn't an update needed right before it, the time when that singular update arrives in 1 vs 2 wont be very different. It's one trip from the server to the client. But, say instead of just a bomb going off, you are trying to continuously relay the activity of someone running through a maze; weaving, ducking, shooting, etc. In the case of UDP, every action will be sent in a datagram, as soon as it happens. In the case of TCP every action will be sent in a packet only if the server is allowed to send. What says it's allowed to send? Having room in the TCP window (assuming delayed ack is active) so that the message can be put on the wire. If not, it has to wait for an ack to arrive from the client before sending.

How long is too long? When multiplayer first person shooter development hit it's stride back in the late 90's and early 2000s low latency connections were not common. A dialup modem would have a typical one-way latency of 180ms. Waiting around for an ack before sending another update, effectively doubling that time to 360ms, was painful; even novice users could definitely feel the difference. When broadband connections caught on, they brought the latency down a lot but it still persisted when bandwidth was in short supply (quite often in some areas). So the preference for lowest possible latency persisted.

Modern home connections and interconnections have changed this, to the point where regional latency, even during congested times of day, are in the 15ms or below range. Choosing TCP instead of UDP would be invisible in most cases, since the latency is "low enough". However, there is still the tendency of UDP to be prioritized over TCP given its history as a low latency protocol. So, for now (and probably some time into the future) UDP will be preferred for real-time communication.

# Answer
> 2 votes
In a high bandwidth MPG, you don't care if you missed a packet giving you the location and health of monster #425, because you'll be getting another update in some fraction of a second. This is and example where UDP makes TCP look stupid for making you wait for instantly obsolete data.

In that same game, you want the patches to show up exactly as they were designed. TCP already has the "tell me if it fails" features built in, facilitating automatic retries and verified failures. You can do it in UDP, but why recreate the technology?

Here's a simple description of what's going on.

UDP - Isolate chunk O'data.
Make a packet.
Encapsulate in IP.
Ship it.

TCP - Isolate a Stream O'data.
Make a packet from the front of the stream.
Encapsulate in IP.
Wait for space in the TCP window.
Ship it.
Keep reshipping until a receipt is received or timeout.
Stay in the TCP window until a receipt is received or timeout.

Shipping just means it made it through the local NIC, no more.

A TCP receipt reception both guarantees data reception and frees space in the window for the next packet.

Resending (slightly) increases the likelihood of eventual receipt.

TCP packets are reassembled on the other side as an ordered stream of data. UPD packets are received as distinct packet. The protocol does not preserve order.

TCP is good for pushing required data and large ordered amounts of data. TCP provides notification of a persistent failure. TCP self-throttles through choked pipes (ref: window). TCP has handshakes to slow down initialization. TCP requires a "connection" prior to transmission.

UDP just puts the data on the wire and lets you proceed without waiting for windows and retransmissions. UDP will blast data at full speed into a choked pipe, no matter how much data is lost.

I designed and wrote a commercially applied UDP Multicast File Transport Utility. I've worked on IP stacks. These are just basics, sans minutia. Explaining "sockets, MTUs and other fun toys" was a little beyond what would be useful for this question.

P.s. (I can't add comments to reply to comments) UDP is also good for data which is desirable but not required. Forward Error Correction is an example of this, lots of unnecessary but desirable packets.

# Answer
> 2 votes
> I know that UDP is usually recommended for real-time multiplayer games with high data usage
> Is UDP still superior in terms of speed and latency? Could recent TCP optimizations have made TCP perform better than UDP?

Your assumptions are wrong. TCP and UDP differ primarily in what model they represent (unreliable datagrams versus in-order reliable virtual stream).

They do not differ in respect of volume ("high data usage") or throughput. TCP will push through just as much data as UDP, it will easily saturate the physical cable.

In presence of packet loss, the two *do differ* in latency, but only in that condition. Otherwise, TCP has just as low latency as UDP (give or take maybe a few dozen nanoseconds because the network stack has slightly more logic to do, but that's rather neglegible).
There is a slight difference in header size, so technically, more bytes must make it over the wire on serial lines, but that one is rather inconsequential, too. It only really matters for bulk transfers, and then it's about a 0.5% difference. Most people with home DSL internet access route all their traffic over ATM which adds upwards of 10% protocol overhead (5 control bytes for 48 bytes of payload, plus partial frames), and nobody even notices.

Some people build reliability on top of UDP. If some level of reliability is desired, but strict in-order deliverance is not needed, that *may* give a small advantage. However, it is still debatable whether the approach makes a lot of sense, and you pay a hefty price for that small advantage.
If you have clients connecting from hotel WiFis or other "weird" places, you will notice that often overall support for TCP is much, much better than for UDP.

Games generally use UDP not because it is superior in one of the forementioned ways -- it isn't -- or because you can reduce jitter by half a millisecond by implementing reliability without in-order, but because games (much like IP telephony) often contain a lot of very volatile data, such as for example position updates.
This volatile data is regularly and quickly obsoleted both by time passing, and by the next datagram coming in. Which means nothing more and nothing less than you actually don't care too much about being 100% reliable (or in-order).

Assuming a network packet is dropped in a service which runs at a steady pace with frequent updates coming in (shooter game, telephone, video chat) it does not make a lot of sense to have the acknowledge time out and resend the packet, and meanwhile freeze everything on the other end while waiting for the resent packet to arrive. That's way too disturbing, and no good.

Instead, you just consider the packet lost and move on, taking the data from the next packet that makes it through and meanwhile, to the best of your ability, hide the fact that a packet was lost from the user. Interpolation, dead reckoning, you name it.

Note by the way that packet loss is a normal condition. While IP is generally "quite reliable", packets occasionally being dropped can happen, and *will happen*. While packets being lost is normally rather on the rare side (\<1% here), it is not something extraordinary or theoretical, or an indication that something is broken. It is perfectly normal.
Every TCP bulk transfer will *necessarily* include lost packets, for example (it's how the congestion control works).

# Answer
> 1 votes
> Has all the TCP optimized routers made TCP perform better than UDP?

One more question is: does "data heavy" mean you will frequently load scenes?

If yes, you may need to send large pieces of data (\>1k) intensively in which TCP may be much more efficient because especially on the server side the NICs will provide various offloads which same lot of cycles. A user space application may issue large writes with TCP while in UDP an attempt to send more than MTU-headers size bytes will cause IP fragmentation and other overheads which will kill performance

# Answer
> 1 votes
Neither UDP or TCP (or any other variant) is out-right *superior*, not even in terms of speed/latency. Your choice must be made depending on the requirements of your application. To do this, you should compare the features each protocol offers, realizing that more features implies more overhead. So, if the goal is to minimize latency or maximize speed, then you should choose a protocol with as few features as possible, but while keeping the essential features needed to meet your requirements.

### A Comparison of Protocols

Generally speaking, UDP (User Datagram Protocol) offers the least amount of features. It is simplistic in that you send data without any sort of receipt/acknowledgement.

On the other hand, TCP (Transmission Control Protocol) offers the most amount of features needed for a reliable, connected communication. A TCP communication sends duplicates or more of packets and tags them with ordering information. Upon receipt at the destination, an ACK (acknowledgement) must be sent back along with information on which packets were lost so that the original sender can resend those lost packets. If I recall correctly, even ACK packets may need acknowledgement for proper reliability.

---

### Example: Skype Conference Call

For a Skype conference call, it is unimportant to ensure that all video and audio data is sent/received in a reliable fashion. Nowadays, UDP does a great job in minimizing packet loss anyways. The important thing to know is that there is absolutely no guarantee in UDP whether or not transmission was successful. For audio/video data in a conference call, UDP is a proper choice because we care more about getting real-time data (that is, the most recent). If a few packets are lost here and there, it will not interrupt the communication in a dramatic way.

However, in a conference call, people can send IM's (instant messages) or send files. In these cases, reliability is an necessary requirement to ensure that files and messages are not corrupted or lost. For IM's you may not need the *connected state* that TCP provides. An intermediary protocol, such as RUDP (Reliable UDP) may be sufficient. However, for files, it may be necessary to have the connected state that TCP provides.

---

### Implementation Choices

If you have a complex application or need to optimize your communication, then it is beneficial to begin with a UDP communication. Afterwards, you can add all features you need on top. This will give you the most control on your network communication.

If you have a simple application where optimization isn't required, consider going with one either standard (UDP or TCP) to meet your needs. That would allow you to move on to more important matters.

# Answer
> 1 votes
I noticed many comments where people believe that TCP packets are bigger than UDP packets. Don't just trust me, read the documentation. The protocol is as follow: a few bytes for Ethernet header (2 bytes message type, 48 bit MAC, 6 bytes) (for Wifi, header may differ) 20 bytes for IP 20 bytes for TCP or UDP x bytes for the data x ranging from 0 to about 1500 (see MTU) Lastly, the checksum to make sure that no corruption occured in that Ethernet packet.

TCP allow to send bigger "stream" packet of about 64K. This "large" block is actually chopped in many smaller Ethernet packets.

# Answer
> 0 votes
I think Both `TCP` and `UDP` should be implemented in the game, `UDP` should be mostly used in the main game and `TCP` for basic things.

For Example, suppose you have a login system, so its better to implement login system over `TCP` using `HTTP`

and on the other hand if you have some tasks such as updating the location of the player in a multiplayer game you should make use of `UDP` rather then TCP.

---

In login system if login fails, (Running on HTTP) or in a chat system message something goes wrong (Running on Web Socket or HTTP) you should inform the player about it, on the other hand if due to some reasons the position of the player doesn't get updated at all or it gets updated multiple times, You don't have to worry about it here, just resume from wherever the user is.

So a mix-up of both `TCP` and `UDP` is better, when it comes to a multiplayer game, so in short you can say the main part of game is implemented on `UDP` most of the time, Its also possible to implement all the stuff in just `UDP`.

So its totally a design decision which defers from game to game

---
Tags: c++, networking, udp, realtime
---


# Question
Title: Strategy for temporarily blocking user input
What are good approaches for disabling user input during certain moments in a game?

In my case, I have a grid-based tactics game (kind of like Fire Emblem) where I periodically want to toggle the user's ability to interact with the board. (For instance, the player may click a unit and then move it to a certain square; while the character is physically walking to the square, I want to disable user input). What's a good strategy for doing this?

1. Add a UI element that overlays the entire game, with a transparent image that blocks raycasts. Toggle this on and off as I want to disable user input.
2. Add a "locked" boolean and toggle the boolean. Then, for every function that processes user input, check if the "locked" boolean is true or not. This requires a lot of long-term maintenance so I don't prefer it.
3. ???

Also, I'm using "OnMouseEnter", "OnMouseExit", etc. Would things be easier if I transition to this event system model, with things like "IPointerHandler"?

I'm looking for a solution that eases long-term maintenance and maximizes flexibility down the road.

# Answer
> 2 votes
As DMGregory noted, a Canvas Group is an easy way to control interactivity for a group of UI controls. Just assign the Canvas Group to the parent containing your UI controls, and update the `interactable` property:

```
canvasGroup.interactable = false;

```

As for user interaction with non-UI GameObjects, there are several approaches depending on how you process input:

* `Update()` does not run if the MonoBehaviour is disabled. For example:

```
public class ClickableGameObject : MonoBehaviour {
    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            //handle click here
        }
    }
}

clickableGO.enabled = false; //disables the Update() function

```
* For other functions like `OnMouseDown()` or `OnPointerClick()`, you'll need a flag you can check to see if the input should be disabled. There are several ways to do this. Here are a few examples:

```
//This solution is clean but may require you to call `Interactable = true;` or
//`Interactable = false;` on many objects depending on your game structure.
public class ClickableGameObject : MonoBehaviour {
    [SerializeField] private bool interactable = true;
    public bool Interactable { get => interactable; set => interactable = value; }

    void OnMouseDown() {
        if (!interactable) return;
        //handle click here
    }
}

```

```
//this solution uses a global static variable, which is generally bad practice,
//but can save a lot of effort in this case:
public static class UserInput {
    public static bool InputEnabled {get; set;} = true;
}

public class ClickableGameObject : MonoBehaviour {
    void OnMouseDown() {
        if (!UserInput.InputEnabled) return;
        //handle click here
    }
}

```

```
//this solution is a compromise between the above two solutions
public class UserInputSettings {
    public bool InputEnabled {get; set;} = true;
}

public class ClickableGameObject : MonoBehaviour {
    public UserInputSettings InputSettings { get; set; }

    void OnMouseDown() {
        if (!InputSettings.InputEnabled) return;
        //handle click here
    }
}

//create the settings instance before instantiating your GameObjects
UserInputSettings settings = new UserInputSettings();

//assign the settings to your GameObjects immediately after instantiating them
ClickableGameObject clickableGO1 = Instantiate(clickableGOPrefab);
clickableGO1.InputSettings = settings;
ClickableGameObject clickableGO2 = Instantiate(clickableGOPrefab);
clickableGO2.InputSettings = settings;

//affects all GameObjects we've assigned the settings to
settings.InputEnabled = false;

```

# Answer
> 1 votes
I created a similar game once where I solved this problem by introducing the concept of states.

The game had different states it could be in (select unit, select walk target, select attack target, wait for animation, wait for AI turn, and so on).

Each state was represented by a different gameObject. Switching states happended through a StateHandler class, which deactivated all of these objects except the one for the current state. Each of these gameObject had a separate script responsible for all input handling during that state. That way I could control precisely what input functionality was available in which state.

---
Tags: unity, c#, unity-ui
---


# Question
Title: How can I destroy particles on collision with specific a GameObject?
I wrote a script to manage my Particle System emission. The starting lifespan is set to infinite so that the particle never dies until it reaches a specific collider. I didn't find any method to destroy a specific particle in the Unity Manual.

How can I do this?

Here's the code (updated to show the partial fix)

```
using UnityEngine;
using System.Collections.Generic;

public class PlayerDamage : MonoBehaviour
{
    private ParticleSystem ps;
    public List<ParticleCollisionEvent> collisionEvents;
    public int attackValue = 1;

    //
    [Range(0.0f, 100f)]
    public int maxParticles;
    public float particleLife;
    public bool neverDies;
    public float particleSpeed = 8.0F;

    void Start()
    {
        ps = GetComponent<ParticleSystem>();
        collisionEvents = new List<ParticleCollisionEvent>();
        //
        var collision = ps.collision;
        collision.enabled = true;
        collision.type = ParticleSystemCollisionType.World;
        collision.mode = ParticleSystemCollisionMode.Collision3D;
    }

    void OnParticleCollision(GameObject other)
    {
        int numCollisionEvents = ps.GetCollisionEvents(other, collisionEvents);

        Rigidbody rb = other.GetComponent<Rigidbody>();
        int i = 0;

        while (i < numCollisionEvents)
        {
            if (rb.CompareTag("Enemy"))
            {
                BaseHealth baseHealth = other.GetComponent<BaseHealth>();

                if (baseHealth != null)
                {
                    Vector3 pos = collisionEvents[i].intersection;
                    Vector3 force = collisionEvents[i].velocity;// * 10;
                    rb.AddForce(force);
                    baseHealth.TakeDamage(attackValue);
                }
            }
            i++;
        }
    }

    void Update()
    {
        var collision = ps.collision;
        collision.maxKillSpeed = particleSpeed;

        Debug.Log("Particles Alive Count: " + GetAliveParticles());

        ps.Emit(maxParticles);
        var main = ps.main;
        main.maxParticles = Mathf.RoundToInt(maxParticles);
        main.startLifetime = particleLife;

        if (neverDies)
        {
            particleLife = float.PositiveInfinity;
        }
        else
        {
            particleLife = 5f;
        }
    }

    int GetAliveParticles()
    {
        ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount];
        return ps.GetParticles(particles);
    }
}

```

# Answer
> 1 votes
I solved the problem.

1. The ps was missing a `render material`. Apparently this prevents the collisions to be detected.
2. I activated `Send Collision Messages` in the Collision Module, without that it won't work.

Thanks all.

---
Tags: unity, c#, collision-detection, particles
---


# Question
Title: Unity: Alpha and color issues with opaque projector/decal shader
I have been attempting to make a simple "overwrite" version of Unity's projector shader. I can either respect the color, or respect the transparency, but not both.

I have simplified the frag method to simply take cookie (the texture of the projection) and color tint, skipping all the fall off and fog stuff for now. I hope to eventually add those back in once I figure out what's going wrong.

```
Shader "Projector/Overwrite" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _ShadowTex ("Cookie", 2D) = "" {}
        _FalloffTex ("FallOff", 2D) = "" {}
    }

    Subshader {
        Tags {"Queue"="Transparent"}
        Pass {
            ZWrite Off
            ColorMask RGB
            Blend DstColor DstAlpha
            //Blend DstColor Zero
            Offset -1, -1

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fog
            #include "UnityCG.cginc"

            struct v2f {
                float4 uvShadow : TEXCOORD0;
                float4 uvFalloff : TEXCOORD1;
                UNITY_FOG_COORDS(2)
                float4 pos : SV_POSITION;
            };

            float4x4 unity_Projector;
            float4x4 unity_ProjectorClip;

            v2f vert (float4 vertex : POSITION)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(vertex);
                o.uvShadow = mul (unity_Projector, vertex);
                o.uvFalloff = mul (unity_ProjectorClip, vertex);
                UNITY_TRANSFER_FOG(o,o.pos);
                return o;
            }

            fixed4 _Color;
            sampler2D _ShadowTex;
            sampler2D _FalloffTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 texS = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
                texS.rgb *= _Color.rgb;
                //texS.a = 1.0 - texS.a;
                return texS;

                /*texS.rgb *= _Color.rgb;
                texS.a = 1.0-texS.a;

                fixed4 texF = tex2Dproj (_FalloffTex, UNITY_PROJ_COORD(i.uvFalloff));
                fixed4 res = texS * texF.a;

                UNITY_APPLY_FOG_COLOR(i.fogCoord, res, fixed4(0,0,0,0));
                return res;*/
            }
            ENDCG
        }
    }
}

```

I am fairly certain the issue lies in the BLEND options. I can either respect the texture * color, or respect the alpha of the texture, but not both together.

Alpha is respected, but the color is no longer accurate:

Alpha is ignored, but the color is accurate:

Thanks for your guidance.

# Answer
It looks like you're trying to use a multiplicative blend mode, where we tint the colour already drawn into the scene. We'll likely want to add a second pair of arguments to leave the destination alpha untouched:

```
Blend DstColor Zero, Zero One

```

Then you want to take the colour you're about to write, and blend it toward white where the alpha is low. Zero alpha means you're outputting white, which multiplied by any other colour, just produces that same colour, unchanged.

```
fixed4 texS = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
texS.rgb *= _Color.rgb;
texS.rgb = lerp(fixed3(1, 1, 1), texS.rgb, texS.a);
return texS;

```

Or if you want standard alpha / layer blending, the formula for that is:

```
Blend SrcAlpha OneMinusSrcAlpha

```

And you can skip the `lerp`-to-white line.
> 1 votes

---
Tags: unity, shaders, graphics, hlsl, graphics-programming
---


# Question
Title: How to Make UI Open and Close on Keypress
I've been working on a 2D RPG and have been trying to make a script that will open or close the public UI element that is selected in properties. I don't receive any errors, but I do receive a warning that says:

> ```
> Assets\Scripts\KeyManager.cs(7,18): warning CS0414: The field 'KeyManager.activeUI' is assigned but its value is never used
>
> ```

Here's the script that is connected to my canvas:

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class KeyManager : MonoBehaviour
{
    private bool activeUI;
    public GameObject UI;

    void Start()
    {
        activeUI = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.I) && (activeUI = false))
        {
            activeUI = true;
            UI.SetActive(true);
        }

        else if (Input.GetKeyDown(KeyCode.I) && (activeUI = true))
        {
            activeUI = false;
            UI.SetActive(false);
        }
    }
}

```

# Answer
This is an syntax error. You compare with == but only one = assigns the value.

The info you get reflects this as well since you only assign the value. You can even shorten the code to something like this

```
if (Input.GetKeyDown(KeyCode.I)) {
    activeUI = !activeUI;
    UI.SetActive(activeUI);
}

```

If a condition has twice the same parameter with the same value, you can usually shorten it. The code is flipping the value of `activeUI` and afterwards assign it to your UI. The info warning about unused `activeUI` will be gone as well since now we use it.

Now to the info part what your code is actually doing. Consider the following code:

```
bool toogle = false;
if ((true) && (toogle = true)) Debug.LogFormat("The first toogle print is {0}", toogle);
if ((true) && (toogle = false)) Debug.LogFormat("The second toogle print is {0}", toogle);
Debug.LogFormat("The toogle at the end is {0}", toogle);

```

When this runs, you would expect that toogle is at the end true, right? But it is actually false. The second condition sets it to false but it does not print the line as well.

Now if we transfer that to your piece of code, you see that the code in your first condition is never executed and only the second piece which closes your UI is working.
> 2 votes

---
Tags: unity, c#
---