# Question
Title: Problems blending biomes together in relation to moisture/temperature
I am trying to achieve smooth biomes blending for my procedural 3D terrain.

I've been doing some research on this creating biomes topic and I found some good sources that talk about creating biomes by the use of generated moisture and temperature maps.

I found this table, that I use as an example.

So far I've done something like this. I've defined regions that are the horizontal row (temperature)

```
[Serializable]
public struct Region
{
    [SerializeField] string type;

    [Range(0, 1)]
    public float temperature;
    public RegionBiome[] biomes;
}
[Serializable]
public class RegionBiome
{
    [SerializeField] string type;

    [Range(0, 1)]
    public float moisture;
    public Biome biome;
}

```

And biomes that are associated with the region

```
[CreateAssetMenu]
public class Biome : ScriptableObject
{
    [SerializeField] new string name;

    public Color color;

    [Header("Noise")]
    public float scale;
    public Wave[] waves;

    public float Sample(float x, float y)
    {
        return Noise.GetPerlinNoise(x, y, scale, 0, 0, waves);
    }
}

```

I have set up the exact biomes table like in the picture.

Then to generate a heightmap I have firstly generated heat and moisture maps and looped through the entire map and sampled each coordinate to get the evaluation

```
void Generate()
{
    float[,] temperatureMap = GenerateNoiseMap(size, 50f, 0f, 0f, new Wave[2] { new Wave(seed * -2, 1, 2), new Wave(seed * 2, .5f, 1) });
    float[,] moistureMap = GenerateNoiseMap(size, 35f, 0f, 0f, new Wave[2] { new Wave(seed * -.5f, 1, 2), new Wave(seed * .5f, .5f, 1) });

    float[,] heightMap = new float[size, size];

    Color[] colorMap = new Color[size * size]; Color color;
    for (int y = 0; y < size; y++)
    {
        for (int x = 0; x < size; x++)
        {
            float heat = temperatureMap[x, y];
            float moisture = moistureMap[x, y];

            heightMap[x, y] = GetEvaluation(x, y, heat, moisture, out color);
            colorMap[x + (y * size)] = color;
        }
    }
    CreateOutput(colorMap, colorOutput, result1);
    for (int i = 0; i < colorMap.Length; i++)
    {
        float value = heightMap[i % size, i / size];
        colorMap[i] = new Color(value, value, value, 1);
    }
    CreateOutput(colorMap, noiseOutput, result2);
}

```

And this is the evaluation function

```
float GetEvaluation(float x, float y, float heat, float moisture, out Color color)
{
    int regionIndex = -1;
    for (int i = 0; i < regions.Length; i++)
    {
        if (i < regions.Length - 1)
        {
            if (heat >= regions[i].temperature && heat < regions[i + 1].temperature)
            {
                regionIndex = i;
                break;
            }
        }
        else
        {
            if (heat == 1)
            {
                regionIndex = i;
                break;
            }
            regionIndex = i - 1;
        }
    }
    int biomeIndex = -1;
    for (int i = 0; i < regions[regionIndex].biomes.Length; i++)
    {
        if (i < regions[regionIndex].biomes.Length - 1)
        {
            if (moisture >= regions[regionIndex].biomes[i].moisture && moisture < regions[regionIndex].biomes[i + 1].moisture)
            {
                biomeIndex = i;
                break;
            }
        }
        else
        {
            if (moisture == 1)
            {
                biomeIndex = i;
                break;
            }
            biomeIndex = i - 1;
        }
    }
    color = regions[regionIndex].biomes[biomeIndex].biome.color;

    float evaluation = regions[regionIndex].biomes[biomeIndex].biome.Sample(x, y);

    float currHeat = regions[regionIndex].temperature;
    float destHeat = heat == 1 ? currHeat : regions[regionIndex + 1].temperature;

    float heatBlend = 0;
    if (destHeat != currHeat)
    {
        heatBlend = Mathf.InverseLerp(currHeat, destHeat, heat);
        evaluation = Mathf.Lerp(evaluation, regions[regionIndex + 1].biomes[biomeIndex].biome.Sample(x, y), heatBlend);
    }

    float currMoisture = regions[regionIndex].biomes[biomeIndex].moisture;
    float destMoisture = moisture == 1 ? currMoisture : regions[regionIndex].biomes[biomeIndex + 1].moisture;

    float moistureBlend = 0;
    if (destMoisture != currMoisture)
    {
        moistureBlend = Mathf.InverseLerp(currMoisture, destMoisture, moisture);
        evaluation = Mathf.Lerp(evaluation, regions[regionIndex].biomes[biomeIndex + 1].biome.Sample(x, y), moistureBlend);
    }

    if (heat < 1 && moisture < 1)
    {
        float cornerBlend = Mathf.Clamp01(heatBlend + moistureBlend);
        evaluation = Mathf.Lerp(evaluation, regions[regionIndex + 1].biomes[biomeIndex + 1].biome.Sample(x, y), cornerBlend);
    }
    return evaluation;
}

```

And these are some utility functions that I used

```
private float[,] GenerateNoiseMap(int size, float scale, float offsetX, float offsetZ, Wave[] waves)
{
    return Noise.GeneratePerlinNoiseMap(size, size, scale, offsetX, offsetZ, waves);
}
void CreateOutput(Color[] colorMap, RawImage image, Texture2D tex)
{
    tex.SetPixels(colorMap); tex.Apply();
    image.texture = tex;
}

```

And the noise class for generating Perlin noise maps

```
public static class Noise
{
    public static float[,] GeneratePerlinNoiseMap(int mapDepth, int mapWidth, float scale, float offsetX, float offsetZ, Wave[] waves)
    {
        float[,] noiseMap = new float[mapDepth, mapWidth];

        for (int zIndex = 0; zIndex < mapDepth; zIndex++)
        {
            for (int xIndex = 0; xIndex < mapWidth; xIndex++)
            {
                float sampleX = (xIndex + offsetX) / scale;
                float sampleZ = (zIndex + offsetZ) / scale;

                float noise = 0f;
                float normalization = 0f;
                foreach (Wave wave in waves)
                {
                    noise += wave.amplitude * Mathf.PerlinNoise(sampleX * wave.frequency + wave.seed, sampleZ * wave.frequency + wave.seed);
                    normalization += wave.amplitude;
                }
                noise /= normalization;

                noiseMap[zIndex, xIndex] = noise;
            }
        }
        return noiseMap;
    }
    public static float GetPerlinNoise(float x, float y, float scale, float offsetX, float offsetZ, Wave[] waves)
    {
        float sampleX = (x + offsetX) / scale;
        float sampleZ = (y + offsetZ) / scale;

        float noise = 0f;
        float normalization = 0f;
        foreach (Wave wave in waves)
        {
            noise += wave.amplitude * Mathf.PerlinNoise(sampleX * wave.frequency + wave.seed, sampleZ * wave.frequency + wave.seed);
            normalization += wave.amplitude;
        }
        noise /= normalization;

        return noise;
    }
}

```

The way I get the final height doesn't seem to be working correctly as the biomes noises are not interpolated correctly. Also, the color map doesn't seem right as well...

The color map

The height map

How do I blend the biomes? I'm definitely missing something here and can't wrap my head around it... What do I and how do I weigh the final evaluation value?

# Answer
> 1 votes
Blending biomes is tricky. Especially if you want it to be fast and not show any grid structure. I wrote an article about this recently: https://noiseposti.ng/posts/2021-03-13-Fast-Biome-Blending-Without-Squareness.html The java code is linked at the bottom, is under CC0, and should be fairly easy to port to C#.

Basically the algorithm is as follows:

* Define a function `GetBiomeAt(x, z)` which queries your biome map at that particular location. It is important that it be implemented like this, and not as a pre-populated array.
* Scatter a bunch of points a la Voronoi noise. I used a triangular grid with a constant jitter length with random jitter direction.
* Pick a radius `r` big enough to always contain points. Define a falloff function based on squared Euclidean distance, which goes to zero at the radius and stays there. I use `max(0, r² - Δx² - Δz²)²`, where Δx,Δz are the relative offsets of your evaluation point to a given scattered point.
* Have some way of querying at least all points that are in range of a given generation chunk, but not too many. Sample the biome at each point.
* For each point, add its weight from the falloff function to its specific biome's accumulating weight value for that coordinate. Also add it to the total. At the end, divide each biome's weight by that total.
* For each biome and weight at a given world coordinate, do a weighted addition of each biome's noise formula.

As an accompanying note to all of this, I don't recommend using the Mathf.PerlinNoise function in Unity, or any unmitigated Perlin function. Notice how, in your images, almost every feature is aligned 45 or 90 degrees relative to the coordinate space. This is an artifact of the Perlin function, and is an unneccessary compromise. Patterns that emulate nature like this should ideally be as isotropic (directionally unbiased) as possible.

It's better to import a library that supports better noise. FastNoiseLite is the one I recommend, and I described particular usage patterns in more detail in this other answer of mine.

---
Tags: unity, c#, procedural-generation, heightmap
---


# Question
Title: What is the relationship between gimbals and Euler angles?
Through reading a lot of articles, I understand what gimbals are (at least I think so). And I know that Euler angles follow the rules of gimbals, but why?

1. Why do Euler angles comply with the rules of gimbals?
2. If that's the definition, Why don't we reduce the limitation when we define it？

# Answer
> 0 votes
The definition of Euler angles inherently includes gimbals.

Let's use Unity's convention as one arbitrary example (technically they're a related convention called Tait-Bryan angles, but nobody calls them that).

An Euler angle triplet `(pitch, yaw, roll)` means...

1. Rotate the outermost gimbal, with its axis parallel to the world y axis, by `yaw` degrees.
2. Rotate the middle gimbal, with its axis perpendicular to the outer gimbal and parallel to the world x axis when `yaw` is zero, by `pitch` degrees.
3. Rotate the inner gimbal, with its axis perpendicular to the middle gimbal and parallel to the world z axis when `yaw` and `pitch` are both zero, by `roll` degrees.

The net orientation of the object is then the orientation of this inner gimbal, stacking up the individual rotations of the middle and outer gimbals.

There are other Euler angle / Tait-Bryan angle conventions, but they all share this pattern where an arbitrary orientation is built-up from a *sequence* of rotations about particular axes. As I explain in this answer, when you compose two rotations in sequence, the angle of one changes the axis of the second \- and that makes the chained rotation behave like two linked gimbals.

To emphasize: *any* rotation scheme that tries to decompose an orientation into multiple angles is inherently modelling a set of linked gimbals. That means it will have situations where it loses a degree of freedom because two of its gimbal axes become parallel - gimbal lock - and you need a correspondingly larger change to your angle triplet to get to a nearby orientation in some direction.

To escape this, you need to leave behind the idea of chaining separate rotations with different axes/angles entirely. Instead we can use...

* **Angle-axis representations**, where we express a particular orientation as a *single* rotation around *one* axis by a particular angle. By allowing arbitrary diagonal axes, we can still reach any orientation we choose this way, without composing multiple rotations in sequence.
* **Quaternions**, which are really a special kind of angle-axis representation, dressed up in 4D space with 3 imaginary dimensions. This might seem like a strange choice, but it lets us take advantage of patterns in the multiplication of these imaginary units to compose and interpolate rotations much more easily than other methods.
* **Matrices**, which can express any arbitrary affine transformation, including rotations.

All of these methods let us express an orientation "all at once" rather than as a sequence of rotations with different angles around different axes, so they let us break out of the gimbal paradigm that comes with that sequencing.

---
Tags: rotation, geometry, euler-angles, gimbal-lock
---


# Question
Title: Issue with Texture2D memory leak in Unity
I have a simple method that converts `RenderTexture` data into `Texture2D`

```
public static Texture2D RenderTextureToTexture2D(RenderTexture renderTexture, int width, int height,
    TextureFormat textureFormat = TextureFormat.RGB24, bool mipChain = false) {

    Texture2D tex = new Texture2D(width, height, textureFormat, mipChain);
    RenderTexture.active = renderTexture;

    tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    tex.Apply();

    RenderTexture.active = null;
    // Here I want some way to release memory occupied by tex
    // I want to release tex here because i believe everytime this method executes tex is not getting garbage collected and stays in memory
    // Only problem is I cannot release it before, and after returning, it is obvious I cannot do that.
    return tex;
}

```

The above mentioned method is working exactly as intended. However, if I call this method multiple times, or in update it starts using so much memory

How can I avoid this problem?

**Edit** I cannot share the entire code but this is minimal code to reproduce the issue

```
[SerializeField] private RenderTexture renderTexture;
private Texture2D mTexture;

private void Start() {
    mTexture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.BGRA32, false);
}

private void Update() {
    mTexture = TextureUtils.RenderTextureToTexture2D(renderTexture, renderTexture.width, renderTexture.height, TextureFormat.BGRA32);

    // Some agora sdk stuff to share the mTexture over the network for screen sharing
}

```

# Answer
Assets in Unity (textures, materials, etc) are not garbage collected as readily as other types. Unity will clean up unused assets on scene loads, but to keep this cruft from piling up it's our responsibility to manage the assets we're creating, and `Destroy()` them when we're finished.

We can't just destroy the texture at the end of your `RenderTextureToTexture2D` method though, because then we'd have nothing to return to the calling code.

A better pattern is to pass the texture to populate into your method as an input, rather than always creating a `new` one every frame. This gives us the option to recycle a texture (or a pool of textures), avoiding unnecessary creation and destruction, and keeping our memory use capped.

```
public static void RenderTextureToTexture2D(RenderTexture source, Texture2D destination) {

    RenderTexture.active = source;

    destination.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);
    destination.Apply();

    RenderTexture.active = null;
}

```

Now the calling code can look something more like this:

```
[SerializeField] private RenderTexture renderTexture;
private Texture2D mTexture;

private void OnEnable {
    if (mTexture == null) {
        mTexture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.BGRA32, false);
    }
}

private void Update() {
    TextureUtils.RenderTextureToTexture2D(renderTexture, mTexture);

    // Some agora sdk stuff to share the mTexture over the network for screen sharing
}

// Clean up after ourselves when no longer needed.
private void OnDestroy() {
    if (mTexture != null) {
        Destroy(mTexture);
        mTexture = null;
    }
}

```

See how we create the texture only once, and recycle it each frame, instead of creating a new one repeatedly. And when we're done with it, we `Destroy()` it so we don't leak memory until the next scene load.

If your "Agora SDK" stuff needs to work with the texture asynchronously, or might run for several frames, then instead of a single texture you'll likely want to set aside a buffer or pool of textures. That way each frame you can write to a different one than the one the Agora SDK might still be reading, ensuring you don't get any contentions, locks, or weird race conditions and bugs between them.
> 5 votes

---
Tags: unity, textures, memory-efficiency, rendertexture
---


# Question
Title: Why don't beat 'em ups allow player character sprites to face toward or away from the screen?
Most beat 'em up games don't allow player character sprites to face away or towards the screen. For example, in Streets of Rage, when you press up, the character moves up, but it is still facing either left or right, and the same is true when you press down.

Even in modern beat 'em ups, this is the case. What is the reason for this? I used to think this is because the graphics are 2D, so it's harder or more work to get characters to face towards or away from the screen. But even in beat 'em ups that use 3D graphics, this is still the case, like Double Dragon Neon.

# Answer
> 34 votes
When you have a side-scrolling beat-em-up game like *Streets of Rage*, then fighting enemies vertically instead of horizontally would have a number of drawbacks:

* While it is easy for the player to see the range of attacks when they are performed horizontally (assuming hitboxes and hurtboxes match the animation), the attack ranges of vertical attacks are a lot harder to judge due to lack of depth perception.
* Either the player-character overlaps the enemy or the enemy overlaps the player-character. This hides information. Either the player can't properly see the tells of the enemy, or they can not properly see what their character is doing. The whole game gets a lot more chaotic, and the game screen gets harder to read for the player.
* It just doesn't look as good. It is far easier to animate a good looking attack animation from the side than one from the front or back. Even walk cycles usually look a lot better from the side than from the front or back.

For those reasons, many side-scrolling beat-em-ups just disable vertical attacking, which forces players and AI enemies to engage each other from the side.

Most of those problems can be solved by moving the camera angle to be from further up (like in *Zelda*) or even straight from the top (like in *Hotline Miami*). But while such a perspective has advantages for the gameplay, it has disadvantages for the aesthetics. The further up you move your camera, the less character detail is visible. In the overhead view, you reduce the character to their hair and shoulders, which does not have a lot of appeal. Also, while moving the camera up improves the viability of walking and attacking in 4 directions, you lose an equal amount of viability for gameplay centered around jumping, falling or climbing.

# Answer
> 7 votes
This is mostly to keep the gameplay simplified. There is simply too little added value for the complexity it adds to the player experience.

The challenges in these games are of course also calibrated to not confront you with this disability.

In addition, more modern games may also consciously do it to evoke nostalgia by directly copying how the game used to work in the arcade.

# Answer
> 4 votes
While others have given excellent answers regarding visual clarity, art resources, and gameplay complexity, I'll add that a major reason is that I haven't seen explicitly stated, though it has perhaps been assumed, is that the Beat 'em Up genre includes side-scrolling as part of its definition.

Doing a Beat 'em Up in 3D has another name. Either they're a "Spectacle Fighter" or a "Hack and Slash" game or possibly the extremely non-specific "Action" label gets involved.

But really, what are the essential parts of being a Beat 'em Up? While I'm not aware of a formal definition, I'd suggest that if the side-scrolling gameplay isn't part of the definition we typically have the following attributes:

* The game is primarily based on fighting enemies in real time by controlling a single character.
* The presence of enemies typically prevents the player from moving forward. Classically the screen mysteriously stops scrolling, but there could be locking doors or some other mechanism.
* Usually multiple enemies will appear at a time.
* Sometimes defeating a wave of enemies will cause even more to appear before the player can leave.
* Progression is mostly linear.
* The player most likely has at least a few different attacks, probably including a ground combo that's performed by repeatedly hitting the same attack button, and a jumping attack.

Of course, genre definitions are a difficult thing and even classic Beat 'em Ups aren't perfectly rigid on these. To take examples from Battletoads: Turbo Tunnel, Clinger Wingers, and that part where you jump on snakes all are very different from typical Beat 'em Up gameplay.

Keeping all this in mind, you could see Devil May Cry, Bayonetta, Darksiders, and God of War games as Beat 'em Ups on at least some level. There are lots of examples of "Beat 'em Up-ish" games that don't include retro Beat 'em Up conventions, but then they don't look like retro Beat 'em Ups.

# Answer
> -1 votes
1. "Punch-Out!" is a 2D fighting game with a front on view. Its controls are radically different which means that controls for integrating both becomes a lot more complicated for a different 2D control scheme.
2. "Absolver" is a true 3D fighting game with combos. It struggles with dealing with more than one opponent as the additional axis means that single target moves can miss for reasons other than range requiring either placing the target front on for having an unusual technique that requires aiming.
3. If we switch to top down instead you have built a shoot'em up not a fighting game.

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


# Question
Title: How to either draw a group of tiles completely behind or completely in front of a player?
Say you're rendering a 2D top-down tile map and there are some objects in the tile map that the player should be "in front" of when below them, and "behind" when on top of them. Like in this example screenshot:

This works because the player is on layer 1, the top two tiles are on layer 2, and the bottom tile is on layer 0.

Let's say in this example that the object has no collision. If the character then walks up, then the character will be half-in-front and half-behind, like this:

The reason why this is a problem is because with tiles, they don't really have a concept of state. If the 3 tiles were part of the same "object", then this wouldn't be a problem, because we could just render the entire group of 3 tiles as a single sprite, and then sorting could be done, and the entire sprite could be rendered behind or in front of the player.

However, with tiles, this knowledge isn't known, as they are purely decorative numbers.

One possible solution is just to instead forsake tiles for these sorts of objects, and force them to be entities in the game itself as opposed to just tiles, but because there can be many of these, that would be a performance hit. It also complicates the logic.

Is there any better solution?

# Answer
This problem is usually worked out by collisions. Hopefully your tile editor allows you to set groups of tiles together along with their collisions, so you don't forget to set them. And that's it.

However, there might be parts of a game where you need to support something like this, and there is a way to do it that is not making everything entities…

As you know, if you use multiple layers of tiles, you can have some be drawn before the entity, some after.

Now, a few new ideas:

* An "object" must exist entirely on a layer.
* There must be layers exclusive to entities.
* The layer on which an entity is, can change.

If each "object" exist entirely on a layer, and entities are never on that layer, then entities are either drawn "behind" or "in front" the "object".

How do you decide the layer of an entity? You annotate layer constraint on a map (e.g. "entity layer must be greater than x"). You can think of it as the "ground layer" for a given position. And use that to constraint the layer of an entity based on where it is. That is, when the entity moves, you check the constraints at its position, and move the entity to a layer that satisfy them.

For the example depicted in the question, you would have layer 0 be the ground, layer 2 be the object. And, depending on where the entity is, it can be on layer 1 or layer 3.

Now a couple things:

* The idea of annotating constraints, and not simply what is the layer for entities, is to allow for flying entities to go above. If an entity is not a flying entity, it would just pick the lower layer that satisfy the constraint.
* You don't have to annotate this constraint on all tiles, only on those that need to make the entity change. *In fact, you may not need a custom system for these constraints, as many systems allow you to set triggers on tiles.*

Consider for example, a bridge. Entities can walk either above or below it. Depending on the direction from where they approach it. For that case, you can have constraints that set the layer of the entities appropriately on the sides of the bridge. You can even have triggers on the edge of the bridge that change the layer and play a "jump down" animation, only for entities that were top side, of course. *And yes, if you are using a system where you need to set triggers per tile, that can be a lot, thus probably not a feature of every map.*
> 1 votes

---
Tags: 2d, rendering, tiles, tiled, draw-order
---


title: Unity Mouse position for weapon wheel

text:
# Question
Title: Unity Mouse position for weapon wheel
Say i have the following wheel:

Now i wish to use the mouse to select weapon by movement:

So

If mouse is to the left it picks the Sword if mouse is at the top it selects the bow and arrow if the mouse is in the bottom then it selects the hand

Since my game is not visually showing the mouse it has to be at any position. i

However, I am not quite sure how to do this? So I am hoping some of you might be able to help. I have looked at getting the mouse position as a vector 2 but I am unsure on how to get the correct position.

# Answer
You can do this mathematically:

```
Vector2 menuPosition = radialMenu.transform.position;  // Assumes the center of your menu
Vector2 mousePosition = Input.mousePosition;
float mouseAngle = Mathf.Atan2(mousePosition.y - menuPosition.y, Input.mousePosition.x - menuPosition.x) * Mathf.Rad2Deg;

```

This should get you the angle (in degrees) of the mouse position from the horizontal. Thus, you would know that any value between 0 and 120 would correspond to one icon, any value between 120 and 240 would be the next, and so on. In your case, you will need to add an offset to the calculation to make sure the start value lines up with the edge of your first icon.
> 1 votes

# Answer
Here's my example: attach this script to the arrow button, fist button etc.

```
public class example : monobehavior {

    void OnMouseOver()
    {
       //select weapon
    }
}

```

For your problem of the mouse not being displayed, you could add a sprite to your canvas that is basically the boundary of the select area, and add the script to that. Then you could disable the sprite renderer so it doesn't show up in the game.

If you only wanted the weapon selected if the player had the mouse over it and released the key that brought the menu up, you could put your code in update (you may need to do this already) and add an if statement:

```
if(Input.GetKeyUp(your key choice))

```

to the OnMouseOver() function
> 0 votes

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


# Question
Title: In-Game Clock Issue converting total seconds to in-game time
I have been trying to create in-game time/calendar system.

In my current project I want to be able to register events at specific times on specific days/seasons.

An in-game day is 30 minutes, each month is 30 days long, there are the usual 4 seasons.

So far I have decided a singleton class called TimeManager will handle the in-game time/date and this is where things can register an event at a specific time.

```
public class TimeManager : MonoBehaviour
{
    public float timeMultiplier = 1f;
    //One in-game day is 30 minutes.
    public float MINUTES_IN_INGAME_DAY = 30f;
    //there are 1800 seconds in 30 minutes
    public float INGAME_DAY_IN_SECONDS = 1800f;
    //there 60 seconds to a minute
    public static float SECONDS_IN_MINUTES = 60f;

    public static int DAYS_IN_MONTH = 30;
    public static TimeManager Instance;

    private int _CurrentDay = 0;
    private int _CurrentYear = 0;
    private int _CurrentMonth = 0;
    private int _CurrentSeason = 0;

    private float CurrentBaseTime = 0;

    public Days CurrentDay = Days.MONDAY;
    public Seasons CurrentSeason = Seasons.SPRING;
    public Months CurrentMonth = Months.JANUARY;

    private void Awake()
    {
        Instance = this;
    }

    private void Update()
    {
        UpdateTime();
    }

    private void OnValidate()
    {
        INGAME_DAY_IN_SECONDS = MINUTES_IN_INGAME_DAY * SECONDS_IN_MINUTES;
    }

    private void UpdateTime()
    {
        CurrentBaseTime += Time.deltaTime * timeMultiplier;

        if (CurrentBaseTime >= INGAME_DAY_IN_SECONDS)
        {
            //new month
            if(_CurrentDay > DAYS_IN_MONTH)
            {
                _CurrentDay = 0;
                _CurrentMonth++;

                //new year, reset season
                if (_CurrentMonth > 12)
                {
                    _CurrentYear++;
                    _CurrentMonth = 0;
                    CurrentSeason = Seasons.SPRING;
                }

                //new season
                if (_CurrentMonth % 4 == 0)
                {
                    _CurrentSeason++;
                    CurrentSeason = (Seasons)(_CurrentSeason % 4);
                }

                CurrentMonth = (Months)_CurrentMonth;
            }
            else
            {
                //same month
                _CurrentDay++;
            }

            CurrentDay = (Days)(_CurrentDay % 7);
            //reset time to "midnight"
            CurrentBaseTime = 0;
        }
    }

    public int GetCurrentDay()
    {
        return _CurrentDay;
    }

    public float GetTimeInMinutes(float elapsedTime)
    {
        return (elapsedTime / SECONDS_IN_MINUTES);
    }

    public float GetTimeInHours(float elapsedTime)
    {
        return (elapsedTime / SECONDS_IN_MINUTES / MINUTES_IN_INGAME_DAY) * 24f;
    }

    private void OnGUI()
    {
        GUI.color = Color.black;
        GUI.Label(new Rect(10f, 0f, 400f, 20f), new GUIContent("World Time Info"));
        GUI.Label(new Rect(10f, 20f, 400f, 20f), new GUIContent("Current Time In Seconds : " + CurrentBaseTime));
        GUI.Label(new Rect(10f, 40f, 400f, 20f), new GUIContent("Current Day : " + GetCurrentDay()));
        GUI.Label(new Rect(10f, 60f, 400f, 20f), string.Format("H: {0} M : {1} S : {2}" , Mathf.Round(GetTimeInHours(CurrentBaseTime)), Mathf.Round(GetTimeInMinutes(CurrentBaseTime)), CurrentBaseTime - GetTimeInHours(CurrentBaseTime)));
    }
}

```

The problem I am having is taking the total seconds of the day and properly converting it to a 24 hour format, **currently for every 2 times the minutes increments the hour value will go up by one**. (gif included watch the minutes and hours)

I am entirely unsure where how to proceed with this, It's reached a point where I am bashing random things in and watching the outcome to see if it matches what I expect, I would like help converting in-game day in seconds to hours/minutes/seconds, in 24 hour format if possible.

I have read up on an alternative but atleast the one I read involved using the DateTime class, which I don't think would help me in my case, as the day and month length are none standard.

Thank you for reading.

# Answer
First I'm going to answer your actual question:

You have configured your day to last 30 minutes. That means 1 hour is `30 / 24 = 1.25 minutes`. That is why the hours appear to increase roughly every 2 minutes.

---

Additionally, your GUI code uses `Mathf.Round()`, when you should be using `Mathf.Floor()`.

For example, let's imagine we're using real time (60 minutes/hour and 24 hours/day) and looking at 12:54:00am (54 minutes, 0 seconds into the day). In 24-hour time, the time should be displayed `00:54`. However, if you use `Mathf.Round()`, the time will be displayed incorrectly.

The current hour is `54 / 60 = .9 hours`. The current minutes is 54. When you round these values, the time is incorrectly displayed as `01:54` because `.9 hours` is rounded to `1 hour`.

---

Additionally, you do not account for minutes correctly when displaying the time. Using a 60-minute hour/24-hour day again, let's say we're looking at 1:29:00am (`01:29` in 24 hour time). This is 89 minutes into the day, or 1 hour and 29 minutes into the day.

Your `GetTimeInMinutes()` function returns the total number of minutes that have elapsed during the day, in this case 89 minutes. Your current GUI code does not subtract the minutes that are part of hours, and thus would render the time like this:

```
01:89:00

```

---

Lastly, it seems like your code is motivated by the idea of having 30 minutes of real-time translate to one day of in-game time. Your solution (which makes in-game seconds and minutes match real-time, but in-game hours last 1.25 minutes) is going to give you major headaches and make you completely miserable.

You should use a time ratio instead. If one in-game day lasts 30 minutes of real time, your in-game clock should move at 48x a real-time clock. You can then use C#'s built-in classes for time.

```
public class TimeManager {
    const float TIME_RATIO = 48;
    private DateTime startDate;
    private float startUnityTime;

    public TimeManager(DateTime startDate) {
        this.startDate = startDate;
        startUnityTime= Time.time;
    }

    public TimeSpan TimeElapsed {
        get {
            float secondsElapsed = Time.time - startUnityTime;
            double scaledSecondsElapsed = secondsElapsed * TIME_RATIO;
            TimeSpan elapsed = TimeSpan.FromSeconds(scaledSecondsElapsed);
            return elapsed;
        }
    }

    public DateTime InGameTime => startDate + TimeElapsed;
}

```

Video games often make the time ratio a multiple of 60. For example, if your ratio is 60:1, that means in-game time passes 60x faster than real time, so 1 real-time second is 1 in-game minute and 1 real-time minute is 1 in-game hour.
> 2 votes

# Answer
Ah, the joys of date and time handling. There is a reason why everyone recommends to leave this to a library.

However, your ingame calendar is a lot simpler than the Gregorian calendar. A minute is always 60 seconds (I assume), a day is always 30 minutes, month is always 30 days, and a year has exactly 12 month, without any funny leap-day shenanigans. This regularity means that there is actually no need to track hours, days, months and years separately, because it is trivial to calculate all of these by just from the seconds since game start.

```
minutes_since_game_start = (int)CurrentBaseTime / 60;
days_since_game_start = (int)CurrentBaseTime / (60 * 30);
month_since_game_start = (int)CurrentBaseTime / (60 * 30 * 30);
years_since_game_start = (int)CurrentBaseTime / (60 * 30 * 30 * 12);

Day_in_current_month = (days_since_game_start % 30) + 1;
Month_in_current_year = (month_since_game_start % 12) + 1;
Season_in_current_year = (month_since_game_start % 12) / 3;

```

Note that the *`_since_game_start` variables will all start at 0. I only made those values start at 1 which you likely want to show in the UI.
> 0 votes

# Answer
Why not take the same approach as linux... Just count the total number of seconds since some fixed point (say the start of the game) and then format for display purposes...

```
    clock_time += Time.deltaTime; // Let's say 654064 seconds for the sake of the example
    var t = TimeSpan.FromSeconds(clock_time);
    Debug.LogFormat(String.Format("Elapsed Time: {0}", t.ToString()));
    // Outputs: "Elapsed Time: 7.13:41:04" when clock_time is 654064

```

You can also pull out the specific properties if you want...

`t.Days`, `t.Minutes`, `t.Seconds`, etc, etc
> -1 votes

---
Tags: unity
---


# Question
Title: Playstation 4 OpenGL ES support (or Xbox)
I know that the Playstation 3 supported at least OpenGL ES 1.0, and the Vita OpenGL ES 2.0. But what about the Playstation 4 (and/or the new PS4 Pro)? Does anyone know for certain if it has native support for OpenGL ES (that is, without using a compatibility/translation layer like ANGLE)?

Because it isn't backwards compatible with regular OpenGL, it'd be helpful to know if this platform supports any version of the OpenGL ES API.

I'm also curious about the Xbox One/Scorpio, although I'd be surprised if they had nativesupport for OpenGL at all.

# Answer
> 3 votes
The PlayStation 4 uses proprietary graphics APIs (GNM, a low-level API, and GMNX, a higher-level one). It does not support OpenGL in any capacity, not even the limited "PSGL" API used in the PlayStation 3, as far as I am aware.

The Xbox doesn't support OpenGL either.

# Answer
> 1 votes
Update:

Xbox support OpenGL ES via ANGLE transition layer which compile as UWP SDK, not Xbox XDK

PS4 support OpenGL ES as native API

---
Tags: opengl, opengl-es, graphics-programming, cross-platform, playstation4
---


# Question
Title: Unity update sizeDelta in OnValidate based on Layout Group computed values
I'm trying to update the sizeDelta of a RectTransform in OnValidate. I'm trying to grab the computed values from a Layout Group.

Here's what I've got:

```
#if UNITY_EDITOR
        void OnValidate()
        {
            UnityEditor.EditorApplication.delayCall += Resize;
        }

        private void Resize()
        {
            if (this == null) return;
            RectTransform parentRect = (RectTransform)gameObject.transform;
            RectTransform textRect = (RectTransform)tabText.transform;
            textRect.sizeDelta = new Vector2(parentRect.rect.height, parentRect.rect.width);
            layoutElement.preferredHeight = parentRect.rect.height;
        }
#endif

```

At first this seemed to be working, but it only works the first time OnValidate runs. Subsequence invocations of Resize() sets the sizeDelta to Vector2(0, 0).

I'm wondering what causes this and if there's a way to avoid it. If I remove the delayCall, the values are correct, but I get warnings:

> SendMessage cannot be called during Awake, CheckConsistency, or OnValidate

I'd like to do this at edit time since there's no need to compute this stuff at runtime.

# Answer
> 0 votes
I think you can try something like this, I think it may help but you need to check, if I'm right your delegate contain duplicated methods:

```
#if UNITY_EDITOR
        void OnValidate()
        {
            UnityEditor.EditorApplication.delayCall += Resize;
        }
        private void Resize()
        {
            if (this == null){
            UnityEditor.EditorApplication.delayCall -= Resize;
            return;
            }
            RectTransform parentRect = (RectTransform)gameObject.transform;
            RectTransform textRect = (RectTransform)tabText.transform;
            textRect.sizeDelta = new Vector2(parentRect.rect.height,
            parentRect.rect.width);
            layoutElement.preferredHeight = parentRect.rect.height;
            UnityEditor.EditorApplication.delayCall -= Resize;
        }
#endif

```

the other solution - you can just use direct method without delegate :

```
#if UNITY_EDITOR
        void OnValidate()
        {
             Resize();
        }
        private void Resize()
        {
            if ((this == null)||tabText.transform == null)
            return;
            RectTransform parentRect = (RectTransform)gameObject.transform;
            RectTransform textRect = (RectTransform)tabText.transform;
            textRect.sizeDelta = new Vector2(parentRect.rect.height,
            parentRect.rect.width);
            layoutElement.preferredHeight = parentRect.rect.height;
        }
#endif

```

---
Tags: unity, unity-ui
---


# Question
Title: Unity : control time interval when using getAxis() in bolt visual scripting
i use bolt visual scripting. I add ‘input.getAxis’ in Bolt and set the axis name to ‘Vertical’ so to get response when i press ‘w’ and ‘s’. When running the game and press the ‘w’ key, the output data (acceleration) will increase from 0 to 1. The problem is the increasing time is too fast or too short. How to make it slower/longer? Let say i want it to take 3 seconds to reach 1.

**Edit :**

This is what i want to achieve (at time 6:10 to 6:25) : https://youtu.be/m8rGyoStfgQ?t=370 And the code is at the same video at time 6:00 . That codes works perfectly fine. And this is all i want to achieve but i want to do it in Bolt (visual scripting) rather than manual scripting.

So that line of code at 6:00 on that video : `Velocity = time.Deltatime * acceleration`

That code is controlling how fast or slow the acceleration can go from 0 to 1 when pressing ‘w’ key. But in Bolt, i use ‘getAxis’ and by using default sensitivity setting, if i press “w” it will take less than half a second for the acceleration to go from 0 to 1. I want to make it slower so i can go from 0 to 1 in 3 seconds or 5 seconds.

In fact , this the same as setting up the sensitivity in input manager to low value, but i want to keep this setting as default and want to control it inside bolt.

Pls check my video here : getAxis

# Answer
> 1 votes
You could use Input.GetAxisRaw instead of Input.GetAxis to get the unfiltered values. So with binary inputs like keyboard keys, you are always going to get -1, 0 or +1. You can then add your own smoothing logic on top of that for a maximum of control. Like in this example, where the input gets multiplied by deltaTime and the factor 0.1 and then added to a variable of an animation controller, which also gets clamped to between -1 and +1:  By the way, the same thing in C# would be this:

```
void Update()
{
    var animator = GetComponent<Animator>();
    var velocity = animator.GetFloat("velocity");
    velocity += Input.GetAxisRaw("Horizontal") * Time.deltaTime * 0.1f;
    velocity = Mathf.Clamp(velocity, -1f, 1f);
    animator.SetFloat("velocity", velocity);
}

```

Or you could go to Edit -\> Project Settings -\> Input Manager and configure the smoothing of your axis. "Sensitivity" determines the speed with which the axis value goes from 0 to 1 when the player presses the key and "Gravity" the speed with which the axis goes back from 1 to 0 when the player releases the key. The Enabling the checkbox "Snap" means the axis will immediately go from 1 to 0 when the player presses the key for the opposite direction.

But considering that you are talking about a build-up time of 3 whole seconds, it seems like what you actually want is physically correct acceleration on the player game-object. In that case you might want to consider using rigidbody physics instead. Instead of pluging the inputs directly into the transform, make them apply a constant force to the rigidbody of the player game-object.

---
Tags: unity, bolt-visual-scripting
---


# Question
Title: Character controller falling with positive speed
I'm having very weird problems with my player's vertical movement. I'm using a Character Controller component with a capsule collider and no rigidbody. For testing purposes, I've ended reducing my jump script to just this line:

```
    owner.CharacterController.Move(new Vector3(0, 0.01f, 0));

```

When executing this script, the player should just fly upwards at a constant speed, right? Well, what ends up happening is that the player starts jumping in place repeatedly. The jumps are smooth, as if the movement was being affected by gravity. I thought that the standard Character Controller doesn't handle gravity automatically and you have to do it yourself, so I can't understand what's going on here. There is no other code affecting the player, if I comment that line it just rests in place. If I try a different direction (like (0.01f, 0, 0)) the player moves in a straight line in the provided direction as expected. But when moving vertically, weird stuff happens :S

# Answer
The problem was that the animator controller had checked the "Apply root motion" option. After unchecking it everything went back to normal. It seems my idle animation was not correctly defined.
> 2 votes

---
Tags: unity, movement, character-controller
---


title: Parameter 'Walk' doesn't exist?

text:
# Question
Title: Parameter 'Walk' doesn't exist?
I'm trying to make walk animation. But when I try to change animation idle to walk, ıt doesn't work. It says 'Parameter "Walk" doesn't exist'but I added parameter and script works. I can manually change parameter and it works(walk animation is playing). But when I try to change via script, ıt doesn't work.

Here are codes

```
public class Controller : MonoBehaviour

private Rigidbody rb;

private float xPos;

Vector3 playerMovement;

[SerializeField] Animator anim;

private void Awake() => rb = GetComponent<Rigidbody>();

private void Start()
{
    xPos = transform.position.x;
}

// Update is called once per frame
void Update()
{
    Move();
}

private void Move()
{
    float mH = Input.GetAxis("Horizontal");
    playerMovement = new Vector3(0, 0, mH);
    rb.AddForce(playerMovement * 2f);
    anim.SetFloat("Walk", 1);
    transform.position = new Vector3(xPos, transform.position.y, transform.position.z);
}

```

# Answer
> 0 votes
I think you need to check if anim field that attached have the same animator controller you show on the screenshot. It should work the name is the same. And also you can have this warning if Controller script attached to the model that does not contain "Walk" variable in animator.

# Answer
> 0 votes
I removed animation clip and then readd. It solved.

---
Tags: unity, animation
---


# Question
Title: How does Unity know where the character is facing?
I just learned `Quaternion.LookRotation` and it's used for rotating an object.

I used it to face my character in the direction where it's moving, but I couldn't understand: how does Unity know which side of my character is the face?

I mean I don't specify front of my character but Unity knows.

# Answer
It doesn't know.

What it does is point the local z axis of the object (that's the blue arrow you see in the scene view when selecting its local transform gizmo) in the `forward` direction you pass to `LookRotation`, and the local y axis (green arrow) as close as possible to the `upwards` direction you pass, or world up if you didn't provide a second argument.

By convention in Unity, we call this blue arrow z direction "forward", and assets built for Unity will typically be set up so that they face along the z+ axis.

So this will "just work" as expected for any asset that's been set up to follow this convention. Not because Unity knows anything about the model, but because the model artist knows something about Unity.

There's an obvious exception to this though: in 2D, the blue "forward" axis points into the screen, and your character sprites might face right (red) or up (green) instead. For those, we either need to use `LookRotation` a bit differently, or make our own convenience function to point our chosen axis in the direction we want.
> 4 votes

---
Tags: unity, c#, rotation, transformation, quaternion
---


# Question
Title: Find the largest empty space inside a cube populated with a point cloud?
Lets say we have a set of points `(x, y, z)` where we know `0 < x < 1` (same for `y` and `z`). Now that 3d space is populated with monsters, players or what not. The points represent their location. We want to find the largest vacant 3d space. What would be an effective algorithm to find, let's say, the k largest disjoint empty boxes inside that space?

I was thinking of using Voronoi Diagram and measuring the space near each seed (the points being the seeds) and looking for pairs of neighbors that have a large space.

# Answer
> 1 votes
EDIT:

My first approach is still below, but I found a problem with it. If the large empty region is on a border (outside the convex hull of your points), it won't be detected. Putting points on the border like I did with the corners doesn't help because the triangles can be made bouncing from your points to those new points.

Another approach, which ought to work but might be too expensive to compute, is to generate a mesh of evenly spaced points across the space and use a nearest neighbors algorithm on each of the points in this mesh to find the point from your original points that's closest. The mesh point that is most distant from anything is the center of the biggest empty region.

I don't know how to find the second most empty region.

OLD ANSWER:

I think you're on the right track. I'm trying to do a similar thing for a scientific application in Python (where my problem is N-dimensional).

Take your set of points and add the corners of the space to the set of points.

Then you can do a Delaunay triangulation (this the dual of Voronoi diagram) in 3 dimensions. (The library call in Python is `scipy.spatial.Delaunay`.)

Go through all the triangles (in 3 dimensions, these are tetrahedrons) and calculate their volume. (The library call in Python is `scipy.spatial.ConvexHull.volume`.) I think these are your biggest empty spaces, or if they're not, it's at least an indicator of a big empty space.

---
Tags: 3d, mathematics
---


# Question
Title: How can I add a delay for each moving object?
The waypoints script :

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

public class Waypoints : MonoBehaviour
{
    public Transform objectToMovePrefab;
    public int numberOfObjectsToMove = 1;
    //with this approach, you use GameObjects to represent your waypoints
    //(they can be empty if you want the waypoint to be invisible)
    [SerializeField] private List<Transform> waypoints;

    private void Start()
    {
        for (int i = 0; i < numberOfObjectsToMove; i++)
        {
            var parent = GameObject.Find("Moving Object Parent");
            var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
            objectToMove.name = "Platfrom";
        }
    }

    public int Count => waypoints.Count;
    public Vector3 GetWaypoint(int index)
    {
        return waypoints[index].position;
    }
}

```

Then in the editor I added this script to the prefab :

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

public class WaypointsFollower : MonoBehaviour
{
    [SerializeField] private Waypoints waypoints;
    [SerializeField] private float speed = 5f;
    [SerializeField] private bool goBack = false;
    [SerializeField] private float delay;

    private float startTime;
    private int waypointIndex = 0;

    private void Start()
    {
        startTime = Time.time + delay;

        waypoints = GameObject.Find("Waypoints").GetComponent<Waypoints>();
    }

    void Update()
    {
        if (Time.time < startTime) return;

        Vector3 waypoint = waypoints.GetWaypoint(waypointIndex);
        //movement
        float distance = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, waypoint, distance);

        //check if we've reached the waypoint
        float threshold = .1f; //how close is considered having reached the waypoint
        if (Vector3.Distance(transform.position, waypoint) < threshold)
        {
            //wraps back to 0 when we reach last waypoint
            if (goBack)
            {
                waypointIndex = (waypointIndex + 1) % waypoints.Count;
            }
            else
            {
                if (waypointIndex != waypoints.Count - 1)
                    waypointIndex = waypointIndex + 1;
            }
        }
    }
}

```

The delay is working but it's delaying all the WaypointsFollower's so they move at the same time after the delay.

I want that even if all the Followers have the same delay value for example 3 so the first one will start moving after 3 seconds then the next follower will start moving after another 3 seconds and so on and not that they all delay for 3 seconds and move together but to make delay so there will be spaces between the followers when they are moving.

# Answer
> 2 votes
**First:** are you sure that you set different value of variable ***delay*** for each object/ minion?? Because problem is here: Time.time is a number of seconds that has passed from **starting the game**. So it will be the same for all objects! So if all minions has variable **delay** set to **3**, and *Time.time* is equal thought the game - means after **3** seconds Time.time+3 will be exactly equal to each object/minion!

**In short, your problem** is that you are counting time from beginning of the game, which is equal to all objects.

**Second:** When I want to delay something I almost always use Coroutines. You can specify the time for delay, and since they are asynchronous, so each object can have its own timer running - independent of each other. Also you can start Coroutines and stop them.

Over the time I found that often even more convenient (less code) is InvokeReapeating or just Invoke \- you specify time when to fire a function, and that's it. And again each object can have its own timer. You can also CancelInvoke to stop it from firing.

*Update() timers gets **messy***, especially if a lot is happening inside Update() function.

P.S. I do not normally use Update(). In most cases of delays, waypoints, cooldowns, respawns, etc.- *Coroutines* or *InvokeRepeating* or *Invoke* do the job brilliantly, without affecting the rest of the code.

**Here would be example** of code sending different minion every three seconds: In your main or manager script you write:

```
public List<GameObject> minions = new List<GameObject>();

 void Start()
  {
        InvokeRepeating("SendOneMinion", 3, 3);
  }

int i=0;
public void SendOneMinion()
 {
  if (i< minions.Count && minions[i]!=null)
    minions[i].GetComponent<WaypointsFollower>().GoRightNow();
  else
    CancelInvoke();
   i++;
}

```

Is not that elegant? All you need to do is to add minions to the list. And oh create function GoRightNow() in each minion script..

**Another example with coroutine** even more elegant:

```
public List<GameObject> minions = new List<GameObject>();

void Start()
{
    StartCoroutine(SendOneMinion());
}

private IEnumerator SendOneMinion()
{

    foreach (GameObject mn in minions)
    {
        yield return new WaitForSeconds(3);
        mn.GetComponent<WaypointsFollower>().GoRightNow();
    }
}

```

here coroutine is running, and inside a loop there is 3 second delay before sending new minion..

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


# Question
Title: How do I click on specific text in an array of text?
I am trying to click on a specific word in an array but I can't think of how.

This is what I have:

```
  for x in range(0, len(names)):
    templine = font.render(names[x], True, WHITE)
    tempRect = templine.get_rect()
    tempRect.midleft = (50, (170+30*x))
    if mouse012[0] == True and tempRect.collidepoint(mouseXY):
      state = AppState.STATS

      detailsName = names[x]
    screen.blit(templine, tempRect)

```

# Answer
I don't know what is your problem. Code seems OK. maybe you draw it in wrong moment - before drawing/cleaning background - and it was removed and you couldn't see selection.

---

It is minimal working code.

First I use list of names to create list with all images and rectangles - because it never change.

And later I use event `MOUSEBUTTONDOWN` to check if it was clicked in one of rectangles and I assign it to variable `selected`

And after clearing background I use `selected` to draw selection, and then I draw all text.

Using `MOUSEBUTTONDOWN` and `selected` I can also unselect text. Using `mouse.get_pressed()` it makes big problem because selection is fliping.

I could also use `MOUSEBUTTONUP` to remove selection when I release button.

---

```
import pygame

# --- constants --- (PEP8: UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)

# --- classes --- (PEP8: CamelCaseNames)

# ... empty ...

# --- functions --- (PEP8: lower_case_names)

# ... empty ...

# --- main ---

names = ['Aaaaa', 'Bbbbb', 'Ccccc', 'Ddddd']

pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

# - create all objects -

font = pygame.font.SysFont(None, 40)

items = []

for x, name in enumerate(names):
    image = font.render(name, True, WHITE)
    rect = image.get_rect()
    rect.midleft = (50, (170+30*x))
    items.append([name, image, rect])

selected = None

# - mainloop -

clock = pygame.time.Clock()

running = True
while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            for name, image, rect in items:
                if rect.collidepoint(event.pos):
                    print(name)
                    if selected != (name, image, rect):
                        selected = (name, image, rect)
                    else:
                        selected = None  # unselect on click
                    break

        #elif event.type == pygame.MOUSEBUTTONUP:
        #    selected = None  # unselect when button released

    # - changes/moves/updates -

    # ... empty ...

    # - draws -

    screen.fill(BLACK)

    if selected:
        (name, image, rect) = selected
        pygame.draw.rect(screen, RED, rect)

    for name, image, rect in items:
        screen.blit(image, rect)

    pygame.display.flip()

    # - FPS -

    clock.tick(FPS)

# - end -

pygame.quit()

```

---

And almost the same with `pygame.mouse` \- but without unselection because flick selection and would need much more work.

```
import pygame

# --- constants --- (PEP8: UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)

# --- classes --- (PEP8: CamelCaseNames)

# ... empty ...

# --- functions --- (PEP8: lower_case_names)

# ... empty ...

# --- main ---

names = ['Aaaaa', 'Bbbbb', 'Ccccc', 'Ddddd']

pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

# - create all objects -

font = pygame.font.SysFont(None, 40)

items = []

for x, name in enumerate(names):
    image = font.render(name, True, WHITE)
    rect = image.get_rect()
    rect.midleft = (50, (170+30*x))
    items.append([name, image, rect])

selected = None

# - mainloop -

clock = pygame.time.Clock()

running = True
while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False

    # - changes/moves/updates -

    if pygame.mouse.get_pressed()[0]:
        pos = pygame.mouse.get_pos()
        for name, image, rect in items:
            if rect.collidepoint(event.pos):
                print(name)
                if selected != (name, image, rect):
                    selected = (name, image, rect)
                #else:
                #    selected = None  # unselect on click
                break
    #else:
    #    selected = None  # unselect when button released

    # - draws -

    screen.fill(BLACK)

    if selected:
        (name, image, rect) = selected
        pygame.draw.rect(screen, RED, rect)

    for name, image, rect in items:
        screen.blit(image, rect)

    pygame.display.flip()

    # - FPS -

    clock.tick(FPS)

# - end -

pygame.quit()

```

---

**EDIT:**

The same with class `Text()`

```
import pygame

# --- constants --- (PEP8: UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)

# --- classes --- (PEP8: CamelCaseNames)

class Text():

    def __init__(self, text, x, y, font, color=WHITE):
        self.image = font.render(text, True, color)
        self.rect = self.image.get_rect()
        self.rect.midleft = (x, y)
        self.selected = False

    def draw(self, screen):
        if self.selected:
            pygame.draw.rect(screen, RED, self.rect)
        screen.blit(self.image, self.rect)

    def is_clicked(self, pos):
        return self.rect.collidepoint(pos)

    def toggle(self):
        self.selected = not self.selected

# --- functions --- (PEP8: lower_case_names)

# ... empty ...

# --- main ---

names = ['Aaaaa', 'Bbbbb', 'Ccccc', 'Ddddd']

pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

# - create all objects -

font = pygame.font.SysFont(None, 40)

all_items = []

for x, name in enumerate(names):
    text = Text(name, 50, (170+30*x), font)
    all_items.append(text)

previous_selected = None

# - mainloop -

clock = pygame.time.Clock()

running = True
while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            for text in all_items:
                if text.is_clicked(event.pos):
                    #text.toggle()
                    #break
                    #if previous_selected == text:
                    if text.selected:
                        # unselect current item
                        text.selected = False
                        previous_selected = None
                    else:
                        if previous_selected:
                           # unselect previous item
                           previous_selected.selected = False
                        # select current item
                        text.selected = True
                        previous_selected = text
                    break

        #elif event.type == pygame.MOUSEBUTTONUP:
        #    if previous_selected:
        #         previous_selected.selected = False
        #         previous_selected = None  # unselect when button released

    # - changes/moves/updates -

    # ... empty ...

    # - draws -

    screen.fill(BLACK)

    for text in all_items:
        text.draw(screen)

    pygame.display.flip()

    # - FPS -

    clock.tick(FPS)

# - end -

pygame.quit()

```
> 0 votes

---
Tags: pygame
---


# Question
Title: How do I adjust my rigidbody velocity on a local axes?
I have an fps rigid body script, code listed here:

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

public class Player : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] Camera cam;
    [SerializeField] float camSpeed;

    float yaw;
    Vector3 direction;

    Rigidbody myrigbody;
    void Start()
    {
        myrigbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        cam.transform.Rotate(new Vector3(-Input.GetAxis("Mouse Y") * camSpeed, 0, 0));

        yaw = (yaw + Input.GetAxis("Mouse X") * camSpeed) % 360f;

        direction = new Vector3(Input.GetAxis("Horizontal"), myrigbody.velocity.y, Input.GetAxis("Vertical"));
    }
    private void FixedUpdate()
    {
        myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0));
        myrigbody.velocity = direction;

    }
}

```

The particular part I'm having trouble with is the last line: `myrigbody.velocity = direction;`This code is moving my character perfectly, except that it doesn't adjust to my rotation in game. If i rotate 90 degrees to the right in game, and press forward, I will move to the left (from the players perspective), I will move in the same direction when i press forward (or any other direction) no matter how I have rotated. How do I alter the rigid bodies velocity while taking into account how the player has rotated?

# Answer
```
Vector3 worldDirection = transform.TransformVector(localDirection};

```

...will map a direction in an object's local space to the corresponding direction in world space, factoring in the object's rotation while ignoring its translation and scale. It's equivalent to:

```
Vector3 worldDirection = transform.rotation * localDirection;

```

or

```
Vector3 worldDirection = rigidbody.rotation * localDirection;

```

As an aside, you don't need to cache stick inputs in Update to apply them in `FixedUpdate`. You can just put the code that reads the analog stick values in `FixedUpdate` directly to simplify your code. Don't do that for instantaneous inputs like button presses/releases/taps, but it's safe for continuous inputs like analog stick deflection and button holds.
> 1 votes

---
Tags: unity, c#, physics, rigidbody, first-person-shooter
---


# Question
Title: Geometric clipping of triangles intersecting near plane
I was reading about how rasterization works but there is one topic I can't quite understand. After perspective projection, our point is in clip space as I understand it. Now we test all points in a triangle like so

```
rejected = true
for every point:
   if (abs(point.x) <= abs(point.w) &&
      abs(point.x) <= abs(point.w) &&
      abs(point.x) <= abs(point.w)
      point.w > 0) {
      rejected = false;
    }

```

So the triangle is only rejected if all points are behind the near clipping plane or fall out boundaries, but it can happen that one point is behind the near clipping plane and others are in front. Now there is a part I don't understand. To deal with this we somehow clip points in 3d space by constructing new triangles.

So how is this exactly works?
And why we can't just interpolate our z values to test if the point is behind or in front of the near plane?

# Answer
> why we can't just interpolate our z values to test if the point is behind or in front of the near plane?

Because a vertex that's behind the near plane might be behind the camera entirely. That means the triangle crosses through a singularity in our projection, and part of it will be projected to the opposite quadrant of the screen from where we expect to see it, and closer to the middle of the screen than it should be (as it recedes into depth *behind* us).

Even points that aren't *quite* behind the camera could get divided by an extremely small `w` component when we do our perspective division, rocketing off to absurdly distant locations in screen space where we have very little numerical precision left, causing the triangle attached to them to swim and vibrate from small changes in the camera transform.

You may have noticed artifacts in very old 3D games where polygons would appear to jitter and distort or the textures slosh along them when they passed very close to the camera — that's this effect in action.

To see why we can't just switch to higher precision numbers to fix this, imagine a long skinny triangle laying on the ground, point toward you. The lines of the left and right edges converge toward the bottom of your field of view. Now move so that the point is just behind you, and lean down so your head is very close to the ground. From this perspective, the lines of the left and right edges of the triangle can appear parallel or even diverging toward the bottom of your field of view, because your perspective magnifies the space between them faster than the space between them is shrinking.

There is no place (no finite coordinates) where we can put that third triangle point in the screen space to achieve this effect. Our only choice to project this properly with triangle rasterization is to split it into more than one triangle whose points are at finite screen coordinates, and rasterize each one.

As for algorithms to perform this clipping, the basic idea is to check: for each edge of the triangle, are its two vertices on opposite sides of the near plane?

* If no, for all edges, then you can draw or reject the triangle as a whole.
* If so for at least one edge, we need to clip.

Generate a new vertex at the intersection of the near plane with each crossing edge, interpolating its vertex attributes accordingly.

After repeating this for each edge, you should have 3-4 (not necessarily distinct) points on or in front of the near plane, including at least one of the triangle's original points.

If you have 3, that's your new (possibly degenerate) triangle to rasterize.

If you have 4 distinct points, then you have a quadrilateral, and you can split it along one diagonal or the other to rasterize it as two triangles.

For the exact implementation, I'll defer to others who have written this up in far more detail. As a consumer of the graphics pipeline, rather than a GPU engineer myself, I've mercifully never needed to implement clipping by hand. I can just let the GPU handle that for me automatically, handling numerical precision issues and edge cases I've never even thought of.
> 1 votes

---
Tags: graphics, clipping, rasterization
---


# Question
Title: Render texture seems to ignore camera background type
I'm currently trying to pull a fog of war for an rts game, and planned it like this. (Unity 2020.2.7, URP 10.3.1)

1. Use units field of view to generate a texture of what is seen (alpha 0).
2. Create other render texture to generate fog (alpha \> 0 && alpha \< 1) by not clearing camera buffer.
3. Use the mask made between the two textures to cut the fog of war (alpha 1).

Now i'm currently stuck at the 2nd step. *Please check the image*

As you can see, the camera is doing what I want, but the render texture somehow clears the buffer, which just gives me the "*Use units field of view to generate a texture of what is seen (alpha 0).*" part again.

This whole buffer thing has been hard to understand, i'm not sure if this implementation is right or not. I would be really thankful for any pointers given! :D

Cheers guys!

# Answer
Finally I ended up doing something I don't like. I'm reading from the normal render texture of my FoW, fog data that I save to a texture2d in the cpu every X ms. I don't really know how to use compute shaders just yet, but I'm thinking of moving that operation over to the gpu.

Still it would be nice if anyone knows how to make sure that the camera buffer information is passed to the render texture.

Cheers~
> -1 votes

---
Tags: unity, camera, rendertexture, fog-of-war, unity-urp
---


# Question
Title: Godot Engine: Why is baking light making my scene darker?
I have an interior scene with some windows. The light is from an OmniLight near the ceiling, default environmental light from outside, and a desk lamp with emission. Without baking light, the scene looks like this:

Consistent with the documentation for emission, the desk lamp is not affecting the surrounding objects. I want to bake the light to see the lamp's effect and to support low end hardware.

I followed the baked lightmaps tutorial and set the BakedLightmap's extents to encompass the entire room. After baking, the scene looks like this:

I can see the lamp's light, as expected, but now everything is too dark. It is unclear to me from Godot's documentation if scenes include indirect light without baking. I have tried this with the OmniLight set to bake "all" and only indirect light.

What am I missing here?

---

**UPDATE 10 April 2021:**

The problem seems to be that baking environmental light isn't working as expected. I was using Godot 3.2.3; now I'm using 3.3rc8. That gives the BakedLightmap options for environmental light, but the problem remains.

I began troubleshooting by shuttering all the light sources as follows:

* Hid the OmniLight, and set its "Bake Model" property to "disabled"
* Unchecked "use in baked light" for the desk lamp
* Set the default environment's background and ambient energy to 0
* Set the BakedLightmap's "environment mode" to "Disabled", verified "Min Light" is set to pure black, and cleared the "Light Data"

When I run the game, I get exactly what I expect--a black screen. If I bake light under these conditions, I continue to get a black screen, as expected.

Here's where things get screwy. When I set the BakedLightmap's "environment mode" to "Scene"--with the environment still without any light--I get dim illumination.

# Answer
At least in Godot Engine . . .

Real time environmental light affects all geometry equally without regard for occlusion. However, light baking does consider occlusion. Therefore, an interior scene will not receive as much light from the environment.

My source is the discussion for this issue. I could not find this distinction discussed in Godot's documentation.
> 1 votes

# Answer
I believe your first picture has a lot of environmental light (that blue hue is sky light). Also I believe either your light or your meshes are not set to cast shadows (which, by the way, I would give you problems with light being so close to the ceiling).

Baking the lights is giving you shadows/occlusion. That makes it darker.

*Also the BakedLightmap has a recently added (Godot 3.2.4 beta 6) `environment_mode` set by default to `Disabled`. Meaning it takes no environmental light. Set it to `Scene`.*

---

The BakedLightmap seems to ignore ambient light, and also ignore background energy. To get the black screen, with environment mode set to Scene, you need to either make Sky, Sun and Ground black, or set their respective energies to 0. I do not know if this is intentional.

---

**Godot 3.3.1 released including fix for this issue.** See Maintenance release: Godot 3.3.1.
> 1 votes

---
Tags: godot, lightmap
---


# Question
Title: Unity UI - Make text come out and go back in
In Unity UI I have a TextMeshPro Button and some TextMeshPro Text like in the following image:

Is there any function in a Tween Library like DOTween that could make the text look like its coming out from the left side then going back in? (not scaling). Or without a tweening library how could this be done?

Something like:

As @DMGregory pointed out, this could be understand in two ways

1. coming out and in letter by letter or
2. smooth transition, cutting the letters.

My aim was to achieve 2) - a smooth transition.

# Answer
> 1 votes
Thank you for the help @Vaillancourt , @DMGregory and @Kevin - a mask works perfectly, will tune it further.

How I done it:

1. Create a Panel near the Button
2. Added a Rect Mask 2D as a component on the Panel

Now the children of the Panel (in this case some Text component) will only be visible when they are over the Panel

https://i.imgur.com/gfZjLhz.mp4

To move the text I used a tweening library (DoTween). If anyone is interested how the code of it would look:

```
private void HintSequence()
    {
        DOTween.Sequence()
            .Append(HintsQuestionMarkButton.transform.DOShakePosition(2.0f, 4.0f, 10, 50.0f, false, true))
            .AppendInterval(1.5f)
            .Append(HintsText.DOAnchorPos(new Vector2(0, 0.58f), 2.5f, false))
            .AppendInterval(1.5f)
            .Append(HintsText.DOAnchorPos(new Vector2(-170, 0.58f), 2.5f, false))
    }

private void Start()
    {
        InvokeRepeating("HintSequence", 2.0f, 25.0f);
    }

```

Final result: https://i.imgur.com/JJ28Q7G.mp4

---
Tags: unity, unity-ui, text-mesh-pro
---


# Question
Title: How do I use the Steamworks API to check if a DLC is installed?
I've developed a game through Unity and now I'm stuck with making DLC work. I want to distribute additional scenarios for a game as a DLC and from the various comments I've seen the best way seems to be to add the scenarios pack to the game through an update and then activate it only for those players who bought the DLC. I have installed Steamworks.NET. I am distributing through Steam and I found the following in Steamworks:

```
static bool IsDlcInstalled( AppId appid )

```

I would assume that the script that would go into a script that manages the various scenarios would look something like this:

```
 void CheckIfDlcInstalled()
 {
    if (!SteamManager.Initialized)
    { return; }
    if(something something something == true)
       DLCScenarios.SetActive(true);
 }

```

I though that the following would go into the if-statement, but I get an error message:

```
  if (SteamApps.BIsDlcInstalled(534270))   error: "cannot convert from int to Steamworks.AppId_t"

```

Or am I completely on the wrong path here?

I have also looked at asset bundles - but that doesn't really work because the scenarios include scripts and you can't add those to an asset bundle.

# Answer
I think you meant to write:

```
public Steamworks.AppId_t myDlcId = new Steamworks.AppId_t(534270);

```
> 2 votes

---
Tags: unity, c#, steam, steamworks
---


# Question
Title: Passing properties as arguments such that the resulting class can modify the original
I'm really not experienced with c# so maybe my whole methodology is wrong but here goes.

I'm trying to build a GUI that allows many many parameters to be modified in real time and have a central repository for all those variables. So I am trying to build a wrapper class around the slider so I don't have to explicitly link it to each property in the parameters class manually, and make it easier to add other generic functionalities like events or whatever.

So right now I have a UI class that holds the sliders, a slider wrapper class that holds some extra functionality, and a central parameters class. The central class shouldn't have any dependencies of the other two classes.

The UI class instantiates the slider wrapper class, and passes a Unity slider object. That part works fine. It also passes the property from the central parameter class to which it should be linked. That's the part I'm stuck on.

UI class:

```
public class UIParams : MonoBehaviour
{

    private GeneralParams _centralParams;   // reference to central parameters class
    private Transform _mainUI;               // reference to main UI panel
    private Transform _panel1;               // reference to sub panel

    private MySlider _mySlider1;           // instance of my slider wrapper class
    // more sliders go here

    void Start()

    {
        //init
        _centralParams = GameObject.FindObjectOfType<GeneralParams>();
        var Panel1 = GameObject.Find("MainUI").transform.Find("Panel1");

        //sliders
        _mySlider1 = new MySlider(
            Panel1.Find("Slider1").GetComponent<Slider>(),  //pass the actual slider to the wrapper
            _centralParams.Parameter_1);                     //pass the central parameters property to the wrapper

        // more sliders go here

    }

}

```

Slider wrapper class:

```
Code (CSharp):
class MySlider
{
    private Slider _slider;                 // object to hold the slider
    private float _sliderValue;                   // value of the slider

    public MySlider(Slider Slider, float CentralParameterProperty)
    {
        _slider = Slider;                                                   // reference to Slider
        _slider.onValueChanged.AddListener(delegate { update();});      // listen for changes to slider, don't want to be checking all the time
        _sliderValue = CentralParameterProperty;                            // set slider to default value in CentralParams. How do I modify that value???
    }

    private void update()
    {
        _sliderValue = _slider.value;       // how do I change the original value from Central Params without explicitly linking each property manually?
    }
}

```

Central parameter class:

```
Code (CSharp):
public class CentralParams : MonoBehaviour
{

    public Action GeneralUpdateEvent;       // tell other classes when an update has occured

    [SerializeField]
    private float parameter_1;
    public float Parameter_1
    {
        get => parameter_1;
        set
        {
            parameter_1 = value;
            GeneralUpdate();
        }
    }

    // more parameters go here

    void GeneralUpdate()
    {
        GeneralUpdateEvent?.Invoke();
    }
}

```

Passing the float CentralParameterProperty into the MySlider instance works to set the default value of the slider. But obviously from that point onwards the slider only modifies the internal variable \_sliderValue, not the property of the central class.

Can I set it up so I pass some object from the UI class into the MySlider on instantiation such that the MySlider instance can both get and set the values of the CentralParams property, without explicitly linking to central class within the MySlider class? Or is this just Wong?

Hope that made sense...

# Answer
Here's a simple implementation along the lines of DMGregory's suggestion, which also invokes an event when the value is changed to make synchronizing UI easier.

```
//wraps a struct and invokes an event when the struct is modified
[System.Serializable]
public class EventProperty<T> where T : struct {
    public delegate void ValueChange(T value);
    public event ValueChange OnChanged = delegate { };

    //might not show in inspector, but would from a concrete child class
    [SerializeField] private T value;

    public EventProperty() {
        value = default(T);
    }

    public EventProperty(T value) {
        this.value = value;
    }

    public T Value {
        get => value;
        set {
            this.value = value;
            OnChanged?.Invoke(value);
        }
    }
}

```

Usage:

```
EventProperty<float> property = new EventProperty<float>(0);
property.OnChanged += Property_OnChanged;
property.Value = .5f;

private void Property_OnChanged(float value) {
    Debug.Log("Value changed to " + value);
}

```

I included the `where T : struct` constraint because it doesn't make sense to wrap a reference type in the EventProperty class. The point of EventProperty is to wrap a value type (struct) so that it can be used like a reference type. If `T` is already a reference type, there could be unexpected side effects:

```
List<float> list = new List<float>{1,2,3,4,5};
EventProperty<List<float>> wrapper = new EventProperty<List<float>>(list);
//does not fire OnChanged because we didn't pass a new value to wrapper.Value
wrapper.Value.Add(6);

```

If you want to serialize the value and be able to see it in the inspector, you'll probably need to subclass EventProperty, e.g.

```
[System.Serializable]
public class FloatEventProperty : EventProperty<float> { }
//...
[SerializeField] private FloatEventProperty floatProperty;

```

Serialized generic fields will show in the inspector if they are given a concrete type in a child class.
> 2 votes

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


# Question
Title: How to manipulate PostProcessing effects settings during execution with c#?
I need to change the intensity value of my current Vignette effect depending in specific conditions.
So far I haven't been able to achieve this. Please help!

*Image of what I want to achieve:*

*My setup:*

* Unity 2019.3.5f1 with URP implemented
* Post Processing Package (v2) installed
* Scene with a GameObject + Volume component with Vignette and Bloom effect overrides added
* A monobehaviour component script in the very same GameObject from above

*My monobehaviour script:*

```
using UnityEngine;
 using UnityEngine.Rendering.PostProcessing;

 public class PostProcessingHandler : MonoBehaviour
 {
   private PostProcessVolume _ppv;
   private Vignette _vignette;

   // Vignette intensity values
   [SerializeField, Range(0f, 1f)]
   private float _lowIntensity = 0.25f;
   [SerializeField, Range(0f, 1f)]
   private float _highIntensity = 0.5f;

   private void Start()
   {
     _ppv = GetComponent<PostProcessVolume>();
     Debug.Log(_ppv);
   }
 }

```

When I try to retrieve PostProcessingVolume component to get it's profile (and further layer manipulation) I always get **"null"**.

*Image of my setup:*

I've seen several guides/posts and even Unity documentation but I cannot get past that starting point of getting the PostProcessingVolume component, what am i missing?

# Answer
> 3 votes
It actually has a tricky way to do it. You need to grab the `PostProcessValue` and then grab the effect that you want to change, in your case the `Vignette`. After that, you will need to "Override" the values, that is the key. Here is an example I did based on the Unity documentation:

```
public PostProcessVolume volume; //Assigned with the editor
Vignette vignette; //The post processing effect you want to change

void Start()
{
    vignette= volume.profile.GetSetting<Vignette>(); //Grab the value of the post processing effect

    vignette.smoothness.Override(0.5f); //override the effect that you want with the value you need.
}

```

As you can see, the "Override" is the key to actually make it work. You can see more in this link.

---
Tags: unity, c#, post-processing
---


# Question
Title: When serializing a class, can its fields take their defaults from the Unity editor?
Can I have a custom serialized class whereby I set a value in the editor and that value persists into runtime, as happens with serialized monobehaviour fields?

Currently it sets itself to 0 or a default hard coded from within the class.

I noticed that using a struct actually works but using a struct breaks the events used in my actual use case (included below).

Example code:

```
public class Class1 : MonoBehaviour
{
    // this variable can be set in the editor and persist into run time
    [SerializeField]
    private float testVar1;

    // this variable can not
    [SerializeField]
    private Class2 class2;

    private void Start()
    {
        class2 = new Class2();
    }
}

[Serializable]
public class Class2
{
    [SerializeField]
    private float testVar2;
}

```

My use case:

```
[Serializable]
public class EditorFloat
{
    [SerializeField]
    public float value;
    public EventProperty<float> eventProperty;

    public EditorFloat(EventProperty<float> eventProperty)
    {

        this.eventProperty = eventProperty;
        Object.FindObjectOfType<CentralParams>().OnUiChange += Update;
        this.eventProperty.OnChanged += UpdateEditor;
    }
    public void Update()
    {
        eventProperty.Value = value;
    }
    public void UpdateEditor(float valueFromEventProperty)
    {
        value = valueFromEventProperty;
    }
}

```

Thanks!

# Answer
This happens automatically. Unless you go out of your way to break it.

Your code goes out of its way to break it.

```
private void Start()
{
    class2 = new Class2();
}

```

This says, "after you've deserialized the value of `class2` that I set in the inspector, please throw that in the garbage and replace it with a `new Class2()` that has default values instead"

If you don't want to overwrite your data with blanks, don't write code that overwrites your data with blanks.
> 1 votes

# Answer
Assuming this question comes from Passing properties as arguments such that the resulting class can modify the original

```
//wraps a struct and invokes an event when the struct is modified
[System.Serializable]
public class EventProperty<T> where T : struct {
    public delegate void ValueChange(T value);
    public event ValueChange OnChanged = delegate { };

    //might not show in inspector, but would from a concrete child class, see below
    [SerializeField] private T value;

    public EventProperty() {
        value = default(T);
    }

    public EventProperty(T value) {
        this.value = value;
    }

    public T Value {
        get => value;
        set {
            this.value = value;
            OnChanged?.Invoke(value);
        }
    }
}

[System.Serializable]
public class FloatEventProperty : EventProperty<float> { }

public class MyBehaviour : MonoBehaviour {
    //won't show in inspector because it's generic
    [SerializeField] private EventProperty<float> floatValue1;
    //will show in Inspector
    [SerializeField] private FloatEventProperty floatValue2;
}

```

If I recall correctly, a generic class/field won't show in the inspector. However, if you have a subclass of the generic class which uses a concrete type (such as `FloatEventProperty`, which uses `float` as the concrete type), the field *will* show in the inspector as long as the concrete type is serializable.
> 0 votes

---
Tags: unity, unity-ui
---


title: How to pass data between game states?

text:
# Question
Title: How to pass data between game states?
Lately I've been using game state stack implementation from a book SFML Game Development and I've stumbled upon a problem with passing data between states. In this implementation State constructors are predefined and I can't really pass values between them. What's the better way to implement game states so I can for example pass player's score from gameplay state to gameover state?

Here is the game state header from the book:

```
#ifndef BOOK_STATESTACK_HPP
#define BOOK_STATESTACK_HPP

#include <Book/State.hpp>
#include <Book/StateIdentifiers.hpp>
#include <Book/ResourceIdentifiers.hpp>

#include <SFML/System/NonCopyable.hpp>
#include <SFML/System/Time.hpp>

#include <vector>
#include <utility>
#include <functional>
#include <map>

namespace sf
{
    class Event;
    class RenderWindow;
}

class StateStack : private sf::NonCopyable
{
    public:
        enum Action
        {
            Push,
            Pop,
            Clear,
        };

    public:
        explicit            StateStack(State::Context context);

        template <typename T>
        void                registerState(States::ID stateID);
        template <typename T, typename Param1>
        void                registerState(States::ID stateID, Param1 arg1);

        void                update(sf::Time dt);
        void                draw();
        void                handleEvent(const sf::Event& event);

        void                pushState(States::ID stateID);
        void                popState();
        void                clearStates();

        bool                isEmpty() const;

    private:
        State::Ptr          createState(States::ID stateID);
        void                applyPendingChanges();

    private:
        struct PendingChange
        {
            explicit            PendingChange(Action action, States::ID stateID = States::None);

            Action              action;
            States::ID          stateID;
        };

    private:
        std::vector<State::Ptr>                             mStack;
        std::vector<PendingChange>                          mPendingList;

        State::Context                                      mContext;
        std::map<States::ID, std::function<State::Ptr()>>   mFactories;
};

template <typename T>
void StateStack::registerState(States::ID stateID)
{
    mFactories[stateID] = [this] ()
    {
        return State::Ptr(new T(*this, mContext));
    };
}

template <typename T, typename Param1>
void StateStack::registerState(States::ID stateID, Param1 arg1)
{
    mFactories[stateID] = [this, arg1] ()
    {
        return State::Ptr(new T(*this, mContext, arg1));
    };
}

#endif // BOOK_STATESTACK_HPP

```

And implementation:

```
#include <Book/StateStack.hpp>
#include <Book/Foreach.hpp>

#include <cassert>

StateStack::StateStack(State::Context context)
: mStack()
, mPendingList()
, mContext(context)
, mFactories()
{
}

void StateStack::update(sf::Time dt)
{
    // Iterate from top to bottom, stop as soon as update() returns false
    for (auto itr = mStack.rbegin(); itr != mStack.rend(); ++itr)
    {
        if (!(*itr)->update(dt))
            break;
    }

    applyPendingChanges();
}

void StateStack::draw()
{
    // Draw all active states from bottom to top
    FOREACH(State::Ptr& state, mStack)
        state->draw();
}

void StateStack::handleEvent(const sf::Event& event)
{
    // Iterate from top to bottom, stop as soon as handleEvent() returns false
    for (auto itr = mStack.rbegin(); itr != mStack.rend(); ++itr)
    {
        if (!(*itr)->handleEvent(event))
            break;
    }

    applyPendingChanges();
}

void StateStack::pushState(States::ID stateID)
{
    mPendingList.push_back(PendingChange(Push, stateID));
}

void StateStack::popState()
{
    mPendingList.push_back(PendingChange(Pop));
}

void StateStack::clearStates()
{
    mPendingList.push_back(PendingChange(Clear));
}

bool StateStack::isEmpty() const
{
    return mStack.empty();
}

State::Ptr StateStack::createState(States::ID stateID)
{
    auto found = mFactories.find(stateID);
    assert(found != mFactories.end());

    return found->second();
}

void StateStack::applyPendingChanges()
{
    FOREACH(PendingChange change, mPendingList)
    {
        switch (change.action)
        {
            case Push:
                mStack.push_back(createState(change.stateID));
                break;

            case Pop:
                mStack.back()->onDestroy();
                mStack.pop_back();

                if (!mStack.empty())
                    mStack.back()->onActivate();
                break;

            case Clear:
                FOREACH(State::Ptr& state, mStack)
                    state->onDestroy();

                mStack.clear();
                break;
        }
    }

    mPendingList.clear();
}

StateStack::PendingChange::PendingChange(Action action, States::ID stateID)
: action(action)
, stateID(stateID)
{
}

```

# Answer
> 1 votes
`StateStack` can route 1 parameter to the state's constructor. Notice how states are registered in `Application::registerStates`.

You could design a new `GameState` subclass that accepts a pointer to the shared data.

// Design a data container.
struct GameData { int HighScore; }

// Add a new member variable to the Application class.
GameData mGameData;

// Add a new member to the relevant state classes.
GameData *mGameData;

// Update state constructors.
GameState::GameState(StateStack& stack, Context context, GameData *gameData) {...}
GameOverState::GameOverState(StateStack& stack, Context context, GameData *gameData) {...}

// Update state registrations.
mStateStack.registerState<GameState>(States::Game, &mGameData);
mStateStack.registerState<GameOverState>(States::GameOver, &mGameData);
```

---
Tags: c++, software-engineering, game-state
---


# Question
Title: Unity animator controller animations don't work
I'm having problems animating a character pack I purchased from unity asset store.

I've placed the character in an environment and created an animator controller. After I drag the animation that to the animator tab, there aren't any motions. Even if I place triggers or booleans in my script as parameters in the animator it doesn't work.

It worked with other characters but the animations were somehow embedded in the 3d models. How is this supposed to work?

# Answer
> 2 votes
For an animation to work in Unity you need:

1.) an Animator component assigned to your gameObject 2.) an Animation Controller asset 3.) an animation clip(s)

The Animator component needs to have the Animation Controller dragged to it's 'Controller' field in the Inspector window. An Avatar is required in the 'Avatar' Inspector field (usually autocreated on import)

Then as long as you've dragged at least 1 Animation clip to the Animation Controller state machine (and possibly set it to default so that it will play first), your gameObject should then animate in Play mode.

http://docs.unity3d.com/Manual/class-Animator.html

It's hard to tell what the issue is without more details/knowledge of the animations/screenshots etc, but make sure you have a look at the actual Animator component on the character in the Scene heirarchy and ensure none of the Inspector fields are set to 'None'. That's where I'd start at least.

# Answer
> 0 votes
This is caused by the fact that the animations are set to 'Legacy', click on the animation clip, in the very top right of the inspector click the three lines with a down arrow on the left of them, click Debug, Untick Legacy, click drop down again and click Normal, Re-drag animations into your Animator Controller, job done

# Answer
> 0 votes
Go to ANIMATOR component -\> right click -\> click on OPTIMIZE TRANSFORM HIERARCHY. I don't know how it works but it works!

---
Tags: unity, animation
---