# Question
Title: How to cache the main camera as a global variable?
I want to create a utility class that will, among other things, return a cached reference to the main camera. Is the below code correct? My concern is that I'm doing it wrong and that FindGameObjectWithTag is being called each and every time the getter is referenced.

```
using UnityEngine;

public static class Utils
{
    public static Camera MainCamera { get; } = Camera.main;

}

```

# Answer
> 1 votes
You would need to use an example below to call `FindGameObjectWithTag` each time:

```
    public static Camera MainCamera => Camera.main;

```

In your example Camera is assigned once.

Although, there is problem with `static`: their initialization is not the same as normal, with Unity it's hard to find deterministic way to check when Camera is actually assigned. It could be Edit mode, or the moment camera is not created yet. If camera is destroyed or scene is changed (and you're not using `DontDestroyOnLoad`), you'll get exceptions on calling missing `MainCamera`.

Consider assignment directly from camera controller:

```
public class CameraController : Monobehaviour {

    private void Awake() {
        Utils.MainCamera = GetComponent<Camera>();
    }
}

```

Obviously, MainCamera will need public `set;` for that.

This way you can guarantee that camera is assigned exactly at the moment it's initialized during runtime. Any new CameraController will overwrite previous one (if old one is destroyed, for example).

It is questionable to introduce such things when you already have `Camera.main`, although static reference would work slightly faster. This trick helps to create references to any object without global access as well.

I would also note that creation of global references and utility classes is considered not the best practice. It is pretty amazing how easy and clean you could set up references with singletons and statics, but it creates tight dependencies which hard to edit, hard to remove and hard to test. And arguably harder to understand. Choose wisely!

# Answer
> 0 votes
The property here doesn't provide any form of caching. It will call the `Camera.main` property getter each time you call it. So it doesn't give you anything over calling `Camera.main` directly.

If you want a caching version of this utility class:

```
public static class Utils
{
    private static Camera _mainCamera;
    public static Camera MainCamera {
        get {
             if (!_mainCamera) {
                  _mainCamera = Camera.main;
             }
             return _mainCamera;
        }
    }
}

```

This will of course stop working if you change which camera is the main camera at runtime. When you do that, then you might want to add another method to `class Utils` which sets the private variable `_mainCamera` back to `null`, so the next call to `Utils.MainCamera` will retrieve the new main camera.

---
Tags: unity
---


# Question
Title: Which parts of Doom (1993) are open source and which are not?
As the original publication of the source code states, you still need an original copy of the game:

https://www.doomworld.com/idgames/idstuff/source/doomsrc

What exactly do you need from those original copies?

# Answer
> 9 votes
Doom is divided into two components:

* The game engine.
* The game data.

Of these, **the source code which was released is for the game engine only**, and as the readme notes, only for the Linux version, as id Software had used third-party sound code for the DOS version, which they were unable to open-source.

The game data is contained in WAD files and includes the following elements:

* Maps.
* Textures.
* Sprites.
* Sounds.
* 2D GUI images.
* Music.

**None of the game data is open-sourced** and you will still need a commercial copy of the game to access it.

**One other item which is open-sourced** is the DOS Doom "Setup" program, which was used to configure sound and other options outside of the game engine.

Other official Doom ports are a mixed-bag; the Windows port from the 90s is apparently lost, but source for the IOS port is available ( and ) as is source for the version that was bundled with the Doom 3 BFG Edition.

# Answer
> 1 votes
You need the doom.wad file that came with it. Alternatively, you can find total conversion mods for free various places online and then you don’t need anything. Although in that case you are looking at an entirely different game, just running on the same engine.

---
Tags: software-engineering, open-source
---


# Question
Title: How to check version of Unity package in project through script
I'm writing an asset that will be used by many people, but it depends on TextMeshPro (TMP). I ran into a bug in TMP that can only be fixed by upgrading to a preview version. I want to warn users that install my asset that they need to upgrade their TMP version if they are using a prior version. Surprisingly, I can't find this anywhere online or in the docs.

just something like

```
if (TextMeshPro.version < MyAsset.RequiredTMPVersion) {
    Debug.LogError("Need to upgrade TMP");
}

```

# Answer
> 1 votes
I believe you can use Unity's **PackageManager**.

First you search for the package you need info of (TMP) with PackageManager.Client (I think it will look something like this: `var tmp = Client.Search("com.unity.textmeshpro").Result;`, be aware that `.Result` is synchronous, maybe there's a better way to implement this using Tasks).

Then you get the package's info (version) with PackageManager.PackageInfo (something like `tmp.version`). Done.

---
Tags: unity, asset-management, asset-workflow
---


# Question
Title: Generating normals from terrain heightmap
I am drawing my terrain by rendering a static quad mesh several times and then displacing vertices using a heightmap. As such I need to generate normals. I am primarily interested in quality over speed.

What is the best way to do this? Precompute a normal-map and sample it in the pixel shader? Or generate them in the vertex shader somehow?

# Answer
Note: These are my experiences so everyone finds their own path!

I use heightmaps in game, but after applying it to the mesh I then add the normal to the vertex as another attribute. I can use this with other attributes so I can ignore areas or apply a bias to a normal, or where I do want to normalise. I pass the normal into the vertex shader along with the rest of the vertex data, the normal will be linear interpolated so I will get normal that accurately is reflected in the pixel shader (just needs to be normalised as lerping denormalises).

This is a far more accurate representation than a normal map, unless you have a high res version of that map than you wont get near the accuracy.

The other piece that I would steer clear of normal maps for terrain. If you ever want to rotate your world, then you need in your pixel shader to sample a point, apply the matrix transform to it then its in world space. If you use normals through the vertex shader, you can apply the same matrix transform once per vertex, not per pixel. Pressure on the pixel shader is the thing I try to avoid. It also means one less bilinear sample in the pixel shader. The transform of the sampling to world space is similar to what you do for calculating normal maps on a model.
> 0 votes

---
Tags: directx11, hlsl, normals
---


# Question
Title: How can I sort a list of integer pairs in sequence?
I have a list of paired integers, every nth integer paired with every nth+1 integer. I'm trying to sort the list such that the pairs form a chain. For example:

Input: {12,72, 38,2, 72,38, 2,12} Output: {38,2, 2,12, 12,72, 72,38}

The trick is that the list may contain several unconnected chains. The chains don't need to be in any sequence, just the pairs within each chain. As per the input, each chain should be a loop unless they chain has only one pair, so any pair in the chain should be a valid first pair.

What I've tried is this (C#):

```
int a = 0;
int b = 0;
int temp;

while (a < list.Count) {
    b = a + 2;
    while (b < list.Count) {
        if (list[b] == list[a + 1]) {
            temp = list[b];
            list.RemoveAt(b);
            list.Insert(a + 2, temp);

            temp = list[b + 1];
            list.RemoveAt(b + 1);
            list.Insert(a + 3, temp);

            a += 2;
            b = a;
        }
        b += 2;
    }
    a += 2;
}

```

Which is giving me mostly correct results, but is still leaving the list with some disconnected pairs that should be part of a chain.

I'm not great with sorting algorithms and this has proven to be a difficult problem to google, so I'm hoping someone can point out the flaw in my code or point me in the right direction for research.

# Answer
# Your algorithm only appends links to a chain to the first encountered pair in the chain, but it does not ensure a is the first item in the chain.

The result is that an example like `{ 1,2, 0,1, 2,3}` will sort to `{1,2, 2,3, 0,1}` instead of `{0,1, 1,2, 2,3}`, so links might be split up. You could check whether the pair at b comes before the pair at a, but with circular links being legal, you need to check for the case where the whole list is one long circular chain, which could result in infinite loops.
> 1 votes

---
Tags: c#, sorting
---


title: Applying wheel sideways friction to car

text:
# Question
Title: Applying wheel sideways friction to car
I'm applying sideways friction to my car from each wheel, but for some reason my car starts to accelerate forward instead of having forces acting sideways and stopping it.

This is the script:

```
    frictionForce = car.transform.TransformDirection(
        car.transform.right *
        sidewaysFriction *
        car.transform.InverseTransformDirection(car.velocity).z
    );

    car.AddForceAtPosition(springForce - frictionForce * sidewaysFriction, transform.position);

```

Thanks for any help.

# Answer
> 1 votes
I've sloved my problem using `Debug.DrawRay()` to visualize what my vectors looked like.

My error was that in my case, my "side" wasnt Vector3.right, but rather Vector3.forward.

I changed code to:

```
       frictionForce = car.transform.TransformDirection(
           Vector3.forward *
           -sidewaysFriction *
           car.transform.InverseTransformDirection(car.velocity).z
       );
       Debug.DrawRay(transform.position, frictionForce, Color.blue);

```

And it worked.

---
Tags: unity, physics
---


# Question
Title: Managing large amounts of data and processes for an economy management game
I'm making a management game in the vein of Anno or Stellaris, but I'm unsure how to manage all my data efficiently.

Short example: the player controls multiple islands. Each island has factories on it. A factory has inputs, a process that does something with the inputs, and outputs. The process depends on the inputs and the outputs and other parameters. The outputs could be another factories input. A factory needs human workers. Human workers have stamina ... ... ...

So the question is: how do you manage so much data and processes programmatically? And it's not only about running many processes simultaneously, they also depend on each other and the data, use each other, inform each other - on each tick. You also need the ability to get information out of those sub processes and put data into it at any time.

I'm struggling to come up with a system/codebase that could handle those things. I've choose C#/dotnet core since I assume it has something to do with threading, but I still haven't got anything that works.

# Answer
I can't say anything about these particular two games, because they aren't open source and I wasn't involved in their development.

But usually when you have game mechanics with a large number of entities each doing relatively simple computations, then you usually use an Entity - Component - System architecture.

The basic gist is this:

* You divide the data required for the functionality of each entity in your game into granular components.
* You create an array for each type of component to ensure that they are in a connected memory section. This improves CPU performance when performing an operation on all components of the same type.
* You implement each game mechanic in form of a system which operates on one or more component-arrays.

> Each island has factories on it. A factory has inputs, a process that does something with the inputs, and outputs. The process depends on the inputs and the outputs and other parameters. The outputs could be another factories input. A factory needs human workers. Human workers have stamina

If you would implement this in an ECS architecture, then you would usually implement it something like this (details can vary depending on the complexity of these mechanics):

* The WorkerStaminaSystem updates the stamina of all workers
* The WorkerProductivitySystem updates the productivity value of all workers depending on their current stamina and other values.
* The FactoryProductivitySystem updates the productivity of all factories depending on their current worker productivity and other attributes of the factory
* The FactoryProcessSystem updates resource stockpiles based on the productivity of all factories

The goal is to have not one large update loop which iterates each entity and does everything that needs to be updated. It instead has many separate update-loops which perform a pretty small operation on a large set of pretty small objects. Why?

* It is much easier for the optimizers of your compiler and the internal optimization of your CPU to process short loops than long loops.
* It is easier on the CPU caches if the data processed by a loop is as small as possible and in a consecutive memory section.
* It is possible to parallelize these update-loops over multiple CPU cores. For example, when your WorkerStaminaSystem has 100,000 workers and you have 4 CPU cores, then each core can process 25,000 of them. You won't need to worry about thread safety or implement expensive thread synchronization techniques, because each worker can be updated without knowing anything about the other workers and you only need read-access at most for the rest of the world.
* It is often possible to run multiple systems in parallel. The limited amount of components processed by each system makes it easy to recognize systems which operate on completely independent data-sets. Those can be run in parallel without having to worry about thread safety.
* It allows to update systems in different intervals. Some systems might not need to run every single update-tick. Perhaps it is sufficient to update the worker stamina just every second or even less? You can even have systems which perform staggered updates. Only update a limited chunk of objects each tick to avoid lag spikes.
> 1 votes

---
Tags: c#, software-engineering, multithreading, simulations
---


title: Limit position rigidbody

text:
# Question
Title: Limit position rigidbody
How can I limit the position of a rigidbody, between two values if I use this code:

```
public Vector3 dir;

Rigidbody rb;

void Awake()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    rb.velocity = new Vector3(0f, 0f, 6f);

    rb.AddForce(dir * 1f, ForceMode.VelocityChange);
}

```

If I use Vector3.Clamp then the object will shake

# Answer
# Your problem is the use of FixedUpdate() for position clamping. You are correct to apply the forces in FixedUpdate() but clamping the position should be done in Update() or LateUpdate().

```
public Vector3 dir;
public Vector3 min;
public Vector3 max;

Rigidbody rb;

void Awake()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    rb.velocity = new Vector3(0f, 0f, 6f);

    rb.AddForce(dir * 1f, ForceMode.VelocityChange);
}

void Update()
{
    transform.position = new Vector3(
        Mathf.Clamp(transform.position.x, min.x, max.x),
        Mathf.Clamp(transform.position.y, min.y, max.y),
        Mathf.Clamp(transform.position.z, min.z, max.z));
}

```

FixedUpdate() is frame-rate independent, which means that there are frames happening in between those calculations. The GameObject's position however is recalculated for every frame. The reason you are seeing shaking when clamping in FixedUpdate() is that there is a force on the object that would cause it to move, causing the position in each frame to be calculated as the distance moved from the last frame, but then you are clamping it at a different rate than the framerate so it returns to the clamped value every few frames.
> 2 votes

# Answer
We can also use physics itself to do the clamping, at the end of each `FixedUpdate`:

```
// Project where our velocity will take us by the end of the frame.
Vector3 positionAtEndOfStep = rb.position + rb.velocity * Time.deltaTime;

// Limit that projected position to within our allowed bounds.
positionAtEndOfStep.x = Mathf.Clamp(positionAtEndOfStep.x, min, max);

// Compute a velocity that will take us to this clamped position instead.
Vector3 neededVelocity = (positionAtEndOfStep - rb.position)/Time.deltaTime;

// You can also calculate this as the needed velocity change/acceleration,
// and add it as a force instead if you prefer.
rb.velocity = neededVelocity;

```

In a step where we're moving toward the edge and about to cross it, this will slow but not quite stop the x velocity, without shifting the other components, so we arrive *at* the edge without crossing.

In a step where we're skating along the edge, this will zero-out the x velocity so we don't go past it. Velocity inward, away from the boundary, is preserved.

Note that if an object collides with this one midway through the step, that could add more velocity and nudge us past the barrier, but we'll correct in the next step.

For even tighter control, you can use a Joint component to limit the object's slide over one axis while leaving the others free. The physics engine will try to iteratively solve these constraints together with collisions that happen in the frame.
> 4 votes

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


# Question
Title: Response to form triggers creation of zero or more duplicate scenes
I've got two scenes, one with room 1 and one with room 2.

In room 1 I've got one table with two 3D assets on top of it. This room also has a door that connects to room 2 through a door but it's closed.

Once going near the 3D assets a dialog pops up saying to click "E". This pops up a 2D form one needs to fill.

Only after filling both forms I'm able to go into room 2.

Now what I would like to do is, depending on the response in the form, one or more duplicate room 2 scenes should be created and dynamically added to the scene. If with scenes isn't possible, what's the way to do such thing?

Know about SceneManager.CreateScene but this creates an empty scene, not exactly what I want to.

# Answer
> 1 votes
This problem seems to me like something I would solve with prefabs instead of scenes.

I would create just one scene for all rooms. Those rooms which appear in any case and always in the same position would be part of that scene. Those rooms which only appear conditionally would be prefabs.

The script which processes the player decisions in the form would get an inspector variable for each room it is able to spawn. I would then assign the room prefabs to those variables in the inspector and write the script to `Instantiate` the room prefabs according to the player's decisions.

Alternatively, if each room will always appear in the same position, you could make all the rooms part of the scene but set all the conditional rooms to inactive. The script would then have references to these rooms in the scene instead of references to prefabs. It would then activate the rooms you want in the game with `room.SetActive(true)`. This approach has the advantage that you can mark the rooms as "static" which improves various performance metrics and that you might be able to use baked lightmaps (under some conditions), which can result in better looking lighting.

---
Tags: unity, scene
---


title: How to make prefabs independent?

text:
# Question
Title: How to make prefabs independent?
I'm working on a Unity's Project and I want to modify a prefab, more precisely I want to change the texture of a prefab. The problem is that my modification is applied also to other prefabs. I read on the documentation how each of the buttons labeled *Select*, *Revert* and *Apply* works, and what I understood is that the modification should update only the selected prefab.

Here is the Prefabs' Manual which I read.

What am I missing?

PS: I'm not the author of the project, I have to apply some modifications only.

# Answer
> 10 votes
It's more likely that you're modifying the material the prefab is using, and other prefabs using that material are being affected. While you are correct that what you're doing shouldn't modify the other prefabs, those prefabs still share a reference to the same material. When modifying a material, it affects all objects and prefabs that reference that material.

You should make a copy of the material and reference the copy from the prefab you want to modify.

# Answer
> 1 votes
Copying over the prefab file will also copy the mesh renderer component including the materials it references.. if you go to that mesh renderer component in the copied prefab asset you should be able to change the referenced materials without affecting the orignal prefab

---
Tags: unity, assets
---


# Question
Title: How can I find the center position of two or more objects?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCameraBehind : MonoBehaviour
{
    public GameObject camera;
    public List<GameObject> targets = new List<GameObject>();
    public float cameraDistance = 10.0f;
    public bool behindMultipleTargets = false;
    public string cameraWarningMsgs = "";
    public string targetsWarningMsgs = "";

    // Use this for initialization
    void Start()
    {
        if (camera == null)
        {
            var cam = GetComponent<Camera>();
            if (cam != null)
            {
                cameraWarningMsgs = "Gettig camera component.";

                camera = transform.gameObject;
            }
            else
            {
                cameraWarningMsgs = "Creating a new camera component.";

                GameObject NewCam = Instantiate(new GameObject(), transform);
                NewCam.name = "New Camera";
                NewCam.AddComponent<Camera>();
                camera = NewCam;
            }
        }

        if(targets.Count == 0)
        {
            targetsWarningMsgs = "No targets found.";
        }
    }

    void FixedUpdate()
    {
        if (targets.Count > 0)
        {
            MoveCameraToPosition();
        }
    }

    public void MoveCameraToPosition()
    {
        if (targets.Count > 1 && behindMultipleTargets == true)
        {
            var center = CalculateCenter();
            transform.position = new Vector3(center.x, center.y + 2, center.z + cameraDistance);
        }

        if (behindMultipleTargets == false)
        {
            Vector3 center = targets[0].transform.position - targets[0].transform.forward * cameraDistance;
            transform.position = new Vector3(center.x, center.y + 2, center.z);
        }
    }

    private Vector3 CalculateCenter()
    {
        Vector3 center = new Vector3();

        var totalX = 0f;
        var totalY = 0f;
        foreach (var target in targets)
        {
            totalX += target.transform.position.x;
            totalY += target.transform.position.y;
        }
        var centerX = totalX / targets.Count;
        var centerY = totalY / targets.Count;

        center = new Vector3(centerX, centerY);

        return center;
    }
}

```

The CalculateCenter function make the targets(objects) to change positions and vanish away far away. Even if there is only one single target.

What I want to do is if there is one object for example one 3d cube position the camera behind the cube. And if there are more cubes for example two or ten and the camera is somewhere else calculate the middle position behind the targets and position the camera in the middle behind them.

To show what I mean in this example the view(like a camera) is behind the two soldiers in the middle position between them from behind.

But what if there are 5 soldiers how can I find the middle position and then position the camera behind them like this example in the screenshot ?

# Answer
> 1 votes
I wanted to comment but I can't yet (not enough reputation) so I'll ask here:

1. > The CalculateCenter function make the targets(objects) to change positions

I'm not sure it's true, since this function doesn't change any `transform` of any object. I assume you meant the calculation in this function is incorrect? See 2 for that.

2. You said the objects vanish far away - since you're talking about 3D object, maybe it's because you haven't set a z value in your CalculateCenter function? Try calculating a `centerZ` and adding it to the `Vector3` constructor.

BTW the

```
new Vector3()

```

is redundant since you're reassigning a new Vector3 to `center` later on that function :)

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


# Question
Title: Where should I put code to be run on the client after connecting to a server?
I'm making a multiplayer game with Unreal Engine, and I need to run some blueprint code on the client after they have connected to the server. This includes creating the HUD widget, uploading the player's loadout, etc. Where should I put this code so that it runs only on the client after connecting to a server?

# Answer
In the sense the game framework is built upon, you define the HUDClass in the GameMode Class. The HUD code only runs on the client.

If you want to do something at the beginning, right after spawning and possessing the Pawn, I suggest you override BeginPlayingState inside the PlayerController and start from there (you can call GetHUD and start asking the hud to do whatever you want to show to the player).

In general, actions from the player should be done through the PlayerController, so if you want to show something on the HUD based on a player action you could use the PlayerController for that and then the PlayerController "delegates" the "business logic" of actually displaying the thing to the HUD class itself.

If you want to know more about the Gameplay Framework, consider reading this: https://docs.unrealengine.com/en-US/Gameplay/Framework/index.html
> 1 votes

---
Tags: networking, unreal
---


# Question
Title: AI does not stop walking like it is supposed to, instead spins in place and lags game
I've got this very simple enemy AI that follows the player and is supposed to stop and shoot at the player when he enters a trigger, however it doesn't seem to do that it doesn't stop or shoot. This is one of my first scripts so it isn't really good. Any and all help will be appreciated.

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

public class EnemyAI : MonoBehaviour

{
    public GameObject Destination;
    NavMeshAgent agent;
    public Collider TriggerCollider;
    public GameObject Enemy;
    public GameObject bullet;
    public float EjectionForce;
    public float firingrate = 20f;
    private float NextFire = 0f;
    public GameObject GunArea;

    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        agent.SetDestination(Destination.transform.position);

    }

    // Update is called once per frame
    void Update()
    {

    }
    void OnTriggerStay(Collider other)
    {
        if (other.transform.tag == "Player" && Time.time >= NextFire)
        {
            agent.isStopped = true;
            AimAndShoot();
            NextFire = Time.time + 1f / firingrate;
        }
        else agent.isStopped = false;
        agent.SetDestination(Destination.transform.position);
    }
    void AimAndShoot()
    {
        Enemy.transform.LookAt(Destination.transform.position);
        GameObject enemybullet = Instantiate(bullet, GunArea.transform.position, GunArea.transform.rotation) as GameObject;
        enemybullet.GetComponent<Rigidbody>().AddForce(enemybullet.transform.forward * EjectionForce);
        Destroy(enemybullet, 1f);
    }
}

```

# Answer
First, are you sure `OnTriggerStay` is called at all? A simple

```
print("OnTriggerStay was called!");

```

at the beginning of `OnTriggerStay` would tell you. If it's **not** called, make sure the "Is Trigger" property in the collider component of your enemy is ticked (set to true). You should find this in the inspector after clicking the enemy game object.

Second, Unity documentation says:

> Trigger events are only sent if one of the colliders also has a rigidbody attached.

Do the enemy or the player (or both) has a rigidbody component?

Third, you set `agent.isStopped` both to true and false in the same function (`OnTriggerStay`), which is called over and over again (once per physics update), so maybe `agent.isStopped` is set to true, then false, then true again and so on and so forth, and it happens so fast you don't notice the enemy stopping. I assume you want to set `agent.isStopped` to false in `OnTriggerExit` instead.
> 0 votes

---
Tags: unity, c#, 3d, ai
---


# Question
Title: Colliders slightly intersecting each other; any solution?
Consider this simple scene:

In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider.

And the problem: **if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height.** The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam-- this *only* exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall.

This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist.

Is there a workaround? How can the box smoothly move across the floor without colliding with the seam?

Notes:

* This *does* occur with capsule colliders but rare and is not very noticeable.
* A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks.
* This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity/position of the transform.

# Answer
> the box is slightly inside the first floor collider

Is this on purpose? If not, it's not the best solution but maybe you can increase the height of the box just by a bit, enough to make it "float" above the floors and not collide with the seam, but not too much to be noticeable while viewing the scene.
> -1 votes

---
Tags: unity, collision-detection, physics, movement, collider
---


# Question
Title: Parent object is too far from children how can I fix it ? Parent is at 0,0,0 but the children in other position/s
When I make double click on the empty GameObject as it should be it's zooming to the children group :

I grouped all the npcs under emprt GameObject name Npcs but first I was reseting Npcs to 0,0,0 Now the arrows of the axis to drag and change the Npcs positions are far away. The idea was to easy move the npcs all the same time.

When I zoom out in the scene window this is where the Npcs is so if I will drag it and change it's positions I will not see where the npcs are moving to they are too far.

# Answer
If I understand correctly your question, you have a parent object and under it a few NPC objects, when the NPCs are in the desired place, but the parent is far off.

Try to move your parent object to the **current position of the NPCs** (this will move the NPCs as well), and then move the NPCs (one by one) to their previous location (which is where the parent should be by now).
> 0 votes

---
Tags: unity
---


title: How To Use Unity With C++?

text:
# Question
Title: How To Use Unity With C++?
In the C++ `Visual Studio` installer, there is an option `Game Development With Unity`. However, after selecting that, I didn't find any changes to regular `Visual Studio`. So I looked it up, and found no results regarding C++. How can I use `Unity` with `Visual Studio` for C++?

# Answer
> 3 votes
The Visual Studio Tools for Unity are primarily for writing C# scripts. They don't expose a C++ scripting API.

The reason they show up when you're working with C++ in Visual Studio is they're related to VS, not C++ specifically. VS will let you develop in several different languages in a single installation, so they don't rule out the possibility that you might want to use C++ for some projects and Unity C# for others.

You *can* use C++ to build a native plugin to call from Unity scripts, though you usually need to do this only to access specialized platform-specific features that the engine hasn't exposed to the C# API in a platform-agnostic fashion.

---
Tags: unity, c++
---


# Question
Title: Get BP FollowCamera Rotation and Location
I'm accessing my FollowCamera https://i.stack.imgur.com/dXKjt.jpg from my BluePrintCharacter class in my C++ code, with this following line :

```
FollowCamera = GetOwner()->FindComponentByClass<UCameraComponent>();
FVector WorldLocationV = FollowCamera->GetWorldLocation();

```

But when I run my game, I get this error : **GetWorldLocation is not a member of UCameraComponent**

Why is this, and how can I get GetWorldLocation from FollowCamera in C++?

In BluePrint this seems to work fine : https://i.stack.imgur.com/FCMcc.png

# Answer
> 0 votes
According to the Unreal docs UCameraComponent you are correct, GetWorldLocation isn't part of UCameraComponent.

Attached to the camera is a camera manager and to get the world location and rotation of the camera, you need to get this.

```
APlayerCameraManager *CameraManager = GetWorld()->GetFirstPlayerController()->PlayerCameraManager;

FVector CameraLocation = CameraManager->GetCameraLocation();
FVector CameraForwardVector  = CameraManager->GetCameraRotation().Vector();

```

In case you need it, the #include is #include "Camera/PlayerCameraManager.h"

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


title: Game build crashes on scene load

text:
# Question
Title: Game build crashes on scene load
I built out my project to Android to do some testing and stuff, but I can't get any further than the main menu scene. I built it out previously and it was running fine. Now as I try loading level0 it crashes **with no error messages** from adb logcat. Just exits the game and that's it. It works fine in the editor.

I tried several things. I changed the color space back and forth, I built my addressables, tried development built and non development one, and the Split application binary checkbox is false as well...

Unity 2019.2

My adb catlog output

# Answer
> 1 votes
Reading your log output, it seems your application is having trouble loading your assets from the device storage. A few suggestions I can make:

1. Make sure your application has been **permitted to access storage** in your android device. You can try this, and if your app isn't listed there, try removing it and re-adding it to your device. Android should ask you to give permission to the app.
2. How are you loading your assets? **If you're prefixing the path with "file://"**, try removing it from the path. (Suggested here)
3. **Check your assets paths** again, they could be wrong. I'm taking about the paths you send as argument to your asset-loading functions in your code. Watch for case sensitivity.
4. If nothing works, you could maybe workaround this by selecting your addressables group, and under the properties, there's a retry/attemps field you can set to 3 or more. Then build the bundles again. (Suggested here)

> I built it out previously and it was running fine.

Built it to android? Or another platform like Windows? This distinction can narrow down the reasons for the error. For instance, the first thing I said isn't relevant if the previous build was for Android and it worked fine then.

---
Tags: unity, android, build-process, error-management, crash
---


# Question
Title: Agent trying to reach same position as other agents, instead start spinning in place
I create units in my game and have a rally point where they should walk to when created, like Age of Empires.

My problem is that since they compete for this position after a while, sometimes they end up doing this:

https://gfycat.com/decentquestionableandeancondor

https://gfycat.com/densehonoredgalapagosalbatross

As you can see one of the guys cant reach the rally point, so he starts rotating.

I realize this has to do with stopping distance, but no matter how high I set the stopping distance this eventually becomes a problem when there are many enough units. And if I set it too high they dont walk to the rally point at all, since its not THAT far from the building they spawn from.

Is there any way to manage this scenario? i.e just making him go as close as he can, and then stop?

My AI Script:

```
using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class BaseAi : MonoBehaviour
{
    [HideInInspector]
    public NavMeshAgent agent;

    [HideInInspector]
    public NavMeshObstacle obstacle;

    float sampleDistance = 50;

    Transform mTransform;

    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
        obstacle = GetComponent<NavMeshObstacle>();
        mTransform = transform;
    }

    private void Start()
    {
        agent.avoidancePriority = Random.Range(agent.avoidancePriority - 10, agent.avoidancePriority + 10);
    }

    void LateUpdate()
    {
        if (agent.isActiveAndEnabled && agent.hasPath)
        {
            var projected = agent.velocity;
            projected.y = 0f;

            if (!Mathf.Approximately(projected.sqrMagnitude, 0f))
                mTransform.rotation = Quaternion.LookRotation(projected);
        }
    }

    /// <summary>
    /// Returns true if the position is a valid pathfinding position.
    /// </summary>
    /// <param name="position">The position to sample.</param>
    public bool SamplePosition(Vector3 point)
    {
        NavMeshHit hit;
        return NavMesh.SamplePosition(point, out hit, sampleDistance, NavMesh.AllAreas);
    }

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

        return false;
    }

    public void Teleport(Vector3 point)
    {
        agent.Warp(point);
    }

    /// <summary>
    /// Return true if agent reached its destination
    /// </summary>
    public bool ReachedDestination()
    {
        if (agent.isActiveAndEnabled && !agent.pathPending)
        {
            if (agent.remainingDistance <= agent.stoppingDistance)
            {
                if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
                {
                    return true;
                }
            }
        }

        return false;
    }

    public void ToggleObstacle(bool toggleOn)
    {
        agent.enabled = !toggleOn;
        obstacle.enabled = toggleOn;
    }

    void OnDrawGizmos()
    {
        if (agent == null) { return; }
        if (agent.path == null) { return; }

        Color lGUIColor = Gizmos.color;

        Gizmos.color = Color.red;
        for (int i = 1; i < agent.path.corners.Length; i++)
        {
            Gizmos.DrawLine(agent.path.corners[i - 1], agent.path.corners[i]);
        }
    }
}

```

# Answer
> 0 votes
Here is strat I could think of:

* Check that agent must gradually get closer to final destination. If he cannot get closer, maybe for about T duration, we will judge that he cannot progress anymore.
* But only check this only if when agent is moving toward "Final Destination", not in between path nodes.

---

## 1. Check if agent cannot progress more

Just simple check if distance could not get closer. With give up timer. These variables for checking are reset on starting new movement.

```
float m_LastDistanceToTarget;
float m_GiveUpTimer;
bool m_WillGiveUpAgent;
const float DefaultGiveUpTime = 1.0f;

void LateUpdate()
{
    if( agenthasPathAndAgentIsRunning )
    {
        float currentDistance = Vector3.Distance( transform.position, agent.destination );
        if( currentDistance < m_LastDistanceToTarget )
        {
            // Agent is getting closer, this is we want to see, go on, also reset give up time
            m_LastDistanceToTarget = currentDistance;
            m_GiveUpTimer = DefaultGiveUpTime;
        }
        else
        {
            // Cannot proceed closer, countdown time to giveup
            m_GiveUpTimer -= Time.deltaTime;
            if( m_GiveUpTimer <= 0 )
                m_WillGiveUpAgent = true;
        }
    }
}

public bool SetDestination(Vector3 point)
{
    if (SamplePosition(point))
    {
        agent.SetDestination(point);

        m_LastDistanceToTarget = float.PositiveInfinity;
        m_GiveUpTimer = DefaultGiveUpTime;
        m_WillGiveUpAgent = false;
        return true;
    }
}

public bool ReachedDestination()
{
    if (agent.isActiveAndEnabled && !agent.pathPending)
    {
        if( m_WillGiveUpAgent ) return true;
        /* Remaining is Omitted */
    }
}

```

## 2. Make above check only run on final corner

This 2nd check is to prevent "false give up" when agent is on complex navigation path because its distance to final position could goes up and down hence we cannot perform 1st check while in this condition.

When NavMeshAgent has path computed, it will has `agent.path.corners` and also `agent.steeringTarget` which point to corner (in path) it is trying to move to. If steeringTarget becomes last index of path.corners, this mean agent is on last straight line to destination.

```
void LateUpdate()
{
    if( agenthasPathAndAgentIsRunning )
    {
        // Agent must be on last index corner
        // PS. Not 100% sure, verify this yourself
        if( agent.steeringTarget == agent.path.corners[lastIndex])
            /* First check code */

```

---

## Final Note

* Code is for simplicity, some variable is left to reader's work and check such as Vector3.Distance is expensive, optimize it if you do care.
* There could still be false positive with this check. If large amount of agent move in group, (plus all of your units are solid) some unit might temporary got obstructed by its moving friends and this could will falsely give up the agent. That would be another challenge to solve.

# Answer
> 0 votes
Here's a cheap little trick you can use:

```
Vector3 lastPosition;

void LateUpdate()
{
    if (agent.isActiveAndEnabled && agent.hasPath)
    {
        Vector3 effectiveVelocity = (transform.position - lastPosition)/Time.deltaTime;

        effectiveVelocity.y = 0f;

        if (effectiveVelocity.squareMagnitude > 0.5f) // Tune this threshold to your needs.
            mTransform.rotation = Quaternion.LookRotation(effectiveVelocity);
    }

    lastPosition = transform.position;
}

```

Here, instead of asking the agent which direction it *wants* to *try* to move, we look at our position history to find out which way we *have actually* moved. If we've stayed in pretty much the same spot, we don't visibly turn the unit.

That way, even if the underlying path planning is hesitating back and forth, the player only sees the agent turn when it successfully finds a new path and makes real progress.

---
Tags: unity, ai
---


# Question
Title: How do I get the player to collide with another object to use as a boundary?
I'm trying to make a simple game where you move a sphere from left/right and try to avoid falling cubes. If a cube touches the player (sphere), the player dies. I'm trying to set up boundaries using a cylinder with a collider, but every time I hit the collider boundary, the player disappears like they would if they hit a cube. Here is my player script:

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

public class Move : MonoBehaviour
{
public float moveSpeed = 1;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{

    transform.position += new Vector3(Input.GetAxis("Horizontal") * moveSpeed, 0, 0);
}

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Cube")
    {
        Destroy(collision.gameObject);
        Destroy(gameObject);
    }
}

```

}

# Answer
To make the if condition apply to both lines, put braces around them like this:

```
void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Cube")
    {
        Destroy(collision.gameObject);
        Destroy(gameObject);
    }
}

```

Note: get in the habit of ***always*** using braces with if-, while-, and for-statements to make it explicitly clear what lines the statement applies to.
> 2 votes

---
Tags: unity, collision-detection, rigidbody, collider
---


# Question
Title: How do Minecraft know where village's buildings are if the village is not generated yet?
I'm trying to understand how chunk generation works in a deep level and all the information I found does not explain how the villages are generated properly without visual glitches during generation.

I mean, if you are in an area where you should see some buildings from a village, how does Minecraft know that they must be rendered? Minecraft generates villages from a main "structure" that probably it is not generated yet.

This video explains the village's generation properly.

So with that in main what should happen is that you could see builds appear from time to time when the "village center" of a village is generated in a new-generated chunk.

Here you have a visual representation of the circumstances I'm describing. The buildings inside the loaded area shouldn't be shown if the village is not generated yet:

The only explanation I can think about is that Minecraft generates way more chunks than the ones that are visually loaded to avoid this problem.

If this what happens, what is the generation area compared to the visual loaded area?

# Answer
> 23 votes
Yes, it generates more chunks (or at least more of the village tree) than you think it does. This is what I call "area of interest" in my voxel code. There are two kinds of area of interest:

1. Logical (which is what we're discussing here)
2. Rendering (which is typically be smaller in radius than the logical area)

Remember that the only way your renderer can have access to part of the complete picture, deterministically, is to generate the entire village's tree structure, topographically, from its root (the village centre). This is because even if your rendering view area only nominally overlaps the village boundaries, full generation still has to be done to get the sequential hash required for the next step.

Every chunk's generation is affected by some combination of:

* Chunk's coordinates within world
* Its neighbours terrain & layout
* The process which is mentioned in that video, which is the generation of a maximum `n`-deep tree of buildings and streets, which MUST be completed in its entirety to be true to the same form that you will see when walking into the centre of that village. At every step of that generation, it may be that a hash is taken from the combined current state of the village - thereby pseudo-randomly determining the next step - note what he says at 3:08 in that video.

...So really, from a determinism point of view, there are no shortcuts here.

This is undoubtedly computationally expensive, especially as if you are only on edge of the of the horizon near to the outermost borders of a village, still the game must generate the village in its entirety, even if it renders very little or none of that.

# Answer
> 10 votes
# Technical stuff

During Minecraft's chunk generation a chunk passes several stages before it is done and can be rendered.

These stages, in order, are as follows:

* `EMPTY`: Just as indicated, the chunk barely exists and is empty.
* `STRUCTURE_STARTS`: Here world generation decides whether a chunk might be the origin of a structure, and if so, it also generates the basic layout (e.g. for a village: which houses to include, where to place them and how to connect them). This is handled on a very abstract level (every piece of a structure is just a cuboid bounding box).

> This stage basically chooses structure pieces and aligns them with jigsaw blocks (as explained in the video).
* `STRUCTURE_REFERENCES`: Other nearby chunks might be the origin of a structure, and if so, it might influence this chunk, so references get added.
* `BIOMES`: Generates exact biome data for the chunk.
* `NOISE`: Initializes noise data (populates some rough height maps). If structures are present, they get included in calculations (but remain unchanged themselves).
* `SURFACE`: As the name suggests, this step generates a biome-specific raw surface (e.g. plains: bedrock, stone, top layer of grass/dirt) using the height map from the previous step.
* `CARVERS`: Carves caves into the chunk.
* `LIQUID_CARVERS`: Carves underwater caves into the chunk.
* `FEATURES`: This is where all the detailing work happens. Ore generation happens here, as well as tree placement, or the actual structure manifestation.

> This stage generates the actual houses from the predetermined structure files and randomizes them a bit. It also generates the connecting paths (which adhere more strictly to the generated terrain.)
* `LIGHT`: Light everything appropriately.
* `SPAWN`: Spawn entities (animals, villagers, drowned, ...)
* `HEIGHTMAPS`: Calculate some very detailed height maps for various purposes.
* `FULL`: Finalize chunk generation. Once this step is complete the chunk is ready for rendering. (whether it will be rendered depends on other factors.)

Do note that chunks are not generated in isolation: Other chunks nearby exist in different stages of generation. Without this, stages like `STRUCTURE_REFERENCES` would make no sense, as where would those references refer to? Before a chunk can enter the stage `STRUCTURE_REFERENCES`, all chunks in region around it must first finish stage `STRUCTURE_START`. (This is the main bottleneck in the generation process, later stages can be processed quite independently.)

# Back to the question

You have drawn some hard borders around the "loaded chunks" area. This is, as already explained above, not really what happens behind the scenes: The "loaded chunks" area has a much softer border of several partially loaded chunks. Among these partially generated chunks is the village center - which is how chunks inside the hard border knew that they should generate some village buildings.

> Fun fact: some of this is visualized by the animation you get to see when generating a new world:
>
> * The black outside area represents empty chunks
> * The light gray area represents chunks that passed the stage `STRUCTURES_START`
> * The white chunks are finished
> * The green chunks are somewhere in between (after `LIQUID_CARVERS`)

---
Tags: procedural-generation, optimization, minecraft-modding
---


# Question
Title: How can I implement foot pedal of a car in unity?
I trying to create 2-D car game in unity for mobile where player controls acceleration by sliding the pedal in touch screen.Mine idea of implementation is using UI slider. Is there any other good I can use? Please suggest me any other implementation if any available.I'm new to this field.

# Answer
I don't know how is your programming skills but i will try to explain it simple.
you can define a float variable for your car which is always effecting the logic ( or the code ) that moves the car.
you can get and set slider current value , max value and min value which they are also the float type, take a look at Slider in docs.
to put things simple i will make it into steps:

1- define a function that will moves the car. ( basically with Translate)
2- Put the slider in the game.
3- Create a script that will pass the slider value to speed value of moving function.
4- Tune the speed by playing with values.

if you have some basic programming skills or watched unity scripting tutorials then you should be able to do it easily, if not then i recommend to stop making game for now and start watching unity tutorials at least.
> 1 votes

---
Tags: unity, input
---


# Question
Title: Small health bar above entity is drawn differently when the entity is rotated differently
**Here is a simple positioning code for my health bar:**

```
transform.position = Camera.main.WorldToScreenPoint(target.position - 0.2f * target.up);

```

**Here is the prefab:**

* HealthBar is middle-center anchored, and 0.5, 0.5 pivoted,
* Background and Fill are stretched and 0.5, 0.5 pivoted, but background is Left, Right, Top, Bottom -1 positioned.

**Here is how it should look:** (all images are zoomed in)

**And here is a video about the entity rotating around: https://i.imgur.com/EOzFEvt.mp4**

2 example rotations, in which the health bar is drawn incorrectly: (see the border of the bar)

Why?

**Edit:** Another interesting artifact:

* If I'm **moving the camera** up, the **healthbars are offsetted** up a bit, and if I start moving down, it's instantly offsetted down, with left and right the same, etc. As soon as I stop, it's at the correct position, but as soon as I start moving, it becomes offsetted to the direction I'm moving.

**See gif:** https://i.imgur.com/K8mwzTW.mp4

**Fix for this:** Place it in LateUpdate.

# Answer
It looks like you're using Unity's 2D Pixel Perfect package, with Pixel Snapping toggled on in the Pixel Perfect Camera component.

That can cause effects like this, as the float-valued positions of your components get snapped inconsistently. In this case, as your character rotates, the background and fill of your healthbar are snapping differently, causing the bar and border to fluctuate in size/shape.

I'll go over some of the causes I've seen, but I imagine there are many more.

**Asset design:**

This is the big one: Building your art exactly to match your intended pixel sizes can remove a lot of snapping issues.

E.g. if you're targeting 640x480, and you want your health bar to be roughly 5% of the screen wide, you might create a 32x8 background and set the PPU appropriately. Then if you want a fill inset by 1 pixel, you create another 32x8 piece of art with the outer 1 pixel transparent, and position it atop the other. Then, you need to round your fill values so that they match the 30 pixels of fill you have.

With same-size art, pixel snapping should be consistent, and you shouldn't see the artifacts in your question.

**Canvas sizing:**

Canvas objects commonly have scale values with numbers like "0.05770617", which does not map to integer values well. You may need to configure your canvases differently, perhaps avoiding Screen Space - Camera/Overlay entirely. (I have not had to avoid them in my projects, but it could be an issue in yours.)

**Object positioning**

You may need to manually snap some object positions to 'safe' values, if the engine isn't doing it correctly for you.

E.g., maybe you need to round the position of your health bar to the nearest 1/16th of a unit, because that works in your testing.

**Object positioning and floating point precision**

If you calculate positions and forget float issues, you might end up failing when you try to overlay two objects. E.g., giving one with position x=0.3 and another with x=(0.2 + 0.1), you may find that they snap differently once in awhile.

**Editor scale:**

Lastly, even with everything above correct, using power-of-two-friendly scales in the Game tab can help reduce this in-editor, e.g. 0.5x, 1x, 2x.
> 1 votes

---
Tags: unity, rendering, gui
---


# Question
Title: Why is my program "not responding" when I run it?
I'm trying to learn to code with python and while using pygame, I came across this: every time I run the window it says "not responding".

Specifically, it happens when I click to drag the window; the title changes to "not responding" and I do not know what to do.

Here is all of my code:

```
import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Game Test")

```

# Answer
> 1 votes
Looking quickly at a hello world with pygame, I landed on this page.

Here is the code they use:

```
import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

```

Your program needs to be "alive", this means that you need to have a *main loop* that will handle *at least* the events that are sent by the OS, Windows in your case.

If you don't process these events, windows will know about it and think that the program is frozen (i.e. *not responding*). You'll also want to make sure that you draw something (that's with the last line in the example).

---
Tags: python, pygame
---


# Question
Title: If I use vertex shader to do all operations on object, then constant buffer can be empty?
The program cycle is

```
Update();
UpdatePipeline();

```

In `Update()` constant buffer for each object, that after transformations, has this object world matrix is copied to GPU upload heap. And in `UpdatePipeline()`, among other things, installed shaders are called. Because we do all matrix transformation using CPU, vertex shader just returns position, right? If yes - is it true that performance will increase?

Now I want to do all transformations using GPU, i.e. via vertex shader. It means that in `Update()` I just should call `memcpy()` with an empty constant buffer as a source?

---

Learning more, I found that I can put in constant buffer position vector `float4` or matrix `float4x4` of vertex, and as a **root constant** choose `ProjectionView` Matrix. The shader will mul one on other. Keep searching... Or constant buffer is one of the root constants? Confused

I don’t understand how to choose what to send as an argument to shader function, like input here:

```
VS_OUTPUT main(VS_input input)
{
...
}

```

As I understand, I can access constant buffer the next way:

```
cbuffer ConstantBuffer : register(b0)
{
float4x4 mat;
}

```

There can be `ProjectionView` matrix, okey got that. But how to send vertex pos to input then?

# Answer
It very much depends on the use case. The best option you could do is to implement different methods and choose depending on which is fastest and easiest to maintain for your project. Some points to keep in mind:

* Vertex shader is a very good place to transform vertices as it is designed exactly for that purpose.
* It is very good to keep the vertex shader to a minimum, too, so if you can premultiply matrices on the CPU. For example, View and Projection matrices are usually premultiplied on CPU, so the shader only has to transform vertex with ViewProjection and World matrix. If you don't care about vertex world position, only the screen position, then you can also premultiply World matrix with ViewProjection matrix.
* Transforming all vertices on CPU by viewprojection matrix is usually not recommended, but transforming them with world matrix or skinning animation is not uncommon.
* You probably want to have matrices in ConstantBuffer, because Root Signature space is very limited. If you store a single matrix in a root signature, you won't be able to store anything else as it takes up all space of 64 DWORDs. Also, the input assembler (vertex buffer, index buffer) want space in the root signature too.
* You can read data from the vertex buffer in multiple ways in a vertex shader. If you use IASetVertexBuffers(), you will receive the vertex properties as input parameters to the shader function. You can also bind a shader resource view of the vertex buffer and have a `uint vertexID : SV_VertexID` input parameter to the vertex shader and index into the vertex buffer (that could be declared as ByteAddressBuffer, StructuredBuffer, or Buffer in the shader).
* You can also use instancing, which will allow to render one vertex buffer multiple times with different transformations. For that, you will need to use instance buffers, which are filled with transformation matrices. Again, which matrices you have in the instance buffer or constant buffer are up to you, but commonly world matrix should be in the instance buffer, viewprojection matrix in a contant buffer. The instance buffers are bound with IASetVertexBuffers() call, but their input layout must specify `INPUT_CLASSIFICATION_PER_INSTANCE_DATA`.
> 1 votes

---
Tags: directx, hlsl, vertex-shader
---


# Question
Title: Multiple cameras using a single skybox with same perspective
I am using the enviro package for weather and to have a moving sun in the background. I'm building an installation with 3 screens and I want to have the sun track across the screens. However what I end up with is 3 separate skyboxes and 3 suns, one on each screen.

Is there a way I can have the cameras share a single skybox?

# Answer
You'll need to set the camera directions on each screen to match the relative display locations and synchronize everything else between the screens.

That way you will with a setup that looks like 3 different cameras looking at the same skybox.
> 0 votes

# Answer
This happens because you are in the Editor, and you have opened 3 Game tabs, each game tab is a separate game render. You need to either move ONE game tab out from the main view and resize stretch it to fit all 3 screens at the same time, or build program and launch it(once) in one window.
> 0 votes

---
Tags: unity, camera, skybox
---


# Question
Title: Question about taking mouse input in unity 2D
I'm learning a course on unity and when we started learning about taking mouse input the following code is used.

```
Vector3 pos = Input.mousePosition;
pos.z = -Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
gameObject.transform.position = pos;

```

My problem is in the second line. Shouldn't our Z be 0 instead of minus wherever our camera is? Because the plane where we our designing our game is in z = 0, right?

Please go slow on me I'm still new to unity. Thank you!

# Answer
The z-coordinate given to ScreenToWorldPoint is the distance from the camera plane. If you set z to 0, the position returned will be in the camera's plane.

Is the ground plane at (0,0,0)? And the camera is at (0,0,-z) and pointing along the +z direction?
> 1 votes

---
Tags: unity, 2d, input, mouse
---


# Question
Title: Unity Transform.Position not returning expected position
So in my scene hierarchy, I have an object laid out like so; -Level1 --Level2 ---Level3 ----Level4

My script is attached to the Level1 object. When I try to find the transform.position of Level4 by way of Debug.Log to the console, I get the position of Level1, and so when I change the position of Level4 inside Level3, the data sent to the console doesn't change, still shows the position of Level1.

I do not believe this may be relevant, but what I am doing is an IK rig to move a character's limb. The object for which I am attempting to find the position is nested inside the skeleton of the character. The value returned to me is the position of the prefab placed in the scene. All of the objects (Level1 through Level4) are not explicitly moved, however they inherit their positions from the rotation of their parent.

My code to read the position is as follows:

```
Debug.Log(object.position);

```

Where object is already a transform. I have also tried:

```
Debug.Log(object.transform.position);

```

But still, all I get is the position of the top level parent.

Thanks for any help.

**ADDITION**

Ok so to expand on the question, I'll explain exactly what I'm trying to do. I have the mecanim example and unity 5.0.1f1. I have the Mecanim Example project from the asset store and I'm in the animator controller scene. I have enabled IK pass on my base layer, and have placed my code in the "idle run jump" script, attached to the top level of the game object for the playable character. I have then attached an empty game object inside the left foot to mark the location of where the left heel meets the floor. This object is attached in the inspector to a variable in the "idle run jump" script, which then receives the ik pass through the function OnAnimatorIK. My aim is to get the foot to follow the same position as another object, where leftFoot follows leftFootObj. My code is as follows;

```
using UnityEngine;
using System.Collections;

public class pos : MonoBehaviour {

    protected Animator animator;
    public float offset = 0.156f;

    public Transform leftFoot;
    public Transform leftFootObj;

    void OnAnimatorIK() {
        if (animator == null)
            return;

        if (leftFoot != null) {
            Debug.Log(leftFoot.position);
            animator.SetIKPositionWeight(AvatarIKGoal.LeftFoot,1);
            animator.SetIKRotationWeight(AvatarIKGoal.LeftFoot,1);
            animator.SetIKPosition(AvatarIKGoal.LeftFoot,(leftFootObj.position+(Vector3.up*offset)));
            animator.SetIKRotation(AvatarIKGoal.LeftFoot,leftFootObj.rotation);
        }
    }

    void Start ()
    {
        animator = GetComponent<Animator>();

        if(animator.layerCount >= 2)
            animator.SetLayerWeight(1, 1);
    }

}

```

# Answer
The position of level4 is dependent of all its parents, if you want to attach your script to the parent level1, you can call the first child of a gameObject by :

```
this.transform.GetChild(0).transform.GetChid(0);

```

This will address the first child of the child of the gameObject attached to the script, if you want to go deeper, just repeat the function. If you would like to call the child directly by Name instead of using this method, just use :

```
GameObject.Find(Level1/level2/level3/level4);

```

and then address its transform, or whatever you need from it.
> 1 votes

# Answer
Despite my late reply this answer might be the solution that some people are looking for. It might save you hours of debugging as it would've saved me quite a lot if I found an answer like this. **The answer is bad pivot points.**

I had the same issue where the nested childs of a gameObject had the same position as the top level parent. In Unity the pivot point is *default* shown at the center of the gameObject. However this might not be the case in the actual model! Simply by toggling the tool handle position from **Center** to **Pivot** should show if pivot points are the issue here (which it was in my case).

The artist on my end had simply detached objects to create children, however the pivot point was not reset to be a zero position of the new mesh (child). It was still the same point as that of the previous mesh (parent). This resulted in the pivot points of nested children being the same as the parent.

If you encounter the same problem, triple check the pivot points in your modelling software before starting countless hours of debugging trying to figure out what is resulting the "fake" position... while the pivot simply isn't in expected position.
> 0 votes

# Answer
I caused this issue to myself by organizing my game objects within an empty game object that didn't have a transform x/y/z of zero. Set that transform x/y/z to zero, and I started getting the correct numbers again.
> 0 votes

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


# Question
Title: Get FVector from Blueprint tick function
In my BluePrint Tick function for my character, I have a FVector that always changes, and in my C++ component, I want to get this changing FVector and use it in my C++ Tick function, is that possible to do?

# Answer
To set this in C++, you need to create a UPROPERTY in your C++ code then write a function to set this property.

In your C++ header file:

```
UPROPERTY(BlueprintReadWrite, Category = "FVectors")
FVector MyCPPVector;

UFUNCTION(BlueprintCallable, Category = "FVectors")
void SetFVector(FVector VectorIn);

```

And in your cpp file

```
void SetFVector(FVector VectorIn)
{
    MyCPPVector = VectorIn;
};

```

Now after you've set the FVector in your Blueprint, call the SetFVector function and plug the BP FVector output into the input of the function.
> 1 votes

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


# Question
Title: How to set drag events on a Phaser 3 group?
I'm trying to set a drag event on a Phaser 3 group, but I wasn't able to achieve what I want. I was reading some Phaser 2 blogs, and they said that it isn't possible to set a drag event on a group.

How can I go about creating similar behaviour?

# Answer
First let me explain the group behaviour here: the group game object does not have any shape or body, as it is basically an Array of game objects `Array<gameObject>`. So, it doesn't have any input events assigned.

As a group stores all its child data in a property called children, I suggest that you iterate through the children and add your mouse event to the game objects individually.

Otherwise, you can add all your gameObjects to the container and add your mouse event to the container, which would also give you the expected result.
> 1 votes

---
Tags: javascript, phaser
---


# Question
Title: AoE 2 DE - Modding a building to have two page interface
I am using Advanced Genie Editor and currently trying to create a copy of a Krepost and give it a second page of units (like the docks). I have so far been unable to do it as the second page just doesn't show up. The unit's train button is, of course, numbered to appear on the second page (i.e. 21). I tried changing the interface to match that of the dock (i.e. 2) but to no avail. Anyone have any idea regarding how to do it?

# Answer
> 1 votes
Turns out the two-page interface is hardcoded to docks and cannot be used by any other building, default or mod.

---
Tags: modding, rts
---


# Question
Title: Managing audio in a RTS - when do I play sounds?
Building an RTS I have several hundred units on screen at one time.

Whenever a Unit attacks/gathers something, I want to play a sound (if camera is close enough).

My question is, how do most RTS games do this? Do I play 1 sound per attack per unit, i.e if 200 units are fighting do I play 200 individuals sounds (one sound each time a unit attacks)?

Same goes for gathering, if 20 workers gather wood, do I play a sound each time they hit a tree?

Does this not use up a lot of resources? Is there a better way?

# Answer
> 2 votes
Yes, every event causes an audio source to play. But if you just naively play sound effects in an additive manner, then it is hard to get the volume right so that one unit can be heard but 100 units don't cause an eardrum-rupturing cacophony of noise.

Fortunately the Unity audio mixer system can help you with that. If you add a normalization filter to your audio mixer chain, Unity will adjust the volume of individual sound effects in a way that the volume of the final mix is always within a reasonable range.

And then there is of course the question of where you place your audio listener. You *could* place it on the camera as usual, but then almost all the battle noise will come straight from the front. Personally I find it quite pleasing to cheat a bit and place the audio listener closer to the ground. This gives you more stereo sound which results in a IMO more satisfying "being on the battlefield" ambience vibe.

I am looking forward to hearing your game.

---
Tags: unity, audio, sound
---


# Question
Title: Intersecting ORCA lines finding non-optimal solution for fast units
I've decided to implement my own algorithm for optimal reciprocal collision avoidance. It doesn't use linear programming, but iteratively projecting velocity on intersections of ORCA lines and checks if it is collision-free. It works great for relatively slow units, but fast units tend to stop under certain circumstances.

The problem arises when there are two or more obstacles with the same velocity, and their velocity obstacles are intersecting with each other, and the goal velocity is inside the both velocity obstacles, and the goal velocity is close to the edges of both of the velocity obstacles rather than the truncated parts.

So, according to the ORCA lines, the closest collision-free velocity sometimes becomes not optimal, or locally optimal, which can cause a unit to slow down or go backward or even stop (when obstacles have zero velocity) while there actually exists a better collision-free velocity but is left out due to ORCA lines.

* I've read some papers, but none of them mentioned such problem.
* I've also tried to inspect the library which the original algorithm resides, but I was unable to understand it.
* I've tried merging obstacles into single bounding obstacle, which worked when the problematic obstacles were only two, but when there were more of them, it caused a very big obstacle, which blocked the whole way the agent was supposed to use.

If anyone is familiar with the concept and can let me know how to deal with the issue, or if anyone has another idea, I'll be glad.

# Answer
> 1 votes
Okay, I've found the problem, and it was written in the original paper, which I missed among all other papers apperantly… I mean, there were tons of papers about it, that, for some reason I never thought of “What about the original research?”

Anyway, if anyone else wonders, it seems that, we are not suppose to use the goal velocity during creation of ORCA lines, but the current velocity of the agent. The reason to that is, the goal velocity is most of the time very big in size, like almost constant, so it has that problem I stated, but the current velocity is more dynamic. For example if an agent can't find a valid collision-free spot and stops or slows down, then in the next turn it will be doing all calculation with that zero or some small velocity, which has much greater chance of finding a solution.

---
Tags: algorithm, collision-avoidance
---


# Question
Title: What folders can be safely deleted after building UE4 from source?
What folders, if any, can be safely deleted, after building UE4 from source? After the build, UE4 files occupy 65 GB of disk space, which is way above comfortable for me, since I only had 72 GB free. I would like to cut the folder down to size, say at least 25 GB. Are there any files that are not required to use the Unreal Engine with full functionality? Thanks

# Answer
You can generate an installed build: https://docs.unrealengine.com/en-US/Programming/Deployment/UsinganInstalledBuild/index.html

This will output a standalone binary engine that is somehow identical to engine you would download from the launcher .

Then you can delete all the source files.
> 1 votes

---
Tags: unreal-4
---


title: Unity: Unsharp edges

text:
# Question
Title: Unity: Unsharp edges
I have a Unity Project and somehow the edges of objects in my Scene (Scene view and game view) look like this:

I think I already had that problem once, but in my recent projects, this didnt happen anymore.

Is there any solution to that?

# Answer
Solved:

Simple answer: The unsharp edges are normal, but anti-aliasing solves the problem.

Longer answer: In my case, the anti-aliasing still did not manage to make it look good enough. However, I discovered the Universal Render Pipeline, one of the 2 new render pipelines by unity (probably, the High Definition Pipeline would give an even better look).

I made a new URP project and in the settings of my main camera I activated anti-aliasing and set it to Fast-Aproximate-Anti-Aliasing.
> 0 votes

---
Tags: unity, graphics, gameobject
---


# Question
Title: What is the correct way to make an Installed Build?
I am trying to use the Automation tool, following the documentation.

> To create an Installed Build:
>
> Run the Installed Build Script by invoking the AutomationTool with the following command line, **replacing \[PLATFORM\] with either Win64 or Mac**.
>
> BuildGraph -target="Make Installed Build \[PLATFORM\]" -script=Engine/Build/InstalledEngineBuild.xml -clean

However, I am getting this error.

> `ERROR: Target 'Make Installed Build [Win64]' is not in graph`

I am not sure what I should put as the platform.

I searched the config file, but don't see any specified platforms.

# Answer
> 0 votes
Remove the brackets.

```
BuildGraph -target="Make Installed Build Win64" -script=Engine/Build/InstalledEngineBuild.xml -clean

```

That works.

---
Tags: unreal-4
---


# Question
Title: TCP vs. Reliable UDP? Sending Reliable Packets in Fast-paced Multiplayer Games?
I'm currently working on a networking framework for Unity3D in order to simplify making multiplayer games. I'm using UDP for any kind of synchronisation and unimportant data.

My question is: how do I send reliable packets such as RPCs or object instantiation? Should I use TCP for that or should I go about writing my own reliable protocol on top of UDP?

Thanks in advance!

# Answer
> 2 votes
Running both TCP and UDP in parallel just leads to problems. Also, you might not need *all* the reliability features of TCP, so it might be overkill anyway.

Most games solve this problem by replicating those TCP reliability features they really need on the application level.

* Do you have the concept of persistent connections? Add a connection-ID to every message.
* Do you need delivery guarantee for certain messages? Have the receiver reply to these message with a confirmation. Resend any message when the confirmation doesn't arrive within a given timeframe.
* Do you need to know the order in which messages were sent? Add sequence numbers to your UDP messages.
* Do you need guarantee that sequences are processed in sequence? Add sequence numbers and allow the receiver to re-request a message with a given sequence number. Have it do that when a missing sequence number doesn't arrive within a given timeframe.

Implementing all of this on your own gives you far more control over what actually happens on the network level than just letting TCP handle it. But the bottom line is, **real-time networking is complicated**. Every game developer is well-advised to not reinvent the wheel and instead take a look at what reliable UDP libraries for game development are available for their programming language.

---
Tags: networking, multiplayer, udp, socket
---


title: Unity shows pixelated noise in Scene

text:
# Question
Title: Unity shows pixelated noise in Scene
I have open Unity today with a weird bug happening. I can see pixelated noise (I don't know what else to call it), and restarting Unity or my Mac does not work. What can I do? It doesn't affect the game, this just shows in the Scene.

EDIT:

It indeed seems that it has something to do with the camera GameObject; when I remove the Camera the problem goes away. Re-creating the camera does not solve the problem.

It seems the problem goes away when setting the Camera setting "HDR" to "Off", but that still doesn't explain why it happens in the first place.

# Answer
> 1 votes
It seems the GameObject "Camera" was the culprit; more specifically setting the option "HDR" to "Off". I'm going to contact the Unity support to see if they can help get to core issue, but for now at least I was able to get rid of the pixel glitch.

---
Tags: unity
---


# Question
Title: How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick?
So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick?

---

**CODE:**

```
public float moveSpeed;

Rigidbody2D myBody;

protected Joystick joystick;

void Start()
{
    myBody = GetComponent<Rigidbody2D>();
    joystick = FindObjectOfType<Joystick>();
}

// Update is called once per frame

void Update()
{
    myBody.velocity = new Vector2( joystick.Horizontal * moveSpeed, joystick.Vertical * moveSpeed );
}

```

# Answer
It sounds like you want something like this:

```
// Minimum amount of joystick deflection that should count to change direction.
public float joystickThreshold = 0.1f;

// Let's save a vector for our current direction of travel.
// (Initialize this to your default movement direction if you don't want to spawn at rest)
Vector2 moveDirection;

// ...(I'm skipping over your other member variables & Start to be concise)

void Update()
{
    Vector2 stick = new Vector2(joystick.Horizontal, joystick.Vertical);

    // If the player leans the stick far enough, update our direction of movement.
    if(stick.sqrMagnitude > joystickThreshold * joystickThreshold) {
        moveDirection = stick.normalized;
    }

    // Continue moving in the last chosen direction.
    myBody.velocity = moveDirection * moveSpeed;
}

```
> 1 votes

# Answer
I don’t know enough about Unity in particular to know how to get the relevant information, but it sounds like the engine-independent way to describe what you want is the following:

If there was any input, store the indicated direction. On each frame, move in the last stored direction.

I’m assuming here that if the player returns the joystick to the center you want the plane to keep moving in the last direction it was moving in. So you might need to specify a deadzone in the center where you don’t count the joystick movement as input for the “if there was any input” check above.
> 0 votes

---
Tags: unity, c#, physics, vector, joystick
---


# Question
Title: Using a state pattern across multiple controllers / general architecture advice
I'm trying to implement a state pattern - having skated by with enums forever - and have hit a bit of a wall when it comes to it's implementation in my game. It's a grid based strategy game with an MVC hierarchy.

The general flow is `InputManager -> CursorManager -> GridManager`. So if the player presses "Up", the InputManager will translate that to the appropriate action and notify the CursorManager. The CursorManager will then update the cursor's world position and then then prompt the GridManager to find what's in the hex in order to update the UI with terrain/unit info.

My new addition is thus having the GridManager change the cursor's state depending on what's in the tile. You pressed up? Let's let the cursor state dictate what happens to the grid. So naturally I created a cursor state object in the CursorManager, but suddenly realized each state needed decent amount of shared information across different the two controllers.

For instance,

```
public class FreeCursor : CursorState
{
    public override void ActionPressed()
    {
        currState = gridManager.selectTile(cursor.position);
    }
}

```

So this means the FreeCursor state would need reference to the GridManager object, reference to the cursor GameObject, and also a reference to the current state itself. All 3 of those are already in the CursorManager, so it's no problem, just throw them all in a constructor: `FreeCursor(CursorState context, GridManager gridManager, GameObject goCursor)`

But d'oh, when `gridManager.tileSelected()` completes, it should return the new state. So the GridManager should be saying

```
public CursorState selectTile(Vector3 position) {
     //...
     return new FreeCursor(this);
}

```

...Except now we're missing the GameObject and the current cursor state, which aren't accessible in the GridManager.

So I could go one or two ways - make the GridManager also contain a reference to the context, so it becomes `return new SelectedUnitState(this, CursorManager)` and changes our flow to be `InputManager -> CursorManager <--> GridManager`. Or I could say screw it, throw the cursor state and GameObject into the GridManager and call it day.

...But both feel just wrong? The latter through combining two somewhat distinct controllers - the former by making the state be passed it's own containing object like a poor man's reflection or something. Because if I do that, I might as well just use Unity's `GameObject.Find(Cursor)`. Am I wrong to think this? And if so, is the problem with my implementation of the state pattern or the way I've laid out my 'architecture'?

**tl;dr:** How do you handle a state pattern with data from multiple controllers?

Thanks!

# Answer
> 1 votes
If anyone comes across this, I think I kind of figured it out.

**It's an architectural problem.** When the game would change state, say entering into a battle cutscene, there's no reason for the InputManager to interact with the CursorManager. The cursor is deactivated in the background and is irrelevant to the current state. Likewise during the AI turn, the player will not be able to move the cursor.

Thus game state instead should have a `HandleInput()` section that just handles it on it's own, or for some reason route to another controller.

The flow for the original scenario becomes something like `InputManager->BattleManager:handleInput(){moveCusor()}`

So yes, in a sense, I'm combining the CursorManager into the GridManager, but it's not pasting two together - it's the way it should probably have been. The only reason I was focused on the direct Input-\>CursorController was because most games just are Input-\>PlayerController.

Which is fine...for single state prototypes. My game is just starting to hit the growing pains of putting off making proper game states, that's all.

---
Tags: unity, c#, design-patterns, state
---


# Question
Title: In rendering pipeline，is there any order between depth test/alpha test and stencil test？
So the order between them is important？Or the order just depends on hardware？I have no idea which one needs to come first.

# Answer
The OpenGL specification defines these as happening in the following order:

* Alpha test
* Stencil test
* Depth test

However, this order may not be strictly applied by all hardware or APIs. One example is if using an API that does not have alpha test, you would need to emulate it with discard instructions in your pixel shader. In that case it would still come first, but it would happen at a different (and earlier) pipeline stage - potentially before other operations that come between.

Another, more common, example is early depth testing. Depending on the combination of other states, modern hardware can often do a depth test before the pixel shader stage rather than after it, which can be a significant performance win. In that case the depth test comes much earlier - before the others you're interested in - but if the result would be the same as if it had run later, this is OK.
> 1 votes

---
Tags: graphics
---


title: how does collaboration in unity work?

text:
# Question
Title: how does collaboration in unity work?
i've been working on a 2d game for a bit now, almost all assets made but when ive tried to collaborate everything was quite glitched out, edits weren't saved, nothing was working at all. im not sure quite what the problem was because we were both on the latest version.

maybe i got to something wrong, or did something wrong im not sure. this was a few months ago now and ive been busy but i want to come back to this project. should i start over?

# Answer
> 1 votes
Maybe you had messed up using collab at the first time. Collab is really simillar to git. Initiallize, update diff, merge conflicts... You'll get along to it.

I suggest you to reset the collab, as it have been a long time from last work. This article should help.

Also, take a look at the manual of Unity Collaborate.

---
Tags: unity, teamwork
---


# Question
Title: How to program (architecturally/organize) a set of customizable changes to a game?
The floor of my game (tower defense) is composed by a set of cubes. I wish to change these on some of the waves. I have a list of the changes that need to be made on each wave in a floorController class. However, in order to decide which floor cubes should appear or disappear on each round, I had to assign each cube a bool for each wave (if this is set to true the floor changes in that wave). However this process is tedious and not ease to change and customize in order to experiment with the level. From an architectural programming perspective how can I better structure this system?

# Answer
> 3 votes
**Code vs. content**

Game level layout is typically stored separately from your codebase. Why? Because as you've discovered, the *cost of change* for code is higher than the *cost of change* for say, a text file.

In your simple case, I would opt for something like what Angband does to describe its vaults:

```
       %%%%%%
    %%%..##..%%%
  %%....####....%%
 %......#&&#......%
%...4.##+##+##.4...%
%.4.4.#&#&9#&#.4.4.%
%.4.4.#&#9&#&#.4.4.%
%...4.##+##+##.4...%
 %......#&&#......%
  %%....####....%%
    %%%..##..%%%
       %%%%%%

```

The structures you need are drawn/typed by hand in a text file this way, for all your levels or for each level as a separate file. You typically load / parse these either at game startup, or whenever they need to be used (e.g. player has reached level 3). You could write these out as text files initially, then store them in `PlayerPrefs` or as text files on server (e.g. Node).

Up to you, *but I'd start by using hand-editable text files loaded from the game's own folder*.

**Your case**

For booleans, a level matrix may be as simple as:

```
11101
01111
01110
11111
00100

```

...this totally depends on how you want to represent a missing vs present floor tile - it doesn't have to consist of 1s and 0s!

If you need more information per cell, you can either use multiple characters with separators (e.g. `|`) for each cell, or you can draw multiple maps per level with one character per cell, as shown.

These are your decisions to make, because you'll be the one writing the code to parse / understand this information in order to create levels with it.

---
Tags: unity, architecture, design-patterns
---


# Question
Title: How to add or increase speed on every 500m distance of player?
I'm a a beginner, creating an endless runner game.

I want to increase speed as the player completed the distance and on every 500 meter speed should be increased. Anyone have an idea of how to implement this kind of logic?

```
speed=10;
//as soon as player reach 500 m distance
//speed should be incremented
//it should be continuous process on every 500m

```

My code:

```
public class Score : MonoBehaviour
{
    [SerializeField]
    GameObject ground;
    [SerializeField]
    AudioClip clip;
    [SerializeField]
    Transform player;
    [SerializeField]
    public Text LiveScore;
    [SerializeField]
    public GameObject gameOver;
    [SerializeField]
    public bool runningScore = true;
    public Text finalScore;
    public Text Highscore, bestScore;
    float distance;
    ball Ball;
    // Start is called before the first frame update
    private void Start()
    {

        Ball = GetComponent<ball>();
        //  PlayerPrefs.DeleteKey("HighScore");
        Highscore.text = "Best :" + ((int)PlayerPrefs.GetFloat("HighScore", 0)).ToString();
        bestScore.text = "Best :" + ((int)PlayerPrefs.GetFloat("HighScore", 0)).ToString();
    }
    // Update is called once per frame
    void Update()
    {

        distance = player.position.z + 500;
        if (runningScore)
        {
            LiveScore.text = distance.ToString("0");

            //  Highscore.text = LiveScore.text;
        }
        if (runningScore == false)
        {
            float score = float.Parse(LiveScore.text);
            finalScore.text = "Score:" + LiveScore.text;
            if (PlayerPrefs.GetFloat("HighScore", 0) < score)
            {

                PlayerPrefs.SetFloat("HighScore", score);
                Highscore.text = "Best :" + score.ToString();

                bestScore.text = Highscore.text;
                AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position);
            }
            else if (score < PlayerPrefs.GetFloat("HighScore", 0))
            {

                bestScore.text = Highscore.text;
            }

        }

        while (distance > 500)
        {
            Ball.speed += 5;
        }

    }

}

```

# Answer
`speed = startSpeed + (int)(trackedDistance / 500) * speedIncrement;`

Now your new question is, *"how to track distance of player"*, Since its endless runner game:

`trackedDistance += speed * Time.deltaTime`

`Ball.speed = speed;`

Your welcome.
> 1 votes

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