# Question
Title: What is the fastest way of reading an atomic counter?
I have an atomic counter in my fragment shader that my application reads after each drawcall. I am currently using `glMapBufferRange` with `GL_MAP_READ_BIT` set. This absolutely destroys my applications performance. To give you an idea of how often the atomic counter gets read, each drawcall consists of a million vertices.

# Answer
> 3 votes
I solved the problem by binding the atomic counter to the `GL_COPY_READ_BUFFER` and using `glCopyBufferSubData` to copy the counter to a buffer bound to the `GL_COPY_WRITE_BUFFER`. Then I mapped the buffer with `glMapBufferRange` and set `Gl_MAP_READ_BIT`. This seemed to sync much better and for now it is sufficient for my use. I did not test glGetBufferSubdata, but that might work as well.

# Answer
> 1 votes
The reason it destroys your performance is that OpenGL commands are asynchronous, so when you try to read the atomic counter, the CPU freezes and waits until all the GPU's atomic-counter-buffer-related operations have completed.

It's basically like sending out an HTTP request and freezing the program until it returns.

There are 2 solutions:

1. Read the data back asynchronously, as explained here. (That article doesn't cover reading back from the framebuffer. If that's something you want to do, then you can use Pixel Buffer Objects and Asynchronous Readbacks.)
2. Don't read the data back. Instead, use OpenGL commands to modify the data however you like, and prepare it for its next draw call. Some useful techniques/commands are:

* You can copy data between buffers with `glCopyBufferSubData`.
    * You can modify data however you like with compute shaders.
    * You can tell OpenGL to store various data from the rendering pipeline (e.g. fragment shader output) using Transform Feedback.

---
Tags: opengl, shaders, optimization
---


title: Where's Anti-Aliasing in LWRP?

text:
# Question
Title: Where's Anti-Aliasing in LWRP?
In Unity 2019.2 -LWRP (lightweight render pipeline project) the default **Game Output(Quality = High) is rendering with jaggies.**

Inorder to get a clear render ,while looking for the Anti-Aliasing option it doesn't seem to be under the default location (Edit-Project settings-Quality )for LWRP projects.

Where is the Anti-Aliasing option in LWRP and is there any other way to get a clear game render?

# Answer
> 1 votes
When your project uses a scriptable render pipelines (like the LWRP one), then settings like these are no longer found in the project settings. They can now be found in the inspector of the render pipeline asset.

When you create a new project based on the "Lightweight RP" template, then you find three of these assets under Assets/Settings. The one used by default is the one named "LWRP-HighQuality" (you can select the pipeline asset being used in the project settings under "Graphics"):

Double-click it to see its inspector. Anti-Aliasing is found under "Quality":

If you still don't see anti-aliasing in the game, also make sure that anti-alliasing ("MSAA") isn't deactivated on the camera game object:

---
Tags: unity, antialiasing
---


# Question
Title: Do I need to keep the old ID3D11Device around after querying for ID3D11Device5?
When attempting to create a directx11 device using the newer `ID3D11Device5` interface the compiler complains that `ID3D11Device5**` is incompatible with `ID3D11Device**`.

Research via docs.microsoft (RIP msdn) says that the proper way to create a version 5 device is to call `QueryInterface` on a `ID3D11Device` to get a `ID3D11Device5`.

**Do I need to keep the pointer to a temporary ID3D11Device around after calling QueryInterface to get a ID3D11Device5 or can I release it as shown below?**

```
#include <array>
#include <vector>

struct AdapterInfo {
    IDXGIAdapter4* adapter = nullptr;
    DXGI_ADAPTER_DESC3 desc{};
    void Release() noexcept {
        if(adapter) {
            adapter->Release();
            adapter = nullptr;
        }
    }
};

//...

struct DeviceInfo {
    D3D_FEATURE_LEVEL highest_supported_feature_level{};
    ID3D11DeviceContext* dx_context = nullptr;
    ID3D11Device5* dx_device = nullptr;
};

//...

DeviceInfo CreateDeviceFromFirstAdapter(const std::vector<AdapterInfo>& adapters) noexcept {
    //Snip Error handling...
    DeviceInfo info{};

    unsigned int device_flags = 0U;
#ifdef _DEBUG
    device_flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
    device_flags |= D3D11_CREATE_DEVICE_BGRA_SUPPORT;

    std::array feature_levels{
    D3D_FEATURE_LEVEL_12_1,
    D3D_FEATURE_LEVEL_12_0,
    D3D_FEATURE_LEVEL_11_1,
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_3,
    D3D_FEATURE_LEVEL_9_2,
    D3D_FEATURE_LEVEL_9_1,
    };

    auto first_adapter_info = std::begin(adapters);

    //Snip Debug/Logging output...

    auto first_adapter = first_adapter_info->adapter;
    bool has_adapter = first_adapter != nullptr;

    //Create a temporary "old" device
    ID3D11Device* temp_device{};
    auto hr_device = ::D3D11CreateDevice(has_adapter ? first_adapter : nullptr
        , has_adapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE
        , nullptr
        , device_flags
        , feature_levels.data()
        , static_cast<unsigned int>(feature_levels.size())
        , D3D11_SDK_VERSION
        , &temp_device
        , &info.highest_supported_feature_level
        , &info.dx_context);

    //Snip error handling...

    //Ask old device for newer interface.
    auto hr_dxdevice5i = temp_device->QueryInterface(__uuidof(ID3D11Device5), (void**)&info.dx_device);

    //Snip error handling

    //Release old device.
    temp_device->Release();
    temp_device = nullptr;
    return info;
}

```

# Answer
This code is perfectly acceptable. The refcount on the underling device is up by one from `QueryInterface` and then back down by one from the release of the `ID3D11Device` interface so it's back where it started.

Note that you should strongly consider using a COM smart-pointer rather than trying to do all the ref stuff manually. Microsoft::WRL::ComPtr is the defacto standard here.

BTW, I do the same thing you are doing in my device creation blog post.

> One issue that I see in your code is that it only works on Windows 10. On Windows 8.1 and Windows 7, you will get an `E_INVALIDARG` error passing in that list of feature levels. See the blog post for details. Of course, if you require `ID3D11Device5` then you already require Windows 10 (15063) or later.
> 2 votes

---
Tags: directx11
---


title: Disabled script works anyway

text:
# Question
Title: Disabled script works anyway
I have a simple code that will be enabled when I kick, so I disable it right away but even though it is disabled, it works somehow. can it be because of his parent or something else I dont know of?

```
//this is the script Kick_Test, i dont reach it from anywhere else
private GameObject ball;
private Rigidbody2D rg2d;
public int power = 30;

void Start()
{
    ball = GameObject.FindGameObjectWithTag("Ball");
    rg2d = ball.GetComponent<Rigidbody2D>();
    this.enabled = false;
}

private void OnTriggerEnter2D(Collider2D col)
{
    if(col.tag == "Ball")
    {
        Debug.Log("KİCK");
        Vector2 pos = (transform.position - col.gameObject.transform.position).normalized;
        rg2d.AddForce(-pos * power, ForceMode2D.Impulse);
    }
}

```

# Answer
Consulting the documentation on OnTriggerEnter2D:

> Trigger events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.

So, this behaviour is exactly what we'd expect based on the docs.

If you want to ignore these messages, just put:

```
if (this.isActiveAndEnabled == false)
    return;

```

at the top of your method to early-out when you're currently disabled.
> 0 votes

---
Tags: unity, 2d, inheritance
---


# Question
Title: How to draw a line based on an angle with a defined size?
I have a game where the player shoots a projectile based on the mouse direction when clicking, which travels 500 pixels.

I wish I could draw a line exactly where the projectile will be destroyed.

What I can do is draw a line from where the projectile is created to where the mouse is when it is clicked.

That is, the line may be longer or shorter than the path taken by the projectile.

**The code is something like this:**

```
draw_line(x,y,mouse_x,mouse_y);

```

**Result in game:**

**Below an image explaining:**

These blue dots would be the click of the mouse. That no matter where it went, the line drawn (green) would be the same (ending in pink x).

I know how to get the direction and how to calculate the distance, but I don't know how to implement it in line drawing.

# Answer
> 0 votes
Just use trigonometry. Sine and cosine. Just get the angle/direction between the object and the mouse click.

**Click Event:**

```
seno=dsin(point_direction(x,y,mouse_x,mouse_y));
cose=dcos(point_direction(x,y,mouse_x,mouse_y));

```

**Draw Event:**

```
draw_line(x,y,x+(500*cose),y+(-500*seno));

```

---
Tags: game-maker, angles, lines
---


title: Unity Dropdown Stays Stuck Open

text:
# Question
Title: Unity Dropdown Stays Stuck Open
As can be seen in the following video:

https://youtu.be/zb3uMUqub00

The dropdown stays stuck open when Unity launches the game. This happens even with a non-modified dropdown that is plopped as a new UI object inside the canvas.

I tried a blank project, and the issue does not reproduce. I tried in a blank project, and the dropdown works. I tried researching a solution, but not too sure how to find one with this problem. Maybe someone here will have an idea or two.

The repo can be downloaded at https://github.com/DenisLabrecque/Warglobe if desired.

# Answer
> 1 votes
My UI System script, a parent of the dropdown, has a statement that gets all components, whether active or not, in children:

`m_Components = GetComponentsInChildren<Component>(true).ToList();`

It then goes through those components and turns them on (in case an artist turned them off or something like that):

```
     foreach (Component screen in m_Components)
     {
        screen.gameObject.SetActive(true);
     }

```

The assumption here is that each component will be a screen. However, it enables the dropdown template as a side effect, which makes the dropdown's initial state be open.

Instead, the loop should have been written as follows:

```
     foreach (Component screen in m_Components)
     {
        if (screen is UIScreen)
        {
           screen.gameObject.SetActive(true);
        }
     }

```

---
Tags: unity
---


# Question
Title: 2D Topdown Shooter - Line of sight based purely on angle and rotation
In a game I'm working on, enemies constantly rotate around as they move around the map. I want them to only shoot the player if they're within a field of view.

This is the function header:

```
bool inLineOfSight(float playerX, float playerY, float enemyX, float enemyY, float enemyRotation);

```

Enemy rotation is in degrees not radians. Picture kind of shows what I'm looking for. An enemy should not be able to see the player unless they're within field of view. Should mention that raycasting isn't necessary as I've already sorted that out.

How would I make sure that the player is within an enemies field of view based on angle and position only?

# Answer
> 1 votes
Any form of visibility checking is based on angles:

Take the direction an enemy is looking at. Let's call this unit vector "D".

```
vec2 D;
D.x = cos(enemyRotation);
D.y = sin(enemyRotation);

```

Now let's take draw a line between the enemy and the player. Let's call this "P"

```
vec2 P = player.position - enemy.position;

```

So, in order to discern, naively, whether the player is within the "cone" of vision for an enemy, we need to do two mathematical checks:

Angle check. Store the length of P, then normalize it so it is unit length (length = 1) get the dot product of D and P, and compare it to the cone angle. If this value is greater than the cosine of the cone angle, then the player is outwith an "infinite" cone of vision. Otherwise, the enemy can potentially see the player.

```
float l = sqrtf(dot(P,P));
vec2 p = P/l;
if ( dot(p,D) > cos(EnemyConeAngle))
    return false;

```

The enemy cone angle is the angle between the look ahead direction, and the edge of the cone. It's max value should be less than 90 degrees.

Second, range check. We need to make the cone finite. This is easily done, by comparing the maximum visual range of the enemy to the length if P.

```
if (l <= enemyRange)
{
    return true;
}

```

This, however, does not take into account if there is an obstruction in the way.

Crudely, you can take P as a ray, and see if any scenery is hit by it before it reaches the player. Google "ray vs bounding box" for more info on this.

I would also recommend you learn to use radians, if you haven't already. Most maths libraries prefer to use radians in their internal calculations, and honestly, it doesn't make a huge difference to your code to support it.

---
Tags: c++, sfml, angles, view, shooter
---


# Question
Title: Setting SteamVR Camera Target Eye before SteamVR installed in Unity
I'm writing a plugin that can be used in both VR and non-VR projects. I have a Camera that is used to display UI containing some game info on a secondary monitor. My problem is that when the end-user adds my plugin and then imports steam vr, this UI camera's Target Eye is set to "Both" by default.

I can't have any SteamVR code in my plugin. But I can't adjust Target eye property of the camera without it. I just want it so that the camera doesn't change when a user imports SteamVR. I want it to always render to the main display (target eye = none)

So just to clarify,

1. I have my plugin, written in a non-vr project with a standard Unity camera. There is no Target Eye setting for this standard camera.
2. User wants to use it in VR project, imports plugin into SteamVR Project
3. Camera used to render UI gets automatically converted (wrongly) into SteamVR camera
4. Defaults to Target Eye = Both
5. Need it to be Target Eye = None

At the moment to avoid users submitting countless bug reports, I have to provide warnings in like 6 places telling users to dig way into my built-in prefabs to adjust this setting manually if they use SteamVR. It's not easy for new Unity users, and I want to make adoption as easy as possible.

# Answer
> 0 votes
It appears that newer versions of unity added the targetStereoEye variable to the camera even when SteamVR is not installed. This means I can pre-set the target eye to my desired value before SteamVR is installed.

Just had to update Unity. It's now 2019.2.12 for reference.

---
Tags: unity, camera, steam-vr
---


# Question
Title: "ui is not declared in current scope" error
I just started development for a game I have to design for school. When using gd in the script to make the character move right I get an error:

```
extends KinematicBody2D

var motion = Vector2()

func _physics_process(delta):

    if input.is_action_pressed(ui.right):
        motion.x = 100

    move_and_slide(motion)

```

This is the line that is giving me problems

```
if input.is_action_pressed(ui.right):

```

and it keeps saying that ui is not declared in the current scope

# Answer
I don't know why this should be a problem. Just do what Mertle told you to do.

"Who the heck is Mertle?" you might ask. "I don't know anyone by that name!"

That's exactly what the compiler is telling you:

> "not declared in the current scope"

is the compiler's way of saying "I don't know who you're talking about. Who is this `ui` person who can tell me about `.right`? You haven't introduced us yet!"

You've used a new name that you haven't introduced before in this conversation (scope), so the compiler has no idea who you mean.

In fact, `ui` is not an object that the compiler can ask for a `.right` member.

`"ui.right"` is a string of text that you want it to pass to the `is_action_pressed` function as-is.

To pass a string, you *must* put double-quotation marks around it, so the compiler knows to treat it as a blob of plain text, not an expression or variable to parse and evaluate.

So, replace this with:

```
if Input.is_action_pressed("ui_right"):

```

...as shown in the Godot documentation on Input events.

As a general rule, when following a programming guide, every character is important. You can't leave any out. So check your examples carefully to make sure you typed out everything. The capitalization of `Input` is important too!
> 1 votes

---
Tags: godot
---


# Question
Title: Why isn't my image's transparency honoured in the Unity sprite?
I'm following through Jesse Freeman's Lynda course Unity 5 2D Essential Training. The exercise files contain sprites with transparency. Here's a screenshot of one such sprite on the trainers screen (sorry it's so small):

But here's how it looks in my scene in Unity 5.5.0F3:

I think that the sprite's alpha properties are set correctly, I have Alpha Source set to "Input Texture Alpha" and Alpha Is Transparency is checked:

When I open the PNG in PhotoShop the transparency is correctly set:

Why is the transparent area rendered as opaque in my sprite?

# Answer
> 2 votes
This may help:

> "simply change the render queue:
> \- select Object Material
> \- change view to Debug Mode (Inspector Window top right drop down menu)
> \- change Custom Render Queue value for example 3000 =\> 3100
> \- now your object will be rendered before other transparent objects"

Check here first as it may be something simple like the format. For example, if you need True Color then you will need to select the format 'RGBA 32bit'.

Check here for more in depth explanations and solutions.

# Answer
> 0 votes
Make sure your Image Editor is set to RGB Color Mode. Ran into this issue myself when I found out CMYK color mode was the culprit with transparency.

Here's how to switch color modes in illustrator.

---
Tags: unity, transparency
---


title: Cant find a way to set fps for sf::Time

text:
# Question
Title: Cant find a way to set fps for sf::Time
```
Myclass
{
void run();
sf::Clock m_clock;
float m_time;
float timestep
}
Myclass::run()
{
if (m_time>= timestep)
{
//update
m_time-=timestep;
}
restartCLock();
}
Myclass::restartCLock()
{
m_time+=m_clock.restartAsSeconds();
}

```

How do i do the same but when m\_time is being sf::Time?

# Answer
> 1 votes
The class `sf::Time` has the operators `>=`, `-=` and `+=` overloaded. You can just change the type from `float` to `sf::Time`.

```
struct Myclass
{
    void      run();
    void      restartCLock();
    sf::Clock m_clock;
    sf::Time  m_time;
    sf::Time  timestep = sf::seconds(1.f / 60.f);
};

void
Myclass::run()
{
    if (m_time >= timestep)
    {
        // update
        m_time -= timestep;
    }
    restartCLock();
}

void
Myclass::restartCLock()
{
    m_time += m_clock.restart();
}

```

---
Tags: c++, sfml
---


title: Tilemap collision in Pure ECS?

text:
# Question
Title: Tilemap collision in Pure ECS?
I'm currently making a 2D topdown dungeon crawler using pure ECS and Data Oriented Design. So I only use structs of arrays for all my components. I have now added tilemap generation, but was wondering what option to pick for tile collision. Should I add the tile collisionbox as an entity or somehow include it in my CollisionSystem?

I am already using collision boxes to check collision for entities. But In my mind, doing so for every tile against every entity might get pretty laggy.

I currently store my terrain data in a linked graph like this:

```
struct Tile{
    struct Tile* up;
    struct Tile* right;
    struct Tile* down;
    struct Tile* left;

    Position pos;
    bool walkable;
};

```

I am not using chunks.

# Answer
> 1 votes
When you have pure tile-based yes-or-no walkability, then there are a lot of optimizations you can do because:

1. Tiles never move
2. Tiles always have the same size
3. Tiles are always found at coordinates which are multiples of the tile size

Your collision system doesn't need to check every tile for collisions with entities, because tiles won't move and won't themselves be affected by collisions (there might be exceptions to this, but those should better be handled on the entity-side). It certainly doesn't need to check tiles for colliding with other tiles. So handling tiles like any other entity would indeed be a waste of CPU cycles.

I would in fact not handle tiles as entities at all, unless I had a game with very "smart" tiles which have so much functionality that they make sense to have multiple components.

You only need to check mobile entities for collisions with tiles, you only need to do so when an entity moves from the border of one tile to the next and you only need to check that specific tile. I assume your CollisionSystem already knows the old and the new (or intended) position of each mobile entity, because you would need that for interpolating collision detection of fast-moving entities and for resolving blocking events.

Your collision system should be able to tell if a specific world position is blocked or not by simply querying your tile graph for the tile at a specific position and checking if that tile is walkable. Unfortunately the data-structure you are using for tiles right now isn't very optimized for that use-case. If you want to get a tile at a specific position, then you need to start with some tile you know and then traverse the graph until you got the one you need. So you might want to create a secondary data-structure which is optimized for retrieving the tile at a specific world location.

The most common solution is to use a 2d array for the tilemap with coordinates representing the position. That way you can obtain a tile at a given position in constant time by simply doing `tile[position.x / TILE_WIDTH][position.y / TILE_HEIGHT]`. But when you are using a graph to store your tilemap data, then you likely intend to use a map of unlimited size and without a meaningful origin. That would make an array a bad choice. In that case you could use a hash table (`std::unordered_map<Position, Tile*>`, possibly with a custom hash function) or a 2-d tree to map positions to tiles.

---
Tags: c++, collision-detection, tilemap, entity-component-system, data-oriented
---


title: Need help with a grab Shader

text:
# Question
Title: Need help with a grab Shader
How can I make grab Shader similar to https://docs.unity3d.com/Manual/SL-GrabPass.html in GLSL.

The idea, is that you grab exact pixels from background (ex. from composited renderTarget) and put on rendered object. So it's like 100% transparency, because it always has the pixels right behind. Later if you disort the pixels, can give very cool effects like https://www.shadertoy.com/view/Mdc3Rl.

SO far I have texture of background (plane to renderTarget), and object cube right before it. My vertex shader for cube is `gl_Position = WVP * spos;` and I have no idea how do the frag shader to copy the pixels from background. Any help appreciated.

# Answer
For my setup it was as easy as:

```
vec2 uv = gl_FragCoord.xy / screenSize;

fragColor.rgb = texture(background, uv.xy).rgb;
fragColor.a = 1.0;

```
> 0 votes

---
Tags: shaders, glsl
---


# Question
Title: PlayerPrefs.SetInt Stops code below from running
This is the code...

```
void storeStarData()
{
    // Code to store star data in PlayerPrefs...
    Debug.Log("Writing to PlayerPrefs");
    PlayerPrefs.SetInt("totStars", NumOfStars);
    int i = 0;
    Debug.Log("test");
    while (i < NumOfStars)
    {
        PlayerPrefs.SetString("starID" + i, StarIDID[(i)]);
        PlayerPrefs.SetString("starName" + i, StarName[(i)]);
        PlayerPrefs.SetString("starHIP" + i, StarIDHIP[(i)]);
        PlayerPrefs.SetString("starHD" + i, StarIDHD[(i)]);
        PlayerPrefs.SetString("starHR" + i, StarIDHR[(i)]);
        PlayerPrefs.SetString("starGL" + i, StarIDGL[(i)]);
        PlayerPrefs.SetString("starBF" + i, StarIDBF[(i)]);
        PlayerPrefs.SetString("starRA" + i, StarRA[(i)]);
        PlayerPrefs.SetString("starDec" + i, StarDec[(i)]);
        PlayerPrefs.SetString("starMag" + i, StarMag[(i)]);
        PlayerPrefs.SetString("starCI" + i, StarCI[(i)]);
        Debug.Log("star " + i + " complete");
        i++;
    }
    PlayerPrefs.Save();

    i = 0;
    int ok = 0;
    while (i < NumOfStars)
    {
        if (PlayerPrefs.GetString("starID" + i) != null)
        {
            ok++;
        }
        i++;
    }
    Debug.Log(ok);
}

```

And this is the Debug.Log output that I am getting...

As you can see, the program gets up to the First Debug Log `Debug.Log("Writing to PlayerPrefs");` But then stops before the `Debug.Log("test");`.

After removing `PlayerPrefs.SetInt("totStars", NumOfStars);` The program gets to the `Debug.Log("test");`. So it is the PlayerPrefs.SetInt causing the issue.

How do I fix this?

# Answer
> 2 votes
Turns out Unity doesn't play very well with System.Threading as I was running this function off the main thread to prevent the GUI from freezing (I am dealing with almost 120,000 records in the list).

Once I ran the function on the main thread, all the problems disappeared and PlayerPrefs started working normally.

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


title: Word Wrap in Editor Console

text:
# Question
Title: Word Wrap in Editor Console
I'm working as an educator - I am wondering is there any way to wrap the text of lines output from the Unity editor *console*?...

Thanks!

# Answer
You can adjust the number of lines of text that appear, up to 10. See here:

https://docs.unity3d.com/Manual/Console.html#LineCount

> To control how many lines of each entry are visible in the list, click the Console menu button, and select **Log Entry \> \[X\] Lines** from the menu, where **\[X\]** is the number of lines you wish to display for each entry.

If that’s not good enough, you can always write your own console window, but that seems like overkill. The short version is, use a subclass off `EditorWindow` and listen to `Application.logMessageReceived`.

There are also various custom consoles on the asset store, some of which have line wrapping. They are not all free though. I just googled “unity editor better console” and found a bunch.
> 2 votes

---
Tags: unity, console
---


# Question
Title: Reducing noise from joystick at small deflections
I have placed in my level a cube, which is my player, and a camera, which will follow the player.

I'm defining a direction ***A*** from camera to player and another ***B*** perpendicular to this one. So I get two perpendicular directions no matter where the camera is located, A and B.

So far so good. I'm multiplying the direction A by the value of the vertical axis of a PS4 joystick. And the B direction by the horizontal input.

Then I make a vector sum: `C = (A * verticalInput) + (B * horizontalInput)`

C faces the direction in which the player should face, regardless of the camera position, so I can move the camera anywhere and the joystick input always corresponds to the camera's view.

The issue is that when the input magnitude is very very small, the C vector oscillates rapidly in a small angle interval. The result is that the player "vibrates" when looking at that direction.

This effect disappears when the inputs are greater than 0.5, but I cannot use a value that large for a dead zone because I want my player to walk very slowly because he is a ninja! (And is about to make a stealth-kill or very slow movement to avoid noise).

In other words, how do I reduce the jitter from noisy joystick input?

# Answer
> 1 votes
At extremely small values of input values, you're essentially creating a lot of vector jitters. Even the smallest change in X or Y can have a big impact on the resultant direction vector.

Given the importance of letting your player move slowly (ninja style) at times, you would want to give them fairly good/fine control over slow motion, yet also give then the ability to move in non-ninja mode. So to do that, you should get away from requiring them to make very small joystick movements to control slower motion.

Let's assume that the joystick input values vary from 0-100, and that your player can move at a speed from 0-100. And any movement under 10 is considered "ninja movement" with special features such as a much lower chance of detection.

Given that, I'm going to suggest several methods for dealing with the input sensitivity with very low input values. It's hard to predict how this might end up working without knowing some of the more precise characteristics of the input values.

**Method 1: "Ninja Mode" movement modifier**

When the player holds down a modifier key (or presses it to toggle the mode), they enter "Ninja Mode", and the joystick input from 0-100 scales to movement speeds of 0-10. If they are full joystick deflection, they only move at maximum "Ninja Mode" speed. You still probably have the jitter with very tiny motion, but you also remove the requirement that the player make very tiny joystick movements to move slowly.

**Method 2: Change the linear increase of joystick input values into a non-linear movement curve**

Rather than a simplistic use of the input fields as you suggest, you might consider making the resultant applied input curve be non-linear. For example you might use a Sigmoid function so that a fair amount of joystick motion is required to begin movement.

**Method 3: Filtering and clipping**

You might find that applying some kind of moving average filter to the inputs will reduce the jitter. You can also simply reject any movement where the length of vector C is below some minimum value. Very tiny (jitter causing) movements of the joystick will be ignored because they will result in very short vector and no movement.

Of course you might also be able to combine the above suggestions in various ways for a hybrid approach.

---
Tags: unity, input, joystick
---


title: My game got stolen, what do I do?

text:
# Question
Title: My game got stolen, what do I do?
I recently released my first game on the Google Play Store (yay!), and a few days later I found my game had been reuploaded to two different shady-looking sites (Softonic and Fibonapps). Needless to say, I did not give either of these sites permission to distribute my game. It is a paid app, so if people download it from these other sites I'm effectively losing money. I sent an email to both about two weeks ago asking them to remove it, I've gotten no response and the listings are still up. How do I proceed from here?

# Answer
The same thing has happened to me in the past. Here are a few things I learnt from it.

Remember if they distribute your game it's not ideal, however you primarily lose out on ratings and publicity on the official play store. If you release games with ads or in app purchases then you should be covered in some sense for your revenue.

I emailed each website and gave them a notice of legal action if they don't remove it. 9/10 times they remove it as they know their site is dodgy but don't want the hassle from a developer.

Sometimes it's hard to find the email so use whois.com and see what you can find on the domain to locate someone to contact.
> 3 votes

# Answer
Those sites are potentially guilty of ip/copyright theft and software piracy.

Speak to a lawyer who is a specialist in Intellectual Property with regards to software.

If you agree to the fees, they will investigate on your behalf, and, if warranted, will send a "cease and desist" letter, and/or notify the relevant authorities of software piracy. What happens after that is up to the authorities/courts.

But honestly, this is a widespread problem, and not easily dealt with.

You may wish to consider some form of digital rights management, or "DRM", but that tends to have a bit of a bad reputation these days, so make sure you are aware of *all* your options.
> 1 votes

---
Tags: legal, google-play, distribution
---


# Question
Title: OnDrag does not work, but OnMouseDown works
There is a code:

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

public class DragAndDropGame : MonoBehaviour, IBeginDragHandler, IDragHandler
{

    Camera MainCamera;

    void Awake()
    {
        MainCamera = Camera.allCameras[0];
        Debug.Log(MainCamera);
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 newPos = MainCamera.ScreenToWorldPoint(eventData.position);
        newPos.z = 0;
        transform.position = newPos;
    }

    void OnMouseDown()
    {
        Debug.Log("OnMouseDown");
    }
}

```

`OnMouseDown` fulfills, but the implementation of`IBeginDragHandler`, `IDragHandler` \- not. What can be wrong?

# Answer
`IDragHandler` (and its associates) are only called for UI elements that are part of a canvas. And even then, only for UI components (Image, text, etc) and not 3D objects and colliders.

You are probably looking for `OnMouseDrag`.
> 5 votes

# Answer
You probably implemented `IDragHandler`, but forgot to implement `IBeginDragHandler` and `IEndDragHandler`.

**All three must be implemented**, otherwise `OnDrag(PointerEVentData eventData)` will not be called for you.

For example, this will be ok:

```
public class Skins_TouchingArea_UI : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler{

    public void OnDrag(PointerEventData eventData){  Debug.Log("dragging"); }

    //required for OnDrag() to work
    public void OnBeginDrag(PointerEventData eventData) {}

    //required for OnDrag() to work
    public void OnEndDrag(PointerEventData eventData) {}
}

```
> 1 votes

# Answer
Try adding this namespace:

```
using UnityEngine.UI

```
> -1 votes

---
Tags: unity
---


title: Why is my map not drawing properly?

text:
# Question
Title: Why is my map not drawing properly?
My code compiles fine but for some reason, I get this white background in my window. what am I doing wrong?

I want to draw my map (sorry, there is a lot of code).

Here is my debugged window image:

Here is my function for drawing my map:

```
void drawmaps()
{
  glClear(GL_COLOR_BUFFER_BIT);

  //glBindTexture(GL_TEXTURE_2D, Textures[0]);
  //suelo
  glBegin(GL_QUADS);
  glColor4f(1, 1, 1, 1);
  glNormal3f(0, 0, 1);
  glTexCoord2f(15, 0);
  glVertex3f(4, 0, 4);

  glTexCoord2f(15, 15);
  glVertex3f(4, 0, -4);

  glTexCoord2f(0, 15);
  glVertex3f(-4, 0, -4);

  glTexCoord2f(0, 0);
  glVertex3f(-4, 0, 4);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //glBindTexture(GL_TEXTURE_2D, Textures[1]);

  //pared1
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-4, 0, 4);

  glTexCoord2f(0, 0);
  glVertex3f(-4, 0, -4);

  glTexCoord2f(0, 1);
  glVertex3f(-4, 2, -4);

  glTexCoord2f(1, 1);
  glVertex3f(-4, 2, 4);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pared3
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(4, 2, 4);

  glTexCoord2f(0, 0);
  glVertex3f(4, 2, -4);

  glTexCoord2f(0, 1);
  glVertex3f(4, 0, -4);

  glTexCoord2f(1, 1);
  glVertex3f(4, 0, 4);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pared2
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(4, 0, -4);

  glTexCoord2f(1, 1);
  glVertex3f(4, 2, -4);

  glTexCoord2f(0, 1);
  glVertex3f(-4, 2, -4);

  glTexCoord2f(0, 0);
  glVertex3f(-4, 0, -4);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pared4
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(4, 2, 4);

  glTexCoord2f(1, 1);
  glVertex3f(4, 0, 4);

  glTexCoord2f(0, 1);
  glVertex3f(-4, 0, 4);

  glTexCoord2f(0, 0);
  glVertex3f(-4, 2, 4);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //glBindTexture(GL_TEXTURE_2D, Textures[3]);

  //techo
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(7, 0);
  glVertex3f(-4, 2, 4);

  glTexCoord2f(7, 7);
  glVertex3f(-4, 2, -4);

  glTexCoord2f(0, 7);
  glVertex3f(4, 2, -4);

  glTexCoord2f(0, 0);
  glVertex3f(4, 2, 4);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //glBindTexture(GL_TEXTURE_2D, Textures[2]);

  //columna1A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-2.5, 0, 2);

  glTexCoord2f(0, 0);
  glVertex3f(-2.5, 2, 2);

  glTexCoord2f(0, 1);
  glVertex3f(-3, 2, 2);

  glTexCoord2f(4, 1);
  glVertex3f(-3, 0, 2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna1B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-3, 0, 1.5);

  glTexCoord2f(0, 0);
  glVertex3f(-3, 2, 1.5);

  glTexCoord2f(0, 1);
  glVertex3f(-2.5, 2, 1.5);

  glTexCoord2f(4, 1);
  glVertex3f(-2.5, 0, 1.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna1C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-2.49999976158142, 0, 2.00000095367432);

  glTexCoord2f(4, 1);
  glVertex3f(-2.49999976158142, 0, 1.5);

  glTexCoord2f(0, 1);
  glVertex3f(-2.49999976158142, 2, 1.5);

  glTexCoord2f(0, 0);
  glVertex3f(-2.49999976158142, 2, 2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna1D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-2.99999952316284, 2, 2.00000095367432);

  glTexCoord2f(4, 1);
  glVertex3f(-2.99999952316284, 2, 1.5);

  glTexCoord2f(0, 1);
  glVertex3f(-2.99999952316284, 0, 1.5);

  glTexCoord2f(0, 0);
  glVertex3f(-2.99999952316284, 0, 2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna2A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(3, 0, 2);

  glTexCoord2f(0, 0);
  glVertex3f(3, 2, 2);

  glTexCoord2f(0, 1);
  glVertex3f(2.5, 2, 2);

  glTexCoord2f(4, 1);
  glVertex3f(2.5, 0, 2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna2B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(2.5, 0, 1.5);

  glTexCoord2f(0, 0);
  glVertex3f(2.5, 2, 1.5);

  glTexCoord2f(0, 1);
  glVertex3f(3, 2, 1.5);

  glTexCoord2f(4, 1);
  glVertex3f(3, 0, 1.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna2C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(3.00000023841858, 0, 2.00000095367432);

  glTexCoord2f(4, 1);
  glVertex3f(3.00000023841858, 0, 1.5);

  glTexCoord2f(0, 1);
  glVertex3f(3.00000023841858, 2, 1.5);

  glTexCoord2f(0, 0);
  glVertex3f(3.00000023841858, 2, 2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna2D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(2.50000047683716, 2, 2.00000095367432);

  glTexCoord2f(4, 1);
  glVertex3f(2.50000047683716, 2, 1.5);

  glTexCoord2f(0, 1);
  glVertex3f(2.50000047683716, 0, 1.5);

  glTexCoord2f(0, 0);
  glVertex3f(2.50000047683716, 0, 2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna3A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(3, 0, -2);

  glTexCoord2f(0, 0);
  glVertex3f(3, 2, -2);

  glTexCoord2f(0, 1);
  glVertex3f(2.5, 2, -2);

  glTexCoord2f(4, 1);
  glVertex3f(2.5, 0, -2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna3B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(2.5, 0, -2.5);

  glTexCoord2f(0, 0);
  glVertex3f(2.5, 2, -2.5);

  glTexCoord2f(0, 1);
  glVertex3f(3, 2, -2.5);

  glTexCoord2f(4, 1);
  glVertex3f(3, 0, -2.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna3C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(3.00000023841858, 0, -1.99999904632568);

  glTexCoord2f(4, 1);
  glVertex3f(3.00000023841858, 0, -2.5);

  glTexCoord2f(0, 1);
  glVertex3f(3.00000023841858, 2, -2.5);

  glTexCoord2f(0, 0);
  glVertex3f(3.00000023841858, 2, -2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna3D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(2.50000047683716, 2, -1.99999904632568);

  glTexCoord2f(4, 1);
  glVertex3f(2.50000047683716, 2, -2.5);

  glTexCoord2f(0, 1);
  glVertex3f(2.50000047683716, 0, -2.5);

  glTexCoord2f(0, 0);
  glVertex3f(2.50000047683716, 0, -2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna4A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-2.5, 0, -2);

  glTexCoord2f(0, 0);
  glVertex3f(-2.5, 2, -2);

  glTexCoord2f(0, 1);
  glVertex3f(-3, 2, -2);

  glTexCoord2f(4, 1);
  glVertex3f(-3, 0, -2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna4B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-3, 0, -2.5);

  glTexCoord2f(0, 0);
  glVertex3f(-3, 2, -2.5);

  glTexCoord2f(0, 1);
  glVertex3f(-2.5, 2, -2.5);

  glTexCoord2f(4, 1);
  glVertex3f(-2.5, 0, -2.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna4C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-2.49999976158142, 0, -1.99999904632568);

  glTexCoord2f(4, 1);
  glVertex3f(-2.49999976158142, 0, -2.5);

  glTexCoord2f(0, 1);
  glVertex3f(-2.49999976158142, 2, -2.5);

  glTexCoord2f(0, 0);
  glVertex3f(-2.49999976158142, 2, -2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //columna4D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(4, 0);
  glVertex3f(-2.99999952316284, 2, -1.99999904632568);

  glTexCoord2f(4, 1);
  glVertex3f(-2.99999952316284, 2, -2.5);

  glTexCoord2f(0, 1);
  glVertex3f(-2.99999952316284, 0, -2.5);

  glTexCoord2f(0, 0);
  glVertex3f(-2.99999952316284, 0, -2);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //glBindTexture(GL_TEXTURE_2D, Textures[4]);

  //pedestalA
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(1, 0, 1);

  glTexCoord2f(1, 1);
  glVertex3f(0.800000011920929, 0.699999988079071, 0.800000011920929);

  glTexCoord2f(0, 1);
  glVertex3f(-0.800000011920929, 0.699999988079071, 0.800000011920929);

  glTexCoord2f(0, 0);
  glVertex3f(-1, 0, 1);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pedestalB
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(0.800000011920929, 0.699999988079071, -0.800000011920929);

  glTexCoord2f(1, 1);
  glVertex3f(1, 0, -1);

  glTexCoord2f(0, 1);
  glVertex3f(-1, 0, -1);

  glTexCoord2f(0, 0);
  glVertex3f(-0.800000011920929, 0.699999988079071, -0.800000011920929);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pedestalC
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(1, 0, 1);

  glTexCoord2f(0, 0);
  glVertex3f(1, 0, -1);

  glTexCoord2f(0, 1);
  glVertex3f(0.800000011920929, 0.699999988079071, -0.800000011920929);

  glTexCoord2f(1, 1);
  glVertex3f(0.800000011920929, 0.699999988079071, 0.800000011920929);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pedestalD
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-0.800000011920929, 0.699999988079071, 0.800000011920929);

  glTexCoord2f(0, 0);
  glVertex3f(-0.800000011920929, 0.699999988079071, -0.800000011920929);

  glTexCoord2f(0, 1);
  glVertex3f(-1, 0, -1);

  glTexCoord2f(1, 1);
  glVertex3f(-1, 0, 1);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //pedestalE
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(5, 0);
  glVertex3f(0.800000011920929, 0.699999988079071, 0.800000011920929);

  glTexCoord2f(0, 0);
  glVertex3f(0.800000011920929, 0.699999988079071, -0.800000011920929);

  glTexCoord2f(0, 5);
  glVertex3f(-0.800000011920929, 0.699999988079071, -0.800000011920929);

  glTexCoord2f(5, 5);
  glVertex3f(-0.800000011920929, 0.699999988079071, 0.800000011920929);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //glBindTexture(GL_TEXTURE_2D, Textures[5]);

  //caja1A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-2.5, 0, 3.5);

  glTexCoord2f(1, 1);
  glVertex3f(-2.5, 0.5, 3.5);

  glTexCoord2f(0, 1);
  glVertex3f(-3, 0.5, 3.5);

  glTexCoord2f(0, 0);
  glVertex3f(-3, 0, 3.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja1B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-3, 0, 3);

  glTexCoord2f(1, 1);
  glVertex3f(-3, 0.5, 3);

  glTexCoord2f(0, 1);
  glVertex3f(-2.5, 0.5, 3);

  glTexCoord2f(0, 0);
  glVertex3f(-2.5, 0, 3);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja1C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-2.49999976158142, 0, 3.50000095367432);

  glTexCoord2f(1, 1);
  glVertex3f(-2.49999976158142, 0, 3);

  glTexCoord2f(0, 1);
  glVertex3f(-2.49999976158142, 0.5, 3);

  glTexCoord2f(0, 0);
  glVertex3f(-2.49999976158142, 0.5, 3.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja1D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-2.99999952316284, 0.5, 3.50000095367432);

  glTexCoord2f(1, 1);
  glVertex3f(-2.99999952316284, 0.5, 3);

  glTexCoord2f(0, 1);
  glVertex3f(-2.99999952316284, 0, 3);

  glTexCoord2f(0, 0);
  glVertex3f(-2.99999952316284, 0, 3.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja1E
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-2.5, 0.5, 3.50000095367432);

  glTexCoord2f(1, 1);
  glVertex3f(-2.5, 0.5, 3);

  glTexCoord2f(0, 1);
  glVertex3f(-2.99999952316284, 0.5, 3);

  glTexCoord2f(0, 0);
  glVertex3f(-2.99999952316284, 0.5, 3.5);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja2A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-1.79999995231628, 0, 3.70000004768372);

  glTexCoord2f(1, 1);
  glVertex3f(-1.79999995231628, 0.5, 3.70000004768372);

  glTexCoord2f(0, 1);
  glVertex3f(-2.29999995231628, 0.5, 3.70000004768372);

  glTexCoord2f(0, 0);
  glVertex3f(-2.29999995231628, 0, 3.70000004768372);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja2B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-2.29999995231628, 0, 3.20000004768372);

  glTexCoord2f(1, 1);
  glVertex3f(-2.29999995231628, 0.5, 3.20000004768372);

  glTexCoord2f(0, 1);
  glVertex3f(-1.79999995231628, 0.5, 3.20000004768372);

  glTexCoord2f(0, 0);
  glVertex3f(-1.79999995231628, 0, 3.20000004768372);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja2C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-1.7999997138977, 0, 3.70000100135803);

  glTexCoord2f(1, 1);
  glVertex3f(-1.7999997138977, 0, 3.20000004768372);

  glTexCoord2f(0, 1);
  glVertex3f(-1.7999997138977, 0.5, 3.20000004768372);

  glTexCoord2f(0, 0);
  glVertex3f(-1.7999997138977, 0.5, 3.70000004768372);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja2D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-2.29999947547913, 0.5, 3.70000100135803);

  glTexCoord2f(1, 1);
  glVertex3f(-2.29999947547913, 0.5, 3.20000004768372);

  glTexCoord2f(0, 1);
  glVertex3f(-2.29999947547913, 0, 3.20000004768372);

  glTexCoord2f(0, 0);
  glVertex3f(-2.29999947547913, 0, 3.70000004768372);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja2E
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-1.79999995231628, 0.5, 3.70000100135803);

  glTexCoord2f(1, 1);
  glVertex3f(-1.79999995231628, 0.5, 3.20000004768372);

  glTexCoord2f(0, 1);
  glVertex3f(-2.29999947547913, 0.5, 3.20000004768372);

  glTexCoord2f(0, 0);
  glVertex3f(-2.29999947547913, 0.5, 3.70000004768372);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja3A
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-3.29999995231628, 0, 3.79999995231628);

  glTexCoord2f(1, 1);
  glVertex3f(-3.29999995231628, 0.5, 3.79999995231628);

  glTexCoord2f(0, 1);
  glVertex3f(-3.79999995231628, 0.5, 3.79999995231628);

  glTexCoord2f(0, 0);
  glVertex3f(-3.79999995231628, 0, 3.79999995231628);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja3B
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-3.79999995231628, 0, 3.29999995231628);

  glTexCoord2f(1, 1);
  glVertex3f(-3.79999995231628, 0.5, 3.29999995231628);

  glTexCoord2f(0, 1);
  glVertex3f(-3.29999995231628, 0.5, 3.29999995231628);

  glTexCoord2f(0, 0);
  glVertex3f(-3.29999995231628, 0, 3.29999995231628);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja3C
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-3.2999997138977, 0, 3.8000009059906);

  glTexCoord2f(1, 1);
  glVertex3f(-3.2999997138977, 0, 3.29999995231628);

  glTexCoord2f(0, 1);
  glVertex3f(-3.2999997138977, 0.5, 3.29999995231628);

  glTexCoord2f(0, 0);
  glVertex3f(-3.2999997138977, 0.5, 3.79999995231628);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja3D
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-3.79999876022339, 0.5, 3.80000114440918);

  glTexCoord2f(1, 1);
  glVertex3f(-3.79999876022339, 0.5, 3.30000019073486);

  glTexCoord2f(0, 1);
  glVertex3f(-3.79999876022339, 0, 3.30000019073486);

  glTexCoord2f(0, 0);
  glVertex3f(-3.79999876022339, 0, 3.80000019073486);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);

  //caja3E
  glColor4f(1, 1, 1, 1);
  glBegin(GL_QUADS);
  glNormal3f(0, 0, 1);
  glTexCoord2f(1, 0);
  glVertex3f(-3.29999923706055, 0.5, 3.80000114440918);

  glTexCoord2f(1, 1);
  glVertex3f(-3.29999923706055, 0.5, 3.30000019073486);

  glTexCoord2f(0, 1);
  glVertex3f(-3.79999876022339, 0.5, 3.30000019073486);

  glTexCoord2f(0, 0);
  glVertex3f(-3.79999876022339, 0.5, 3.80000019073486);
  glEnd();
  glColor4f(1.0, 1.0, 1.0, 1.0);
}

```

Here is my main function:

```
int main(int argc, char** argv)

{

  //Initialise GLUT with command-line parameters.
  glutInit(&argc, argv);

  //Set Display Mode
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);

  //Set the window size
  glutInitWindowSize(2560, 1080);

  //Set the window position
  glutInitWindowPosition(100, 100);

  //Create the window
  glutCreateWindow("HellBlasters Game");
  // sets the window in fullscreen
  glutFullScreen();

  // display function
  glutDisplayFunc(drawmaps);
  // display idle function
  glutIdleFunc(drawmaps);
  //Enter the GLUT event loop
  glutMainLoop();
  // here we init our handles and start our game up
  while (gameloop == true)
  {
    //EngineInits
    GraphicWindow(); // gets the window handle
    EngineUpdate();  // gets the engine handle
    sectorbarrels(); // gets the barrel handle
    sectorceilings(); // gets the ceiling handle
    sectordoors();    // gets the door handle
    sectorfloors();  // gets the floor handle
    sectorpillars(); // gets the pillar handle
    sectorstairs();  // gets the stair handle
    sectorwalls();   // gets the wall handle
    player();        // gets player handle
    frameperSec();   // gets framepersec handle
    fpscamera();     // gets fpscamera handle
    ShadersDat();    // gets shader handles
    playercheats();  // gets player cheat handles
    renderfloorMath(); // gets math of floor
    renderceilingMath(); // gets math of ceiling
    renderdoorMath();    // gets math of door
    renderbarrelMath();  // gets math of barrel
    renderpillarMath(); // gets math of pillar
    renderstairMath(); // gets math of stair
    renderwallMath(); // gets math of wall
    renderenginemath(); // gets engine math
    renderframepersecMath(); // gets fps math
    renderplayercheatsmath(); // gets cheat math
    renderplayermath(); // gets player math
    rendershadermath(); // gets shader math
    drawbarrelsmath(); // draws barrel polygons
    drawceilingsmath(); // draws ceiling polygons
    drawdoorsmath();    // draws door polygons
    drawenginemath_M(); // draws engine polygons
    drawfloorsmath();   // draws floor polygons
    drawframepersecMath(); // draws framepersec
    drawpillarsmath();     // draws pillar polygons
    drawplayersmath();     // draws player polygons
    drawplayer_m();        // draws player_m polygons
    drawscameramath();     // draws camera polygons
    drawshadermath();    // draws shader Images
    drawstairsmath();   // draws stair polygons
    drawwallsmath();    // draws wall polygons
    maploader();      // loads map data
    system("pause /n");
  }
  return 0;
}

```

# Answer
You're getting a white square because that's what you've told OpenGL to draw. You are drawing a square without a texture and with the colour set to white, so you get a white square.
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: Why has my object detached itself from the parent?
I made an two objects in blender, animated them, and saved them.

Firstly, when I reloaded them, half of the animations I created had disappeared, which is annoying itself but the real annoyance is that the item, a sword, detached itself from the parent, the character. I exported as fbx but for some reason it is completely seperated.

Also, my mesh has holes everywhere. Is this normal for untextured objects?

> How it should look
>
> Whats actually happening

# Answer
Your normals are flipped, search for shortcut or how to flip normals in Blender, that is causing invisible faces. Make sure your sword is parented correctly to the bone that is holding the sword.

I would suggest setting up position for a sword in T pose and to not animate the sword position itself `(this could have been the problem, as object was animated, once not in Blender world space it MIGHT behave differently relative to other objects)`, it should be driven by position and rotation of the bones.

The common practice is to separate sword and character models, then parent a sword to a `GameObject` that would be a bone that should hold a sword.

This is from my old project as an example.
> 1 votes

---
Tags: unity, animation, blender, models, objects
---


# Question
Title: Storing a List to PlayerPrefs Not Working
I have a test database of 37 records and I have stored each column into a list and I am storing each record into PlayerPrefs.

```
void storeStarData()
{
    // Code to store star data in PlayerPrefs...
    PlayerPrefs.SetInt("totStars", NumOfStars);
    int i = 0;
    while (i < NumOfStars)
    {
        PlayerPrefs.SetString(("starID" + i), StarIDID[i]);
        PlayerPrefs.SetString(("starName" + i), StarName[i]);
        PlayerPrefs.SetString(("starHIP" + i), StarIDHIP[i]);
        PlayerPrefs.SetString(("starHD" + i), StarIDHD[i]);
        PlayerPrefs.SetString(("starHR" + i), StarIDHR[i]);
        PlayerPrefs.SetString(("starGL" + i), StarIDGL[i]);
        PlayerPrefs.SetString(("starBF" + i), StarIDBF[i]);
        PlayerPrefs.SetString(("starRA" + i), StarRA[i]);
        PlayerPrefs.SetString(("starDec" + i), StarDec[i]);
        PlayerPrefs.SetString(("starMag" + i), StarMag[i]);
        PlayerPrefs.SetString(("starCI" + i), StarCI[i]);
        PlayerPrefs.Save();
        i++;
    }
    PlayerPrefs.Save();
    Debug.Log(PlayerPrefs.GetString("StarID0"));
    Debug.Log(PlayerPrefs.GetString("StarID1"));
    Debug.Log(PlayerPrefs.GetString("StarID2"));
    Debug.Log(PlayerPrefs.GetString("StarID3"));
    startSimulation();
}

```

First record in list StarIDID\[0\] = 1 Last record in list StarIDID\[36\] = 37

At the end, I've added 4 Debug.Logs that return the IDs of the first 4 stars. For some reason, only the first StarIDID is being stored into Player prefs.

Here is the output of the Debug.Log:

As you can see, StarID0 is the only PlayerPref with a valid value stored, the other ones don't have any values stored in them for some reason.

Is there a way to fix this and am I doing anything wrong here?

# Answer
> 1 votes
You are setting the value for `starID1` (lower case s) but you are getting the value for `StarID1` (upper case S). Key names in `PlayerPrefs` are case sensitive, so these are not the same key.

You likely get a value for `StarID0` because you set that value at some point in the past.

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


# Question
Title: Assertion b2Assert(m_bodyCount > 0) showing an error
I have the following code for deleting a Box2D body:

```
void b2World::DestroyBody(b2Body* b)
{
    b2Assert(m_bodyCount > 0);
    b2Assert(IsLocked() == false);
    if (IsLocked())
    {
        return;
    }

    // Delete the attached joints.
    b2JointEdge* je = b->m_jointList;
    while (je)
    {
        b2JointEdge* je0 = je;
        je = je->next;

        if (m_destructionListener)
        {
            m_destructionListener->SayGoodbye(je0->joint);
        }

        DestroyJoint(je0->joint);

        b->m_jointList = je;
    }
    b->m_jointList = NULL;

    // Delete the attached contacts.
    b2ContactEdge* ce = b->m_contactList;
    while (ce)
    {
        b2ContactEdge* ce0 = ce;
        ce = ce->next;
        m_contactManager.Destroy(ce0->contact);
    }
    b->m_contactList = NULL;

    // Delete the attached fixtures. This destroys broad-phase proxies.
    b2Fixture* f = b->m_fixtureList;
    while (f)
    {
        b2Fixture* f0 = f;
        f = f->m_next;

        if (m_destructionListener)
        {
            m_destructionListener->SayGoodbye(f0);
        }

        f0->DestroyProxies(&m_contactManager.m_broadPhase);
        f0->Destroy(&m_blockAllocator);
        f0->~b2Fixture();
        m_blockAllocator.Free(f0, sizeof(b2Fixture));

        b->m_fixtureList = f;
        b->m_fixtureCount -= 1;
    }
    b->m_fixtureList = NULL;
    b->m_fixtureCount = 0;

    // Remove world body list.
    if (b->m_prev)
    {
        b->m_prev->m_next = b->m_next;
    }

    if (b->m_next)
    {
        b->m_next->m_prev = b->m_prev;
    }

    if (b == m_bodyList)
    {
        m_bodyList = b->m_next;
    }

    --m_bodyCount;
    b->~b2Body();
    m_blockAllocator.Free(b, sizeof(b2Body));
}

```

When I close the game I get an exception, and the debugger points to the first line :

```
b2Assert(m_bodyCount>0);

```

What exactly does this mean?

# Answer
An assertion failure happens when the expression returns 0, in this case when m\_bodyCount is lower or equal to 0. This means that, whenever your code executes `b2World::DestroyBody();`, all the previously created `b2Body`s are already destroyed, if there ever were any created in the first place.

If you did create at least one (1) b2Body\* instance, make sure that that specific instance isn't deleted multiple times in the code (in multiple instances of your `class A` for example), since very weird bugs can occur because of that.
> 2 votes

# Answer
The issue was that i was deleting every pointer to b2 objects in a class itself.
> 0 votes

---
Tags: c++, box2d
---


# Question
Title: Understanding arguments to a signed distance field function
I'm looking into drawing a box using Inigo Quilez's code:

```
float sdBox( in vec2 p, in vec2 b )
{
    vec2 d = abs(p)-b;
    return length(max(d,vec2(0))) + min(max(d.x,d.y),0.0);
}

```

Do I understand correctly that for `p` is a point anywhere in 2d space?

If so, what is `b`?

I tried to draw a 2x2 rectangle at origin (assuming `b` is then `vec2(2,2)`) and do those calculations but nothing good came out. It should calculate the distance between the point and nearest edge, right?

# Answer
> 2 votes
`b` is the size of the box, measured from the center to one corner - what we often call the "half-extents" of the shape.

So a box 10 units wide and 2 units tall would use `b = vec2(5, 1)`

To draw a 2x2 square, you'd want `b = vec2(1, 1)`

---
Tags: glsl, signed-distance-field
---


# Question
Title: How can I improve the performance of my A* pathfinding code?
I'm currently working on implementing A\* pathfinding into a little project of mine. My ideal goal is that my game should be able to handle about 1000+ objects without any noticable impact on performance.

Right now I'm using threading to handle my pathfinding as best as I can and it's working pretty nicely but once I start to reach upwards 1000 objects it'll start eating away at my performance regardless.

How could I improve my performance further? Any tips or tricks? I'll answer questions if you need more information, and I appreciate any help you can give me :)

Here's how I handle my pathfinding:

```
public class Pathfinding
{
    // Returns a Vector3 list, representing a path on the AStarGrid.
    public static List<Vector3> CalculatePath(Vector3 fromPos, Vector3 toPos)
    {
        // Get a reference to the pathfinding grid.
        AStarGrid grid = AStarGrid.instance;

        // Get the start- and endnode.
        GridNode startNode = AStarGrid.instance.GetNodeAtPosition(fromPos);
        GridNode endNode = AStarGrid.instance.GetNodeAtPosition(toPos);

        if(startNode == null || endNode == null || startNode == endNode)
        {
            // No need to calculate a path if the startNode or endNode is null,
            // or if the endNode is already on the startNode.
            return null;
        }

        // The dictionary used to pair a node together with some data so that we dont have to modify a node directly since,
        // we want this function to be able to be run several times simultaneously with threads.
        Dictionary<GridNode, NodeData> openNodes = new Dictionary<GridNode, NodeData>();

        // A separate dictionary which couples a node with another in order to be able to retrace a path by following a nodes parents.
        Dictionary<GridNode, GridNode> nodeParents = new Dictionary<GridNode, GridNode>();

        // The closedNodes only need to be a HashSet since we'll only be checking if a node exists in it, nothing else.
        HashSet<GridNode> closedNodes = new HashSet<GridNode>();

        // Begin the search and keep searching for as long as there are open nodes or the currentNode is the endNode.
        openNodes.Add(startNode, new NodeData());
        GridNode currentNode;
        while(openNodes.Count > 0)
        {
            currentNode = GetLowestFCostNode(openNodes);

            // Check if the current node is the endNode, meaning we found our path.
            if(currentNode == endNode)
            {
                // Path was found, retrace the path and return it.
                return RetracePath(endNode, startNode, nodeParents);
            }

            // Loop through the current node's neighbours.
            List<GridNode> neighbours = GetNeighbours(currentNode, grid);
            for(int i = 0; i < neighbours.Count; i++)
            {
                GridNode neighbour = neighbours[i];

                // Ignore closed nodes.
                if(closedNodes.Contains(neighbour))
                    continue;

                // Calculations used to determine gCost and hCost
                int hDistanceFromCurrentToNeighbour = openNodes[currentNode].gCost + GetHeuristicDistance(currentNode, neighbour);
                int hDistanceFromNeighbourToPathEnd = GetHeuristicDistance(neighbour, endNode);

                // Check if the neighbour is already in the open set.
                if(openNodes.ContainsKey(neighbour))
                {
                    // Check if the gCost is lower using this path, recalculate costs and parent if it is.
                    if(hDistanceFromCurrentToNeighbour < openNodes[neighbour].gCost)
                    {
                        openNodes[neighbour].gCost = hDistanceFromCurrentToNeighbour;
                        openNodes[neighbour].hCost = hDistanceFromNeighbourToPathEnd;
                        nodeParents[neighbour] = currentNode;
                    }
                }
                else
                {
                    // Add it to the open set along with its data, store its parent and calculate costs.
                    NodeData neighbourData = new NodeData();
                    neighbourData.gCost = hDistanceFromCurrentToNeighbour;
                    neighbourData.hCost = hDistanceFromNeighbourToPathEnd;
                    nodeParents.Add(neighbour, currentNode);
                    openNodes.Add(neighbour, neighbourData);
                }
            }

            // Remove the current node from the open set and add it to the closed set instead.
            openNodes.Remove(currentNode);
            closedNodes.Add(currentNode);
        }

        // No path was found, return null.
        return null;
    }

    // Retraces the path from the specified node by following its data parents which are stored in the openNodes dictionary.
    static List<Vector3> RetracePath(GridNode fromNode, GridNode toNode, Dictionary<GridNode, GridNode> nodeParents)
    {
        List<Vector3> path = new List<Vector3>();
        GridNode currentlyTracing = fromNode;
        while(currentlyTracing != toNode && currentlyTracing != null)
        {
            path.Add(currentlyTracing.position);
            currentlyTracing = nodeParents[currentlyTracing];
        }
        return path;
    }

    // Gets the heuristic distance from one node to the other.
    static int GetHeuristicDistance(GridNode fromNode, GridNode toNode)
    {
        // Casting is a little faster than Mathf.RoundToInt and the nodes shouldn't be in a floated position anyway.
        int dx = Mathf.Abs((int)fromNode.position.x - (int)toNode.position.x);
        int dy = Mathf.Abs((int)fromNode.position.y - (int)toNode.position.y);

        // The longest axis tells us how many times a node needs to move vertically.
        // The difference between the longest axis and the shortest axis tells us the diagonal moves required.
        // Moving vertically has a cost of 14 and moving diagonally has a cost of 10.
        if(dx > dy)
            return 14 * dy + 10 * (dx - dy);

        return 14 * dx + 10 * (dy - dx);
    }

    // Gets the neighbouring nodes of a target node within the specified grid.
    static List<GridNode> GetNeighbours(GridNode targetNode, AStarGrid grid)
    {
        List<GridNode> neighbours = new List<GridNode>();
        for(int x = -1; x <= 1; x++)
        {
            for(int y = -1; y <= 1; y++)
            {
                // Skip self.
                if(x == 0 && y == 0)
                    continue;

                // Fetches the neighbour, will be null if it's out of bounds etc.
                GridNode neighbour = grid.GetNodeAtPosition(new Vector3(x + targetNode.position.x, y + targetNode.position.y, 0));
                if(neighbour == null || !neighbour.isWalkable)
                    continue;

                neighbours.Add(neighbour);
            }
        }
        return neighbours;
    }

    // Get the node with the lowest fCost.
    // Pretty slow. Optimize using a min heap somehow maybe? Got to look into this.
    static GridNode GetLowestFCostNode(Dictionary<GridNode, NodeData> openNodes)
    {
        GridNode lowestNode = null;
        NodeData lowestNodeData = null;
        foreach(KeyValuePair<GridNode, NodeData> pair in openNodes)
        {
            if(lowestNode == null)
            {
                lowestNode = pair.Key;
                lowestNodeData = pair.Value;
            }
            else
            {
                if(pair.Value.fCost < lowestNodeData.fCost)
                {
                    lowestNode = pair.Key;
                    lowestNodeData = pair.Value;
                }
            }
        }
        return lowestNode;
    }

    // NodeData class, in order to pair a node with data.
    class NodeData
    {
        public int gCost;
        public int hCost;
        public int fCost
        {
            get
            {
                return gCost + hCost;
            }
        }
    }
}

```

# Answer
Well firstly, your openSet needs to be a priority queue. Here's one I wrote specifically for pathfinding.

Secondly, unless you are a pathfinding and optimization expert, you're not going to beat an off-the-shelf implementation. I highly recommend you find one rather than implementing it yourself.

Thirdly, and most importantly, pathfinding optimization in games usually involves finding tricks to pathfind as infrequently as possible, rather than optimizing the pathfinding itself.

You said you're trying to pathfind for 1000 units.

* Do they all have the same destination? If so, you can do a single reverse pathfind instead of 1000 normal ones, or a single normal one + a flocking algorithm.
* Is it possible to pre-compute the paths to save time at runtime, using something like a vector field?
* Will *approximate* best paths work, like HPA\*?
> 3 votes

# Answer
To improve performance you need to know what to optimize. To do this tough, profile your code enough to know where the hotspots are.

To find hotspots i recomend using the System.Diagnostics.Stopwatch; You can then encapsule some code between the start and stop. this will tell you the amount of MS thats beeing used on those lines.

From there you sort of need to figure out whats going wrong, and i don't think anyone can just tell you whats wrong. you unfortunately need to do the profiling and optimisation yourself. If you however find that some piece of code is slow, posting that particular code might be easier for someone to dissect and say whats not really optimzed and what is.
> 0 votes

---
Tags: unity, c#, path-finding
---


# Question
Title: How do you execute Trigger-collider collision only in one gameobject?
I'm trying to deal with units (generated from the same prefab) dealing damage to each other on collisions. Each Unit has both a Collider2D and a trigger on the front, that deals damage to other units that enter it.

I drew a small image (with Paint, sorry) to better illustrate what I mean and want.

**The problem I am having is that when a collision occurs (one unit enters the trigger of the other), both units damage each other, meaning Unit 2 also deals damage to Unit 1.**

I have seen that you can create a separate gameObject as a child of the unit and attach the trigger to this gameObject.

However, the number of units will be very high so if possible I don't want to double the number of gameObjects used by units.

Also, the amount of damage dealt is calculated from many other parameters from many other scripts on the units and doubling all those references doesn't look like an elegant solution.

**Any Ideas?** Thanks

# Answer
> 2 votes
> Also, the amount of damage dealt is calculated from many other parameters from many other scripts on the units and doubling all those references doesn't look like an elegant solution.

You can have a reference to the unit and call a method of that unit, removing the necessity to copy all of the stuff.

---

1. First and maybe the most easiest solution in case your other `Collider` is not trigger. Is to use `isTrigger` which would tell you if the collider that invoked this method is the one that is trigger.

```
private void OnTriggerEnter(Collider other)
{
    if (other.isTrigger)
}

```
2. Create a child `GameObject` attach trigger collider to it and a script that would notify main object of that collision. To differentiate between colliders, if you have many of them, you can give those objects `tags`, `id` and any other identification approach...

If you don't want to create another `GameObject` as a child then you could ask yourself a question "What are the conditions under which the collision damages a unit?". When answering this you will come up with methods to check if those conditions are satisfied.

3. `Raycasting`, one of the methods to check if condition is satisfied. If you know that a collider in case of damage event would be in front of the object raycasting or in any other direction you could then determine which entity should receive the damage.
4. Any other type of collision casting. Similar approach to `Raycasting`, but using `Physics.BoxCast()` and other things alike.
5. Vector comparison. This one is very similar to `Raycasting`, but instead of using `Physics` we can compare two vectors of the `GameObjects` that collided. If one is pointing to another then it's probably the vector that should do that damage based on conditions of inflicting the damage `[basically if direction to other GameObject and active GameObject forward direction align - then the one pointing towards other is the active]`.
6. Getting the contacts of collision and using this information to determine a damage inflicting collider.
7. ... Other methods that depend on what information you are provided with, on the state of the game and on conditions.

# Answer
> 0 votes
I would just use a child object with one collider for its Rigidbody and a separate child object with a collider for the damage effect.

If you really want to use just one collider, then you could use the OnCollisionEnter event and then use collision.GetContacts to find out how the objects collided and implement your game mechanics accordingly.

If your game needs to handle a very large number of objects, then you might want to consider to not use GameObjects but instead use Entities with the new Entity - Component - System architecture. But keep in mind that the whole feature is still in a preview state, which means it is poorly documented, poorly supported by the editor and might constantly change with every update (the link I just posted does actually have a lot of information which is already outdated, but it still gives a good introduction into what ECS actually *is*).

# Answer
> -1 votes
I think you are using `OnCollisionEnter` / `OnCollisionStay` *which are triggered for any colliders* instead of `OnTriggerEnter` / `OnTriggerStay` *which are triggered only if any collider collide with a **trigger** collider in your gameobject*.

So `OnTriggerEnter` or `OnTriggerStay` would only be triggered if any collider (trigger or not) is colliding with your Trigger collider.

With this, if anything collide with your *weapon* trigger, you should damage it.

```
OnTriggerStay(Collider other)
{
    Damage(other.GetComponentInParent<Unit>()); // Damage would remove hp from the given unit
}

```

Docs on those colliding functions `OnTriggerEnter` `OnCollisionEnter`

---
Tags: unity, collider
---


# Question
Title: When to destroy Google AdMob InterstitialAd object?
There are  few answers on this question but they don't give a satisfactory answer.

I am using a singleton AdManager class that persists throughout the game. I am not sure if I should destroy the instance of InsterstitalAd each time after displaying an ad. This answer says that an InterstitalAd object can only be used once, however in my current implementation I use the same instance multiple times without any ill effect.

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;

public class AdManager : MonoBehaviour
{
    public InterstitialAd interstitialAd;
    private string InterstitialAdId = "test-code";
    public static AdManager Instance = null;

    void Awake()
    {
        MobileAds.Initialize(initStatus => {});
        RequestInterstitialAd();
        SceneManager.sceneLoaded += OnSceneLoaded;

        // Singleton class
        if (Instance == null) {
            Instance = this;
        } else if (Instance != this) {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
        DisplayInterstitialAd();
    }

    public void RequestInterstitialAd() {
        interstitialAd = new InterstitialAd(InterstitialAdId);
        interstitialAd.OnAdClosed += HandleOnInterstitialAdClosed;
        interstitialAd.LoadAd(new AdRequest.Builder().Build());
   }

    public void HandleOnInterstitialAdClosed(object sender, EventArgs args) {
        interstitialAd.LoadAd(new AdRequest.Builder().Build());
    }

    public void DisplayInterstitialAd() {
        if (interstitialAd.IsLoaded()) {
            interstitialAd.Show();
        }
    }

    public void DestroyInterstitialAd() {
        interstitialAd.Destroy();
    }
}

```

As I understand the InterstitalAd object refers to a UI element, while the actual content of the ad comes from AdRequest, so I can reload the ad content without affecting the InterstitalAd object. **Do I need to call DestroyInterstitalAd() after each time after an ad is displayed?** I want to prevent any memory leaks from happening during long plays.

# Answer
> 1 votes
Just because you don’t *see* any ill effects doesn’t mean you’re doing everything right. Destroy your interstitial ads. Google’s example implementation does this before loading the next ad:

```
private void RequestInterstitial()
{
    //...

    // Clean up interstitial ad before creating a new one.
    if (this.interstitial != null)
    {
        this.interstitial.Destroy();
    }

    // Create an interstitial.
    this.interstitial = new InterstitialAd(adUnitId);

    //...
}

```

---
Tags: unity, c#, performance, admob
---


# Question
Title: Moving large group of units 1 by 1 takes too long, how can I improve this?
I use use Unity's own NavMesh/AI system and I think it works pretty well. The only problem I have is that when I move large groups of units, they will find a path one by one, but it takes a really long time as you can see in the video:

https://gfycat.com/blankhalfdartfrog

To set destinations I use this:

```
    public bool SetDestination(Vector3 point)
    {
        if (SamplePosition(point))
        {
            agent.SetDestination(point);
            return true;
        }

        return false;
    }

```

I know I could wait until they all have `pathPending == false`, but that would mean the entire group moves with a huge delay. Is there some way I can improve or fix this issue?

Edit: It is quite simple to recreate (if you have some basic knowledge on Unity NavMesh): simply create a "click to move"-script that moves a List of units to where you clicked using the code above (just fill the list in Start on each unit). Put down a few obstacles and you're done.

# Answer
> 3 votes
There are multiple ways you can go about it.

**Specific Approaches**

1. Faking the movement in required direction while path is calculated in the background, once path is calculated the movement along the path starts.
2. Smaller `NavMeshSurface` chunks. By splitting large area of a `NavMesh` into smaller parts - you can decrease the time required to calculate a path which would speed up processing of path queue.

\[This one is quite tough. There are multiple optimizations that could be done here. Just making multiple `NavMeshSurface`s won't cut it as units cannot move by default between different parts of `NavMesh`. But if you split `NavMesh` when moving units in a group you can determine in which area the destination falls in, get path points and do processing on them and recalculate path for each unit only in this "destination area"\].

3. Similarly to (1) (optimizations from (2) may apply) you could have second `Navigation` system that is less precise, takes less memory and/or processing to calculate initial path to start the movement. And when more precise path is calculates, you replace it.
4. This one is just a combination of all of them. To get movement, animations ... - (1). Having second, faster navigation system from (3) will help you calculate a path which then can be used to determine which chunks from (2) are responsible for calculating more precise path. Then when you know the end destination on the first chunk of `NavMesh` \[usually the one where unit is at the moment\] you calculate a precise path to that destination and start moving accurately. During that time calculate a better path.
5. If you are developing an RTS with lots of units. `FlowField` might prove useful, I suppose it uses a lot more memory than `NavMesh` but should be a lot faster.
6. If you still need more optimizations for a game with thousands of units I suggest digging into DOTS. Some useful links: DOTS Navigation, zulfajuniadi Unity Ecs Navmesh.
7. **Opinion-based:** I believe a complex combination of high speed - low precision `NavMesh` and `FlowField` split into chunks and loaded during run-time when required would be the best and would suit any game size.

**General Optimizaitons**

* When moving a group of units all at once. A group can be formed and a path can be found for a whole group, then positions for each unit could be determined by some conditions once whole group reaches the end point. Or even last path point for each unit could be modified to it's own destination.
* If in your game units can change direction frequently - it's better to use the techniques from (4) because recalculation of the path would be frequent as well. Thus when path is most likely to change, you don't lose processing time that was taken for a full previous path.

**More Resources**

I suggest using `NavMeshComponents`. More info about them here: Unite Europe 2017 - Finding the path: New navigation features.

# Answer
> 0 votes
You might try the following if you're units are all grouped together (moving as a **single group**):

1. Have an invisible/placeholder unit which acts as the navigator
2. Use this unit for pathfinding (only this unit will have a navigation component and pathfinding) and you will set the destination for only this unit
3. for the rest of the units you can simply apply a primitive "Follow" behaviour (a simple lerp position will do)

That's the general idea, of course, you also can group nearby units (for example, every "n" close units can be a "group") and each group/cluster can have a single navigator while the rest simply follow it.

For example, if you have 40 units, you can have 4 groups of 10 units each and 4 navigators (1 for each group)

---

If you insist on having a separate navigation component for each unit, then I think you'd be better off trying 3rd party navigation solutions instead.

---
Tags: unity, ai
---


title: Referencing Tilemap inside Grid Prefab

text:
# Question
Title: Referencing Tilemap inside Grid Prefab
I have a prefab of a grid which contains 3 different tilemaps:

Main, Foreground, & Background

I want to reference the tilemaps inside a script of the prefab but can't figure out how to do that... I just need to edit the tiles in the tilemaps located inside the prefab.

# Answer
I figured it out! Rather than pre-creating the tilemaps inside of the prefab, You just have to add the tilemaps after the prefab was created (in the game).

Reference: https://stackoverflow.com/questions/54044398/how-to-programmatically-add-tilemaps-to-a-grid

You can add the 3 tilemaps to the grid in the awake function and use their variables:

```
    GameObject go = new GameObject("Main");
    mainTileMap = go.AddComponent<Tilemap>();
    TilemapRenderer tileRenderer = go.AddComponent<TilemapRenderer>();

    mainTileMap.tileAnchor = new Vector3(0, 0, 0);
    go.transform.SetParent(gameObject.transform);
    tileRenderer.sortingLayerName = "Default";

```

and do this for every tilemap. The 'mainTileMap' GameObject will store the reference to the tilemap.
> 0 votes

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


# Question
Title: How do i draw sprite on fixture position?
```
b2BodyDef bd;
    bd.position.Set(1700 / sfdd::SCALE, 150 / sfdd::SCALE);
    bd.type = b2_dynamicBody;
    b2PolygonShape squareShape;
    squareShape.SetAsBox(70 / sfdd::SCALE, 13 / sfdd::SCALE);
    m_body1 = m_world->CreateBody(&bd);
    m_body1->CreateFixture(&squareShape, 100);
    squareShape.SetAsBox(38 / sfdd::SCALE, 16 / sfdd::SCALE,b2Vec2(-54/sfdd::SCALE,-30/sfdd::SCALE),90*DEGTORAD);
    m_body1->CreateFixture(&squareShape, 20);

    squareShape.SetAsBox(30 / sfdd::SCALE, 10 / sfdd::SCALE, b2Vec2(60 / sfdd::SCALE, -20 / sfdd::SCALE), 90 * DEGTORAD);
    m_body1->CreateFixture(&squareShape, 100);

```

# Answer
Typically the fixtures would approximate the shape of the sprite, they're locked to the body and won't change their transformation. So you just draw the sprite with the body's transformation (position/rotation), and don't care about individual fixtures.

If you really need to draw the fixtures, see the `b2World::DrawDebugData()` method implementation. It uses user-provided `b2Draw` object that would perform actual painting of required primitives.
> 1 votes

---
Tags: c++, box2d
---


title: How to directly change a vector3

text:
# Question
Title: How to directly change a vector3
I'm new to unity, and written code in general, but I haven't been able to change the value of a vector3.

```
public Vector3 VARIABLE = (5f, 5f, 5f)

```

# Answer
> 1 votes
Did you mean to write

```
public Vector3 variable = new Vector3(5f, 5f, 5f);

```

like this instead? The `new Vector3` constructor is necessary - the C# compiler doesn't know where to stick each `5f` inside the data structure without it. Don't worry, since this is a struct, that `new` doesn't perform extra allocation or generate garbage: the memory for this vector is already accounted-for in its parent type's footprint.

Another common error in Unity is to write something like this:

```
transform.position.x = 5f;

```

This again is because vectors are structs - value types. So `transform.position` give you a *copy* of the variable inside the transform. To change just one component of a vector inside another instance, you have to take a copy, change it, and assign it back as a whole:

```
var modifiedPosition = transform.position;
modifiedPosition.x = 5f;
transform.position = modifiedPosition;

```

Since vectors are blittable types (able to be moved around as just a raw byte-for-byte copy), this is super fast, so you shouldn't worry that those three lines are somehow going to make your code slow.

If you want to increment a vector, there are often convenience methods that let you do this a bit more easily. Say we want to *add* 5 to `x` instead of *setting* it to 5. We can do that with a one-liner:

```
transform.Translate(5f, 0f, 0f, Space.World);

```

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


# Question
Title: Formatting Unity data for communication with a REST API
I am pretty new to unity but I am not new to programming. I am building a Hololens application in Unity 2017.2 and it communicates with a REST api that I built. I am using Unity as a front end more or less and it manages my state. Coming from the web developement world, I have my server converting my models into JSON and I am sending that as a response. For the most part, it works well but since Unity works on an older version of C#, I am having issues working with the JSON data, mainly if the data type is not a string, int, float, or double. For example, if my model contains a date data type I am having issues converting it back into a c# model or even arrays are proving to be a pain. I don’t want to rely on unity packages too much as most I have tried don’t do what I need but I am open to any good ones if you know of any.

My question is, what is the best way to send data from my API to Unity? Should I send xml or a csv instead? Or even a more C# native approach? (If that makes sense)

# Answer
> 1 votes
I was able to find a solid solution at this link

I put the static method in my server

```
public static string GetXMLFromObject(object o)
{
    StringWriter sw = new StringWriter();
    XmlTextWriter tw = null;
    try
    {
        XmlSerializer serializer = new XmlSerializer(o.GetType());
        tw = new XmlTextWriter(sw);
        serializer.Serialize(tw, o);
    }
    catch (Exception ex)
    {
        //Handle Exception Code
    }
    finally
    {
        sw.Close();
        if (tw != null)
        {
            tw.Close();
        }
    }
    return sw.ToString();
}

```

And all worked well.

And then the method for sending the response called the function like in the link

```
[HttpGet]
public string GetData(){
    Employee emp = new Employee();
    emp.FirstName = "Code";
    emp.LastName = "Handbook";
    string xml = GetXMLFromObject(emp);
    return xml;
}

```

And in my Unity C# script, I parsed the response using the second static method given in the link but two changes had to be made.

```
public static Object ObjectToXML(string xml, Type objectType)
{
    StringReader strReader = null;
    XmlSerializer serializer = null;
    XmlTextReader xmlReader = null;
    Object obj = null;
    try
    {
        strReader = new StringReader(xml);
        serializer = new XmlSerializer(objectType);
        xmlReader = new XmlTextReader(strReader);
        obj = serializer.Deserialize(xmlReader);
    }
    catch (Exception exp)
    {
        //Handle Exception Code
    }
    finally
    {
        if (xmlReader != null)
        {
            xmlReader.Close();
        }
        if (strReader != null)
        {
            strReader.Close();
        }
    }
    return obj;
}

```

The changes were easy enough to implement, they were: Unity C# does not support `XmlReader` using the System namespace so I had to add a conditional statement to the `using` statement. You can read more about it in the official unity documentation here

```
#if NETFX_CORE
using XmlReader = WinRTLegacy.Xml.XmlReader;
#else
using XmlReader = System.Xml.XmlReader;
#endif

```

The second change was that `strReader.Close()` does not exist in the Unity C# scripting.

Change this:

```
if (strReader != null)
{
    strReader.Close();
}

```

To this:

```
if (strReader != null)
{
    strReader.Dispose();
}

```

I found that solution in a forum here

One last thing to note, `Object` was giving me some issues so I had to add the `System` to it. `System.Object` although Visual Studio said I did not need it, errors were thrown with out it. The final method looked like this:

```
public static System.Object ObjectToXML(string xml, Type objectType)
{
    StringReader strReader = null;
    XmlSerializer serializer = null;
    XmlTextReader xmlReader = null;
    System.Object obj = null;
    try
    {
        strReader = new StringReader(xml);
        serializer = new XmlSerializer(objectType);
        xmlReader = new XmlTextReader(strReader);
        obj = serializer.Deserialize(xmlReader);
    }
    catch (Exception exp)
    {
        //Handle Exception Code
    }
    finally
    {
        if (xmlReader != null)
        {
            xmlReader.Close();
        }
        if (strReader != null)
        {
            strReader.Dispose();
        }
    }
    return obj;
}

```

And to use it, I did this:

```
// handled response above
string xml = response.text;
Employee emp = new Employee();

try{
    System.Object obj = ObjectToXML(xml,typeof(Employee));
    emp = (Employee)obj;
}
catch (Exception ex){
    Debug.Log(ex.message);
    emp = null;
}
finally{
    if(emp != null){
        // do stuff
    }
    else{
        // handle error
    }
}

```

This was a lot easier than trying to parse JSON and I am able to throw the XML right into an object. The actual object I used was more complex than the `Employee` example and it worked just fine.

# Answer
> 0 votes
I’ve found using simplejson as an easy way to handle json responses

https://wiki.unity3d.com/index.php/SimpleJSON

For the setup, you just need to place the simplejson file in a project folder. When handling responses, you can access the data like this:

```
jsonresponse["players"][2]["items"][5].Value;

```

for string values, and:

```
jsonresponse["players"][1]["life"].AsInt;

```

for int values and so on.

It solves the problem of having to predefine the expected json response data beforehand.

---
Tags: unity, data-structure, json
---


# Question
Title: Unity Tilemaps not Rendering as I move camera
As I move the main camera in my Unity game towards the left or right, the camera just stops rendering any of the tilemaps in the scene.

Here, the camera is at x = 25.7, and the preview isn't showing anything (Neither is the game view), but as I move the camera inwards towards x = 24.7, everything renders normally...

I can clearly see the tilemap objects in the scene view though...

# Answer
I found the problem! The camera doesn't render the objects even though they exist because the camera moves far enough away from them, to not render.

The Tilemaps I create are centered at 0,0 (even the ones that generate the tiles far away). So when the camera moves a certain distance away from them, it just stops rendering the tilemaps.

To fix it, I just had to centre the tilemaps closer to the place they would be generating their tiles (chunkNo * chunkSize).

This fixed the issue!
> 2 votes

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


title: Updating texture memory via shader?

text:
# Question
Title: Updating texture memory via shader?
What the title says.Is it possible to update a texture via a glsl shader ? Something like :

```
//Read
vec4 Pixel = texture2D(TextureID,gl_TexCoord[TextureIndex].st);

//Write to texture memory ?
vec4 NewPixel = Pixel + vec4(0.0,0.0,0.0,AlphaPatch);

// ?? How to write back to texture memory ??
texture2D(TextureID,gl_TexCoord[TextureIndex].st) = NewPixel;

```

??

# Answer
What you want is to bind a texture to a shader and then render to that texture. I could spit through miles of documentation specification of OpenGL, but I'm going to give the feeling my gut gives me:

I don't think that's possible.

What I do know is possible, however, is that you create a Frame Buffer Object (FBO) and render to that. First, you must generate an FBO and attach a texture to it with the same size as the one you want to update.

```
GLuint fbo_handle, fbo_texture_handle;

GLuint texture_width = GetTextureWidth();
GLuint texture_height = GetTextureWidth();

// generate texture

glGenTextures(1, &fbo_texture_handle);
glBindTexture(GL_TEXTURE_2D, fbo_texture_handle);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texture_width, texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

// generate framebuffer

glGenFrameBuffers(1, &fbo_handle);
glBindFrameBuffer(GL_FRAMEBUFFER, fbo_handle);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo_texture_handle, 0);

GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
    LOG_ERROR("Could not validate framebuffer);
}

glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

When you want to update your texture, you must take the followings steps.

First, you attach the FBO:

```
glBindFramebuffer(GL_FRAMEBUFFER, fbo_handle);

glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, texture_width, texture_height);

```

Now you can render a fullscreen quad with a shader that outputs the updated color:

```
vec4 frag_texture = texture2D(TextureID, gl_TexCoord[TextureIndex].st);

vec4 frag_updated = frag_texture + vec4(0.0, 0.0, 0.0, AlphaPatch);

gl_FragData[0] = frag_updated;

```

And then you have to copy the resulting framebuffer to the original texture.

```
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_handle);
glBindTexture(GL_TEXTURE_2D, original_texture_handle);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, texture_width, texture_height);

glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

glPopAttrib();

```

However, you should consider the following:

* How often do you update this texture?
* If you don't have to update it every frame, is this method worth the speed penalty?
* Can you generate multiple version of this texture and cycle between them?
* Is there another way to achieve the same effect?
> 6 votes

# Answer
If your hardware supports it, the GL\_ARB\_shader\_image\_load\_store extension allows you to write to a texture.
> 5 votes

# Answer
Yes it's possible, texture/imageLoad are for reading and imageStore is for writing.
> 1 votes

---
Tags: opengl, textures, shaders, glsl
---


title: Bubble Text appears issue?

text:
# Question
Title: Bubble Text appears issue?
I'm trying to make a dialogue between characters using bubbles witth text. But the text appears not clear to player.

The Cam is far from the canvas 13.5f. What to do fix it ?

# Answer
It's a known issue with Unity built-in `Text` component. The larger the text - the less vivid it is. From experience, the issue is happening because `Text` component uses pixels (a constant texture) to draw each letter, but I am not sure.

The solution is to use officially supported `TextMeshProUGUI` component which gives much clearer results and works well with text size and distance. You can find `TextMeshPro` in `Window -> Package Manager -> TextMeshPro`.
> 1 votes

---
Tags: unity, gui, text
---


# Question
Title: C++ property is none when accessed in bp
I have a class in C++ that I want to access in BP. It appears to be fine in C++ but in BP I get Accessed None errors when I try to use it in BP. Here is the class declaration that I am trying to use in BP

```
UCLASS(BlueprintType)
class ZOMBIEHORDE_API UQualitySettings : public UObject
{
    GENERATED_BODY()

public:

    // constructors

    UQualitySettings();

    // class functions and properties
};

```

I am holding on to it in the `GameInstance` as below so I can access it through the `GameInstance` reference.

```
CLASS(Blueprintable)
class ZOMBIEHORDE_API UZombieHordeGameInstance : public UGameInstance
{
    GENERATED_BODY()

public:

    UZombieHordeGameInstance();

    UPROPERTY(BlueprintReadOnly, Category = "Zombie Game Instance")
    UQualitySettings *QualitySettings = nullptr;
};

```

And `GameInstance` .cpp

```
UZombieHordeGameInstance::UZombieHordeGameInstance()
{
    QualitySettings = NewObject<UQualitySettings>();
    ensure(QualitySettings);// this passes and does not throw an error
}

```

This shows how I am accessing it in a widget blueprint.

So how can it be that accessing `QualitySettings` in BP is `None`?

# Answer
> 1 votes
Perhaps the reflection system doesn't like the

```
UPROPERTY(BlueprintReadOnly, Category = "Zombie Game Instance")
UQualitySettings *QualitySettings = nullptr; //try to remove the = nullptr from here.

```

Generally in UE4 we set the variables in constructor because of CDO and reflection system on-behalf.

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