# Question
Title: Problems setting up and adding classes and compiling in UnrealEngine
I just installed UDK and Tried compiling a project in C++ at first it didn't compile I searched for it and it only said like "try again till it works" and I did then it worked "magically" with no explanation for what happened wrong but I said ok moved to adding a class and had a problem adding it it says "Successfully added but couldn't compile" and I recompile and it fails to do that so I searched and asked till someone told me to download and try the source code and I did but this is what I get after setting it up and generating the project trying to build it from the VS solution :

```

1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1509/3074] MagicLeapARPinImplModule.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1510/3074] Module.MagicLeapAudio.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1511/3074] Module.AvfMediaEditor.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1512/3074] Module.ImagePlateEditor.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1513/3074] Module.CodeView.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1514/3074] Module.MagicLeapMediaEditor.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1515/3074] Module.DatasmithIFCTranslator.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1516/3074] Module.MagicLeapHandTracking.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1517/3074] Module.DatasmithDeltaGenTranslator.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1518/3074] Module.ControlRigEditor.cpp
1>cl : Command line error D8049: cannot execute 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX64\x64\c1xx.dll': command line is too long to fit in debug record
1>  [1519/3074] Module.MagicLeapEyeTracker.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1520/3074] Module.MagicLeapAudio.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1521/3074] Module.MagicLeapController.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1522/3074] Module.MagicLeapController.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1523/3074] Module.MagicLeapEyeTracker.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1524/3074] Module.SteamVREditor.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached
1>  [1525/3074] UE4Editor-AssetRegistry.dll
1>LINK : fatal error LNK1340: failed to create heap: error code = 8
1>  [1526/3074] UE4Editor-NetCore.dll
1>LINK : fatal error LNK1102: out of memory
1>  [1527/3074] UE4Editor-SourceCodeAccess.dll
1>LINK : fatal error LNK1102: out of memory
1>  [1528/3074] UE4Editor-AudioPlatformConfiguration.dll
1>LINK : fatal error LNK1102: out of memory
1>  [1529/3074] Module.QuadricMeshReduction.cpp
1>D:\Unreal\UnrealEngine-release\Engine\Source\Runtime\Core\Public\Containers/Map.h(115): fatal error C1060: compiler is out of heap space
1>  [1530/3074] UE4Editor-ClothingSystemEditorInterface.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\ClothingSystemEditorInterface\UE4Editor-ClothingSystemEditorInterface.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\ClothingSystemEditorInterface\UE4Editor-ClothingSystemEditorInterface.suppressed.exp
1>  [1531/3074] UE4Editor-GeometryAlgorithms.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\GeometryAlgorithms\UE4Editor-GeometryAlgorithms.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\GeometryAlgorithms\UE4Editor-GeometryAlgorithms.suppressed.exp
1>  [1532/3074] UE4Editor-PropertyPath.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\PropertyPath\UE4Editor-PropertyPath.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\PropertyPath\UE4Editor-PropertyPath.suppressed.exp
1>  [1533/3074] UE4Editor-DynamicMesh.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\DynamicMesh\UE4Editor-DynamicMesh.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\DynamicMesh\UE4Editor-DynamicMesh.suppressed.exp
1>  [1534/3074] UE4Editor-TextureFormatAndroid.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\TextureFormatAndroid\UE4Editor-TextureFormatAndroid.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\TextureFormatAndroid\UE4Editor-TextureFormatAndroid.exp
1>  [1535/3074] UE4Editor-SlackIntegrations.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\SlackIntegrations\UE4Editor-SlackIntegrations.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\SlackIntegrations\UE4Editor-SlackIntegrations.exp
1>  [1536/3074] UE4Editor-NetCore.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\NetCore\UE4Editor-NetCore.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\NetCore\UE4Editor-NetCore.exp
1>  [1537/3074] UE4Editor-PropertyPath.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\PropertyPath\UE4Editor-PropertyPath.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\PropertyPath\UE4Editor-PropertyPath.exp
1>  [1538/3074] UE4Editor-AssetRegistry.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\AssetRegistry\UE4Editor-AssetRegistry.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\AssetRegistry\UE4Editor-AssetRegistry.exp
1>  [1539/3074] UE4Editor-Concert.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Developer\Concert\ConcertMain\Intermediate\Build\Win64\UE4Editor\Development\Concert\UE4Editor-Concert.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Developer\Concert\ConcertMain\Intermediate\Build\Win64\UE4Editor\Development\Concert\UE4Editor-Concert.exp
1>  [1540/3074] UE4Editor-DynamicMesh.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\DynamicMesh\UE4Editor-DynamicMesh.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\DynamicMesh\UE4Editor-DynamicMesh.exp
1>  [1541/3074] UE4Editor-ClothingSystemEditorInterface.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\ClothingSystemEditorInterface\UE4Editor-ClothingSystemEditorInterface.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\ClothingSystemEditorInterface\UE4Editor-ClothingSystemEditorInterface.exp
1>  [1542/3074] UE4Editor-ReliabilityHandlerComponent.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\ReliableHComp\UE4Editor-ReliabilityHandlerComponent.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\ReliableHComp\UE4Editor-ReliabilityHandlerComponent.suppressed.exp
1>  [1543/3074] UE4Editor-GeometryAlgorithms.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\GeometryAlgorithms\UE4Editor-GeometryAlgorithms.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\GeometryAlgorithms\UE4Editor-GeometryAlgorithms.exp
1>  [1544/3074] ShaderCompileWorker-ImageWrapper.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\ShaderCompileWorker\Development\ImageWrapper\ShaderCompileWorker-ImageWrapper.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\ShaderCompileWorker\Development\ImageWrapper\ShaderCompileWorker-ImageWrapper.exp
1>  [1545/3074] UE4Editor-PacketHandler.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\PacketHandler\UE4Editor-PacketHandler.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\PacketHandler\UE4Editor-PacketHandler.suppressed.exp
1>  [1546/3074] UE4Editor-MeshConversion.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\MeshConversion\UE4Editor-MeshConversion.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\MeshConversion\UE4Editor-MeshConversion.suppressed.exp
1>  [1547/3074] UE4Editor-CollectionManager.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\CollectionManager\UE4Editor-CollectionManager.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\CollectionManager\UE4Editor-CollectionManager.exp
1>  [1548/3074] UE4Editor-GeometryCollectionCore.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\GeometryCollectionCore\UE4Editor-GeometryCollectionCore.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\GeometryCollectionCore\UE4Editor-GeometryCollectionCore.exp
1>  [1549/3074] UE4Editor-SlackIntegrations.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\SlackIntegrations\UE4Editor-SlackIntegrations.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\SlackIntegrations\UE4Editor-SlackIntegrations.suppressed.exp
1>  [1550/3074] UE4Editor-SourceCodeAccess.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\SourceCodeAccess\UE4Editor-SourceCodeAccess.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\SourceCodeAccess\UE4Editor-SourceCodeAccess.exp
1>  [1551/3074] UE4Editor-AudioPlatformConfiguration.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\AudioPlatformConfiguration\UE4Editor-AudioPlatformConfiguration.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\AudioPlatformConfiguration\UE4Editor-AudioPlatformConfiguration.exp
1>  [1552/3074] ShaderCompileWorker-TextureFormatPVR.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\ShaderCompileWorker\Development\TextureFormatPVR\ShaderCompileWorker-TextureFormatPVR.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\ShaderCompileWorker\Development\TextureFormatPVR\ShaderCompileWorker-TextureFormatPVR.suppressed.exp
1>  [1553/3074] UE4Editor-RiderSourceCodeAccess.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Developer\RiderSourceCodeAccess\Intermediate\Build\Win64\UE4Editor\Development\RiderSourceCodeAccess\UE4Editor-RiderSourceCodeAccess.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Developer\RiderSourceCodeAccess\Intermediate\Build\Win64\UE4Editor\Development\RiderSourceCodeAccess\UE4Editor-RiderSourceCodeAccess.suppressed.exp
1>  [1554/3074] UE4Editor-LauncherServices.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\LauncherServices\UE4Editor-LauncherServices.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\LauncherServices\UE4Editor-LauncherServices.suppressed.exp
1>  [1555/3074] UE4Editor-MeshSolverUtilities.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\MeshSolverUtilities\UE4Editor-MeshSolverUtilities.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Plugins\Experimental\GeometryProcessing\Intermediate\Build\Win64\UE4Editor\Development\MeshSolverUtilities\UE4Editor-MeshSolverUtilities.suppressed.exp
1>  [1556/3074] UE4Editor-TargetPlatform.dll
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\TargetPlatform\UE4Editor-TargetPlatform.suppressed.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\TargetPlatform\UE4Editor-TargetPlatform.suppressed.exp
1>  [1557/3074] Module.EditorSubsystem.gen.cpp
1>  [1558/3074] Module.NiagaraCore.cpp
1>  [1559/3074] Module.AudioMixerXAudio2.cpp
1>  [1560/3074] UE4Editor-AudioMixerXAudio2.lib
1>     Creating library D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\AudioMixerXAudio2\UE4Editor-AudioMixerXAudio2.lib and object D:\Unreal\UnrealEngine-release\Engine\Intermediate\Build\Win64\UE4Editor\Development\AudioMixerXAudio2\UE4Editor-AudioMixerXAudio2.exp
1>  [1561/3074] Module.OpenGLDrv.3_of_3.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.MakeFile.Targets(44,5): error MSB3073: The command "..\..\Build\BatchFiles\Build.bat -Target="UE4Editor Win64 Development" -Target="ShaderCompileWorker Win64 Development -Quiet" -WaitMutex -FromMsBuild" exited with code 6.
1>Done building project "UE4.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 2 up-to-date, 0 skipped ==========

```

I am having some errors that it skips I guess like

```
1>  [1515/3074] Module.DatasmithIFCTranslator.gen.cpp
1>c1xx : error C3859: Failed to create virtual memory for PCH
1>  c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
1>
1>
1>  c1xx: note: please visit https://aka.ms/pch-help for more details
1>c1xx : fatal error C1076: compiler limit: internal heap limit reached

```

and I searched all that and one answer was to add "interface IUnknown;" in C:\Program Files (x86)\Windows Kits\8.1\Include\um\combaseapi.h before "extern "C++""

also verified my account on windows

but still having the same problem I guess

im working on a laptop: OS windows 10 64bit, intel core i7-8565U CPU @ 1.80 (1.99), RAM 8GB, GPU Radeon 520, intel UHD Graphics 620 memory 2048mb

and which is better the source code or the "Epic Launcher" installation way ?

I need someone to help me with both the Epic Launcher problem which is mintioned first then the source code if possible

help please ? what's wrong with this engine I used godot and unity and alot more and it was easier to setup and use than this

# Answer
> 0 votes
A Windows paging file is virtual memory, stored on the hard drive that Windows can use when it runs out of physical memory to perform operations. Obviously hard drive speeds are considerably slower than memory so this is never optimal but sometimes essential.

To check the size of your existing paging file, you need to do the following:

1. Right-click on This PC and open Properties.
2. Select Advanced System Properties.
3. Click Advanced tab.
4. Under Performance, click Settings.
5. Under Performance Options, click Advanced tab.

Here you will see information about the paging file and you can click on the Change button to alter this although most of the time, Windows is just set to automatically manage.

If this is the case and you're still getting the error, you may need to check how much physical space the hard drive has left because if it hasn't got room to create a paging file, it won't be able to use it.

As for installation, I've always used the Epic Launcher and never had any problems installing any version of the engine.

---
Tags: unreal-4, unreal, support
---


# Question
Title: How to use a .cube LUT file with Color Lookup?
I have used "Image 2 LUT" to create a LUT for Unity from a certain movie. However, currently "Image 2 LUT" only outputs ".cube" files.

For HDRP, this is great, but for some reason, URP doesn't accept .cube file. URP expects specially laid out .png LUT file.

Is there any way to convert a .cube LUT file to a PNG that I can put into the slot of Color Lookup-\> Lookup Texture with URP?

Unity expect this format:

The tutorial that Google finds and recommends is this.

However, I don't have Photoshop. Also, the tutorial deals with a square LUT that looks like this:

So even if I had Photoshop and I would follow the tutorial, I would still have a square LUT which is not laid out as Unity would expect it, so I did not use that tutorial.

How do I create a LUT png from a .cube file that I can use with URP?

Thank you.

# Answer
> 1 votes
Using GIMP, one can download and install this free add-on.

Restart GIMP.

Now import this neutral LUT in GIMP:

(Right click and select Save As)

Then select "Filter -\> G'MIC-Qt".

Select "Colors-\> Apply External CLUT".

Select your .cube file as "HaldCLUT Filename".

Click "Ok".

Make sure you don't apply the same filter twice by accident!!

Export the processed LUT png by choosing "File -\> Export As..." Select ".png" and these settings:

In Unity, import the file and set the following settings:

---
Tags: unity, color
---


# Question
Title: Approximately circular range of motion on a square tile grid
I've been working on a grid based tactics style game to learn the ropes of Unity. I have an issue with movement range for a player unit. Let's say the units move range is 3 spaces..

If I set up each grid tile with 4 neighbours (up down left right), I get this movement range:

If I give each tile diagonal neighbours too- 8 in total, I get this;

What I'm actually looking for is what you'd see in these type of games traditionally, like this;

Here is the code that finds the unit move range list, starting at tile (5, 5). It adds the initial tile/node and its neighbours to the movelist, then works outward looping through all their neighbours. It's based off a youtube tutorial.

```
public HashSet<Node> getUnitMovementOptions() {

    float[,] cost = new float[mapSizeX, mapSizeY];
    HashSet<Node> moveList = new HashSet<Node>();
    HashSet<Node> tempMoveList = new HashSet<Node>();
    HashSet<Node> finalMoveList = new HashSet<Node>();

    int moveSpeed = 3;
    Node unitStartNode = graph[5, 5];
    finalMoveList.Add(unitStartNode);

    /// Initial costs for the neighbouring nodes
    foreach (Node n in unitStartNode.neighbours) {
        cost[n.x, n.y] = costToEnterTile(n.x, n.y, unitStartNode.x, unitStartNode.y);
        if (moveSpeed - cost[n.x, n.y] >= 0) {
            moveList.Add(n);
            }
        }

    finalMoveList.UnionWith(moveList);

    while (moveList.Count != 0) {
        foreach (Node n in moveList) {
            foreach (Node neighbour in n.neighbours) {
                if (!finalMoveList.Contains(neighbour)) {
                    cost[neighbour.x, neighbour.y] = costToEnterTile(neighbour.x, neighbour.y, n.x, n.y) + cost[n.x, n.y];

                    if (moveSpeed - cost[neighbour.x, neighbour.y] >= 0) { tempMoveList.Add(neighbour); }
                    }
                }
            }

        moveList = tempMoveList;
        finalMoveList.UnionWith(moveList);
        tempMoveList = new HashSet<Node>();
        }

    Debug.Log("Total move spaces for this unit is: " + finalMoveList.Count);
    return finalMoveList;
    }

```

Here is the costToEnterTile function:

```
public float costToEnterTile(int targetX, int targetY, int sourceX, int sourceY) {

    Tile t = tileTypes[tiles[targetX, targetY]]; // get current tile type
    float cost = t.movementCost;

    // diagonal
    if (sourceX != targetX && sourceY != targetY) {
        cost += 0.3f;
    }

    return cost;
}

```

If I tamper with the cost value in here, I can get different results in the movement range overall shape, but it's a bit hit and miss depending on the movement range.

Can anyone offer insights in to what path I need to head down to solve this?

# Answer
> 1 votes
I recognise the metrics you used, they are the City Block and the Chessboard metrics respectively. The former resembles a 4-connectivity grid whereas the latter is about 8-connectivity, and you'll be happy to know that there *IS* a metric that merges the two to achieve the circle-looking shape you are looking for.

The quasi-Euclidean metric measures the total Euclidean distance along a set of horizontal, vertical, and diagonal line segments:

But, there's something more you can do to detect the right cells to move through (you need to work with pathfinding, I guess). You can first find out the potential cells involved in the movement, and find out what is the best metric to use: quasi-euclidean is a very particular metric and could be a little bit overkill for your scopes.

A simple euclidean distance with the right values could do the job, and later you may play around with pathfinding algorithms on the previous result. I suggest these two great guides by Red Blob Games: *Circle fill on a grid*, addressing the very problem your question is about, and *Pathfinding for Tower Defense* that focuses both on pathfinding and grid search for games.

---
Tags: unity, c#, geometry, grid
---


# Question
Title: Animating MultiPart 2D Character with RigidBodies
Some background to the question:

I am attempting to animate and control a large multi sprite 2D Boss character for a platforming game.

Up until this point I had been assigning individual animators for each of the limbs and using RigidBody2D to control the movement of each one respectively.

This worked fine except for one thing: synchronizing each animation state with the other controllers was a huge pain in the ass and error prone.

---

Hence my next step was creating one single Animation Controller using multiple layers to manage the animations together. This worked great, on the animation side of things. Catch was that now it had become completely impossible to alter the Transform of the the individual limbs (any child component below the animator)

---

```
 - Boss Character (main scripts and animator)
   -- BossHead (collider)
       -- SpriteHolder
   -- BossTorso (collider)
       -- SpriteHolder
   -- BossLeftHand (collider)
       -- SpriteHolder
   -- BossRightHand (collider)
       -- SpriteHolder

```

---

* I have tried using transform.Translate instead of a RigidBody2D (same result)
* I have tried checking apply root motion in the animator (same result)
* I have doubly checked that no transform values were being modified during the animation (same result)

Unity version 2018.2.11

This use case does not seem to be all that unusual so there must be a correct workflow for this. Question is, what is the Unity correct way to achieve this?

EDIT: Code That updates the RigidBody2D

```
Void LateUpdate() {
    if (_path == null)
        return;

    if (_currentWaypoint >= _path.vectorPath.Count)
    {
        if (!_reachedEndOfPath)
        {
            _reachedEndOfPath = true;
            _rb.velocity = Vector2.zero;
            _callback?.Invoke();
        }
        return;
    }
    else
    {
        _reachedEndOfPath = false;
    }

    Vector2 direction = ((Vector2)_path.vectorPath[_currentWaypoint] - _rb.position).normalized;
    Vector2 force = direction * speed * Time.deltaTime;
    _rb.AddForce(force);

    float distance = Vector2.Distance(_rb.position, _path.vectorPath[_currentWaypoint]);
    if (distance <= _nextWaypointDistanceMargin)
        _currentWaypoint++;
}

```

Example of the effect I am attempting to create:

Main boss with two disembodied hands that can float around to chase the player.

# Answer
Animators and Rigidbodies do not work well together. If the Animator alters the `transform.position` of the different components, this will override any Rigidbody physics. You might see twitching from the Rigidbody "fighting with" the Animator.

If I'm understanding your situation correctly, there are two possible approaches:

1. Throw out the Animator and animate everything with code. This can be tedious and the resulting code can be hard to follow in some cases, but it may be your best option if you want to combine physics with animation.
2. Throw out force-based physics and only use Animators. If you still need the body parts to have Rigidbodies for the purposes of collision detection, set the Rigidbodies to be Kinematic and set the Update Mode of the Animator(s) to "Animate Physics"
> 0 votes

---
Tags: unity, 2d, sprites, rigidbody, animation-controller
---


# Question
Title: Multiple Input.GetKeyDown happens in low frame rate
There is a code that needs to be invoke each time user pressed specific button in my game. So I used Input.GetKeyDown to achieve that, but some reason, that code invokes multiple times even I keep pressing the button.

After some tests, I figured out this happens a lot when the game has low frame late. In a very laggy moment, GetKeyDown returns true very many times.

```
void Update() {
    if(Input.GetKeyDown(KeyCode.RightArrow)) {
        print("Pressed");
    }
}

```

I saw a similar issue in here but couldn't find any related information. https://forum.unity.com/threads/problems-with-input-at-low-framerates.16828/

My game is a very input sensitive game, so my code when the user each time pressed a specific button always invoke when they pressed.

I checked my keyboard is something wrong, but there was no problem with my keyboard.

Why does this happen? According to the Unity doc, it said:

> Returns true during the frame the user starts pressing down the key identified by name

If I used wrong way, then how do I check each time user pressed a button?

Using Unity 2019.1.0f2.

# Answer
> 1 votes
This sounds like a Unity bug, in which case your best bet is to update Unity (why are you using 2019.1.0f2? That's *very* out of date) and file a bug report if the issue persists.

A possible workaround:

```
float lastPressedTime = 0;

void Update() {
    if(Input.GetKeyDown(KeyCode.RightArrow) && Time.time != lastPressedTime) {
        print("Pressed");
        lastPressedTime = Time.time;
    }
}

```

---
Tags: unity
---


# Question
Title: How to capture image from camera with post effects? Mysteriously only get emission(?) pass
I have a separate camera from my main camera, whose purpose is to take screenshots, or render a "live feed" of the action, at different angles. Hierarchy as such:

* The game object labeled as "main camera" captures the 3D scene just like a normal main camera would, including post-processing components.
* The GUI camera captures just the UI layer.
* The canvas and image are simply a watermark, rendered by the GUI camera. I have removed this and it has no bearing on the issue at hand.

I point both the main camera and GUI camera to the same target render texture. The result of the render texture appears to be correct in the inspector.

One way or another, it appears that I can only get access to the "bloom," and nothing else:

(On black so it's easier to see.)

If I assign the render texture onto a Raw Image canvas element, it only shows the "bloom."

If I try to convert the render texture to a regular texture, it also only shows the "bloom."

```
RenderTexture.active = renderTexture;
destination.ReadPixels(new Rect(0f, 0f, renderTexture.width, renderTexture.height), 0, 0);
destination.Apply();

```

(I have also tried AsyncGPUReadback. Its resulting texture looks like a flat gray without variance in the inspector.)

I have found if I disable post-processing, everything works as intended, no changes required. Of course, I am missing the post processing, which I want!

Somehow, somewhere, Unity is getting data external of the texture itself, depending on context:

* Using Unity's ReadPixels method only picks up the "bloom."
* Using Unity's EncodeToPNG method only picks up the "bloom."
* Putting the RenderTexture on a Raw Image only picks up the "bloom."
* If I use a separate PNG encoder using the same Color32 data, I get the final correct image.
* The inspector successfully renders the final correct image.

I have actually run into this issue multiple times, and never found a proper solution, and definitely never a real-time solution, which I now desperately need.

# Answer
To answer my own question: On the PostProcessLayer component, there is a "Keep Alpha" checkbox that needs to be checked to avoid the transparency issues.

When reading the description of that check box, I got the impression that when enabled, it would essentially "enable alpha," which is why I kept it unchecked until now. It appears to have the opposite effect, checking the "Keep Alpha" checkbox seems to make the result opaque, which is exactly what I wanted! Hooray!

It does make me wonder if that "Keep Alpha" checkbox is reversed. If so, that does have a performance and visual impact, at least according to the description. Should I keep it enabled by default?
> 0 votes

---
Tags: unity, textures, rendering, post-processing, rendertexture
---


# Question
Title: Cannot implicitly convert type 'UnityEngine.Vector3' to 'Vector3'
I've defined an abstract method in an abstract class with a generic return type. However, when I try to use the generic type as a Vector3 (or any other variable) I get this error :

**Cannot implicitly convert type 'UnityEngine.Vector3' to 'Vector3'**

this is my code : the error is in the line

```
return direction;

```

```
using UnityEngine;

public class DashAbility : Ability
{

    public Vector3 direction;

    public override Vector3 getAbilityData<Vector3>()
    {
        return direction;
    }

    public override bool trigger(pointerData pointer)
    {
        return InputMaster.tryPointer(rollInputTest);
    }

    bool rollInputTest(pointerData p)
    {
        return (p.phase == pointerPhase.Dragging) && p.startHit.collider.CompareTag("Player");
    }
}

```

and this is the class I'm deriving from:

```
using UnityEngine;

public abstract class Ability : MonoBehaviour
{
    public abstract bool trigger(pointerData pointer);
    public abstract T getAbilityData<T>() ;
}

```

# Answer
When you write this:

```
public override Vector3 getAbilityData<Vector3>()
{
    return direction;
}

```

It wants to override from this:

```
public abstract T getAbilityData<T>() ;

```

In this function, `<T>` is a placeholder that represents "Some arbitrary type I'll call T".

So in order to match this, the compiler has to interpret the `<Vector3>` as "Some arbitrary type I'll call Vector3" - ie. it's no longer referring to the type `UnityEngine.Vector3`, it's just using the string of characters "Vector3" to serve as a placeholder for this arbitrary type, matching the parent.

Naturally, there's no implicit conversion available from a real actual `UnityEngine.Vector3` and this arbitrary type that we're just *calling* "Vector3", but could just as easily be an `int` or a `bool` or...

It looks like what you meant instead was something like this:

```
// "There are different kinds of ability, each with their own data type"
public abstract class Ability<T> : MonoBehaviour
{
    public abstract bool trigger(pointerData pointer);

    // "The getAbilityData method returns an instance of this particular ability's data type"
    public abstract T getAbilityData();
}

// "DashAbility is an Ability that uses Vector3 data"
public class DashAbility : Ability<Vector3>
{
    public Vector3 direction;

    public override Vector3 getAbilityData()
    {
        return direction;
    }

    // ...
}

```

Here we've constrained `T` to be one specific type for each derived form of `Ability`. For `DashAbility`, it's `UnityEngine.Vector3`, so now `DashAbility.getAbilityData()` no longer has to have versions to handle any arbitrary type, only the real actual `Vector3` version.
> 1 votes

---
Tags: c#, scripting
---


title: IDirect3DDevice9Ex and D3DPOOL_MANAGED?

text:
# Question
Title: IDirect3DDevice9Ex and D3DPOOL_MANAGED?
So I wanted to switch to IDirect3DDevice9Ex, purely for the SetFrameLatency function, as fullscreen vsynced D3D seemed to produce noticable input lag.

But then it tells me 'ha ha ha! now you can't use D3DPOOL\_MANAGED!':

Direct3D9: (ERROR) :D3DPOOL\_MANAGED is not valid with IDirect3DDevice9Ex

Is this really as unpleasant as it looks (when you're relying quite heavily on managed resources) - or is there a simple solution?

If it really does mean manual management of everything (reloading all static textures, VBs, and IBs on a device reset), is it worth the hassle, will IDirect3DDevice9Ex bring enough benefit to make it worth writing a new resource manager?

Starting to think I must be doing something wrong, due to this:

Direct3D9: (ERROR) :Lock is not supported for textures allocated with POOL\_DEFAULT unless they are marked D3DUSAGE\_DYNAMIC.

So if I put my (static) textures in POOL\_DEFAULT, they need flagging as D3DUSAGE\_DYNAMIC, just because I lock them once to load the data in?

# Answer
This doesn't completely solve your problem but in DirectX 9EX device loss only happens the same times it does in D3D11 (GPU driver changes, PC sleeps, etc..).

This means you don't need to worry about reloading your resources unless you wan't to support those cases. I think that's why they removed D3DPOOL\_MANAGED since it would be basically the same as D3DPOOL\_DEFAULT

MSDN Info
> 6 votes

# Answer
There is no simple solution I am aware of, you'll have to transition your resources to another pool type. I haven't ever really noticed the input latency issues you're describing, so I would venture to guess that they might be caused by a bug elsewhere in your code. Can you verify that it's a D3D-related issue (maybe it's a driver/card problem?) Or at least provide a more in-depth description of the problem?

My hunch is that it's not worth the effort to transition to D3D9Ex just for that method.
> 3 votes

# Answer
I ran into this exact issue. In our app, the user can change any texture at any time, so we need them to be dynamic. I now create D3DUSAGE\_DYNAMIC D3DPOOL\_SYSTEMMEM textures and for each one I create a D3DPOOL\_DEFAULT texture counterpart. For the D3DPOOL\_DEFAULT textures I have a flag which indicates when it was last used. If I get a memory error allocating a D3DPOOL\_DEFAULT texture, I find the oldest one, delete it, and try again, (until I run out of textures to free, but it never goes that far). If we try to use a freed texture, I simply re-create the D3DPOOL\_DEFAULT texture from the D3DPOOL\_SYSTEMMEM texture.

For you, if you never change your textures, don't try to lock them to put the initial image on there. Instead create a D3DPOOL\_SYSTEMMEM texture, call UpdateTexture() to draw it onto your write-only D3DPOOL\_DEFAULT texture, and then free the SYSTEMMEM texture if you wish.
> 3 votes

# Answer
You can try using QueryInterface with IID\_IDirect3DDevice9Ex to see if the D3D9 device is really a D3D9 EX device in disguise.
> 0 votes

---
Tags: directx, rendering, input
---


# Question
Title: Need Help Figuring Out Damage Calculations for Diablo RPG Clone
I'm building a Diablo clone using Unreal Engine 4 and have been having trouble wrapping my head around how the combat calculations should work. I copied a lot of the core stats from the original diablo game as a starting point.

Visited Websites:

How to develop RPG Damage Formulas?

http://diablo.blizzpro.com/2014/05/17/basic-theorycrafting-damage-formula/

https://diablo.fandom.com/wiki/Damage

http://diablo3blog.blogspot.com/p/diablo-3-damage-explanation-and-guides.html

So for the data model, I'm storing the character stats in a struct called PlayerStatsStruct.h. I also set some limits for how high the stats could go.

PlayerStatsStruct.h:

```
USTRUCT()
struct FPlayerStatsStruct {
    GENERATED_USTRUCT_BODY()

    FPlayerStatsStruct();

    UPROPERTY(EditAnywhere)
    FString Name;

    UPROPERTY(EditAnywhere)
    float TotalExperience;

    UPROPERTY(EditAnywhere)
    int32 Strength; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Dexterity; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Vitality; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Magic; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Agility; // MAX OF 99

    UPROPERTY(EditAnywhere)
    float Health; // MAX OF 1000

    UPROPERTY(EditAnywhere)
    float Mana; // MAX OF 1000

    UPROPERTY(EditAnywhere)
    bool Invulnerable;
};

```

Here is the struct I'm using for every monster.

MonsterStatsStruct.h

```
USTRUCT()
struct FMonsterStatsStruct {
    GENERATED_USTRUCT_BODY()

    FMonsterStatsStruct();

    UPROPERTY(EditAnywhere)
    FString Name;

    UPROPERTY(EditAnywhere)
    int32 Level;

    UPROPERTY(EditAnywhere)
    float Health; // MAX OF 1000

    UPROPERTY(EditAnywhere)
    float Defense;

    UPROPERTY(EditAnywhere)
    float AttackSpeed;

    UPROPERTY(EditAnywhere)
    float AttackDamageMin;

    UPROPERTY(EditAnywhere)
    float AttackDamageMax;

    UPROPERTY(EditAnywhere)
    float MovementSpeeed;
};

```

I made these formulas for determining the current Max Mana and Max Health like so:

MaxHealth = 218.f * FMath::Loge(Stats-\>Vitality) // MAX OF 1000 when Vitality is 99

MaxMana = 218.f * FMath::Loge(Stats-\>Magic) // MAX OF 1000 when Magic is 99

The main things that I'm stuck on are:

1. How do I determine the net damage inflicted on an enemy given both the Player Stats and the Enemy stats?
2. What exactly does defense do in combat?
3. How is dexterity related to defense?

I think at large the concept is this right?: TotalDamageToEnemy = PlayerAttack - Enemy Defense

The problem is that the concept of defense is really abstract to me right now.

Thanks for your help.

# Answer
> 1 votes
When you intend to create your own game inspired by Diablo and not an authentic clone, then I would recommend a more iterative approach to game design. Start simple and add complexity gradually.

Don't add player stats before you know exactly what they are supposed to be doing. Start with very few stats and very simple formulas. Then playtest to see how it plays in practice. While playtesting, you will notice that there are some situations where your game mechanics are not particularly interesting, have balance problems or do not deliver the game experience you intended. You can now modify your formulas or add more mechanical features to your game to address these itches.

When you look at a finished game made by other teams, then you usually see the end-result of following this process for several months or even years. A system which started out simple, but got increasingly complex as they iterated the design. But the choices they made for their game are not necessarily the same choices which are the right ones for your game.

---
Tags: mathematics, game-design, unreal-4
---


# Question
Title: How to throw an object without having a curve trajectory?
I am making a game that slingshots an object using a line renderer. I wanted to know how I can throw my object when I unclick my mouse without having a curve trajectory like throwing a basketball to a ring. I already coded some script that will make an object throw but with a curve.

**Here's an example that I want to achieve?**

***RED*** \- How I want my object to happen.

***BLUE*** \- How I don't want my object to happen.

---

**CODE**

---

```
public float power;
public Vector2 minPower;
public Vector2 maxPower;

Vector2 force;

void Update()
{
    MouseControl();
}

void MouseControl()
{
    //When touched
    if (Input.GetMouseButtonDown(0))
    {
        //CODE
    }

    //When touch is hold
    if (Input.GetMouseButton(0))
    {
        //CODE
    }

    //When touch is release
    if (Input.GetMouseButtonUp(0))
    {
        force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x),
        Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));

        myBody.velocity = force * power;
    }
}

```

# Answer
> 2 votes
First disable the gravity of the objects rigidbody when it gets spawned. You can do that in the inspector of the prefab for your projectile, or you can do it with code.

For a 3D rigidbody you do that with:

```
GetComponent<Rigidbody>().useGravity = false;

```

For a 2D rigidbody you do that with:

```
GetComponent<Rigidbody2D>().gravityScale = 0f;

```

When the object collides with something, reactivate gravity so that object falls down freely.

for 3D:

```
void OnCollisionEnter(Collider other) {
     GetComponent<Rigidbody>().useGravity = true;
}

```

for 2D:

```
void OnCollisionEnter2D(Collider2D other) {
     GetComponent<Rigidbody2D>().gravityScale = 1f;
}

```

# Answer
> 1 votes
Before Trowing object just disable the gravity of the object and upon reaching to the destination or by reaching the velocity of the object to 0 or nearly 0 then reenable object gravity so that object falls down freely.

I hope this will achieve the required effect.

(Converting comments to an answer so that next person in need can find it easy).

Thanks to @rtpax, @Theraot for commenting solution.

---
Tags: unity, c#, 2d, physics, game-design
---


title: How can I save game "professionally"?

text:
# Question
Title: How can I save game "professionally"?
I am a novice programmer and just learned about the concept of saving and loading games. The way I am doing it is to write data into a text file and read it afterward. However, I realize how insecure this method is. What is going to stop someone to just open the text file and edit it? Furthermore, after going through game folders of popular games, I do not seem to find any text file dedicated to saving data at all. So there must be more advanced saving methods than simply writing and reading from a text file. What are they then and how can I do something similar to that? (I mainly use Java and C++)

# Answer
> 10 votes
Text files are a perfectly fine way to create savegames. It's easy to implement and it allows you as the developer to edit savegame files in a text editor in order to test things more quickly.

But for easier parsing and better compatibility between versions, you might want to use a standard markup format like XML, JSON or YAML which you serialize and deserialize with a library. This requires some more time to set up correctly and learn the interface of the library (please don't try to write your own - pain and misery awaits you down that path). But when you got it running, it is usually worth it in the long run.

Another way to do savegames is to not use text files but binary files. This is often even easier to implement, because many data types which don't use pointers/references internally can just be written to disk as they are in memory. And they are often more compact than text-based savegames. But binary savegames are harder to troubleshoot because files are no longer human-readable and it is harder to ensure compatibility between versions.

When your savegames can get very large, then it can be useful to run them through a stock compression algorithm like ZIP to conserve the players storage space. It might seem counter-intuitive, but in some cases it even has speed benefits. Loading uncompressed data from storage can take longer than decompressing data in memory (sometimes - you might want to measure it on your target hardware).

Modern games usually do not store files in their own program directory. On some operating systems that's not even allowed anymore unless the game runs as administrator. Best practice is to store savegames in the personal files directory of the user. On UNIX systems, that's `~/.[game]`. On Windows, that's `C:\Users\[username]\AppData\Local\[company]\[game]`. Many programming languages, frameworks and engines have platform-independent convenience functions to locate the user directory. Stackoverflow.com will certainly be able to tell you how to do it with the programming language / framework / engine you use for your current project.

Encrypting your savegames is usually not necessary. Few players will actually invest the effort to locate, understand and edit their savegames. Of those who do, they usually consider it a benefit if a game allows easy savegame editing. When it's a single player or cooperative multiplayer game, then editing a savegame allows the player to experiment with the game and create interesting situations or work around bugs. When it's a competitive multiplayer game, then any savegame data worth manipulating should be stored on a server, not on the clients.

---
Tags: c++, java, savegame
---


# Question
Title: How to receive data on a Python socket only when data is available?
I am writing an update to a game I have written in python, and I am currently adding server support. I can't show you the main code (for the client), as it is hundreds of lines long. However, what I can do is show you this snippet of code from lines 34 to 47:

```
s = ""
serverMode = "noServer"
def getserver(server_ip,server_num):
    global s, serverMode
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.settimeout(2)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        s.connect((server_ip,server_num))
        print "connected to " + str(server_ip)
        serverMode = "activeServer"
    except:
        easygui.msgbox("The server is not running or does not exist.")
        s = None

```

the 's' variable is where the server socket is kept. the 'serverMode' holds the information on wether the game is connected to an active server or not, so that if so, it can be constantly checking for updates in the code. Here is the server code, which is significantly shorter than the main code:

```
import socket, signal

print "[SERVER INFO] hosted at " + str(socket.gethostname())
print "[SERVER INFO] loading server..."

def doStuff():
    pass

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
#socket.fork()
serversocket.bind((socket.gethostname(), 80))
serversocket.listen(5);

print "[SERVER INFO] server started."

clients = []

running = True
while running:

    (clientsocket, address) = serversocket.accept()
    if not [clientsocket, address] in clients: clients.append([clientsocket, address])
    data = clientsocket.recv(2048)
    if not data: pass
    elif data.startswith("[SERVER INFO]"): print data
    elif data == "disconnect":
        pass
    elif data.startswith("[BLOCK PLACEMENT]"):
        blocktype = data.split(' ')[1]
        loc = [data.split(' ')[2], data.split(' ')[3]]
        for client in clients:
            try: client.send(bytes("[BLOCK] " + str(loc[0]) + "," + str(loc[1]) + "," + blocktype))
            except: pass
    elif data.startswith("[CHAT MESSAGE]"):
        for client in clients:
            try: client.send(bytes(data))
            except: pass
    clientsocket.sendall(bytes("0,0,wood.png\n20,20,wood.png"))

serversocket.shutdown(0)
print "[SERVER INFO] server shutdown correctly."
raw_input()

```

As I mentioned, the client is constantly checking for server updates. It uses the recv function in sockets. So because of this, it runs extremely slow. I have looked at online tutorials on how to fix similar things, but nothing seems to work for me. Nevertheless, here is the code that checks for updates:

```
if serverMode == "activeServer":
    #s.setsocketopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        recvbuff = 100
        rx_bufftmp = s.recv(recvbuff)
        rx_bufftmplen = len(rx_bufftmp)
        recvbuff = max(recvbuff, rx_bufftmplen)
    except: data = False
    if not data == False and data.startswith('[BLOCK]'):
        blk = rx_bufftmp.split(' ')[1].split(',')
        blx = blk[1]
        bly = blk[2]
        bln = blk[0]
        bls.append(Block(bln, [int(blx), int(bly)]))

```

The code runs in the pygame mainloop. So, since I was not able to find any ways to optimize performance, may there be a way instead to only grab data if there is incoming data? Maybe also some other ways to optimize performance as well?

FYI:

I am running a 32 bit version of python 2.7 on a 64 bit installation of Windows 10.

# Answer
I assume that your client runs its server checking in the main thread. That means that (from what I saw of your code) every frame your main thread additional to rendering has to connect to the server.

Using a class like this should solve your problem because the main thread now can work only on rendering while the server connection is dedicated to this class.

```
from threading import Thread

class ServerConnection(Thread):
    def __init__(self):
        super(ServerConnection, self).__init__()
        self.connection = # set up your connection here

    def run(self):
        while True:
            # code for receive message from server here

```

If you're not familiar with multithreading have a look at Wikipedia or watch a video on youtube
> 0 votes

---
Tags: python, pygame, socket
---


# Question
Title: EndScreen Not Loading My Best Score And Current Score How To Fix?
I am trying to make my endscreen save last score and current score but it just appears as 0 for both everytime I die event he I picked up the coins image ***so basically it isnt saving my coins I had and my coins I have right now***

here is my endScreen

```
#---------------------------------------------------
def endScreen():
    global pause, score, speed, obstacles
    # We need to reset our variables
    pause = 0
    speed = 30
    obstacles = []

    # another game loop
    run = True
    while run:
        pygame.time.delay(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

        # This will draw text displaying the score to the screen.
        window.blit(bg, (0,0))
        score = 0
        largeFont = pygame.font.Font('BLOODY.ttf', 80) # creates a font object
        lastScore  = largeFont.render('Best Score: ' + str(updateFile()),1,(255,255,255)) # We will create the function updateFile later
        currentScore = largeFont.render('Score: '+ str(score),1,(255,255,255))
        window.blit(lastScore , (800/2 - lastScore .get_width()/2,150))
        window.blit(currentScore, (800/2 - currentScore.get_width()/2, 240))
        pygame.display.update()

def updateFile():
    f = open('scores.txt','r') # opens the file in read mode
    file = f.readlines() # reads all the lines in as a list
    last = int(file[0]) # gets the first line of the file

    if last < int(score): # sees if the current score is greater than the previous best
        f.close() # closes/saves the file
        file = open('scores.txt', 'w') # reopens it in write mode
        file.write(str(score)) # writes the best score
        file.close() # closes/saves the file

        return score

    return last
#----------------------------------------------------------

```

this is my coins text where I run it on my main loop

```
    font = pygame.font.Font('times.ttf',29)
    score = 0
    text = font.render("Hearts  =   " + str(score), True, (255,255,255))
    textRect = text.get_rect()
    textRect.center = ((80,70))

```

and here where is when I die the endScreen loads

<pre><code>           if playerman.health < -5:
               endScreen()

```
</code></pre>

# Answer
At this point where your score probably should be displayed to the screen you're setting it to `0` before.

```
        # This will draw text displaying the score to the screen.
        window.blit(bg, (0,0))
        score = 0
        largeFont = pygame.font.Font('BLOODY.ttf', 80) # creates a font object
        lastScore  = largeFont.render('Best Score: ' + str(updateFile()),1,(255,255,255)) # We will create the function updateFile later
        currentScore = largeFont.render('Score: '+ str(score),1,(255,255,255))
        window.blit(lastScore , (800/2 - lastScore .get_width()/2,150))
        window.blit(currentScore, (800/2 - currentScore.get_width()/2, 240))
        pygame.display.update()

```

When you assign the score to `0` when you leave the loop (when you leave the end screen) your problem should be solved.

Could I help you?
> 0 votes

---
Tags: python, pygame
---


title: Properly updating Singleton variables

text:
# Question
Title: Properly updating Singleton variables
I have a GameManager Singleton script, which a public property:

```
public bool IsDroneDeployed = false

```

When I set this value to true/false using a script... it seems these two versions of the value are different.

```
IsDroneDeployed = !IsDroneDeployed;
//GameManager.Instance.IsDroneDeployed

```

If I set the first one and log it out, the "instance" version isn't updated.

I would think when I'm in the GameManager, since it's a singleton I could just directly manipulate the variable, is that not the case?

Here's part of the code to show what I'm talking about...

```
public class GameManager : Singleton<GameManager>
{
    public bool IsDroneDeployed = false;

    public void LoadMapViewScene() //This is the action I kick off from an onClick event on a panel
    {
        Debug.Log($"=============Loading Map View");
        //LoadLevel(MapViewSceneName);
        SwitchDroneDeployedValue();
    }

    public void SwitchDroneDeployedValue()
    {
        Debug.Log($"============= Switching IsDroneDeployed Value BEFORE Switch: {IsDroneDeployed}");
        Debug.Log($"============= Switching GameManager.Instance.IsDroneDeployed value BEFORE Switch: {GameManager.Instance.IsDroneDeployed}");

        IsDroneDeployed = !IsDroneDeployed;
        //GameManager.Instance.IsDroneDeployed = !GameManager.Instance.IsDroneDeployed;
        Debug.Log($"============= Switching IsDroneDeployed value AFTER Switch: {IsDroneDeployed}");
        Debug.Log($"============= Switching GameManager.Instance.IsDroneDeployed value AFTER Switch: {GameManager.Instance.IsDroneDeployed}");
    }
    }

```

This results in this log..

```
============= Switching IsDroneDeployed Value BEFORE Switch: False
============= Switching GameManager.Instance.IsDroneDeployed value BEFORE Switch: False
============= Switching IsDroneDeployed value AFTER Switch: True
============= Switching GameManager.Instance.IsDroneDeployed value AFTER Switch: False

```

You can see that the "Instance" version doesn't get updated. Why is that? Only if I update GameManager.Instance.IsDroneDeployed directly

```
(GameManager.Instance.IsDroneDeployed = !GameManager.Instance.IsDroneDeployed;)

```

it updates, but that seems wrong to me because the code is already in this class.

==== Adding the Singleton code as requested:

```
public class Singleton<T> : MonoBehaviour where T : Component
{
    //The instance is accessible only by the getter
    private static T _instance;

    public static bool IsInitialized => Instance != null; //Check if the instance exists already

    public static T Instance
    {
        get
        {
            if(_instance == null)
            {
                Debug.Log("Looking for existing instance of " + typeof(T).Name + " in memory to return");
                //Making sure there not other instances of same type in Memory
                _instance = FindObjectOfType<T>();

                if(_instance == null)
                {
                    Debug.Log("Instance not found.. creating instance of " + typeof(T).Name + " in memory");
                    GameObject obj = new GameObject();
                    obj.name = typeof(T).Name;
                    _instance = obj.AddComponent<T>();
                }

            }

            return _instance;
        }
    }

    public virtual void Awake()
    {
        if(_instance == null)
        {
            //If null, then this instance is now the singleton of the assigned type
            _instance = this as T;

            //making sure this instance is kept persisted across screens
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Debug.Log("Imposter of " + typeof(T).Name + " found. Destroying! pew pew pew.. boom!");
            //Destroy the imposter!
            Destroy(gameObject);
        }
    }

    protected virtual void OnDestroy()
    {
        if (_instance == this)
        {
            _instance = null;
        }
    }

}

```

This is the tree of: this.gameObject:

```
-       this.gameObject "GameManager (UnityEngine.GameObject)"  UnityEngine.GameObject
-       base    "GameManager (UnityEngine.GameObject)"  UnityEngine.Object
        hideFlags   None    UnityEngine.HideFlags
        name    "GameManager"   string
-       Static members
-       Non-Public members
        OffsetOfInstanceIDInCPlusPlusObject -1  int
        cloneDestroyedMessage   "Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake." string
        objectIsNullMessage "The Object you want to instantiate is null."   string
-       Non-Public members
        m_CachedPtr 0x1e770033870   System.IntPtr
        m_InstanceID    -1186   int
        m_UnityRuntimeErrorString   null    string
        activeInHierarchy   true    bool
        activeSelf  true    bool
        audio   System.NotSupportedException: audio property has been deprecated    UnityEngine.Component
        constantForce   System.NotSupportedException: constantForce property has been deprecated    UnityEngine.Component
+       gameObject  "GameManager (UnityEngine.GameObject)"  UnityEngine.GameObject
        isStatic    false   bool
        layer   0   int
        light   System.NotSupportedException: light property has been deprecated    UnityEngine.Component
        renderer    System.NotSupportedException: renderer property has been deprecated UnityEngine.Component
        rigidbody2D System.NotSupportedException: rigidbody2D property has been deprecated  UnityEngine.Component
-       scene   {UnityEngine.SceneManagement.Scene} UnityEngine.SceneManagement.Scene
        buildIndex  -1  int
        handle  -12 int
        isDirty false   bool
        isLoaded    true    bool
        isSubScene  false   bool
        name    "DontDestroyOnLoad" string
        path    "DontDestroyOnLoad" string
        rootCount   4   int
-       Non-Public members
        dirtyID 0   int
        guid    "00000000000000000000000000000000"  string
        loadingState    Loaded  UnityEngine.SceneManagement.Scene.LoadingState
        m_Handle    -12 int
        tag "Untagged"  string
-       transform   "GameManager (UnityEngine.Transform)"   UnityEngine.Transform
+       base    "GameManager (UnityEngine.Transform)"   UnityEngine.Component
        childCount  0   int
+       eulerAngles "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       forward "(0.0, 0.0, 1.0)"   UnityEngine.Vector3
        hasChanged  true    bool
        hierarchyCapacity   1   int
        hierarchyCount  1   int
+       localEulerAngles    "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       localPosition   "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       localRotation   "(0.0, 0.0, 0.0, 1.0)"  UnityEngine.Quaternion
+       localScale  "(1.0, 1.0, 1.0)"   UnityEngine.Vector3
+       localToWorldMatrix  "1.00000\t0.00000\t0.00000\t0.00000\n0.00000\t1.00000\t0.00000\t0.00000\n0.00000\t0.00000\t1.00000\t0.00000\n0.00000\t0.00000\t0.00000\t1.00000\n"  UnityEngine.Matrix4x4
+       lossyScale  "(1.0, 1.0, 1.0)"   UnityEngine.Vector3
        parent  null    UnityEngine.Transform
+       position    "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       right   "(1.0, 0.0, 0.0)"   UnityEngine.Vector3
+       root    "GameManager (UnityEngine.Transform)"   UnityEngine.Transform
+       rotation    "(0.0, 0.0, 0.0, 1.0)"  UnityEngine.Quaternion
+       up  "(0.0, 1.0, 0.0)"   UnityEngine.Vector3
+       worldToLocalMatrix  "1.00000\t0.00000\t0.00000\t0.00000\n0.00000\t1.00000\t0.00000\t0.00000\n0.00000\t0.00000\t1.00000\t0.00000\n0.00000\t0.00000\t0.00000\t1.00000\n"  UnityEngine.Matrix4x4
+       Non-Public members
-       Non-Public members
        isStaticBatchable   false   bool

```

This is the tree of GameManager.Instance.gameObject

```
-       GameManager.Instance.gameObject "GameManager (UnityEngine.GameObject)"  UnityEngine.GameObject
-       base    "GameManager (UnityEngine.GameObject)"  UnityEngine.Object
        hideFlags   None    UnityEngine.HideFlags
        name    "GameManager"   string
-       Static members
-       Non-Public members
        OffsetOfInstanceIDInCPlusPlusObject -1  int
        cloneDestroyedMessage   "Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake." string
        objectIsNullMessage "The Object you want to instantiate is null."   string
-       Non-Public members
        m_CachedPtr 0x1e770033870   System.IntPtr
        m_InstanceID    -1186   int
        m_UnityRuntimeErrorString   null    string
        activeInHierarchy   true    bool
        activeSelf  true    bool
        audio   System.NotSupportedException: audio property has been deprecated    UnityEngine.Component
        constantForce   System.NotSupportedException: constantForce property has been deprecated    UnityEngine.Component
+       gameObject  "GameManager (UnityEngine.GameObject)"  UnityEngine.GameObject
        isStatic    false   bool
        layer   0   int
        light   System.NotSupportedException: light property has been deprecated    UnityEngine.Component
        renderer    System.NotSupportedException: renderer property has been deprecated UnityEngine.Component
        rigidbody2D System.NotSupportedException: rigidbody2D property has been deprecated  UnityEngine.Component
-       scene   {UnityEngine.SceneManagement.Scene} UnityEngine.SceneManagement.Scene
        buildIndex  -1  int
        handle  -12 int
        isDirty false   bool
        isLoaded    true    bool
        isSubScene  false   bool
        name    "DontDestroyOnLoad" string
        path    "DontDestroyOnLoad" string
        rootCount   4   int
-       Non-Public members
        dirtyID 0   int
        guid    "00000000000000000000000000000000"  string
        loadingState    Loaded  UnityEngine.SceneManagement.Scene.LoadingState
        m_Handle    -12 int
        tag "Untagged"  string
-       transform   "GameManager (UnityEngine.Transform)"   UnityEngine.Transform
+       base    "GameManager (UnityEngine.Transform)"   UnityEngine.Component
        childCount  0   int
+       eulerAngles "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       forward "(0.0, 0.0, 1.0)"   UnityEngine.Vector3
        hasChanged  true    bool
        hierarchyCapacity   1   int
        hierarchyCount  1   int
+       localEulerAngles    "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       localPosition   "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       localRotation   "(0.0, 0.0, 0.0, 1.0)"  UnityEngine.Quaternion
+       localScale  "(1.0, 1.0, 1.0)"   UnityEngine.Vector3
+       localToWorldMatrix  "1.00000\t0.00000\t0.00000\t0.00000\n0.00000\t1.00000\t0.00000\t0.00000\n0.00000\t0.00000\t1.00000\t0.00000\n0.00000\t0.00000\t0.00000\t1.00000\n"  UnityEngine.Matrix4x4
+       lossyScale  "(1.0, 1.0, 1.0)"   UnityEngine.Vector3
        parent  null    UnityEngine.Transform
+       position    "(0.0, 0.0, 0.0)"   UnityEngine.Vector3
+       right   "(1.0, 0.0, 0.0)"   UnityEngine.Vector3
+       root    "GameManager (UnityEngine.Transform)"   UnityEngine.Transform
+       rotation    "(0.0, 0.0, 0.0, 1.0)"  UnityEngine.Quaternion
+       up  "(0.0, 1.0, 0.0)"   UnityEngine.Vector3
+       worldToLocalMatrix  "1.00000\t0.00000\t0.00000\t0.00000\n0.00000\t1.00000\t0.00000\t0.00000\n0.00000\t0.00000\t1.00000\t0.00000\n0.00000\t0.00000\t0.00000\t1.00000\n"  UnityEngine.Matrix4x4
+       Non-Public members
-       Non-Public members
        isStaticBatchable   false   bool

```

# Answer
> 1 votes
You probably call your `SwitchDroneDeployedValue()` on a self created instance. With Unity's implementation of the singleton pattern you don't have to do this.

This should work for you. Replace your method call with this call:

```
GameManager.Instance.SwitchDroneDeployedValue();

```

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


title: Cannot create a C++ Class on UE4

text:
# Question
Title: Cannot create a C++ Class on UE4
I'm new to UE4 (4.24 on Ubuntu 16.04) and I'm using AirSim and the Blocks world.

Whenever I create a C++ class, I get the following message:

> "Successfully added class 'MyActor', however you must recompile the 'Blocks' module before it will appear in the Content Browser. Failed to automatically compile the 'Blocks' module".

And here is my Message log:

> WARNING: Library 'stdc++' was not resolvable to a file when used in Module 'AirSim', assuming it is a filename and will search library paths for it. This is slow and dependency checking will not work for it. Please update reference to be fully qualified alternatively use Public System Library Paths if you do intended to use this slow path to suppress this warning.

> ERROR:'/home/user/AirSim/Unreal/Environments/Blocks/Intermediate/Build/Linux/B4D820EA/UE4Editor/Inc/Blocks/MyActor.generated.h': Changes to generated code are not allowed - conflicts written to '/home/user/AirSim/Unreal/Environments/Blocks/Intermediate/Build/Linux/B4D820EA/UE4Editor/Inc/Blocks/MyActor.generated.h.conflict'.

The .h and .cpp are created in a Source folder within Bocks and AirSim, but nothing appears in the "Content" folder where initially I right clicked it to add a C++ Class. I've tried closing UE4 but I've no idea how to open the Source folder on UE4, and the files do not appear in the Content folder. I've already searched for this error message, I've found some things, but they couldn't solve my issue. Can anyone help? TIA

# Answer
Had to create a project from scratch and migrate what I had. I tried to create a new C++ class and it worked
> 1 votes

---
Tags: c++, unreal-4
---


# Question
Title: Should I do interactions between a new class and the main engine via a redirector class, or directly refer to only the classes the new class needs?
I'm making an open-source voxel engine, and there's an architectural problem that I would like an answer to. I have come up with 2 different solutions, and would like your opinions on:

When I'm creating a new class for a feature that uses the voxel engine, should the new class only refer to a big re-director class called `VoxelWorld` that redirects the calls to whatever component is responsible for it (solution 1), OR should the new class directly refer to only the classes it actually needs. Simply put, should the new class refer to the entire voxel engine, or just the parts it needs to?

This may be similar to a monolithic vs microservice problem?

**Solution 1:** All interactions go through a single entry point (I shall call it the `VoxelWorld` class). It's a single class, which would redirect all calls to whichever component is responsible for it. Examples of those calls would be for example `VoxelWorld.GetVoxelData(position)` or `VoxelWorld.UnloadChunk(position)`. These calls would be coming from wherever, maybe a custom class made by the user such as a `TerrainDeformer`.

The `TerrainDeformer` would only have a reference to `VoxelWorld`, and nothing else (except for all the parameters it needs to deform the terrain, such as the deformation range). The `TerrainDeformer` would simply call `VoxelWorld.EditTerrain(listOfModifications)`, and that's it. The `VoxelWorld` would be responsible for redirecting the `EditTerrain` call to whichever class is responsible for editing the terrain, for example, a `VoxelWorldEditor`.

The `VoxelWorld.UnloadChunk` call would be redirected to `ChunkManager`, which is responsible for managing chunks. Here's a picture to better explain it:

The `public VoxelWorld` would be the only public class in assembly A. Everything else is internal, meaning they are only visible for other classes inside assembly A. The assembly A is also like a black box, it is mostly (except for the `VoxelWorld`) hidden from the outside project. *It just works*, that's not a good ideology, but sometimes a necessary one. Everything in assembly B is easily extensible and public to the user. It contains the code the user would be messing with.

`VoxelWorld` would essentially by only a redirector of calls. It would have absolutely no logic, only redirections. A function in `VoxelWorld.cs` could look like this:

```
public void LoadChunk(int x, int y, int z){
    ChunkManager.LoadChunk(x, y, z);
}

```

**Solution 2:** Everything that the user wants to add refers to only the classes it really needs. Now, forget all that public/internal/redirecting stuff from solution 1, but keep in mind the different classes. This is kind of like the interface segregation principle, but just without the interface part.

> The interface-segregation principle (ISP) states that no client *\[e.g. `TerrainDeformer`\]* should be forced to depend on methods it does not use *\[e.g. `LoadChunk`\]*

In solution 1, everything depends on everything. That's the blessing and the curse of solution 1. In solution 2, that's not a problem because a class only depends on what it actually needs.

Solution 2 is more traditional and maybe cleaner -\> easier to maintain. I feel like I like solution 2 more than solution 1, but both seem good. Here's the main benefits and disadvantages:

Solution 1:

+Easy to use API (`VoxelWorld.DoWhatever()`)

-It contains a black box, so it's harder for the user to extend the very core features. (Of course, it wouldn't be an actual black box, this is open source, it's just something that the user shouldn't mess with)

Solution 2:

+Easier to maintain and extend

-More difficult API, everything is scattered so the user has to explicitly know if some feature already exists (in solution 2, the user can just scroll through the suggested functions for `VoxelWorld.___()`)

So, which solution do you recommend, and why? Or is there some third solution that I haven't thought about?

This was quite a long question, but I hope it can help others who might have the same problem. I tried googling but didn't find anything related to this kind of problem, but I didn't really even know what to search for.

# Answer
> 1 votes
In first case, you are creating God's Facade (combination of God Object and Facade), which sole purpose is convenience. There are many downsides to it, but I want go straight to the elephant in the room: you'll have to build underlying systems first before you can build your facade on top of these. My conclusion here is that facade should be optional and low priority, assuming user is going to use it at all (I personally would prefer more granular approach).

In second case, you are going for default and sensible approach: principle of minimal power. It has no additional costs (besides *not* saving a little typing here and there), and not being over-burdened during initial phases of development is just good idea.

But there are better ways. Let me introduce you to:

### Service Locator

SL is also known as Dependency Injection in some industries (where it is also a gold standard). There is ton of information about it; I am going to review main points, which should be important for gamedev:

* SL allows to provide different implementations for each "service" (subsystem or other part of engine's API) depending on execution mode: debug, release, testing, headless dedicated server.
* SL allows mods and other third-party tools to inject and request their own modules. Let users to make their own tools. Let players keep game alive with mods (see e.g. Skyrim).
* SL allows to make features optional: some features may be missing on current platforms, other features may be excluded from shipping to save space.

# Answer
> 0 votes
When you have just one god-object for your whole voxel engine, then the API will unlikely end up being very "easy to use". When the user types `VoxelWorld.` into their IDE, they will get confronted with a huge list of methods, with those they would actually use on a regular base somewhere hidden between obscure methods few people ever need.

For that reason it's likely much cleaner and easier for the user if you move most functionality to sub-objects which are obtained through or created by the `VoxelWorld` class.

I believe that it would in fact makes your documentation more navigable. If I want to know what your engine can do in regards to voxel data generation, then I just need to look at the documentation of `VoxelDataGenerator` and I have all the methods and properties about this topic in one place.

Note that what you expose as an external interface for the users does not necessarily need to reflect the inner workings of your engine. It is very well possible that some or most of these classes are also just facades which contain no data and only reference internal data structures. Perhaps your engine does not even use chunks internally but stores the whole game world in a k-d tree with dynamic loading and unloading. Then `Chunk` is actually just a facade which translates to positions in the k-d tree.

It's also not uncommon to have object-oriented frameworks which only expose interfaces to the external world and have all the implementing classes internal. This allows some neat tricks, like having the same object implement two different interfaces. So there might be a `IChunkReader` and an `IChunkWriter` which are both an object of the same class `Chunk`, just presented under different interfaces.

---
Tags: unity, architecture, voxels
---


# Question
Title: Game transitions rapidly between states with no apparent cause
I am working on an idle game for my portfolio (or release it if it's good enough). It consists of a few modules at the time of this post: Exploration, Anomaly, Encounter, and Combat. Each of these modules flows into each other automatically.

I am having an issue where it would rapidly go from Exploration to Encounter without any code telling it to do so. It's also flipping from Exploration to Anomaly sporadically without my consent. I am unsure of what is wrong here. I shall present some code samples for context

Exploration code:

```
    public IEnumerator Exploration()
    {
        ProcessVisualizer.ResetRotation = true;
        IsExploring = true;
        GameObject.Find("Process Visualizer").GetComponent<MeshRenderer>().enabled = true;
        GameObject.Find("Process Visualizer").GetComponent<ProcessVisualizer>().enabled = true;
        GameObject.Find("Status").GetComponent<Text>().text = "STATUS: EXPLORE";
        GameObject.Find("Status").GetComponent<Text>().color = new Color(0, 244, 0);

        int BombExplodeChance = Random.Range(0, 1000000); // Go do a lottery if he explodes.
        int AnomalyChance = Random.Range(5, 20);
        int AnomalyChanceHit = Random.Range(5, 20);

        string[] ExploreText = { "Redacted text array here." };

        H.text = ExploreText[Random.Range(0, ExploreText.Length)];
        H.fontSize = (int)(.1 * Screen.height);
        yield return new WaitForSeconds(Random.Range(5,10));

        if(AnomalyChance == AnomalyChanceHit && IsExploring == true)
        {
            IsExploring = false;
            StartCoroutine(AnomalyInvestigate()); // Something interesting in the horizon.
        }
        if(AnomalyChance == BombExplodeChance)
        {
            H.text = NameOfPlayer + "'s bomb hums so loud with excitement that it blew up the ship, killing " + NameOfPlayer + ".";
            GameObject.Find("Status").GetComponent<Text>().text = "STATUS: DEAD (BOMB)";
            GameObject.Find("Status").GetComponent<Text>().color = new Color(255, 0, 0);
        }
        else
        {
            IsExploring = false;
            StartCoroutine(Exploration());
        }
    }

```

Anomaly code:

```
    public IEnumerator AnomalyInvestigate()
    {
        ProcessVisualizer.ResetRotation = true;
        IsInvestigating = true;
        GameObject.Find("Process Visualizer").GetComponent<MeshRenderer>().enabled = true;
        GameObject.Find("Process Visualizer").GetComponent<ProcessVisualizer>().enabled = true;
        GameObject.Find("Status").GetComponent<Text>().text = "STATUS: ANOMALY";
        GameObject.Find("Status").GetComponent<Text>().color = Color.yellow;
        string[] InvestigationBanter = { "Redacted Anomaly Text Array" };
        int EventChance = Random.Range(5, 20);
        int ContactChance = Random.Range(5, 20);
        int BombExplodeChance = Random.Range(0, 1000000); // Go do a lottery if he explodes.

        H.text = InvestigationBanter[Random.Range(0, InvestigationBanter.Length)];
        H.fontSize = (int)(.1 * Screen.height);
        yield return new WaitForSeconds(Random.Range(5, 20));

        if(EventChance > ContactChance && IsInvestigating == true)
        {
            IsInvestigating = false;
            StartCoroutine(Encounter());
        }
        if(EventChance < ContactChance && IsInvestigating == true)
        {
            IsInvestigating = false;
            StartCoroutine(Exploration());
        }
        if (EventChance == BombExplodeChance)
        {
            H.text = NameOfPlayer + "'s bomb hums so loud with interest that it blew up the ship, killing " + NameOfPlayer + ".";
            GameObject.Find("Status").GetComponent<Text>().text = "STATUS: DEAD (BOMB)";
            GameObject.Find("Status").GetComponent<Text>().color = new Color(255, 0, 0);
        }
        else
        {
            IsInvestigating = false;
            StartCoroutine(AnomalyInvestigate());
        }

    }

```

Exploration is supposed to be the majority of the game, but it's flipping between that an anomaly as well as encounter (which is similar to anomaly). The process visualizer gives the player something else to look at if they get bored with the text.

To conclude my cry for help, I haven't been able to identify the problem. Some suggestions would be nice.

# Answer
Having code which heavily relies on coroutines can get pretty messy. It gets very hard to stay aware of which coroutines are active at the same time and how they interact with each other. But what I think what might be going on here is the following.

First this gets executed

```
if(EventChance > ContactChance && IsInvestigating == true)
{
    IsInvestigating = false;
    StartCoroutine(Encounter());
}

```

What happens here is that the coroutine `Encounter` is started. But that does not mean that this function we are currently in gets aborted. No, it keeps executing and comes to this part:

```
else
{
    IsInvestigating = false;
    StartCoroutine(AnomalyInvestigate());
}

```

What happens here is that a second `AnomalyInvestigate` coroutine gets started.

Now we have two coroutines running at the same time: `Encounter` and `AnomalyInvestigate`. Both use a very long pause for 5 to 20 seconds before doing something, so first one does something and then a couple seconds later the other does something.

---

So... How do we fix that?

If your intention is to abort the current coroutine and start a new one, then immediately leave the current coroutine with `return;` after scheduling the next one. That way the current coroutine will abort after scheduling the new one and won't execute any of its following code:

```
StartCoroutine(Encounter());
return;

```

But honestly, I think you should seriously overthink your software architecture. I am not seeing the full picture here, but one architectural pattern which seems to be appropriate to me here is the state machine. A state machine means that there are multiple states your game can be in, and when that state notices that some condition is true, it leaves to a different state.

An elegant way to do this in Unity is to implement every state with an own game object. But only one of these objects is active at the same time - the one for the state the game is currently in. Each state has a separate MonoBehaviour controlling what happens during that state. The `Update` method of these scripts are a good place to check if a condition is fulfilled which requires to switch to a different state. When that's the case, the object activates the corresponding object and deactivates itself.

But keep in mind that even when an object deactivates itself with `gameObject.SetActive(false);`, it will run the current method to the end. So you still should follow it with `return;`. The code you want to run at the beginning of switching to each state can be implemented in `OnEnable`. You can also use `OnDisable` for any cleanup code which is supposed to be run when the state is left.

The state objects also can have sub-objects which include things which are only supposed to be in the game while the game is in that state. Like a canvas with state-specific UI, for example.

Oh, and by the way, these states can also have coroutines. When an object gets deactivated, then any coroutines it is currently running also get stopped. So if you insist on using a coroutine to handle the internal logic of some states, you are free to do that.
> 1 votes

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


# Question
Title: How to copy text from an InputField to the clipboard in WebGL?
I would like to know if there is a solution to copy/paste the text from/to an InputField in a WebGL Unity app.

For security reasons, Unity WebGL doesn't allow text copy and paste in/from browser.

# Answer
I don't know if this works well but an attempt at a solution is to use the browser's copy and paste events. In paste pass that into Unity and append to the current InputField. On copy ask the inputfield to copy then pass unity's clipboard back to the browser

Here's some code and a working example

https://github.com/greggman/unity-webgl-copy-and-paste
> 1 votes

---
Tags: unity, webgl, unity-webgl
---


title: change widget's size through blueprints

text:
# Question
Title: change widget's size through blueprints
I want to change the size X of my 'Horizontal Box' widget's through blueprints but cannot figure out how to do that... the properties that I want to be able to control from blueprints are marked red below:

To give you some context, I need this to instantiate my widget dynamically. I first add a bunch of child widgets which works just great, but I also need to kinda resize the quad in the background to fit in size the child widgets that I am 'spawning'. Isn't there really any way to do this? Because this seems a super-basic thing to do as from my point of view but can't find it anywhere...

# Answer
To change the X and Y values, you need to click the "Size To Content" box under them which will do this for you.

There is a function called "Set ZOrder" as well. Get a reference to Self, get the Slot As Canvas Slot then call it.
> 2 votes

---
Tags: unreal-4, ui-design, blueprints
---


# Question
Title: Godot 3.2 Bomb explosion doesn't affect player or npc
I finished the Godot 2D game tutorial Dodge the Creeps, and i'm adding a few additional features to reinforce the things learned and make more interesting the base game.

Basically i added a Scene with a area2d as root node with a collisionShape2d,a 2 timers for the Bomb scene.

The bomb appears randomlly in the main scene, for a few seconds is supposed to be ticking and then explodes.

My problem is that neither the player or the creeps( the npc enemies) are being removed from the scene. They don't interact at all,

This is the code for the Bomb.tscn scene:

```
extends Node

func _ready():
    # Area collison disabled until animation finishes
    $CollisionShape2D.disabled = true
    # Bomb ticking animation
    $AnimatedSprite.animation = "bomb"
    # Until BombTimer times out we change animation and activate collisionArea
    $BombTimer.start()

func _on_BombTimer_timeout():
    # Change animation sprite
    $AnimatedSprite.animation = "explosion"
    # Enable Collision area
    $CollisionShape2D.disabled = false
    # Start timer to remove bomb object
    $RemoveTimer.start()

func _on_RemoveTimer_timeout():
    queue_free()

```

The code for the creep/mob when hit by the bomb:

```
func _on_Mob_body_shape_entered(body_id, body, body_shape, local_shape):
     $CollisionShape2D.set_deferred("disabled", true)
     queue_free()

```

The code for collision detection for the player when is hit:

```
func _on_Player_body_entered(body):
     hide()  # Player disappears after being hit
     emit_signal("hit")
     $CollisionShape2D.set_deferred("disabled", true)

```

If the creep/mob touches the player the game is over, but if the bombs explodes nothing happens. What i'm missing in the code?

# Answer
The body\_shape\_entered signal doesn't detect Areas, only Bodies (Kinematic, Rigid, or Static). In general Bodies can't detect Areas.

However, Areas can detect Bodies. So you can use the body\_shape\_entered signal on the Bomb Node. Then you can check the type of body collided with, and call a method on the Mob.

On Bomb.gd after connecting the signal:

```
var Mob = preload("Mob.gd")
func _on_bomb_body_shape_entered(body_id, body, body_shape, area_shape):
    if body is Mob:
        body.die()
        queue_free()

```

On Mob.gd:

```
func die():
    queue_free()

```

Since the player is an Area, we can use the Area's area\_entered signal similarly.
> 3 votes

---
Tags: collision-detection, godot
---


title: Unable to get child index in Unity

text:
# Question
Title: Unable to get child index in Unity
I'm trying to create a infinite racing game. I have a RoadSystem game object that instantiates a slab of road. On awake about 8 slabs are created. I'm trying to create a system where once the car passes the second or the third slab, the first slab is destroyed and then a new one is added at the end. I'm unable to get the index of the slabs. This is the code I have attached to a trigger which is just an empty gameobject with a box collider attached:

```
public class AddRemoveRoadSlab : MonoBehaviour {

  Public Road road

  private void OnTriggerExit(Collider other)
   {
      if (other.gameObject.tag == "RoadSlab"){
      Debug.Log(road.GetComponent<Transform>().GetSiblingIndex());
   }
}

```

What the debug.log statement is printing is the index of the Road gameobject in the Hierarchy that includes the camera, direction light etc. I want to get the index of the children of the Road gameobject. Can someone please help?

**EDIT**

Here is a screenshot of how the Road and slab are configured. The road script generates the slabs. The slabs are just unity plane objects.

# Answer
It looks like you meant to write this:

```
private void OnTriggerExit(Collider other) {
    if (other.CompareTag("RoadSlab")) {
       Debug.Log(other.transform.GetSiblingIndex());
    }
}

```

You want the index of whichever collider you're interacting with, not the single road stored in your member variable.
> 0 votes

---
Tags: unity
---


# Question
Title: UE4 bone sockets imported from blender have buggy local transform
I'm exporting this armature with two sockets for left and right hands. As you can see on the Transforms location and rotation are all 0s.

Here's my export settings on blender:

Now I import it into UE4 and if I check the socket I get this:

The Y axis local transform has value -0.085241. And I cannot get rid of it for the life of me.

# Answer
Okay so I kind of found a workaround.

Firstly, I believe UE4 only allows to import sockets for static meshes and not for skeletal meshes. So what I was importing wasn't sockets, it was just adding them as bones to the rest of the skeletal tree.

Still doesn't explain the weird transform inconsistency. But it turns out having them imported as bones was even better. I simply added the socket within UE4 to the imported socket bone. Then I adjusted the sockets transform with the equivalent opposite value of the inconsistency and now the placement matches pixel perfect with what I see in blender.
> 0 votes

---
Tags: unreal-4, blender, unreal
---


# Question
Title: Looking for tips on how to optimize/debug Java/Eclipse
I made a raycasting engine with wall textures. Before adding the texture the engine was silky smooth. With textures it has small lags (or stutters) when i move around and i would like to know why. My code is not super clean so im not providing it (yet). I'm looking for general tips on where to start when you want to optimize for performances. It's the first time i have to do this.

I monitored my pc performance while the engine was running. My CPU had very low usage and none of my cores were over 30%. Memory and disk usage were all fine. GPU was at 0% (its in 2d). All wall textures are loaded in memory at game launch so in theory my engine should not have to read from disk while running.

Im using Eclipse and the code is in Java + Swing.

# Answer
I used Jprofiler and found out i had many waiting/blocked threads. Using this tip from another user i was able to find out the problematic calls in my code:

"Go to the call tree view, record CPU data and set the thread status selector to "Blocking", than you see in which call stacks the blocking occurs.Detailed analysis of blocking situations is available in the "Monitors & Locks" view section"
> 0 votes

---
Tags: java, optimization, eclipse, swing
---


# Question
Title: Determine Whether Ray Intersects Given Rectangle
I'm building a city generator for my game and I want to ensure buildings are never placed in such a way that they overlap roads. Currently I have the system build the roads, then place buildings alongside those roads.

I have the beginning and end points of the roads as Vector3s (only using X and Z, Y is never considered for road/building placement). For buildings, I use the size of their Box Colliders to check if they can fit in a given space (with rotation and scale applied appropriately). I've done a fair amount of research for answers on lines intersecting planes, though they always seem to be incredibly hard to follow or just don't properly apply to my situation (such as determining if the line is coterminous or not). I simply need to know if the line at any point exists within the bounds of the building's rectangle. I do not need to know where or at what angle.

I also understand that my problem is essentially a 2D math problem, as I'm ignoring Y, and some of the 2D solutions I've seen to this would be extremely costly to do in city generation.

Any help would be greatly appreciated.

# Answer
You can consider the building's rectangle as 4 lines, as shown in this image:

Then you need the check if the road's line intersects any of the rectangle's lines. Here's another answer, which shows intersection between lines: https://stackoverflow.com/a/3746601/8715999
> 1 votes

---
Tags: unity, mathematics, raycasting
---


# Question
Title: Is it a useful strategy for Mobile VR titles to render faster than their simulation loop?
For example - If a title had a very heavy simulation loop (say 20ms), is it desirable to render at a greater rate, say 90hz?

This would always a present head pose correct to the view, without being stalled on simulation.

Or does this result in discomfort for the player, and instead render and sim should stay in lockstep?

# Answer
> 1 votes
Oculus implements a feature called Asynchronous Time Warp, where if a new rendered simulation state is not available when it's time to present a new frame to the user, the previous rendering is re-projected using the latest head tracking information, to minimize the apparent judder.

This is not quite the scenario you describe, but it is a situation in which VR experts have found it's worthwhile to display an old simulation state from a new perspective - breaking the 1:1 match between simulation time and presentation time for better perceived responsiveness.

A similar logic may well apply to your case: *try it and see* if it improves your game.

Note that it's actually very common for games to run their simulation at a different rate than the rendering, and interpolate the result to get smooth gameplay even on frames intermediate between simulation steps. So I don't see reason to doubt this tactic could also be useful in VR.

---
Tags: rendering, mobile, virtual-reality
---


# Question
Title: Why when using Lerp and StartCoroutine to Lerp between -3 and 3 it's not working?
```
private bool alreadyFading = false;

```

Then

```
private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Teleporting Object")
        {

            if (!alreadyFading) StartCoroutine(Teleport(-3, 3, 5f));
        }
    }

```

And

```
IEnumerator Teleport(float from, float to, float duration)
    {
        alreadyFading = true;

        var timePassed = 0f;
        while (timePassed < duration)
        {
            var factor = timePassed / duration;
            var value = Mathf.Lerp(from, to, factor);

            material.SetFloat("_DissolveAmount", value);

            yield return null;
        }

        material.SetFloat("_DissolveAmount", to);

        alreadyFading = false;
    }

```

Using a break point it's getting to the Teleport function but it's not changing the values from -3 to 3. It does nothing to the shader to the property \_DissolveAmount.

I want it to change the value from -3 to 3 with duration once not ping pong. but it's not just it's just don't do anything.

# Answer
I think the main issue here is that you're not incrementing the variable `timePassed` so the Coroutine is stuck infinitely in the while loop.

As for the `yield return null`I think it's best explained here but basically once a coroutine has yielded, the Main Thread continues running. On the next frame, Unity will find stacked coroutine and will call them from where they left off at the yield.

I suggest you change it to this (didn't test the code but it should hopefully work)

```
IEnumerator Teleport(float from, float to, float duration)
    {
        alreadyFading = true;

        var timePassed = 0f;
        while (timePassed < duration)
        {
            var factor = timePassed / duration;
            var value = Mathf.Lerp(from, to, factor);

            material.SetFloat("_DissolveAmount", value);
            timePassed += Time.deltaTime;
            yield return null;
        }

        material.SetFloat("_DissolveAmount", to);

        alreadyFading = false;
    }

```

`Time.deltaTime` is the amount of seconds it took for the engine to process the previous frame
> 0 votes

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