# Question
Title: How to create a glowing corona/halo around a sun and make it emit light
I am trying to understand material and shaders in Unity. make my object glow like a sun. For the moment I do not care if it's not looking like a star, but I would like that it at least emit light.

How do I make something that look like a star, and emit light? Like this:
(And if possible, be able to change the light color)

I tried to play with the Standard shader, and add some emission like this :

I tried legacy self illuminated, but they look like 2d, and have no depth

# Answer
In order for that shiny halo to appear around HDR-colored materials, you need to add a Bloom post-processing effect to your scene.

How to do that and what settings that filter has available differs a bit depending on whether you use the Universal Render Pipeline, the High-Definition Render Pipeline or the build-in render pipeline.

For HDRP and URP:

1. Create a global post-processing volume in your scene with Volume -\> Global Volume.
2. Add a new Profile to that volume.
3. Click on "Add Override..." and add the "Bloom" effect to that profile. Enable the "Intensity" property and set it to 1.0 for now. You can tweak it later.
4. Select your camera and enable the "Post Processing" checkbox.
5. Give your sun's material an HDR color for its emission property in the desired color, and crank up its intensity
6. You can tweak the emission color of your material and the bloom effect on your post-processing volume by configuring it according to the documentation for URP Bloom or HDRP Bloom

For the Build-in Render Pipeline:

1. Install the post-processing package via the package manager.
2. Create an empty gameObject (your post-processing volume)
3. Set the Layer of that game object to a new layer "Post Processing"
4. Add the Post-Processing Volume Component to the game object (Rendering -\> Post-process Volume)
5. Check "Is Global" on the volume
6. Add a new Profile to that volume.
7. Click on "Add Effect..." and add the "Bloom" effect to that profile. Enable the "Intensity" property and set it to 1.0 for now. You can tweak it later.
8. Select the game object with your camera and add the Post-Processing Layer Component to it Rendering -\> Post-process Layer.
9. On that post-processing layer, set the setting "volume layer" to your new layer "Post Processing"
10. Give your sun's material an HDR color for its emission property in the desired color, and crank up its intensity
11. You can tweak the emission color of your material and the bloom effect on your post-processing volume by configuring it according to the documentation for Build-in RP Bloom

From now on, remember to wear sunscreen while working on this scene :)
> 4 votes

---
Tags: unity, shaders, lighting, graphic-effects, glow
---


# Question
Title: How to implement Vector3.MoveTowards follow with random movement
I want to implement an AI behavior where an enemy runs towards the player while sidestepping randomly and aggressively (like in this video: https://www.youtube.com/watch?v=35Ut\_C4eL40)

Currently I am just using `Vector3.MoveTowards` but that results in smooth movement which isn't exactly what I need. I've tried adding an offset to the target using `Random.insideUnitCircle` but it just doesn't work.

If anyone could give me an algorithm to implement it'll be great. Thanks

# Answer
There are lots of ways you could accomplish this, I'll just give you one to get started.

Attach this script to a gameobject, and give it another gameobject as target to follow. Uncomment line 29 if you're using a top-down view.

```
using UnityEngine;

public class AssassinMove : MonoBehaviour
{
    public Transform target;
    [Range(0, 10)] public float speed;
    [Range(0, 10)] public float dodgeSpeed;
    public bool assassinMove;

    void Update()
    {
        if (assassinMove)
            MoveAssassin();
        else
            MoveNormal();
    }

    void MoveNormal()
    {
        transform.position =
            Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }

    void MoveAssassin()
    {
        //get a random direction
        Vector3 r = Random.insideUnitCircle;    //for 2D
        //for 3D top down, you need to swap the x and z components
        //r.Set(r.x, 0, r.y);

        transform.position =
            Vector3.MoveTowards(transform.position, transform.position + r, dodgeSpeed * Time.deltaTime);
        transform.position =
            Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
}

```

That will get you some very random jittery movement, not dissimilar to the assassin, but not the same.

The next question is how to make the movement look good and work how you're picturing it. That's an entirely separate issue, but some ideas:

* Restrict the dodge vector to a perpendicular vector so it's only a sidestep. (`r = Vector2.Perpendicular(v)`)
* Run the dodge separately in a coroutine so it only dodges every so often, instead of every frame
> 1 votes

---
Tags: unity, c#, movement, ai, shooter
---


# Question
Title: Should the interaction between the player and world objects be handled from the player class or as an event from the object classes?
Suppose you're making a 3D platformer like Super Mario, if you jump on a Goomba, does Mario (the class) know that it just landed on a Goomba and then tell that Goomba to die, or does the Goomba realize that he is being smashed and dies ?

I want to go with the first approach but it will end up with a huge If/then (or Switch/Case) script, also the reason why this is "problematic" is that many objects will make the player have a "reaction", for example if you land on a Goomba, you don't just kill it, but it forces you to jump, that jump event, what's the best way to handle it ?

Thanks

# Answer
This is a fairly timeless question I think, which means that the answer is going to depend on what exactly you need to do, if something needs to be optimized (only if it's running slow!) and other case-dependent issues.

The question DMGregory linked has a lot of good information, but I'd like to address this specific line in your question:

> for example if you land on a Goomba, you don't just kill it, but it forces you to jump, that jump event, what's the best way to handle it ?

Your question up to that point might have a single perfect answer, which is suddenly not the right answer when you add this requirement. This is particularly an issue in game development when your prototyping phase is defined by the vague requirement of "what feels fun to play?"

So the answer I'm suggesting is similar to optimization. First narrow down your requirements, and just plan refactoring your code into your prototyping.

I recently had the same issue, and the solution that worked best was to implement every game mechanic in the easiest way possible. Using inefficient methods like `SendMessage` makes it vastly simpler to get a mechanic working and find out if it's even worth implementing or needs changing. As you continue to implement mechanics, you'll see what requirements you need to focus on, but you'll also find which connections are used less often than you expected and don't need to be super-robust. Even more importantly, you'll find those that are critical and not only need to be optimized, but maybe need to be written in a particular way that makes your design work easier (for example, customizing enemy types without rewriting a lot of boilerplate code).
> 1 votes

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


title: How to sample a TextureCube texture

text:
# Question
Title: How to sample a TextureCube texture
I'm converting old shader code to be a bit more modern. So far this works out great, but I'm having a though time figuring out how to convert shader code that works with cubic textures.

In the old code I would declare a generic texture in HLSL and create a `samplerCube` to do the sampling. Then I would use the intrinsic `texCube` function to actual sample in the direction of the normal `N`.

```
texture Irradiance;
samplerCUBE irradianceSampler = sampler_state
{
    Texture = (Irradiance);
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    MipFilter = LINEAR;
    AddressU = Clamp;
    AddressV = Clamp;
    AddressW = Clamp;
};

float3 N;
float4 irradiance = texCUBE(irradianceSampler, N);

```

In the updated shader I would like to use the texture objects. In case of a cubic texture I would assume I'd have to use the `TextureCube` type. This type has a regular `Sample` method but that method does not accept a `samplerCube` only a `sampler`. Using a regular sampler I have no idea how to pass the normal argument `N` to look up the pixels.

To summarize in code, this is the code that I expected to have to write

```
TextureCube Irradiance;
samplerCube irrandianceSampler = sampler_state {...};

float3 N;
float irradiance = Irradiance.Sample(irradianceSampler, N);

```

But that doesn't compile because samplerCube does not conform to the first argument of Irradiance.Sample.

**TLDR**

Who can show me the right syntax to sample from a `TextureCube` in `HLSL` Shader Model 5+.

# Answer
> 3 votes
This doesn't work the way you're expecting because texture slots and sampler slots are decoupled in D3D10/SM4+. So unlike legacy code, you can have a texture at slot *x*, a sampler state at slot *y* (and remember that sampler state slots are no longer the same as texture slots) and combine them to sample that texture. You can also use the same sampler state at slot *y* to sample other textures at other texture slots, and even sample your original texture at slot *x* with other sampler states at other sampler slots.

If that sounds complicated and confusing - don't panic. It's actually quite simple and clean when you see it in code.

Here's a definition for a bunch of samplers (note: I'm **not** using Effects here):

```
sampler samLinearWrap : register(s0);
sampler samLinearClamp : register(s1);
sampler samPointWrap : register(s2);
sampler samPointClamp : register(s3);

```

I've just named these according to the state configured for each, and explicitly specified their slots using the `register` keyword.

Here's a diffuse texture (don't worry, I'll come to cubemaps before too long):

```
Texture2D<float4> mainTexture : register(t0);

```

So I can now sample this texture like so:

```
float2 texcoords = ....
float4 diffuse = mainTexture.Sample (samLinearWrap, texcoords);

```

I could just as easily declare any other texture at any other slot number, and likewise sample it using the same samLinearWrap. So, for example, if I was doing some lightmapping:

```
Texture2D<float4> lmapTexture : register(t1);
float2 lmcoords = ....
float4 lightmap = lmapTexture.Sample (samLinearWrap, lmcoords);

```

Same sampler, different texture, and it all works.

Of course I can also use a different sampler if I wish:

```
float4 lightmap = lmapTexture.Sample (samLinearClamp, lmcoords);

```

This seamlessly extends to cubemaps, array textures and other texture types. Obviously for cubemaps it makes more sense to use a clamp sampler state, but otherwise it works the very same:

```
TextureCube<float4> cubeTexture : register(t2);
float3 cubemapcoords = ....
float4 cubetex = cubeTexture.Sample (samLinearClamp, cubemapcoords);

```

And just for completeness, and to have this answer be more generally useful:

```
Texture2DArray<float4> arrayTexture : register(t3);
float3 arraycoords = ....
float4 arraytex = arrayTexture.Sample (samLinearClamp, arraycoords);

```

(Again notice: same sampler object, different texture objects, and the fact that I used samLinearClamp for my second lightmap/2D texture example doesn't prevent me using it for cubemaps, array textures or any other type).

---
Tags: directx11, hlsl
---


# Question
Title: Plugin system with AssemblyLoadContext and unloading
I'm building a game engine from scratch and trying to implement a basic plugin system within my engine.

Using `AssemblyLoadContext` to load the target dll dynamicly and unloading it with `AssemblyLoadContext.Unload()`

However it seems even if there is a one class instance created from this assembly hanging somewhere in the whole app domain `AssemblyLoadContext.Unload()` does not unload it until the all the instances are dereferenced.

This is where my problem begins.

There are infinite number of scenarios whether a class which belongs to the plugin can be instantiated and used across the whole appdomain right?.

So how do i keep track of the plugin instances across the whole `AppDomain`.

**(How unity unloads the user scripts and cleans every last one of the instances i wonder)**

My engine system is nearly identical to both unreal and unity.

I have entities and the components just like unity.

My current unload workflow is like this.

1. Loop through every component via reflection and check if one the assembly classes instantiated then set that field/property null
2. Loop through every assembly and check for static fields/properties which might contain some instance
3. Now unload it.

However the approach above seems well idiotic and sluggish not to mention it should be slow as hell.

It seems i have a desing problem within my plugin system and i fear if i overcomplicated things.

Are there better way to cleanup assembly instances or am i missing something? (Please tell me im missing something obvious)

# Answer
> 1 votes
### AppDomain

The most established and bulletproof method for plugin isolation is to use `AppDomain`. Anything allocated withing one `AppDomain` will be disposed together when `AppDomain` unloads or reloads.

As a downside, communication between domains (the default and isolated one) is tricky, because it requires serialization and deserialization, which may lead to performance issues and coding inconvenience bottleneck.

More importantly for your case, `AppDomain` **is not fully supported in .Net Core** — only events will work, but not a domain management. Although, the support is back in .NET 5 (and later).

### AssemblyLoadContext and disposable proxies

AssemblyLoadContext is the second preferable option. It is much easier for communication, but it also makes to easy to cause a memory leak.

In my knowledge, absolute most leaks are caused by registering references inside a long-lived object, the most common example being events such as in singletons or application services.

The straightforward solution is to not allow any short-lived code to register itself with a long-lived object. Instead, short-lived code should be provided with a reference to a short-lived proxy that allows same registrations. The proxy subscribes to actual underlying service and redirects (or dispatches differently) the events to the short-lived clients.

When game session is finished, the proxy must be disposed, making whole "island" of objects to go away at once. The role of the proxy is to ensure that all the registration is happening in one place, so there is no need to rely on plugin developers not forgetting to unsubscribe (and not skipping it due to bug).

```
    public class EngineServices : IDisposable
    {
        public event Action<Foo> FooEvent(Foo foo);
        public IEnumerable<Baz> BazRegistry => _bazRegistry;

        public EngineServices(ActualEngineServices actual)
        {
            _actual = actual;
            _actual.FooEvent += RelayFoo;
        }

        public void Dispose()
        {
            _actual.FooEvent -= RelayFoo;
        }

        public void Register(Baz baz) => _bazRegistry.Add(baz);

        ActualEngineServices _actual;
        List<Baz> _bazRegistry = new(); // come to the darkside, we have C#9

        void RelayFoo(Foo foo) => FooEvent?.Invoke(foo);
    }

```

You still may want to scan the object graph to find possible escape routes.

### Sandbox process

As a last resort, it is possible to use dedicated process for plugin isolation. Setting it up would be slightly harder, communication could be slower (and not without a lag), but otherwise it almost the same as `AppDomain`.

One interesting feature of a separate process is that it can crash itself without crashing the parent application.

### Gameplay process

If you are feeling adventurous, design the main process to be a fancy-looking launcher for a game session. Same as the previous method, but allows gameplay objects to be coupled with the engine. Bonus points for making process switching seamless. Looking at you, Noita.

---
Tags: architecture, code-reflection
---


# Question
Title: How to transition a coin to the middle of the screen then up when collecting it?
I have a **coin** sprite that animates spinning in place, like this.

When the player picks up the coin, I want to make a transition while keeping the animation. First moving towards middle, then much faster all the way up until it leaves the screen like this:

My question: Is this done mostly via adjusting the Transform component component via scripting? Or are games implementing something like this in a different way?

# Answer
> 0 votes
If the coin always starts out in the same place (bottom-right corner of the screen in your example), you can do everything with animations. For example, you could use a separate animation on the coin's *parent* to move the coin to the center of the screen and then upward.

If the coin might start out anywhere on the screen, I would suggest animating the movement (to center-screen and then up) using a coroutine instead of a keyframe animation. E.g.:

```
private IEnumerator CollectCoin() {
    Vector3 start = coin.transform.position;
    Camera camera = Camera.main;
    Vector3 screenCenterPos = new Vector3(camera.pixelWidth / 2, camera.pixelHeight / 2, 10);
    Vector3 end = camera.ScreenToWorldPoint(screenCenterPos);

    //fly to center of screen
    float duration = 1; //adjust as needed
    float elapsed = 0;
    while (elapsed < duration) {
        yield return null;
        elapsed += Time.deltaTime;
        float t = elapsed / duration;
        coin.transform.position = Vector3.Lerp(start, end, t);
    }

    //fly up
    start = end;
    end.y += 5; //adjust as needed
    duration = .5f; //adjust as needed
    elapsed = 0;
    while (elapsed < duration) {
        yield return null;
        elapsed += Time.deltaTime;
        float t = elapsed / duration;
        coin.transform.position = Vector3.Lerp(start, end, t);
    }
}

```

The above will do simple linear animations. If you would prefer to incorporate easing, you can use a tween library.

---
Tags: unity, animation
---


title: Unity Cutting a hole in mesh

text:
# Question
Title: Unity Cutting a hole in mesh
I've set myself a stupid task, that I didn't solve couple years back, again. I've got few meshes with normals pointing inside. Caves. Like mostly circular rooms and tunnels that should connect them. Making tunnels to connect to a room is not a problem, just have their sides open and make a connector that will hide connecting edges if there are some sort of artifacts. But what to do with rooms. I need to cut holes in random positions in walls.

# Answer
> 2 votes
Solution was to use Parabox CSG for boolean operations. But there was a problem. If I just take a box flip normals and try combining it with a room I'll get a recessions in walls, but not holes. And then I tried to remove one face of that flipped cube and positioned it inside that flipped dome mesh, so that they do not intersect.

And in result I had exactly what I was looking for. A clean mesh. Cubes material is not present in the result, nor any triangles.

I hope it will help those few that try to do similar things and fail to find any semi acceptable results. With this you can go full procedural and do anything you want.

---
Tags: unity, 3d-meshes, csg
---


# Question
Title: Is an ECS viable in garbage collected languages?
I've done some research on Entity Component System architectures. Right now I have a convoluted OOP implementation which I'm planning on rewriting, so I was considering switching to a different architecture. Since everything was already composed using components, the switch from OOP to ECS shouldn't be too difficult. However, I'm doing my project in a language with managed memory and GC, and a lot of the benefits of ECS are to do with memory management, processor cache, etc. so I was wondering whether there is any real performance advantage of ECS over OOP in a garbage collected language?

Also, I'm not too familiar with manual memory management and I haven't really used C/C++ for anything big.

# Answer
The Garbage Collector (GC) is not really an obstacle to implement an Entity-Component-System (ECS) architecture.

All you need is a root object for your ECS. It would hold references to the containers you use for your components (and references to your systems, if that makes sense in your implementation). Those containers will likely hold arrays of components, which is how you have the components contiguous in memory. Which is important for for cache optimization (and yes, that remains important for performance regardless of GC).

As long as you have a reference to the root, the GC will not collect any of it.

In fact, there isn't a lot of manual memory management in ECS. Usually, you will not store your components by de/allocating in the heap (because then you lose control over memory layout), instead you will be storing components as elements of arrays. Then the memory management is about allocating the arrays, for which you would use a an Object Pool pattern.

---

The obstacles an object oriented language could pose to implement an ECS are others. For instance, if the language does not allow you create custom value types (e.g. C# `struct`), it means that your arrays would only hold references to the actual components. And those components would be stored elsewhere. Thus, you lose that cache optimization you want.

I also want to mention that depending on the language, you may need to pay attention on whether or not arrays guarantee that values are contiguous in memory. Some runtimes would offer sparse arrays or other structures by default.

---

An object oriented approach would suggest that an entity is a container of components. And semantically, that is the case. However, implementing it that way means that components of the same kind are not contiguous in memory. Instead, the entity will be an integer, which you would use to find its components. *Unless you can't have chunks of contiguous in memory anyway, then go ahead and implement the ECS on more object oriented grounds.*

*By the way, if your language is one of those that poses obstacles, chances are it is a dynamic language where you can add components to an object at runtime directly. Which means you don't have to implement that part. Also, you would have a more idiomatic syntax.*

---

Which reminds me, cache optimization is not the only benefit of an ECS. Thus, there is still value in an ECS even if you don't have chunks of continuous memory.

What is the value of an ECS without cache optimization? First, composition. For starters, you can add and remove components at runtime, plus you can iterate over all the entities that have components of a given kind. This allows you to have components work both as state and as messages. And second, going against the object oriented approach, having the systems separate from the entities help in keeping your code easier to manage. Without that, in order to not repeat code, behavior tends to accumulate in a base class for all entities. Base class which has to deal with all cases.

*By the way, I don't to suggest that ECS is the only solution, nor that everything should be in an ECS. There is also value in having some aspect of a game exist outside of an ECS. Similarly, remember that making games without an ECS is perfectly possible.*

---

I'll recommend you to watch the video: RustConf 2018 - Closing Keynote - Using Rust For Game Development by Catherine West and the response video Rant: Entity systems and the Rust borrow checker ... or something.. Although, these videos are about Rust, they manage to do a good job of explaining the problems of an orthodox object oriented approaches and the memory management challenges in implementing an ECS. *You will hear about the Rust borrow checker… If you are not familiar with Rust, suffice to say, that the borrow checker, is part of the Rust compiler and it is there to make sure that your memory management is correct and safe. Code has ownership of memory when it is responsible for de-allocating, and borrowing means to access some memory without taking ownership. Could the owner de-allocated the memory while borrowed? The borrow checker, well, checks that.*
> 7 votes

# Answer
The performance cost of garbage-collection can be greatly reduced by avoiding the creation of garbage.

Garbage is created whenever you create a short-living object. Like in this example:

```
foreach (var thing in veryLargeCollection) {
    new ConsoleOutputter(new ThingFormatter(new ThingReader(thing).Read()).Format()).Write();
}

```

Each loop iteration will allocate memory for 3 short-living objects which then immediately become garbage and will need to be garbage-collected later. How can we avoid that? Just the way how responsible people should manage their garbage in real-life: Reduce is better than Reuse is better than Recycle.

Reduce garbage by avoiding the creation of short-living objects. Avoid `NounVerber` classes in your software architecture and instead try to put their functionality into methods of other classes. Keep in mind that there are also short-living objects which can be created by library-functions. For example, you might be using a vector library which likes to create temporary objects. `distance = (vectorA - vectorB).magnitude` Subtracting one vector from another might create a short-living new Vector-object.

When you can not reduce object-creation, then the next best thing is to reuse objects.

* If you do have `NounVerber` classes in your architecture, give them a way to change their subject, so they can be reused.

```
thingFormatter.SetThingProvider(thingReader);
consoleOutputter.SetInputStream(thingFormatter);

foreach (var thing in veryLargeCollection) {
    thingReader.SetThing(thing);
    consoleOutputter.Write();
}

```
* Avoid encapsulating small amounts of data in reference-types (like classes in most languages). Try to use value-types instead. Like primitives (in *most* languages) or `struct`'s in C#.
* Do object pooling. For example, let's say you have a bullet hell shooter with lots of bullets, and those bullets are reference-type. Don't create a `new Bullet()` whenever something shoots a bullet and don't let them just become garbage by removing them from the collection of active bullets when they leave the screen. What you should do instead is create a lot of bullets at game start an store the references to them in an array of unused bullets (creating them all at once increases your chances that the VM will put them in relatively unfragmented memory, by the way). When something shoots a bullet, take one from the unused bullet array and initialize its values. When you no longer need a bullet, put a reference back into the array of unused bullets. That way no bullet will ever exist without a reference pointing to it, so it will never become garbage.

---

Another problem which is not a problem of garbage collection per-se but which is frequently a problem in languages which do garbage collection is to ensure memory locality. In a manged language like C# or Java, you don't have much control over how exactly the VM allocates memory. So you can not *force* it to keep data which gets processed together in the same section of memory to ensure cache-friendliness. But you can at least try to make its job easier by avoiding data-structures which are designed for dynamic memory allocation and reallocation. For example, consider using fixed-size arrays instead of variable-sized lists. And when you do use dynamically-sized containers, see if there is some way to tell them how large they are going to get when they are created.
> 2 votes

# Answer
There is another performance-related aspect of ECS: **parallelization**.

During the update cycle, each system writes to the limited set of components, often just 1. The components that are not being written at that moment may be safely shared across the multiple threads, which allows multiple systems to run in parallel.

Garbage-collected language may be even more preferable when aiming for parallelization, due to the better multi-threaded safety of a managed memory model.
> 1 votes

---
Tags: architecture, software-engineering, entity-component-system
---


# Question
Title: Unity freezes when running BFS update instead of visualizing each step
I made a visualization of Breadth First Search in Unity. It consists of an area of square planes which will change color as they are visited.

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

public class BFS : MonoBehaviour
{
    public GameObject blockArea;
    (int, int)[] moves = new (int, int)[4] { (1, 0), (0, 1), (-1, 0), (0, -1) };

    public void bfs()
    {
        List<(int, int)> starts = new List<(int, int)>();
        List<(int, int)> goals = new List<(int, int)>();

        GameObject[][] blocks = blockArea.GetComponent<Area>().area;
        int[][] area = new int[blocks.Length + 2][];

        for (int i = 0; i < area.Length; i++)
        {
            area[i] = new int[blocks[0].Length + 2];
            for (int j = 0; j < area[i].Length; j++)
            {
                if (i == 0 || j == 0 || i == area.Length - 1 || j == area[i].Length - 1)
                {
                    area[i][j] = 1;
                }
                else
                {
                    area[i][j] = blocks[i - 1][j - 1].GetComponent<Block>().state;
                    if (area[i][j] == 2)
                    {
                        starts.Add((i, j));
                    }
                    else if (area[i][j] == 3)
                    {
                        goals.Add((i, j));
                    }
                }
            }
        }

        ExecuteBFS(ref area, ref blocks, ref starts, ref goals);
    }

    (int, int) AddTuple((int, int) first, (int, int) second)
    {
        return (first.Item1 + second.Item1, first.Item2 + second.Item2);
    }

    void ExecuteBFS(ref int[][] area, ref GameObject[][] blocks, ref List<(int, int)> starts, ref List<(int, int)> goals)
    {
        for (int s = 0; s < starts.Count; s++)
        {
            Queue<(int, int)> q = new Queue<(int, int)>();
            q.Enqueue(starts[s]);

            while (q.Count != 0 && q.Peek() != goals[0])
            {
                (int, int) cor = q.Dequeue();

                for (int i = 0; i < moves.Length; i++)
                {
                    (int, int) newCor = AddTuple(cor, moves[i]);
                    if (area[newCor.Item1][newCor.Item2] == 3)
                    {
                        //showPath
                        goals.Remove(newCor);
                        if (goals.Count == 0)
                        {
                            //stats
                            return;
                        }
                    }
                    else if (area[newCor.Item1][newCor.Item2] == 0)
                    {
                        //coordinate in process
                        blocks[newCor.Item1 - 1][newCor.Item2 - 1].GetComponent<Block>().SetState(5);
                        area[newCor.Item1][newCor.Item2] = 5;

                        q.Enqueue(newCor);

                        //delay
                        MyDelay(0.01f);
                        //coordinate visited
                        blocks[newCor.Item1 - 1][newCor.Item2 - 1].GetComponent<Block>().SetState(4);
                        area[newCor.Item1][newCor.Item2] = 4;
                    }
                }
            }
            //stats
        }
    }

    public static void MyDelay(float seconds)
    {
        DateTime dt = DateTime.Now + TimeSpan.FromSeconds(seconds);

        do { } while (DateTime.Now < dt);
    }

```

This is my Block script:

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

public class Block : MonoBehaviour
{
    public Material[] materials;
    //0 - empty
    //1 - wall
    //2 - start
    //3 - goal
    //4 - visited
    //5 - current
    public int state;

    void Start()
    {
        state = 0;
        GetComponent<MeshRenderer>().material = materials[state];
    }

    void OnMouseDown()
    {
        SetState(Area.selectedState);
    }

    public void SetState(int s)
    {
        state = s;
        GetComponent<MeshRenderer>().material = materials[state];
    }
}

```

When I start the BFS search, the whole Unity editor freezes. After some time depending on the delay argument, it starts responding and the visited planes are all colored. But it won't color them one by one as they are visited.

Where is the problem?

# Answer
> 0 votes
Your code is written under the assumption that the player can see directly into the memory of the program as it's running. So as long as you change a variable, the player should be able to immediately observe that change, like if you'd flipped a physical card on the table in front of them.

Games don't work that way. If we want a player to see something change in our world, we need to draw it to an image and put that image on the player's screen first. That takes some work from the CPU to initiate. And the CPU can't do that work if it's busy doing something else.

A typical game loop looks something like this, in a simplified model:

1. Process window messages - this is what keeps the application from hanging, and allows it to read user input provided from the OS
2. Update the game state, running any per-object update scripts
3. Render the resulting frame and present it to the screen
4. Sleep until it's time for the next frame

This most often runs single-threaded, and that's the case for the Unity game loop too. (Even systems that use threading typically use it to "go wide" in a single step, like running multiple non-conflicting state updates in parallel in step 2, while still finishing all step 2 work before taking a state snapshot to render in step 3)

So, as long as you're keeping the CPU busy in step 2, it never gets to step 3, so you never get to see an intermediate state rendered. And it also never gets back to step 1, which is what makes the app go unresponsive until your script finishes its work.

The culprit is your `MyDelay` function:

```
public static void MyDelay(float seconds)
{
    DateTime dt = DateTime.Now + TimeSpan.FromSeconds(seconds);
    do { } while (DateTime.Now < dt);
}

```

This is what's called a "Busy Wait" - it tells the CPU to sit there checking and re-checking the time, burning millions of cycles doing nothing useful at all, until it's allowed to continue on to the next line of code. You've temporarily suspended any real processing and turned this CPU core into a space heater.

(There are times when a busy wait is appropriate, when you think you'll very likely be waiting less time than it takes to sleep and wake a thread. A busy loop running for a hundredth of a second as you have here is *never* a good idea, and you should throw away any tutorial that told you to do that)

Because you've kept this thread busy this whole time, it's not allowed to exit step 2 and continue on to step 3, rendering your changes for the player to see them, until the whole routine has finished. At that point it shows only the finished state.

The better way to do something like this in Unity is to use Coroutines. This is a function that can run *partially*, then `yield` control flow back to the code that called it, so the CPU can finish the rest of step 2 and draw it in step 3. Then, in the next iteration of the game loop, the calling code can resume your coroutine right where it left off, and continue until the next `yield`. In this way it takes turns with all the other work needed to update and render your scene, rather than hogging the CPU to itself until it's finished.

Here's an example of what that could look like. Along the way I also cleaned up some issues:

* Used a descriptive enumeration instead of magic numbers to define the different tile states
* Swapped empty and wall so we get the border around the map for free from default initialization
* Used the built-in `Vector2Int` type instead of a tuple that needs a new add method defined
* Reduced the number of temporary collections allocated during the search

```
public class BFS : MonoBehaviour
{
    public enum TileState {
        Wall,
        Empty,
        Start,
        Goal,
        Visited,
        Current
    }

    static readonly Vector2Int[] MOVES = new Vector2Int[] {
        Vector2Int.right, Vector2Int.up, Vector2Int.left, Vector2Int.down
    };

    public float delayPerStep = 0.01f;

    TileState[,] InitializeSearchSpace(Block[,] blocks, Queue<Vector2Int> startingPoints, out int goalCount) {
        goalCount = 0;

        int width = blocks.GetLength(0);
        int height = blocks.GetLength(1);
        TileState[,] area = new TileState[width + 2, height + 2];

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < width; y++) {
                TileState state = blocks[x, y].GetState();
                switch (state) {
                    case TileState.Start:
                        startingPoints.Enqueue(new Vector2Int(x + 1, y + 1));
                        break;
                    case TileState.Goal:
                        goalCount++;
                        break;
                }
                area[x + 1, y + 1] = state;
            }
        }

        return area;
    }

    IEnumerator RunSearch(Block[,] blocks, TileState[,] area, Queue<Vector2Int> openSet, int goalsRemaining) {

        float timeBudget = Time.deltaTime;

        while (openSet.Count > 0 && goalsRemaining > 0) {
            var tile = openSet.Dequeue();

            foreach(var move in MOVES) {
                var next = tile + move;
                switch(area[next.x, next.y]) {
                    case TileState.Wall:
                    case TileState.Visited:
                        continue;
                    case TileState.Goal:
                        goalsRemaining--;
                        break;
                }
                blocks[next.x - 1, next.y - 1].SetState(TileState.Current);

                timeBudget -= delayPerStep;
                while (timeBudget <= 0f) {
                     yield return null;
                     timeBudget += Time.deltaTime;
                }

                blocks[next.x - 1, next.y - 1].SetState(TileState.Visited);
                area[next.x, next.y] = TileState.Visited;

                openSet.Enqueue(next);
            }
        }
    }

    public void BreadthFirstSearch(Block[,] blocks) {
        var openSet = new Queue<Vector2Int>();

        var area = InitializeSearchSpace(blocks, openSet, out int goalCount);

        StartCoroutine(RunSearch(blocks, area, openSet, goalCount));
    }
}

```

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


title: Rotating fps rigid body on the Y axis

text:
# Question
Title: Rotating fps rigid body on the Y axis
I'm currently attempting to make a first person character using a rigid body. I am aware that the character controller exists, but I believe my game will be very physics based so it's better if my character is a rigid body. I currently can walk, and rotate the camera up and down with the mouse. I am now trying to rotate my character left and right with the mouse, but this requires me to rotate my rigid body, not just the camera. Here's my code so far.

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

public class Player : MonoBehaviour
{
    [SerializeField] float walkSpeed = 3;
    [SerializeField] float cameraSpeed = 3;

    Vector3 direction;
    float cameraX;

    Rigidbody myRigidBody;
    [SerializeField] Camera myCamera;
    // Start is called before the first frame update
    void Start()
    {
        myRigidBody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        cameraX = -Input.GetAxis("Mouse Y") * cameraSpeed;

        myCamera.transform.Rotate(new Vector3(cameraX, 0, 0));
    }
    void FixedUpdate()
    {
        myRigidBody.AddRelativeForce(direction * walkSpeed, ForceMode.Acceleration);
    }

```

I *believe* that the rigid body function I should use to rotate left and right is MoveRotation (I'm still new to rigid bodies), but I'm open to ideas. MoveRotation uses Quaternions, and I have no idea how to translate my mouse axis into a quaternion.

Here's my question, How do i implement the Y rotation for my rigid body first person controller? Should I use torque, or somehow directly alter my rotation without using forces? Also, How do i translate the Mouse Axis into something I can use to rotate something? thnx.

Edit:

I tried adding this line of code:

```
myRigidBody.MoveRotation(Quaternion.Euler(0, mouseX * cameraSpeed, 0));

```

for some reason it has no effect on my character at all, but I feel Like it's on the right track. Why isn't this working?

Edit 2:

I added this line in Update:

```
rotateDirection = new Vector3(0, Input.GetAxis("Mouse X"), 0);

```

And this line in FixedUpdate:

```
myRigidBody.MoveRotation(Quaternion.Euler(rotateDirection));

```

Now when I move my mouse (I commented out my camera up and down movement to test) my character moves left and right for a tiny bit, but jitters back to it's original position, so It feels like I'm fighting it. The rotation in the inspector jitters in the correct direction, negative if i move the mouse left, positive if right, but only for a very small amount, 1.45 being the most, and then reverts back to zero. Also, it doesn't rotate smoothly, but jitters. Anybody know whats going on?

Edit 3: changed it from addforce to addrelativeforce because that make it move forward based on local coordinates not global.

# Answer
> 1 votes
Your code assumes that `MoveRotation(rot)` takes an *increment* to *add* to the current rotation. That's not what it does. It takes an *absolute* orientation to move *to*, completely discarding the previous orientation.

So by passing just the travel of the mouse in this frame, your rotation will snap back to zero yaw anytime the mouse stops moving.

It looks like you want something more like this, where you accumulate your desired yaw frame over frame:

```
[SerializeField] float rotationSpeed;

float _yaw;
Rigidbody _body;

void Update() {
    _yaw = (_yaw + Input.GetAxis("MouseX") * cameraSpeed) % 360f;

    _body.MoveRotation(Quaternion.Euler(0, _yaw, 0));
}

```

---
Tags: unity, rotation, rigidbody, first-person-shooter, character-controller
---


# Question
Title: How does a subpass dependency guarantee the layout transition of a swapchain image happens after presentation engine finish reading the very image?
I'm going through vulkan-tutorial:

https://vulkan-tutorial.com/Drawing\_a\_triangle/Drawing/Rendering\_and\_presentation

And I found something weired:

How does this subpass dependency guarantee the layout transition(from UNDEFINED to COLOR\_ATTACHMENT\_OPTIMAL)of swapchain image happens after present engine finish reading(or working on) this swapchain image?i.e.Layout transition of this swapchain image bewteen external and subpass0 guarantees to happen after the imageAvailableSemaphores is signaled.

I did find some explanations on this topics from this blog:

http://themaister.net/blog/2019/08/14/yet-another-blog-explaining-vulkan-synchronization/

> External subpass dependencies Render passes in Vulkan have a concept of EXTERNAL subpass dependencies. This is arguably the most misunderstood aspect of Vulkan sync. I’d like to dedicate a section to this, because too many developers are lured into using it in cases where it’s not terribly useful and very likely to cause bugs.
>
> The main purpose of external subpass dependencies is to deal with initialLayout and finalLayout of an attachment reference. If initialLayout != layout used in the first subpass, the render pass is forced to perform a layout transition.
>
> If you don’t specify anything else, that layout transition will wait for nothing before it performs the transition. **Or rather, the driver will inject a dummy subpass dependency for you with srcStageMask = TOP\_OF\_PIPE\_BIT. This is not what you want since it’s almost certainly going to be a race condition.** You can set up a subpass dependency with the appropriate srcStageMask and srcAcessMask. The external subpass dependency is basically just a vkCmdPipelineBarrier injected for you by the driver. The whole premise here is that it’s theoretically better to do it this way because the driver has more information, but this is questionable, at least on current hardware and drivers.
>
> There is a very similar external subpass dependency setup for finalLayout. If finalLayout differs from the last use in a subpass, driver will transition into the final layout automatically. Here you get to change dstStageMask/dstAccessMask. If you do nothing here, you get BOTTOM\_OF\_PIPE/0, which can actually be just fine. A prime use case here is swapchain images which have finalLayout = PRESENT\_SRC\_KHR.
>
> Essentially, you can ignore external subpass dependencies. Their added complexity give very little gain. Render pass compatibility rules also imply that if you change even minor things like which stages to wait for, you need to create new pipelines! This is dumb, and will hopefully be fixed at some point in the spec.
>
> However, while the usefulness of external subpass dependencies is questionable, they have some convenient use cases I’d like to go over:

> Automatically transitioning swapchain images Typically, swapchain images are always just used once per frame, and we can deal with all synchronization using external subpass dependencies. We want initialLayout = UNDEFINED, and finalLayout = PRESENT\_SRC\_KHR.
>
> **srcStageMask is COLOR\_ATTACHMENT\_OUTPUT which lets us link up with the swapchain acquire semaphore.** For this case, we will need an external subpass dependency. For the finalLayout transition after the render pass, we are fine with BOTTOM\_OF\_PIPE being used. We’re going to use semaphores here anyways.
>
> I also do this in Granite.

# Answer
> 0 votes
After days of struggling with spec,I found this stackoverflow post that perfectly solved my question:

> https://stackoverflow.com/questions/60339191/synchronizing-a-render-pass-layout-transition-with-a-semaphore-in-acquire-pres

---
Tags: vulkan
---


title: Head rotation according to weapon sight

text:
# Question
Title: Head rotation according to weapon sight
I have a 2D game and I'm working on head rotation with my newbie coding skills. My **Player** has child sprite object called `DefaultPistol` (which is the whole arm and pistol attached to it) and it has a `Weapon` script. The arm turns 360 (centered from the shoulder) in the scene.

What I need is for my player turn his `Head` wherever arm turns (the `Head` is also another child sprite object attached to Player like `DefaultPistol`) but not like rotating the head, I just simply want to mirror the head to face left or right.

I tried setting the head's x scale to 1 or -1, but it didn't work and I couldn't find what is the problem. (I also checked the inspector if I didn't attach anything, but everything is in order as far as I can see)

Here is my Weapon. You can see where I tried to implement this in `Flip`. How can I fix this?

```
public class Weapon : MonoBehaviour {

    public GameObject projectile;
    public Transform shotPoint;
    public float timeBetweenShots;
    private Animator cameraAnim;

    private float shotTime;
    private bool facingRight;
    public GameObject head;

    private void Start()
    {
        cameraAnim = Camera.main.GetComponent<Animator>();
    }

    private void Update()
    {   //this code paragraph here is calculating the shotPoint player rotation
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle + 90, Vector3.forward);
        transform.rotation = rotation;

        if (Input.GetMouseButton(0))
        {
            if (Time.time >= shotTime)
            {
                Instantiate(projectile, shotPoint.position, transform.rotation);
                cameraAnim.SetTrigger("shake");
                shotTime = Time.time + timeBetweenShots;
            }

        }

    }

    private void Flip(float horizontal)
    {
        if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
        {
            facingRight = !facingRight;
            Vector3 theScale = transform.localScale;
            head.transform.localScale = new Vector3();
            theScale.x *= -1;

            transform.localScale = theScale;
        }

    }

}

```

# Answer
You should use `SpriteRenderer`'s `FlipX` property.You dont need any kind of `Vector` scale operations just simply use `SpriteRenderer`'s builtin property

**Example**

```
public class CharacterHeadFlipScript : MonoBehaviour
{
    public SpriteRenderer characterHeadSpriteRenderer; // just drag and drop the sprite renderer of your character's head via editor

    void Update()
    {
        /*
         * First get the current mouse world position
         */
        Vector2 mouseScreenPosition = Input.mousePosition; // gets the current position of the mouse in screen space coordinates (Pixels)
        Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(mouseScreenPosition); //Converts screen space coordinate to world coordinates

        /*
         * Get the character's body position
         * Im asuming you add this script to the character you want to flip its head
         */
        Vector2 characterPosition = this.transform.position;

        /*
         * Check if mouse is on the right side of your character or on the left side
         * I will assume that your character's default head direction is the right side
         */
        if(mouseWorldPosition.x > characterPosition.x) // mouse on the right side of the character
        {
            /*
             * This means character should look to default direction(right side) so we should disable FlipX of the SpriteRenderer
             */
            characterHeadSpriteRenderer.flipX = false;
        }
        else // mouse on the left side of the character
        {
            /*
             * This means character should look to opposite direction(left side)
             */
            characterHeadSpriteRenderer.flipX = true;
        }

    }

}

```
> 2 votes

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


# Question
Title: How to process events as well as do OpenGL rendering using multithreading?
I am working on a very complicated graphics rendering, using OpenGL, and it is very time consuming, in the sense that it creates a delay in the event handling, of my application to an extend that, the OS will think my application is freezing ! Therefore, I was thinking of running two threads, one for the OpenGL rendering and the other for event handling. But, I dont think this is possible for my current framework that I'm using!

Basically, I'm using SDL 2.0 to set up an OpenGL context, and then using vertex and fragment shaders to do the rendering.

Code:

```
// Initialize OpenGL context
// Set up VAO, VBO, compile vertex/frag. shaders, link, use program  etc.
//
bool run = true;
SDL_Event e;
while(run)
{
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       render(); // Complicated rendering :(
       SDL_GL_SwapWindow(window);
       while(SDL_PollEvent(&e))
       {
             switch(e.type){
                   case SDL_QUIT:
                        run = false;
                        break;
             }
       }
}

```

As you might realize if `render` is slow, then event handling will lag. This might crash my application !

The SDL library wants everything in the same thread I guess. If I move the event handling part to another thread, then OpenGL won't render anything! Similarly, if I move the OpenGL based `render` function to another thread, still it won't render anything!!! In fact event handling is a must for SDL in particular and to the OS in general.

What is the practical remedy to this issue?

# Answer
> 1 votes
OpenGL is not multithreaded. All your GL commands must run in the same thread in which the GL context was created: it is not shareable between threads.

Any attempt to share the context between threads will lead to undefined behaviour.

Your high ms/frame time is due to everything being done on a single thread.

I propose two practical solutions to your problem:

1. Create a dedicated graphics thread.
2. Offload all other work to other threads, and keep graphics on the main thread.

Generally this is 6 and half a dozen. Just choose one and go for it.

But as a general guide for the first solution:

When your program starts, spool up a thread for graphics. Refactor all your rendering code into a renderer class, that can be called from your rendering thread function.

The renderer handles window and context creation & destruction, and all rendering calls. It should also keep track of renderable "objects", which will be modifiable by the main thread. This means the renderer will need to be made "thread-safe" via mutexes.

Your renderer API should look something like this:

```
class Renderer
{
public:
    Renderer(void) { }
    virtual void addEntity(entity* e) = 0;
    virtual void removeEntity(entity* e) = 0;
    virtual void clearAllEntities(void) = 0;
    virtual void init(void) = 0; // creates window/context
    virtual void render(void) = 0; //performs actual drawing
    virtual bool shuttingDown(void) = 0;
    virtual void shutDown(void) = 0;
    virtual ~Renderer(void) { }
}

```

This is known as the *Interface* for the renderer. You will *implement* that interface yourself. Your main thread will call the add/remove/clear functions.

Your thread function should look like this:

```
int threadFunc(void* arg)
{
    Renderer* renderer = std::dynamic_pointer_cast<Renderer>(arg);
    renderer.init();
    while (!renderer->shuttingDown())
    {
        renderer->render();
    }
    return 0;
}

```

Now the thread will just draw as fast as it can, whilst your main, and other, threads do other processing.

Once you do this, that thread, and ***only*** that thread will perform GL calls.

If you want to load resources (mesh data, textures etc) to the gpu, you either need to load it first into memory, then let the renderer handle the upload to gpu ram, or have a seperate gl context specifically for loading resources on another thread. However, if you choose the latter, then you need to make fool around with making contexts "current", which is a headache too, so some thought is required on that part.

I won't say much more on this, because, quite honestly you could write a book on this subject. The general idea is the same as Ghostbusters: *Don't cross the streams!*

Keep all your GL code to a single thread, but there are no restrictions on which thread that is.

# Answer
> 1 votes
From the Blue Book (OpenGL Superbible 7th ed., pp. 662f.):

You can have multiple contexts and share data between them, but that isn't very effective. The approach sketched in the other answer (one render thread - mutliple data generation threads) is surely the best practice.

You can have buffer objects to your application's needs and pass pointers around between threads and synchronize between threads and OpenGL calls. See OpenGL documentation for its synchronization functionalities.

You can also create commands for OpenGL by packing parameters into buffers and signal the main thread to turn them into OpenGL calls. This approach builds data structures in the generating threads and sends them to the main thread for analysis, to choose between varying functionalities and to hand them over to OpenGL. See glDrawElementsInstancedBaseVertexBaseInstance() to find out which data can be parametrized in that way.

The rest is programming :-)

---
Tags: opengl, sdl2, multithreading
---


# Question
Title: How to deal with data that needs to be accessed by all objects?
I have a `World` class that currently only has one instance. It has data and methods that need to be accessed by all other game objects. Right now I'm hardcoding a reference to the global variable `world` in all of my methods, and this doesn't seem to be the right approach.

Another idea I tried was a dependency-injection-esque approach, where each object stores its own reference to the `world` object, but this clutters memory with unnecessary references, so I don't think this is the right approach either.

Another approach I tried was passing `world` as an argument directly into the method call, but this led to repetitive code as I was constantly passing `world` into any function that needed it.

A bit of research hasn't worked for me because it's hard to summarise my problem into a few words that can return Google search results. It seems this isn't a problem in the majority of applications, so I'm wondering if this is mainly a gamedev situation.

What is the best way to solve this problem?

# Answer
You are looking for an alternative to dependency injection. I'll offer you a perspective shift: The game world is external. You are just sending and receiving messages. It is not a great idea to have a dependency on something external that you can't control.

*Wait. We are making games. And a game is a piece of software, it isn't a portal to another world. Or is it? (cue Jake Chudnow - Moon Men (instrumental), extended version to make sure it lasts while you read).*

*Hey Gamedev, Thereot here.* And how do you handle things external to your game? For example, game input.

---

You need to access your `input` from your update code. And we want that code well delimited. Remember, don't mix concerns or responsibilities.

**However, we have this problem of passing things around**. We could have singletons, or do dependency injection. I have here a different solution: The `input` service will *send messages*.

That is, the game objects will have a sort of "inbox". A notification mechanism. *For example, the service calls a method on them, or sets a property.*

Since not every game object needs input, the service could have list of game objects that should receive the messages (call them observers, listeners, subscribers, fan club).

This approach can be applied for any services that deals with an external (or a let-us-pretend-external) input device. For example, we can use to handle actual messages from the `network`, or to handle collisions in our `physics` simulation.

---

But how would you handle output?

There are some services that that do output (`physics`, `network`, `graphics`, `audio`), and you need to tell them what to do. For example, you tell to the `physics` service to apply a force or a velocity.

**However, we have this problem of passing things around, again**. Well, I have another box for you: an "outbox". The game objects could publish messages for the services to pick up, where they describe what they want the service to do.

Those services already have a list of game objects that need to interact with them. So they could go over the list, and pick messages from the "outbox" of each game object.

*We have a name for a message that describe what to do. We call it a Command.*

---

> I need to access terrain data to do a lot of actions, based on the object's current position. How do I store and access this data?

There are a lot of spatially aware logic that makes sense to handle as external to the core logic of the game. For example, you may need to find nearby game objects, or find a path to navigate the world. There are also collisions, and so on. And you would find a good idea to have dedicated data structures to handle that (e.g. grids, quad-trees, etc).

Perhaps for you, terrain is physics. For example, in a 3D game we could have a raycast downwards to check if the player avatar is on the ground, *and what kind of ground*. Or perhaps for you terrain is its own thing. For example, in a 2D game, you probably have a tile-map (or perhaps a texture) that you can query with some coordinates to get terrain information. *Or it is a voxel game, and you just query the voxel.*

When there is a collision (including the raycast contacting a different object), or when a game object moves to another tile, you can *send a message*.

---

> What is the best way to solve this problem?

I don't know about best. But, the command pattern is a good counterpart for dependency injection.

Let us say you have a class that has a dependency. Your class calls a method on the dependency, and gets a return value. Ok, we are going to flip that around. Instead of calling a method we publish a command. Some time later, the "dependency" takes the published command. When it has a result, it calls a method in our class (or perhaps the command object includes a callback), which is the opposite of what we had before. Somehow we had your class call the other, now the other calls yours. The return value became a parameter. We left synchronous and arrived at asynchronous. And we left coupled and arrived at decoupled.

In fact, there could be one object taking the commands, or there could be multiple, or none.

This idea is a way to bring back the concept of passing messages that we had at the origins of object oriented programming.

*Let us be honest, this is not free. You would be instantiating messages. If they are reference types, you would be making garbage, unless you pool them. As per dependencies, we have moved from A depends on B, to A and B depend on M, where M is the message type.*

Of course, that is not the only way. I'll mention that you can use an actor model. An actor has in and out channels on which they do push and pull operations to communicate with other parts of the software (*cough* queues *cough*). In this case if you want something to happen in a different part of your system, push a message to the appropriate channel, on the other side an object can pull it some time later. *"Queues decouple spacetime." -- Kain0\_0 (source).*

*Make the above thread-safe, and parallelism becomes easier.*

Since, Entity-Component-System has popularity in game development, I'll also mention that if you are doing an ECS sending a message could mean attaching a component to the entity for some another system to read it.

By the way, if you want, you can use an actual external device for communication. For example, one part writes to a file, and the other reads from the file. Hopefully a memory mapped file. Or it could be a network connection (and then you can start thinking about how to do a distributed system).

---

Remember that you can think about your architecture in terms of internal and external things, and passing messages between them. Then worry about the mechanism for that communication. Plus, often you can flip those around.
> 1 votes

---
Tags: architecture, software-engineering, gameobject, oop, objects
---


# Question
Title: How to render thin glass with proper refraction?
I want to render thin bumpy glass with refraction. But it offsets too much(look at the black frame of the glass). Looks **thick**.

How to do thin glass refraction properly? Or is it possible to exclude object(e.g. the black frame) from refraction?

# Answer
> 0 votes
I would look into the `Refraction Depth Bias` parameter of the material you are using. It is mentioned in the Unreal Engine documentation.

# Answer
> 0 votes
I would suggest parameterizing several of the pins of bumpyGlass, especially those that are currently fed by constants, instantiate the material to the shower door, and play with the values in real time. I wonder if lowering the value for metalness would do the trick.

This is how: In the material editor, cut the connection to the constant. Right-click on the pin and promote the pin to parameter. Right-click on the mat in the content browser to create an instance. Drag the instance to the shower door. Double-click the instance in content browser to access the sliders. I created an eyeball in Unreal, and jockeying the sliders while observing in real time was the only sensible way to arrive at reasonable values.

You definitely can apply a different mat to the door frame with a seperate (or disabled) refraction, and, since it's black, you could exclude it from being affected by Unreal's lighting engine entirely (left panel in Material Editor). I can tell you how to break a single model into regions that will take seperate materials in Blender and port to Unreal, but unfortunately I don't know how to do this solely in Unreal.

Of course, you can scale the door to make it thinner, but I don't think that will give you the desired results.

This is my first ever answer on Stack Exchange. If I have suggested the obvious (or the useless), it was not my intent.

---
Tags: shaders, rendering, unreal-4
---


# Question
Title: How do I set the opacity of a Button to 0? (Unity)
I'm trying to hide a button when you click that button (I meant setting the opacity to 0, not disabling the game object of the button). What the button does is it loads a scene async. If I disable the game object I won't be able to load the scene async. Any way to set the opacity of the button?

Sorry if the question is already asked as I wasn't able to find any questions related to this.

# Answer
> 0 votes
You can set the alpha-value of the renderer of the button to zero. When your button has a text or any other child-nodes, then those also need to be made transparent:

```
foreach(var renderer in GetComponentsInChildren<CanvasRenderer>()) {
    renderer.SetAlpha(0.0f);
}

```

Another way to make a button disappear without also disabling any of the scripts on it is by setting its scale to `0:0:0`. This will also make all its children disappear:

```
GetComponent<RectTransform>().scale = Vector3.zero;

```

However, when your problem is that you need a script which is on the button to run after the button was removed, then I would recommend you to better separate your UI logic from your game logic. The components of an UI element should only govern the UI element itself.

I assume you are building some kind of main menu? In that case I would create one component `MainMenu` and assign it to an invisible gameObject in the scene. I would then give it a method `public void StartGame()` which starts the game (as well as methods for everything else the player can do on the main menu). I would then create a "Start Game" button and then use its OnClick assignment in its inspector to make it call the `MainMenu.StartGame` method of the invisible gameObject. The advantage of this pattern is that you can easily add more ways to call that StartGame method. Like have a keyboard key to call it or call it automatically based on a timer when the player does nothing.

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


title: How do I create an infinite tower

text:
# Question
Title: How do I create an infinite tower
So I had this idea of creating a 2D game where the player would just climb a tower the furthest he could.

I do already have a camera and a scene class somewhat ready, but I'm not sure how I would add the side sprites and make it so I dont use all the memory on the 10th update. Could anyone please shed some light on this?

# Answer
> 1 votes
While the player ascends the tower, delete the tower sections below the camera viewport and generate new tower sections above the camera viewport.

Continuously allocating and deallocating memory might result in memory fragmentation, which could become a performance problem. Considering that your game idea seems rather light and simple, this might not actually be a real problem. But when it does become a problem, you can solve it by not discarding but reusing the deleted tower section. Move it from the bottom to the top and then use your generation algorithm to remodel it.

But now there is of course the question about what you do if the player decides to not move up but down the tower. In that case you would need a way to re-generate old tower sections in the same way the player saw them before.

Many games take the easy way out here and just don't allow the player to go back. The screen only ever scrolls up, and when the player-character crosses the lower edge of the screen, that's a lose-condition.

But if you don't want that, then you need a section generation algorithm which is deterministic. There are several approaches to this.

* Re-initialize your random number generator for each chunk. You can calculate those "chunk seeds" by determining a constant "run seed" at the beginning of each run, then create a hash value of the "run seed" plus the y-coordinate of the chunk you want to generate and use that as the "chunk seed". (But keep in mind that the first couple numbers generated by many random number generators right after seeding are of very low quality)
* Save the state of your RNG for each chunk you generated. That way you can restore the RNG to a prior state. The RNG states should consume a lot less memory than the chunks themselves (assuming your chunks aren't tiny).
* Generate the random input for each chunk by sampling a noise pattern. Here is a very interesting GDC talk explaining this technique.

# Answer
> 0 votes
There are two ways how i implement this behaviour on my games

**Using physics**

I would create big collider box at the bottom of the screen when this collider box touches the sprites in your case Vertical and horizontal walls it would destroy them.

**Pooling**

I would create a class which is responsible for registering and removing existing objects in my game. In this case i would add register my sprites and destory them using a max distance parameter

**Example**

```
public class SpriteGarbageCollector
{
    public float removeDistance;
    private List<Object> _objects;
    private Player _targetPlayer;

    public SpriteGarbageCollector(Player player)
    {
        _targetPlayer = player;
    }

    public void Register(Object newObject)
    {
        _objects.Add(newObject);
    }
    public void Tick()
    {
        foreach(Object object in _objects)
        {
            if (removeDistance <= Distance(object, _targetPlayer))
            {
                Destroy(object);
            }
        }
    }
}

```

These two way can provide you the garbage collection you need so you can just focus on your desing to how you should spawn your objects

---
Tags: c#, monogame, game-mechanics
---


# Question
Title: How to best simulate the space in a boxing game to account for footwork and angles?
When trying to prototype a (top-down, so far) boxing simulation I've run into a huge roadblock with trying to set the space in which the boxers will fight, because it's important for the fighters' reach to be a factor in setting the distance of the fight, which is easier in a continuous space. On the other hand, they should also be able to cut angles where the opponent is out of position when compared to themselves (like Tyson did below), which would probably be easier to represent in a discrete space, like a hex, but the rotation would be very rigid. The difference between stances would also be more difficult to represent in a discrete gamespace, since foot position is entirely different, as well as the reach.

I've been coding this in Godot, so it would not be that much more difficult to do a continuous space and use their signals and collision shapes to do it, my only concern being the computational cost of actions would be raised with the amount of positions available, so I'd rather have an abstraction.

Is there any obvious solution I'm missing? Some way both things can be represented (in a way an AI can easily interact with) without unnecessary granularity? Or a way to do it in a continuous space that wouldn't greatly increase computational overhead with the massive array of new positional possibilities?

# Answer
*I'll be referring as agent to the opponent controlled by the game. And agent controller to the code that, well, controls the agent.*

---

You can have an abstraction for your agent controller, and still allow continuous movement. To do that, you would have code to **translate between those representations**.

That is, the agent controller would understand the game in abstract way. One that makes sense from the point of view of the agent. You would translate the parts of the world that are relevant to the agent controller to that representation. Then the agent controller makes its decision. And that decision needs to be translated to the world representation, and executed (playing animations, moving physics objects, and so on).

---

For the abstract representation, I suggest you start with a polar system, expressed in angle (relative bearing) and distance (from the agent). And yes, those are still too many possible values, so make them discrete.

For example, you will represent distance as "near", "medium" and "far", that would translate to ranges of distance. And represent the angle as "front", "rear", "port", "starboard" (or however you want to slice them and name them).

Since those are ranges, to translate, you check on what range does the distance and position fall into, and give that to the agent controller.

By doing that, the agent controller logic can work with a finite, discrete, and well defined set of position information.

---

The agent controller would have an internal state, and you would call into it when needed… And it gives you a command.

I suggest to make your commands as descriptive as you can. They could express things such as "Punch", "Move away", or "Keep distance", and so on. And then we need to translate that.

How much distance does it has to move exactly, and how much does it has to rotate to punch the opponent, and what animation to play… Those aren't concerns of the agent controller. The agent controller does not have the needed information to them, anyway. Instead, you would have code that does the right thing depending on the command.

*By the way, the commands need not to be strings. You can, for example, have a custom command class to represent them, so you can include parameters. You may even create a class for each possible command, and put in that class the logic to execute it. Given that we are talking Godot, I'd make a node for each command, and put on that node a function to execute the command. Then you can get the node by name from the scene tree and call the function on it. Plus, you can package that logic along with the agent in a scene.*

---

There are things you need to report to the agent controller. Such as success in executing the actions. Action executed by other agents (or the player) on it. Collisions, etc.

You can imagine that the agent controller issues a "Taunt" command, and that triggers and animation, when completed you tell the agent controller that the taunt completed. Or perhaps, the player punches the agent, and you notify that to the agent controller.

Then the agent controller updates its internal state, and gives you new commands.

You could have more complex commands… Er... Can't think of something for a boxing game. But imagine it is a military shooter, and there is a "Go to cover" command. To execute it, there is another system that figures out where is cover and how to get there, then the agent moves and plays corresponding animations, and you also tell the agent controller when that is completed.

---

So you want the agent to get close to the opponent. It will move. But you also need to play animations. You would have a direction for the motion, and from that you pick the corresponding animation (or blend of animations) to play.

Then, when the agent is in range, you want the agent to punch. Again, you are going to play the corresponding animation. Perhaps that could mean using inverse kinematics to make sure it makes contact. In fact, if you care enough about foot positioning, you can use inverse kinematics to tell the rig "this foot go there, and this foot go there".
> 1 votes

---
Tags: 2d, rotation, godot, grid, simulations
---


title: My timer won't work in Unity

text:
# Question
Title: My timer won't work in Unity
In my game, you can spawn a cube by clicking. After 10 seconds I want the cube to disappear. That's what I'm trying to do in my code but it won't work:

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

public class circleThing : MonoBehaviour
{
    public GameObject circle;
    public GameObject block;
    public float time;
    void Start() {
         Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         temp.z = 5f;
         transform.position = temp;
         if (Input.GetMouseButtonDown(0)) {
             StartCoroutine(timer());
             Instantiate(block, temp, Quaternion.identity);
         }
         if (time >= 10) {
             Destroy(block);
         }
    }
    void Update()
    {

    }
     IEnumerator timer(){

        while (true)
        {
            Debug.Log(time);
            yield return new WaitForSeconds(1);
            time++;
        }
    }
}

```

What am I doing wrong? I get the error: `Destroying assets is not permitted to avoid data loss.`

# Answer
> 0 votes
In essence, **you are not using `Instantiate` correctly**. You pass in a `GameObject` (and other data) and it returns a copy.

In your code, you are not instantiating an object and setting it to `block`, you are instantiating a copy of `block` (which is nothing at this point I assume since you are not assigning anything to it in your code snippet) and not storing the returned `GameObject` in anything:

```
Instantiate(block, temp, Quaternion.identity);

```

What you need to do is create a variable that stores a `Prefab` cube that you then `Instantiate` and assign to block:

```
public GameObject circle;
    public GameObject CubePrefab; // use the Inspector to assign a cube prefab here
    public GameObject block;
    public float time;
    void Start()
    {
         Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         temp.z = 5f;
         transform.position = temp;
         if (Input.GetMouseButtonDown(0))
         {
             StartCoroutine(timer());
             block = Instantiate(CubePrefab, temp, Quaternion.identity);
         }
         [...]

```

or you can create a primitive `Cube` and manipulate its position/rotation:

```
[...]
if (Input.GetMouseButtonDown(0))
{
    StartCoroutine(timer());
    block = GameObject.CreatePrimitive(PrimitiveType.Cube);
    block.transform.position = temp;
    block.transform.rotation = Quaternion.identity;
}
[...]

```

As for your destroy method, unless you are trying to learn `Coroutine`s, I would suggest you just use the built-in delay parameter in the signature for the `Destroy` method (as you already determined), which you would do immediately after creating the object:

```
block = Instantiate(CubePrefab, temp, Quaternion.identity);
Destroy(block, 10);

```

or alternatively you can do something like this:

```
public float blockCreateTime;
[...]
void Update()
{
    [...]
    block = Instantiate(CubePrefab, temp, Quaternion.identity);
    blockCreateTime = Time.time;
    [...]
    if (blockCreateTime - Time.time > 10)
    {
        Destroy(block);
    }
    [...]
}

```

I don't like that way of doing it, just letting you know that you can track time without creating a "timer" `Coroutine`.

**As a little disclaimer**, I haven't tried doing any of the above, that's just how `Instantiate` and `GameObject.CreatePrimitive` work. Also, in case you didn't know, `Time.time` will return how long the game has been running, so the check above subtracts the current duration the game has been running from the duration stored when you created the `block` to see if it is greater than the threshold (in this case 10s).

# Answer
> 0 votes
So what I did is just this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 using UnityEngine.UI;

public class circleThing : MonoBehaviour
{
    public GameObject circle;
    public GameObject block;
    public float time;
    GameObject newBlock;
    void Start() {

    }
    void Update()
    {
      Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         temp.z = 5f;
         transform.position = temp;
         if (Input.GetMouseButtonDown(0)) {
             newBlock = Instantiate(block, temp, Quaternion.identity);
         }
             Destroy(newBlock, 10);
    }
}
```

---
Tags: unity
---


# Question
Title: Gun clipping through arm during third-person animation
I have been setting up a Blend Tree for motion animation in Unity. I'm using Root Motion for now. I parented the gun to the root of the player and then I use `OnAnimatorIK` to lock the two hands in position.

The overall looks and feel is great by my standards. The only thing I am disappointed about is the butt of the gun clips through the character's upper arm when running.

Is there a way to crop this in the game? I'd like to avoid going into a 3d Editor and making it two separate meshes which I could then I guess somehow disable. I'm hoping there is a better way to handle this situation.

Also I wonder if the gun being parented to the Root player object is wise. I had tried parenting to the 'right-hand' bone but this made the gun point upwards about 45° and looked silly.

# Answer
> 1 votes
Basically thanks to DM Gregory's help, I have managed to fix it very simply.

I already had a 'pivot' object as a parent to my Gun. This itself is child directly of players root.

All I had to do was drag its local position forwards a little and it stopped the problem. In doing this I noticed dragging it upwards also looked a little better. Now it looks pretty great in all animations. Not perfect but decent enough for my first try at making such animations.

Hope this helps someone in future.

---
Tags: unity, animation, mecanim
---


# Question
Title: How can I reference for a two cameras on prefab through script?
I have this script for controlling the cameras :

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

public class CamerasViewSwitch : MonoBehaviour
{
    public List<Camera> cameras = new List<Camera>();
    public string currentViewMode;

    // Start is called before the first frame update
    void Start()
    {
        if (cameras[0].enabled)
        {
            currentViewMode = "Third Person";
        }
        else
        {
            currentViewMode = "First View";
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            cameras[0].enabled = !cameras[0].enabled;
            cameras[1].enabled = !cameras[1].enabled;

            if (cameras[0].enabled)
            {
                currentViewMode = "Third Person";
            }
            else
            {
                currentViewMode = "First View";
            }
        }
    }
}

```

In the Assets, I have a prefab with two children's cameras that I want to use in this script.

In this screenshot to show what I mean, I dragged the prefab name Platform to the hierarchy to show where the cameras are. The script is on the object name Cameras Switch.

How do I get these two cameras from the prefab and using them in the script?

I'm using the Platform prefab with this script but the problem is when I'm starting the game the CamerasViewSwitch script is missing the two cameras I'm not to get/find them.

# Answer
Are you just looking for how to programmatically get the `Camera` objects that are not children of the `GameObject` your script is on?

If so, you'll need a way to determine specifically which object to look under, but if you can reliably assume there will only be 1 `GameObject` in the scene with the name "Platform", then something like this:

```
public GameObject Platform;
private Camera FirstPersonCamera;
private Camera ThirdPersonCamera;
private void Start()
{
    Platform = Platform ?? GameObject.Find("Platform");
    var cameras = Platform.GetComponentsInChildren<Camera>();
    FirstPersonCamera = cameras.FirstOrDefault(c => c.name == "First Person View Camera");
    ThirdPersonCamera = cameras.FirstOrDefault(c => c.name == "Third Person View Camera");
}

```

I've created variables to hold each camera so that you only have to do a lookup once in `Start()` and also so you can more reliably know which camera is which instead of relying on the order of the `Camera`s as children of "Capsule" (if you want to be even more confident, create Tags like "\[1st|3rd\] Person Camera" or something, assign them to the appropriate `Camera`s in the Prefab, and do a lookup on the Tag instead of the Name).

If you can't assume that there will only ever be 1 `GameObject` in the scene called "Platform", then you'll have to figure out how to get the reference of the correct one.

**EDIT:** This also assumes that the "Platform" prefab exists in the scene when `Start()` is executed (when the `GameObject` the script is on becomes active in the scene). If that is not the case, you'll have to create a function to assign the cameras after "Platform" is placed in the scene.
> 0 votes

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


# Question
Title: Double jump, without allowing two jumps after falling down a cliff
I created a script that allows the player to double jump, which works like a charm.

The problem is if the player walks off a cliff, they will still be able to jump twice. But that isn't how double jump works, right?

Can someone tell me how to make it so that if the player falls down a cliff, they will be able to jump only once?

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

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb;
    private Animator anim;

    private float movementInputDirection;

    public float movementSpeed = 10f;
    public float jumpForce = 16f;

    public int amountOfJumps = 1;
    private int amountOfJumpsLeft;

    private bool isFacingRight = true;
    private bool isWalking;
    private bool isGrounded;
    private bool canJump;

    public float groundCheckRadius;
    public LayerMask whatIsGround;

    public Transform groundCheck;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    void Start()
    {
        amountOfJumpsLeft = amountOfJumps;
    }

    void Update()
    {
        CheckInput();
        CheckMovementDirection();
        UpdateAnimations();
        CheckIfCanJump();
    }

    private void FixedUpdate()
    {
        ApplyMovement();
        CheckSurroundings();
    }

    private void CheckMovementDirection() //flips sprite
    {
        if (isFacingRight && movementInputDirection < 0)
        {
            Flip();
        }
        else if (!isFacingRight && movementInputDirection > 0)
        {
            Flip();
        }

        if(rb.velocity.x != 0)
        {
            isWalking = true;
        }
        else
        {
            isWalking = false;
        }
    }

    private void UpdateAnimations()
    {
        anim.SetBool("IsWalking", isWalking);
    }

    private void CheckInput()
    {
        movementInputDirection = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump"))
        {
            Jump();
        }
    }

    private void ApplyMovement() //player movement
    {
        rb.velocity = new Vector2(movementSpeed * movementInputDirection, rb.velocity.y);
    }

    private void Flip()
    {
        isFacingRight = !isFacingRight;
        transform.Rotate(0f, 180f, 0f);
    }

    private void Jump()
    {
        if (canJump)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            amountOfJumpsLeft--;
        }
    }

    private void CheckSurroundings()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
    }

    private void CheckIfCanJump()
    {
        if (isGrounded && rb.velocity.y < 0.01)
        {
            amountOfJumpsLeft = amountOfJumps;
        }

        if (amountOfJumpsLeft <= 0)
        {
            canJump = false;
        }
        else
        {
            canJump = true;
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
    }
}

```

# Answer
The trick here is to count air jumps separately from the initial ground jump. You always allow a jump from the ground, and you decrement your remaining air jumps only if you're *not* on the ground.

So your `amountOfJumpsLeft` variable becomes `airJumpsRemaining`, and you can do something like this:

```
// Call this when you want to jump - it will report back whether is was successful.
public bool TryJump() {
    if (isGrounded && rb.velocity.y < jumpSpeed) {
        // Your first jump from ground is always valid.
        Jump();
        return true;
    } else if (airJumpsRemaining > 0) {
        // Only air jumps decrease the count.
        airJumpsRemaining--;
        Jump();  // Alternatively, you can call a different air jump method here.
        return true;
    }
    return false;
}

// No conditionals or state management in Jump() itself anymore.
private void Jump() {
    // Just don't call your variable "force" if you're using it as a "speed".
    // That'll confuse someone down the line to think it's in Newtons, not m/s.
    rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}

```

Then when you update your grounded state, you immediately restore your air jumps.

```
private void CheckSurroundings()
{
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);

    if(isGrounded)
        airJumpsRemaining = amountOfJumps - 1;
}

```
> 1 votes

# Answer
In your `Jump` method, why don't you first do a check for `IsGrounded` and adjust the number of jumps? Something like:

```
private void Jump()
{
    if (canJump)
    {
        if (!isGrounded)
        {
            amountOfJumpsLeft--;
        }
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        amountOfJumpsLeft--;
    }
}

```

Essentially, if you call `Jump` and you **are not on the ground**, it reduces the number by 1 before executing the jump, so then when you perform the jump and it removes 1 more you are at 0 after the first jump. If you **are on the ground**, if skips this and removes 1 only after the first jump. The only caveat to this is that if you are on the ground when you first jump, then your second jump will reduce `amountOfJumpsLeft` by 2... but if it doesn't matter that `amountOfJumpsLeft` can be \< 0, then who cares?

**EDIT:** Alternatively, if you can't have `amountOfJumpsLeft` \< 0, you can do the same thing but just modify `canJump` so the next time `Jump` is called it fails the check:

```
private void Jump()
{
    if (canJump)
    {
        if (!isGrounded)
        {
            canJump = false;
        }
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        amountOfJumpsLeft--;
    }
}

```
> 0 votes

---
Tags: unity, 2d, movement, jumping
---


# Question
Title: Visual Studio not recognizing Unity's new Input system
I'm attempting to learn Unity's new input system, but when I try to add `using UnityEngine.InputSystem;` to my code it gets a red squiggly line under it. It doesn't cause any compiler errors, but it's very annoying. How do I get Visual Studio to recognize this so Intellisense will work again?

# Answer
> 6 votes
I found the answer online! I had to go to the editor preferences (Edit -\> Preferences) and under External Tools, there's a section with checkboxes under "Generate .csproj files for:." All I had to do was check "Registry Packages," click Regenerate project files, and it worked! Thanks to everyone who tried to help, and to DMGregory for his comment on generating project files. I hope this question can help someone else.

---
Tags: unity, c#, input, visual-studio
---