# Question
Title: How to handle "identity" of unit/building types within an RTS context?
**TL; DR: How do I give unit and building types a unique "identity" without turning my codebase into a mess?**

I've been reading the genius Game Programing Patterns and it's made me very (painfully) aware of bad code design. I'm currently building a somewhat unconventional RTS that still abides by the basic conventions of the genre (i.e lots of different types of units and buildings). I want selectable objects to be able to intelligently know the nature of other selectable objects. For instance, if I were to click on a trading wagon and then click some allied selling destination, it would intelligently know to begin moving goods and selling them there, whereas if I clicked it and then a repair shop, it would know to go and get repaired.

My question is how to give every independent building and unit type its badge of "type-ness" that can be read by other units.

# Class Inheritance?

### Solution 1a:

Every unit and building type gets its own class. There's an extremely wide and shallow hierarchy, with all of them just inheriting from `Building` or `Unit` which inherits from `SelectableObject`. The issue that makes this a non-starter for me is the amount of code duplication. I don't want to give every individual combat unit the same combat code.

### Solution 1b:

The objects are divided into very specific groups and subgroups. `WagonryBuilding` inherits from `ProductionBuilding` which inherits from `EconomyBuilding` which inherits from `Building`. I get an extremely dense and vertical hierarchy that one can traverse as far as they need to understand what sort of object they're dealing with.

**Pros**:

* Everything is neatly categorized
* I can serve UI views based on what general type of building/unit I'm dealing with
* Object interactions can deal with most abstract type needed, allowing for some powerful polymorphism/dynamic dispatch.

**Cons**:

* The only way I can think of enabling a unit to divine exactly what I'm clicking on is a big if-else tree using `typeof()`. I suppose I could maintain an enum of all the object types to upgrade to a switch statement, but it sounds like my `HandleClick` code could get extremely messy.
* The nature of the game is such that some units and buildings defy easy categorization. Take Age of Empires for instance. You may say the Town Center is an `EconomyBuilding`, but it shoots arrows at nearby enemies! That sounds like a `DefenseBuilding` like a Castle or a Tower. Are not Castles and Towers similar, yet a Castle is a sort of `ProductionBuilding` and `ResearchBuilding` and so on. I think I could end up with similar amounts of code duplication if I took this route.

# Interfaces?

### Solution 2a:

Instead of trying to describe an *identity* when interacting between units, I describe a *behavior*. I go back to the wide and flat hierarchy, but this time I define an **interface** for every unit behavior. `ISelectable`, `ICombat`, `IMovement`, `IInventory`, etc. So then units can inspect each other for certain behaviors and prioritize some over the other. For example, a trading unit would look for an `IInventory` where they could deposit their goods. Secondarily, they might engage in some other behavior like garrisoning, transporting, etc, all depending on which interfaces they find on the target.

**Pros**:

* Far fewer types to check for. I can only think of a dozen or so behaviors to turn into interfaces
* Abstraction away from the unit/building divide so I can treat a unitInventory and buildingInventory the same way: `IInventory`.
* I can cross categories and defy any specific sorting of buildings into "production" or "military". Everything can be everything at once.

**Cons**:

* Still need big control flow trees. I'm trying to figure out some way to do a dynamic dispatch of an `InteractionHandler()` method or something but I can't see how to avoid the if-else pyramid of doom.
* Interface implementation seems somewhat more complex and expensive to check for than typeof() (at least in C#).
* LOTS of code duplication unless I use default implementations with the interfaces, but I'm not sure if I can call `base.method()` if I want to extend on it.

### Solution 2b

I use the Unity Component system to get a similar outcome. Instead of interfaces, I load GameObjects with different `MonoBehaviors` that represent different abilities/attributes.

**Pros**:

* Everything that 2a has

**Cons**:

* No extensibility beyond the default implementation of a behavior. Lots of `GetComponent<>()` calls that feel unsafe and expensive.
* Navigating the Component structure can make doing simple stuff very convoluted if I want to store any actual functionality within the different components.

# Prefabs?

### Solution 3:

Just have a `Unit` and `Building` class. Configure them using public fields to shape unique instances of the Unit with different sprites, abilities, etc. This one also feels like a non-starter because every unit has to carry all of the code and data for every other type of unit with it, which is extremely non-optimal.

Is one of these solutions a clear winner? I'm leaning toward 2a but I don't want to pull the trigger and start coding it all up if it's the wrong way. What have RTSes historically used? Is there something I haven't even mentioned that is a better way to think about this? Thank you for reading my novel.

# Answer
> 3 votes
For the type of problem you're describing, I'd recommend shifting your focus away from "**identity**" (is-a) toward "**affordance**" (has-a). This is part of the classic principle of composition over inheritance, with which Unity's component-based structure tends to work well (and it has a great write-up in the Game Programming Patterns book too).

Here, my trading wagon doesn't need to know whether the thing I clicked on was a "Market Building" or a "Town Center" or a "Storehouse" etc. It just needs to know that it **offers the "Goods Receiver" affordance** \- it has the capability to receive goods. We could express this as a `GoodsReceiver` component, which we could attach to multiple different kinds of buildings, or even units (like a nomadic trader unit).

This way I can change the particular set of buildings and units that offer this affordance dozens of times during development, without needing to re-wire this trade wagon behaviour every time. As long as I attach the component my trade wagon looks for, it will know that this target is valid for processing a trade order.

Note that this also neatly solves the Town Center problem you describe, where multiple "kinds" of entity intersect. Instead of needing multiple inheritance from each of these distinct "kind" classes, we can compose all of the affordances of ranged attack, unit production, research, and goods receiving as separate components living side-by-side on one parent object

Similarly, each unit or building can expose a set of components that give **affordances for the kinds of orders that entity can act on**. Let's make an `IOrderReceiver` interface for that:

```
public interface IOrderReceiver {

    // Handle orders issued by clicking a point on the map.
    bool TryProcessOrder(Vector3 target);

    // Handle orders issued by clicking on a unit or building.
    bool TryProcessOrder(GameObject target, AllianceState relationship);
}

```

Now when we click to issue an order, our interface system can iterate over the order-receiving affordances on the selected entity and execute the first one that matches. By stacking our components in priority order, we can decide which orders we want to take precedence over which, independently for each unit/building we might issue orders to. So for instance, by putting our movement component(s) at the bottom of the list, we can the ensure "move to / follow" order responses it exposes will act as a fallback behaviour if no more specialized behaviours match from the components higher-up on the object.

This gives us a fully generic way to issue orders, without the `if-else` pyramid of doom you describe. And the unit/building designers retain full control to adjust the order selection rules in a data-driven fashion, rather than hard-coding it.

Such an order-issuing routine could look like this:

```
List<IOrderReceiver> _receivers = new List<IOrderReceiver>();

void IssueOrder(GameObject clickedTarget) {
    AllianceState relationship = AllianceState.Neutral;
    if (clickedTarget.TryGetComponent(out Allegiance allegiance)) {
        relationship = allegiance.GetRelationshipTo(localPlayer);
    }

    selectedEntity.GetComponentsInChildren(_receivers);
    foreach (var receiver in _receivers) {
        if (receiver.TryProcessOrder(clickedTarget, relationship))
            break;
    }
}

```

Note here that we can use the `TryGetComponent` method to address the safety concern you raised - it neatly handles checking whether the component is present at the same time we try to fetch it, kind of like `Dictionary.TryGetValue`. It also does so without creating any garbage in editor mode, unlike `GetComponent`.

Now our trade wagon can have a component a bit like this on it:

```
public class GoodsTransport : MonoBehaviour, IOrderReceiver {

    [SerializeField]
    GoodsType _goodsType;

    // Goods transports don't afford any specific behaviour
    // when directed to a position.
    public bool TryProcessOrder(Vector3 position) {
        return false;
    }

    // Goods transports have no special behaviour toward enemies,
    // or GoodReceivers that do not process their own carried goods.
    public bool TryProcessOrder(GameObject target, AllianceState relationship) {
        if (relationship == AllianceState.enemy
            || !target.TryGetComponent(out GoodsReceiver receiver)
            || !receiver.CanReceive(_goodsType))
            return false;

        SetTradeRoute(receiver);
        return true;
    }

    public void SetTradeRoute(GoodsReceiver receiver) {
        // TODO: talk to movement component to execute delivery routine.
    }
}

```

The component lookup and iteration does have a cost, but for the case of responding to a user's click (ie. work that you'll do at most once per frame) it's quite reasonable, and won't create a performance bottleneck.

For interactions that can trigger more frequently - like say units on standby/patrol reacting to enemies who enter their line of sight - you can use things like physics layers to pre-filter the items to those that will matter.

# Answer
> 2 votes
I still use interfaces, inheritance and all the rest traditional OOP stuff but far less often. What I gradually began to value most is fast to create and modify while not being too "fragile". Without a big team all the rest is secondary. (honest translator: I gave up on being amazing so I can at least be effective)

I came to an approach that works surprisingly well for me. I began to make extremely generalized behaviours of 2 types - event based or pure behaviours. Event ones are like OnCollision, OnButton, OnRepeat, OnDelay, etc. They react to an event and then trigger `UnityEvent`. Behaviour ones (say Spawn, AssignMovement, Destroy, Damageable, etc) usually have one or more public methods as input and `UnityEvent` as output. `UnityEvents` pass mostly the same types like `GameObject`, `float`, `Vector3`, `Collider`, that way I can wire components in any combination.

This allows me to create all kinds of game entities with the same set of components hard wired mostly through the inspector (then saved as prefabs). And because all game entities use the same components there is rarely a need for interfaces to achieve the non-hard wired/dynamic comunication between them.

To put it from a different angle: instead of insisting on OOP way went to do things Unity way. Prefab variants as inheritance, component composition as polymorphism, UnityEvents as hard wiring interfaces, event components as dynamic wiring interfaces. Of course this doesn't replace the use of OOP it just adds more options that often work well.

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


title: Point System Using a GameManager?

text:
# Question
Title: Point System Using a GameManager?
I am trying to use a GameManager script to store and hold my players points, across multiple levels. The problem is that I have no idea how I should implement this. Should I declare the points variable in the GM script (starting at 0 of course), and use the GM to read the point value from enemies and objects I interact with and add them as needed, or is there some other, better way to do this?

# Answer
First, check out the discussion about implementing singletons for best practices on for creating a persistent script. I typically have my level controllers keep track of things like scores and other states and update the global game manager when saving or changing levels. I find this approach to be more flexible when building and testing individual levels, but your mileage may vary.

Another pattern to consider is a persistent scene (with a Game Manager script and little, if anything else) and with actual scene content handled by loading (and unloading) scenes on top of it in an additive manner. This has the advantage of being relatively easy to implement with Addressables and avoids the controversial singleton pattern.
> 1 votes

---
Tags: unity, c#, architecture, scenemanager
---


# Question
Title: Finding nearby tile objects with a certain tag more easily
I have generated a grid with hex tiles. I am using two different types of tiles and would like to **at some points** ask the tiles, how many tiles of each type they have as neighbours (or really, it would be enough to know if they have neighbours of one type at all).

I have managed to get this running by getting each tile to fire six rays in the neighbouring directions and checking the tags of the returned objects. This worked but it seems quite overly complicated for what I want to achieve. What would be a better way to do this? Should I use colliders? Any other way?

# Answer
> 1 votes
**TL;DR: WebGL Demo & UnityPackage Download**

# Recursive Nodes

In the past I have tackled a similar problem by attaching a node component to each grid object. Each node component in turn keeps track of its neighbor nodes in a what could be described as a recursive manner.

In my experience this approach works with thousands of nodes in a game world in a WebGL project, with no appreciable impact on performance as compared to other methods I've tried.

```
public class Node : Monobehaviour
{
public List<Node> neighbors;
public NodeType type; // an enum defined elsewhere

// other properties and methods as needed...
}

```

## Populating the Nodes

You could use your raycasting method in an editor script to do a one-time data population of these node instances, or any number of other methods depending on whether performance is an issue. Once you have your nodes populated it's straightforward to set up A\* or other kinds of path following logic.

# Example 1: Generating Tiles & Finding Neighbors

We'll start a simple scene with just a Controller object added -- this will be used to hold the script to generate our grid and populate the neighbor data of each tile. The assets we need for the demo are some materials to differentiate the tiles, two scripts, and a hextile prefab.

The hexTile prefab has the usual usual rendering components and a convex mesh collider. Importantly, it has a HexTile component added:

In this example HexTile is the equivalent of a node as described above. For this first example the only thing that really matters is the list of neighbors which are also HexTiles. There could be all kinds of other properties and functionality, and you could derive other classes from this for specialized behavior (maybe a volcano that erupts or who knows what)... anyway:

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

public class HexTile : MonoBehaviour
{
    public List<HexTile> neighbors = new List<HexTile>();
}

```

Now on to the controller script. I have some variables for generating the hex grid that I can set in the inspector:

```
 [SerializeField] private int rows;
 [SerializeField] private int columns;
 [SerializeField] private float xOffset;
 [SerializeField] private float zOffset;

```

I also have a reference to the prefab, a list of "standard" materials, and a special highlight material for demo purposes.

```
 [SerializeField] private GameObject hexTilePrefab;
 [SerializeField] private Material[] hexMaterials;
 [SerializeField] private Material hilightMaterial;

```

Finally, a keep an internal list of the hext tiles I generate:

```
 List<HexTile> tiles = new List<HexTile>();

```

The code to generate the grid is simple-- a nested loop that instantiates gamebojects and adds their HexTile component to the list. I won't dwell on this as you already have your own working solution:

```
void CreateGrid()
    {
        float xPos = 0;
        for (int x = 0; x < rows; x++)
        {
            float zPos = x % 2 == 1 ? zOffset / 2 : 0;
            for (int z = 0; z < columns; z++)
            {
                var go = Instantiate(hexTilePrefab);
                go.name = "Hex_" + x + "_" + z;
                go.transform.position = new Vector3(xPos, 0, zPos);
                go.GetComponent<Renderer>().sharedMaterial = hexMaterials[Random.Range(0, hexMaterials.Length)];
                tiles.Add(go.GetComponent<HexTile>());
                zPos += zOffset;
            }
            xPos += xOffset;
        }
    }

```

My code for populating each HexTile with its neighbors is dumb and inefficient -- but it works. I'm simply looping thru all the tiles and checking whether they are within a unit distance, if so they are added. There are some obvious optimizations that I'll leave for an excercise for the reader (hint: each tile only has at most 6 neighbors.) And note this has a hard-coded magic number that will break if the tiles aren't approximately 1 unit in diameter.

If this code was only used in the editor to bake values it should be fine -- if not and there are huge numbers of tiles at runtime there are no doubt other faster and more efficient approaches to tackle this...

```
void PopulateHexTiles()
    {
        foreach (HexTile tile in tiles)
        {
            foreach(HexTile testedTile in tiles)
            {
                if (testedTile == tile)
                {
                    continue;
                }
                if ((tile.transform.position - testedTile.transform.position).magnitude < 1) //TODO Fix magic number
                {
                    tile.neighbors.Add(testedTile);
                }
            }
        }
    }

```

Finally, I have function to call a tile and "light up" its neighbors -- for demo purposes.

```
void ColorNeighboringHexes(HexTile tile)
    {
        foreach (HexTile neighbor in tile.neighbors)
        {
            neighbor.gameObject.GetComponent<Renderer>().sharedMaterial = hilightMaterial;
        }
    }

```

Here's the entire script:

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

public class HexGridController : MonoBehaviour
{
    [SerializeField] private int rows;
    [SerializeField] private int columns;
    [SerializeField] private float xOffset;
    [SerializeField] private float zOffset;
    [SerializeField] private GameObject hexTilePrefab;
    [SerializeField] private Material[] hexMaterials;
    [SerializeField] private Material hilightMaterial;
    List<HexTile> tiles = new List<HexTile>();

    void Start()
    {
        CreateGrid();
        PopulateHexTiles();
        //Demo accessing neighbors
        ColorNeighboringHexes(tiles[Random.Range(0, tiles.Count)]);
    }

    void CreateGrid()
    {
        float xPos = 0;
        for (int x = 0; x < rows; x++)
        {
            float zPos = x % 2 == 1 ? zOffset / 2 : 0;
            for (int z = 0; z < columns; z++)
            {
                var go = Instantiate(hexTilePrefab);
                go.name = "Hex_" + x + "_" + z;
                go.transform.position = new Vector3(xPos, 0, zPos);
                go.GetComponent<Renderer>().sharedMaterial = hexMaterials[Random.Range(0, hexMaterials.Length)];
                tiles.Add(go.GetComponent<HexTile>());
                zPos += zOffset;
            }
            xPos += xOffset;
        }
    }

    void PopulateHexTiles()
    {
        foreach (HexTile tile in tiles)
        {
            foreach(HexTile testedTile in tiles)
            {
                if (testedTile == tile)
                {
                    continue;
                }
                if ((tile.transform.position - testedTile.transform.position).magnitude < 1)
                {
                    tile.neighbors.Add(testedTile);
                }
            }
        }
    }

    void ColorNeighboringHexes(HexTile tile)
    {
        foreach (HexTile neighbor in tile.neighbors)
        {
            neighbor.gameObject.GetComponent<Renderer>().sharedMaterial = hilightMaterial;
        }
    }
}

```

And here is how the HexGridController component is configured:

Here is a sample result when the thing runs:

# Example 2: Illuminating Neighbors by Tag (or Type)

Now we'll extend this to address the OPs specific problem -- getting neighbors that match a certain tag. To do that we'll create a HexTile.TileType enum for this.

```
public enum TileType
    {
        grass,
        water,
        sand
    }

```

I'm also going to add a public property to hold this value for each tile...

```
    public TileType type;

```

and we'll add a method that returns all neighboring tiles that match the requested type:

```
 public List<HexTile> GetNeighborsWithTag(TileType requestedType)
    {
        return neighbors.FindAll(x => x.type == requestedType);
    }

```

Here's the complete, revised HexTile script:

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

public class HexTile : MonoBehaviour
{

    public enum TileType
    {
        grass,
        water,
        sand
    }
    public TileType type;

    public List<HexTile> neighbors = new List<HexTile>();

    public List<HexTile> GetNeighborsWithTag(TileType requestedType)
    {
        return neighbors.FindAll(x => x.type == requestedType);
    }
}

```

Next we want to modify our controller to take tile type into account when generating tiles. The first step is to define a struct we can serialize that will associate a material with a HexTile.TileType:

```
  [System.Serializable]
    public struct HexTileData
    {
        public Material material;
        public HexTile.TileType type;
    }

```

Now, we need to create a set of these HexTileData that the generation script can choose from that we can configure in the inspector:

```
[SerializeField] private HexTileData[] tileData;

```

Then, a modification of our generation code to chose from these data randomly, and assign materials and tile types accordingly:

```
  void CreateGrid()
    {
        float xPos = 0;
        for (int x = 0; x < rows; x++)
        {
            float zPos = x % 2 == 1 ? zOffset / 2 : 0;
            for (int z = 0; z < columns; z++)
            {
                var go = Instantiate(hexTilePrefab);
                go.name = "Hex_" + x + "_" + z;
                go.transform.position = new Vector3(xPos, 0, zPos);
                var data = tileData[Random.Range(0, tileData.Length)];
                go.GetComponent<Renderer>().sharedMaterial = data.material;
                go.GetComponent<HexTile>().type = data.type;
                tiles.Add(go.GetComponent<HexTile>());
                zPos += zOffset;
            }
            xPos += xOffset;
        }
    }

```

We'll add a new demo test method to light up only neighboring tiles that match the requested type:

```
void ColorNeigborTilesMatchingType(HexTile tile, HexTile.TileType type)
    {
        foreach (HexTile neighbor in tile.GetNeighborsWithTag(type))
        {
            neighbor.gameObject.GetComponent<Renderer>().sharedMaterial = hilightMaterial;
        }
    }

```

And with that, here's the complete, modified HexGridController script:

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

public class HexGridController : MonoBehaviour
{
    [SerializeField] private int rows;
    [SerializeField] private int columns;
    [SerializeField] private float xOffset;
    [SerializeField] private float zOffset;
    [SerializeField] private GameObject hexTilePrefab;
    [SerializeField] private HexTileData[] tileData;
    [SerializeField] private Material hilightMaterial;
    List<HexTile> tiles = new List<HexTile>();

    [System.Serializable]
    public struct HexTileData
    {
        public Material material;
        public HexTile.TileType type;
    }

    void Start()
    {
        CreateGrid();
        PopulateHexTiles();
        ColorNeigborTilesMatchingType(tiles [Random.Range(0, tiles.Count)], HexTile.TileType.sand);
    }

    void CreateGrid()
    {
        float xPos = 0;
        for (int x = 0; x < rows; x++)
        {
            float zPos = x % 2 == 1 ? zOffset / 2 : 0;
            for (int z = 0; z < columns; z++)
            {
                var go = Instantiate(hexTilePrefab);
                go.name = "Hex_" + x + "_" + z;
                go.transform.position = new Vector3(xPos, 0, zPos);
                var data = tileData[Random.Range(0, tileData.Length)];
                go.GetComponent<Renderer>().sharedMaterial = data.material;
                go.GetComponent<HexTile>().type = data.type;
                tiles.Add(go.GetComponent<HexTile>());
                zPos += zOffset;
            }
            xPos += xOffset;
        }
    }

    void PopulateHexTiles()
    {
        foreach (HexTile tile in tiles)
        {
            foreach(HexTile testedTile in tiles)
            {
                if (testedTile == tile)
                {
                    continue;
                }
                if ((tile.transform.position - testedTile.transform.position).magnitude < 1)
                {
                    tile.neighbors.Add(testedTile);
                }
            }
        }
    }

    void ColorNeighboringHexes(HexTile tile)
    {
        foreach (HexTile neighbor in tile.neighbors)
        {
            neighbor.gameObject.GetComponent<Renderer>().sharedMaterial = hilightMaterial;
        }
    }

    void ColorNeigborTilesMatchingType(HexTile tile, HexTile.TileType type)
    {
        foreach (HexTile neighbor in tile.GetNeighborsWithTag(type))
        {
            neighbor.gameObject.GetComponent<Renderer>().sharedMaterial = hilightMaterial;
        }

```

Now the GridController game object with this controller is configured like so in the inspector:

And a sample output looks like this:

# Optimization: What about all those Monobehaviours?

You might be concerned that having hundreds or thousands of objects with Monobehaviours might be a serious drag on performance. I don't think this is a big issue, assuming the HexTile behaviours aren't responding to events like Update and so on. To test this, I rewrote the scripts to leave the individual tiles "dumb" (no extra components attached) and instead stored the data in the controller. Performance was, as far I could tell, identical up to 100 x 100 tiles; by far a bigger drag is all the extra draw calls, which I demonstrated by turning off all the renderers. Optimizing the draw calls is a different subject (mesh combination, etc.) and probably off topic. But if anyone is interested I can share the version of the project that does not rely on individual Monobehaviours attached to each tile.

# More Info

You can try a slightly enhanced version of this demo (mouse position determines which tiles are polled, and you can choose tile type to highlight as well as generate larger or smaller grids) **here on my itch.io page.** The project with code is available there as a unitypackage download, as well.

# Answer
> 1 votes
Sure there is!

If you have a grid you do not need a collider. By definition grid works *instead* of collider. What you need to do is:

**Store (and retrieve) each tile address into (from) data structure** (hashtable, dictionary or array, list). So now when you select (or do something) with one tile you can immediately access its neighbors!

For simplicity lets assume you got rectangle grid 100x100 and each cell size is 1m. So we will have to lay down 100 rows each containing 100 cells.. Let's programmatically place all cells - cell1 will have address(x=1,y=1), cell2(2,1), cell3(3,1), ... , cell100(100,1). So we placed 1 row! now lets do another. It will look something like cell101(1,2), cell3(2,2), cell3(3,2) ... , cell100(100,2). Lets do this for all the rows.

Store the address of each tile in Vector2. And add it (as a key) to dictionary. As value you can add string (or sth else) with type of this tile.

It would look something like this:

```
Dictionary<Vector2,string> allMyNiceTiles= new Dictionary<Vector2,string>();
...
allMyNiceTiles.Add(new Vector2(456,183), "grass"); // to add
...
theType= allMyNiceTiles[new Vector2(15,132)];  // to take out tile at adress 15,132

```

Thus you can access any tile (or its neighbors by address).

P.S. hexagonal will be very similar, just always store discreet addresses (integers NOT floats), convert to integers before storing in dictionary.

---
Tags: unity, c#, tiles, hexagonal-grid
---


title: Facebook login using Godot 3.1 in iOS

text:
# Question
Title: Facebook login using Godot 3.1 in iOS
In my game I have to integrate Facebook login. I searched about custom modules and all.

I found one but it not working in ios and its for older version.

Any help would be appreciated

# Answer
> 0 votes
I started this one, didn't try it yet though. Someone told me about it.

# Answer
> 0 votes
You can use Facebook Plugin

If you're integrating this for iOS, you'll also need to implement login via Apple.

You can use the Apple Plugin for this.

* Both plugins have detailed instructions for installation and use.
* Both plugins work on the same methods and signals for convenience.
* Both plugins support `Godot >= 3.3.3`

---
Tags: ios, godot, facebook
---


# Question
Title: How to gradually interpolate smoothly between two yaw rotations in Minecraft MCP/Forge?
I am coding a custom client for Minecraft using MCP. (Please no hate, I'm not making a hacked client!) I have two variables `currentYaw` which is the current yaw rotation of the player, and `targetYaw` which is the yaw rotation that I want the player to be looking at. I have a function called `lerpAngle` and here is the code for it:

```
public static float lerpAngle(float fromRadians, float toRadians, float progress) {
    float delta = ((toRadians - fromRadians + PI2 + PI) % PI2) - PI;
    return (fromRadians + delta * progress + PI2) % PI2;
}

```

There is a float in `minecraft.timer` called `elapsedPartialTicks`. This variable is always between 0 and 1. Now I want to *interpolate* between `currentYaw` and `targetYaw` so that the transition is smooth. I passed in `elapsedPartialTicks` as `progress` but the screen moves way too fast. I am running all this code from the `tick` method.

What can I do to interpolate smoothly between `currentYaw` and `targetYaw`, but without the screen moving so fast.

Thank you for all the help!

Please note that I don't need any code, so it doesn't matter if you're answer is based on Forge or MCP. I just need a logic; I can write the code myself.

Again, thank you so much!

**EDIT:** In my current implementation, I have the following code:

```
float progress = (cameraInterpolationTimer.getCurrentTicks() + minecraft.timer.elapsedPartialTicks) / cameraInterpolationTimer.getTargetTicks();
minecraft.thePlayer.rotationYaw = (float) Math.toDegrees(InterpolationMath.angleLinearInterpolate((float) Math.toRadians(minecraft.thePlayer.rotationYaw), (float) Math.toRadians(yaw), progress));
minecraft.thePlayer.rotationPitch = (float) Math.toDegrees(InterpolationMath.angleLinearInterpolate((float) Math.toRadians(minecraft.thePlayer.rotationPitch), (float) Math.toRadians(pitch), progress));

```

The variables `pitch` and `yaw` are the rotations that I intend on facing. I also have variables `prevPitch` and `prevYaw`, which are set to `pitch` and `yaw` at the end of the function. `cameraInterpolationTimer` is a repeating timer (which is currently at a fixed interval) which gets reset when the difference between `yaw` and `prevYaw` is too large (because the target is moving; thus the `pitch` and `yaw` variables change each time the function is called). The function `getCurrentTicks` in the timer returns the amount of time that is passed since the timer was either created or reset. `getTargetTicks` is just another way of returning the fixed interval that the timer has been set for.

This should be interpolating smoothly to face the target yaw and pitch. It is working, but there is a mild stutter. It is pretty mild, but it is very annoying to look at and can be easily seen. How can I solve this?

# Answer
> 1 votes
Slow down your progress. Let it take more than 1 tick (if I'm reading your situation right).

For example, when starting the transition - choose the desired tick duration (e.g. `tickDuration = 10` ticks) and store the `startedOnTick`. Now in the `lerp` you can lerp with the `progress = (currentTick + elapsedPartialTicks - startedOnTick) / tickDuration`. This way you will have your transition take more ticks and be longer.

---
Tags: mathematics, rotation, minecraft-modding, interpolation
---


# Question
Title: How can I encouraging variety and diversification in food production?
I am planning a colony builder game, and one part will be food production. There will be a variety of crops available, but in the end they all serve the same purpose, feeding the inhabitants.

Many games offer different grow rates/yields for different crops, but this is a rather unsatisfactory solution, as it can easily lead to an 'optimal' crop, that then gets planted exclusively.

Instead I'd rather encourage having planting a variety of crops, since people like having a selection and not eating the same food all the time. On the other hand, I'd rather abstract away different kinds of food as much as possible, to not overwhelm the player with tracking a multitude of near identical resources.

Does anyone know of good methods on how to track the 'variety' that goes into a resource?

# Answer
> 1 votes
Yes, humans like to have variety in their food, and your concern on a game design point of view is valid. A few short ideas about it; some other very clever folks here will probably chip in and give more/better tips but here goes:

Humans *like* variety in their food because it makes them happy. You could have a "happiness" meter attached to your settlers which includes how much variety there is in their food (I believe Banished has something like this).

Humans *need* variety in their food because it makes them more healthy. You could have a "health" meter attached to your settlers which includes this as well. Both "happiness" and "health" traits should be tied to the ability/desire of the settler to work and generate new settlers.

Humans need variety in the food they produce because they need to feed animals. For instance, you could feed cabbage to humans and sheep, and use wheat to produce bread for humans and feed hens.

If you have trading game mechanics, allowing the player to sell some types of crops could encourage them to allow more variety in what they plant and grow.

A way to avoid tracking food types once it's produced and still encourage the player to add variety is by adding random events such as droughts, plant illness and parasites. Those events would target only a specific type of plant and kill them before they produce edible food, and so if the player only has that type planted that year, famine arise due to lack of food.

Finally: seasons! Some food needs to be eaten *fresh* and can't be stored for later, like strawberries, but some food can be kept for colder seasons when crops don't grow (like potatos). Link this to the fact that some plants grow *fast* and some other grow *slow*, you make sure that players *need* to diversify what they plant.

On a final note, I believe Banished, Stardew Valley and Minecraft have interesting game mechanics regarding food and crops, so you might want to take a peak at those games and see how they did it.

# Answer
> 1 votes
I would probably handle this by tracking subcategories of food. Lets say for the example you have subcategories meat, cheese and fruit but on the main game window they may all just be summed up as "food".

Then provide a benefit from having variety but don't make it mandatory. Like if a colonist eat different types of food they get a small bonus to productivity or health but otherwise nothing bad happens.

This will add some logic for you to code like tracking each colonists food consumption and AI for selecting the next food bit to eat out of the store. If the requirement for max bonus is eating 3 different food items you track the last two eaten for each colonist and a simple priority logic could be:

1. Eat whatever is not on the previous list that the colony has the most of in stock
2. Eat whatever the colony has the most of in stock

This way you give the player choice in how much they care to bother with the food details. You could even have a game option to enable or disable detailed food consumption (just apply some fixed average level bonus). This is because the food system is pretty much self-contained and not a core game mechanic. The downside is you still have to spend some effort coding and balancing something that is more a cool feature than a core mechanic.

You would of course have opportunities to integrate it further into the rest of the game if you want. Like making some colonists have food preferences, differences in yields or skill requirements for production. It all depends on the specifics of your game what would be a good fit and make for interesting mechanics.

# Answer
> 0 votes
> Instead I'd rather encourage having planting a variety of crops, since people like having a selection and not eating the same food all the time.

One common solution to encourage this is to give some bonus for food variety. The more different kinds of food are available to the colonists, the happier and healthier they are, which improves their performance in some way.

> On the other hand, I'd rather abstract away different kinds of food as much as possible, to not overwhelm the player with tracking a multitude of near identical resources.

This is mostly an UI problem.

A common solution to this problem, as seen in many successful colony builder games like *Dwarf Fortress* or *Rimworld* is to design the inventory UI as a tree view with multiple levels of subcategories the player can expand and collapse. That means a player can see that they have 120 "Food". But if they want to know more precisely they can expand that "Food" node to see that they have 82 "Meat" and 38 "Vegetable". And then expand the "Vegetable" node to see that they have 12 "Strawberry", 21 "Lettuce", 4 "Pumpkin" and 1 "Grapes".

Similarly, the player can create stockpiles or item orders on any of these level. So they can designate a storage for "Pumpkins", "any Vegetable", "any Food" or "anything". That means the player can micro-manage by setting very precise designations if they want to, or macro-manage if they don't care what their colonists eat as long as they don't starve.

Note that if you intend to make micro-management optional, then you need to make sure that the macro-management settings still lead to acceptable results. For example, if reaching a large food variety bonus is important in your overall game design, then setting a food stockpile to "any food" should result in the colonists automatically filling it with a wide variety of food instead of just filling it to the brim with nothing but cabbage because there happens to be a cabbage patch nearby.

---
Tags: game-design, strategy
---


title: Optimizing a deferred renderer

text:
# Question
Title: Optimizing a deferred renderer
I've been creating a game engine with Kotlin and LWJGL. I wanted to render scenes that support many light sources, so I worked on implementing a deferred renderer.

My basic pipeline is as follows (just point lights for now):

1. Render scene to GBuffer \[2ms\]
2. Render fullscreen quad with ambient light shader \[0.2ms\]
3. Fill an UBO with data (color, strength, matrix, ...) for all the lights \[0ms\]
4. Draw light volume spheres (instanced) \[**25ms**\]:

```
if (numActiveLights > 0) {
    OpenGL.enable(GL_CULL_FACE)
    OpenGL.cullFace(GL_FRONT)
    OpenGL.enable(GL_DEPTH_TEST)
    OpenGL.depthFunc(GL_GEQUAL)

    blinnShader.bind()
    Primitives.unitSphere.renderInstanced(numActiveLights)
}

```
5. Post processing (AO, FXAA etc.) \[1-2ms\]

I've added the per-frame GPU times of each step in the pipeline, and I'm sure the problem is fairly obvious. Even at just 95 lights, this call takes upwards of 25ms, which ruins the framerate.
Since the problem also occurs (15+ ms) with just an extremely simple shader (`FragColor = vec4(1,1,1,1)`, no lighting calculation / texture accesses), I think the problem is not with the lighting calculations themselves. I suspect it is because of the large amounts of overdraw.

I've seen deferred renderers handle thousands of lights, so clearly I'm doing something wrong. How can I go about optimizing this?

**Edit**: About the sphere, I'm generating triangles for a sphere with a resolution of 20 vertices using this bit of code (did not write it myself). The sphere is centered at \[0,0,0\] and has a radius of 1 (I called that a "unit sphere"). The lighting shader later has a matrix to make the actual light volume out of that.

The sphere mesh is loaded to a simple VAO with one `GL_FLOAT` VBO attached to it for the vertices. `renderInstanced()` then just draws them instanced like this:

```
fun renderInstanced(amount: Int) {
    glBindVertexArray(vao)
    // type: GL_TRIANGLES
    // vertexCount: Class attribute that contains number of verts
    glDrawArraysInstanced(type, 0, vertexCount, amount)
}

```

# Answer
> 1 votes
Many hours of debugging later, and while looking at an unrelated problem, I noticed that for whatever reason, I configured all my G-buffers with `RGBA_32F` precision, which with all textures resulted in **48 bytes per pixel** that were fetched by multiple shaders, multiple times per frame.

I reduced to more reasonable 16-bit buffers and now my lighting pass is at a more reasonable 4ms, and my framerate more than tripled (19fps -\> 67fps).

---
Tags: opengl, deferred-rendering
---


# Question
Title: Does the function SDL_DestroyWindow() free the memory allocated by the renderer(s) in it as well?
I know the renderer frees memory allocated for its textures when destroyed but is this the case with SDL\_DestroyWindow() as well?

# Answer
Looking at the source code, while the window does seem to know about the renderer associated with it, there does not seem to be any kind of call to the renderer layer of SDL from the implementation of `SDL_DestroyWindow`, so you'll need to simply call `SDL_DestroyRenderer` yourself.
> 2 votes

---
Tags: sdl, sdl2
---


# Question
Title: Why do multiplayer games often use custom physics implementations?
Big game engines all have a physics engine whose job is to resolve forces, collisions and constraints efficiently. I think the majority of modern games use a physics engine to some extent. Nevertheless, I have noticed that it is not uncommon for developers to implement features using a "kinematic simulation" instead of a "physics simulation" especially in multiplayer environments. Using the example of a car simulation to clarify these terms a bit more (since I don't think there is standard terminology).

Kinematic Simulation: Collect all the forces (suspension force, gravity, engine force etc). Calculate (and store) the acceleration, velocity, new position etc. Set the location and rotation outside the physics engine (which still handles collisions and motion of objects not related to the car).

Physics Simulation: Collect all the forces add them to the car and let the physics engine resolve what happens.

Is there something that makes client prediction/corrections easier in the kinematic version than the physics version?

Unreals character movement component would be a specific, concrete and very common example. AFAIK while the physics engine is still used for checking for collisions the character itself doesn't simulate physics via the engine but forces are instead added to the movement component which runs its own simulation.

# Answer
> Is there something that makes client prediction/corrections easier in the kinematic version than the physics version?

This is a good example. If you want an authoritative server, you would run all of your physics on the server. There is no need to run it again on the client for important parts, such as the player. So when the server tells the client the updated positions, you not only save the client-side calculations of physics, but you also get deterministic results.

Another example is when you don't want to use the engine's physics. For example, your character can push through a bunch of enemies. Using standard physics, your character may get stuck. But by kinematically pushing your character forward, it still lets the enemies react to the collision with the player, but lets the player ignore the collision with the enemies.
> 1 votes

# Answer
One problem with many physics engines is that they are not deterministic. That means that two computers executing the same physics simulation with the same input parameters might end up with two different results. For example because one of them runs at a higher framerate leading to a more detailed resolution.

This is often not much of a problem in singleplayer games. But it can become a big problem in multiplayer games, because even slight differences between clients can often have a butterfly effect which result in the game becoming completely out of sync between players. This is in addition to the latency problem in multiplayer games which causes the game to never be *really* in sync between players. So not even the input parameters might be the same.

Which is why many multiplayer games roll their own physics engine. Having an own engine instead of a black box allows them to resync the clients regularly.
> 1 votes

---
Tags: physics, multiplayer
---


# Question
Title: What are mathematical ways to write down a manual for a game?
Suppose one were to write a manual for a game, where 'game' can be either a video game or board game - that doesn't matter. Are there *symbolical/analytical ways* to write down a set of rules for a game, as for example a *formal language*?

# Answer
> 4 votes
Joris Dormans's Machinations is an attempt to create a formal diagramming language for expressing game mechanics - especially those that relate to resource flows.

By thinking of "player action" as a resource, or mechanics involving navigating connected locations in space as a series of resource pools that the "player presence" resource can move between, you can stretch this to cover more general classes of game mechanics - with a little squinting/imagination.

This language takes the form of a kind of flow chart, with tokens that can sit within each node, and well-defined rules for when and how tokens are moved from one node to another.

There's a web-based tool you can use at machinations.io to create these diagrams, as well as to "run" them as automated simulations or interactive minigames, to explore the dynamics produced.

This is suitable for documenting the dynamical engine at the heart of a game design, for an audience of fellow designers/game developers well-versed in this particular diagramming dialect. It's not so suitable for communicating to players or other less specialized audiences. It also abstracts away many aspects of game mechanics - like the means the player uses to provide input, or the perceptible affordances and feedback the game provides, so it can't serve as a complete game design document on its own.

---
Tags: game-design
---


title: Timestep Jittering

text:
# Question
Title: Timestep Jittering
I've been trying to implement the famous Fix your timestep in C++ and SDL2 using a simple example. I have a square that moves around on the screen but I cannot understand why it keeps jittering/stuttering sometimes when I run the application. By this I mean you can see the square "shaking" but it's very subtle.

My game loop is simply

```
int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[])
{
    init();
    while (true)
    {
        update();
        render();
    }
    return 0;
}

```

My update code is the following

```
template<typename T>
struct Vector
{
    constexpr Vector() : x(0), y(0) {}
    constexpr Vector(T x, T y)
    {
        this->x = x;
        this->y = y;
    }

    // Linear interpolate between two vectors
    static constexpr Vector lerp(const Vector& A, const Vector& B, double alpha) noexcept
    {
        assert(alpha >= 0.0 && alpha <= 1.0);

        // A* t
        Vector<float> lerpVectorA = A;
        lerpVectorA.x *= alpha;
        lerpVectorA.y *= alpha;

        // B* (1.f - t);
        Vector<float> lerpVectorB = B;
        lerpVectorB.x *= 1.0 - alpha;
        lerpVectorB.y *= 1.0 - alpha;

        // A* t + B * (1.f - t);
        return Vector(lerpVectorA.x + lerpVectorB.x, lerpVectorA.y + lerpVectorB.y);
    }
    T x;
    T y;
};

// Timestep
static constexpr double dt = 1000.0 / (double)60;
static constexpr double maxFrameTime = 60;
double currentTime = 0;
double accumulator = 0;
double alpha = 0;

void update() noexcept
{
    if (currentTime == 0)
    {
        currentTime = SDL_GetTicks();
    }

    auto const timeNow = SDL_GetTicks();
    auto frameTime = timeNow - currentTime;
    if (frameTime > maxFrameTime)
    {
        frameTime = maxFrameTime;
    }

    currentTime = timeNow;
    accumulator += frameTime;

    while (accumulator >= dt)
    {
        // Lerp
        previousPosition = currentPosition;

        // Move
        currentPosition.x += xSpeed;
        currentPosition.y += ySpeed;
        if (currentPosition.x <= 0 || currentPosition.x > 640 - 64)
        {
            xSpeed *= -1;
        }
        if (currentPosition.y <= 0 || currentPosition.y > 480 - 64)
        {
            ySpeed *= -1;
        }

        accumulator -= dt;
    }
    alpha = accumulator / dt;
    drawPosition = Vector<float>::lerp(previousPosition, currentPosition, alpha);
}

```

`render()` simply renders the square on the screen at `drawPosition`. Vysnc is enabled (so it runs at 60fps) but it doesn't make any difference if I disable it.

I can't see anything wrong in my implementation and I don't understand why it jitters/stutters sometimes.

# Answer
Your Lerp looks backwards. I'd expect something more like this:

```
static constexpr Vector lerp(const Vector& A, const Vector& B, double alpha) noexcept
    {
        assert(alpha >= 0.0 && alpha <= 1.0);

        // A * (1 - t) + B * (t);
        return Vector((1.0 - alpha) * A.x + alpha * B.x,
                      (1.0 - alpha) * A.y + alpha * B.y);
    }

```

When `alpha` is small, our result should be close to the first input (`A` / `previousPosition`). The closer `alpha` gets to 1.0, the more the result should lean toward the second input (`B` / `currentPosition`).

If this isn't intuitive right away, imagine the opposite: if increasing `alpha` took us back *toward* `A` / `previousPosition`, then accumulating a little extra time (but not enough to trigger the next update) would cause the object to move *backwards*! Definitely not what we expect when time increases.
> 1 votes

---
Tags: c++, sdl2, timestep
---


# Question
Title: Regarding performance, when is it okay and and when is it not okay to use LINQ with Unity?
As the title mentions I am interested in LINQ performance in Unity. When is it okay and when is it not okay to use it?

As I understand it is bad to use it in something like `Update` which gets called every frame; that makes sense. But what about using it in events and methods that are not called on every frame but only when something specific happens?

# Answer
You can't generalize things like that, because they always require context. A LINQ expression can include a lot of different operations, and operate on very different quantities of data.

Any LINQ operators which transform one sequence of values into another (like `.Select` or `.Filter`) will have to do at least one complete loop over the input sequence. Those which return only one element (like `.First(predicate)`) will at least loop until they found what they were looking for. So their runtime complexity is at least linear to the size of the collection. And operators like `.Sort` or `.Group` which needs to jump back and forth over the input set will have runtime complexity which is worse than linear. The documentation unfortunately does not give much information about which operator has which big-O runtime complexity. But with some theoretical knowledge of computer science or practical experience in programming it's pretty easy to make an educated guess about what you can expect from an implementation which is not optimized for any particular use-case.

Also, you can not expect LINQ to do any form of caching. So if you repeat the same operation over and over again even though the data won't have changed, then you might be wasting a lot of CPU cycles.

So the bottom-line is: LINQ isn't magic. Be aware of what kind of loops will need to happen behind the scenes when you perform a LINQ operation and the amount of data those loops will have to loop over.
> 3 votes

# Answer
Profile your code and see for yourself. Others can only speculate about your game's performance.

As a general rule of thumb: It is fine for infrequent things. Try to avoid it for per-frame operations.
> 2 votes

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


# Question
Title: How to use different drag values for the X and Y axes on a Rigidbody2D?
I'm building a small 2D character controller using Unity physics to simulate an oldschool platformer. I know this is not the best way to do it and I have my own version using just raycast and custom physics.

This morning I was adding the jump and noticed that the rigidbody drag property affects X and Y axis. I mean, if I apply an impulse following up direction and I get a jump of 10 units if I make the drag value higher it will jump lower (less than 10). I don't know why, I was assuming that drag was going to affect just movement in X axis.

So, what I need is a way to keep the jump height independent of the drag value I use to keep things consistent and make tweaking easier.

Is this possible?

# Answer
I can think of two ways to address your problem (while still using Physics2D) :

### Increase Gravity

You could try increasing the gravity scale to offset the extra drag.

### Implement your Own Drag

You could zero the rigidbody drag factor and instead add a script that adds an force on the x-axis only of the rigidbody that increases with speed.

Here's a (simplistic) script that you could attach to your character with a Rigidbody2D component that will add lateral drag in proportion to lateral velocity:

```
using UnityEngine;

public class XDrag : MonoBehaviour
{
    Rigidbody2D rb;
    public float dragFactor = 10.0f;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        rb.AddForce(new Vector2(-(rb.velocity.x * dragFactor), 0));
    }
}

```
> 3 votes

# Answer
No, Unity does not offer you the option to apply different drag on different axis'. However what you can do is:

* Implement your own drag mechanic, as in the answer by Acme Nerd Games
* Change the drag coefficient in FixedUpdate depending on the current direction of the velocity vector. This is a solution I used once to implement a "drifting" mechanic where vehicles sliding sideways experienced higher drag than vehicles driving straight.
> 1 votes

---
Tags: unity, 2d, physics
---


# Question
Title: Performance degrading when resolution increases for a 4k screen
I am new to Unity. I have a problem where my game has good performance on my non-4k screen.

Bur when I play it on my 4k screen, the performance gets really bad.

It looks like the resolution is changing based on the resolution on the screen. I am also basing this on the fact that both my text and buttons are getting smaller.

Is it possible to set a maximum resolution?

# Answer
> 12 votes
One way to limit the resolution of your game is to have your camera render to a RenderTexture.

You can create a RenderTexture in script to match the current aspect ratio of your window/screen, or even adapt the resolution of the texture dynamically in response to performance measurements. Assign it to the target texture property of your camera to redirect your rendering to that texture.

When you first do this, you suddenly won't see anything in your game — all the content is being rendered to this off-screen texture instead of to the screen. So then we need to display that texture full-screen, which we can do in a couple of ways:

* Add a UI canvas in ScreenSpace Overlay mode, and put a RawImage component under it that displays this texture. Or...
* Add a textured quad to your scene, using an unlit material to display this texture. Put it in a layer your main camera doesn't see, then add a new camera that sees only that layer, framed to match the quad.

What this does is limit the expensive scene rendering steps to operate at the fixed resolution of your texture. Then at the end you do a cheap texture sampling operation to stretch that texture to the full output resolution. You'll get some blurring because of this stretching, of course — that's the trade off we're making to save rendering performance. But you can also use a custom shader in the last step to control the texture interpolation scheme used.

If you're using URP/LWRP, this technique is built in as the Render Scale parameter on the pipeline asset, under Quality. Set this to a value less than 1 to downscale the render target used for scene rendering, and automatically stretch it to the size of the screen, without needing to juggle the RenderTexture yourself. UI will still be rendered at full res on top of this stretched result.

# Answer
> 6 votes
The text & button size issue can be addressed by changing the Canvas Scaler component on the canvas to a mode other than ***Constant Pixel Size***:

In ***Scale With Screen Size*** mode, you set a reference resolution that the UI elements are scaled to, regardless of the actual pixel dimensions of the running game canvas.

To restrict the WebGL to a certain resolution, choose your desired resolution in the player settings and be sure to choose an HTML template that supports that resolution (e.g. the Minimal template that ships will resize the game to fill the entire browser window, regardless of the default resolution specified.)

**Edit:** *Note DMGregory's answer for an effective way to force resolution in a WebGL build regardless of HTML container size.*

To diagnose your issues with poor performance, more information is needed. Generally when a game suffers when resolution increases it's due to GPU fillrate limitations. This page is always a good place to start when tackling performance issues: Unity: Optimizing Graphics Performance

# Answer
> 5 votes
I know that you tagged the question as , but some people might find this question while developing a desktop game and might find this answer useful:

For a desktop game, you can use the method `Screen.SetResolution(int width, int height, bool fullscreen)` to change the resolution at runtime. Note that when you do not pass `false` for the third argument, then the game will run in a window which the player can then still resize themselves.

---
Tags: unity, performance, webgl, resolution, unity-webgl
---


# Question
Title: How do I get the player from the LivingEntity so I can make this knockback effect on the amethyst sword?
Like the title says, how do I get the player from the LivingEntity so I can make this knockback effect on the amethyst sword? i want the amethyst sword to give knockback 10 to any entity i hit and in the direction im looking at

```
@SubscribeEvent
public static void onPlayerAttack(LivingAttackEvent event){
    Entity entity = event.getEntity();
    LivingEntity living = event.getEntityLiving();
    Item item = ItemInit.AMETHYST_SWORD.get();
    if (event.getEntity() instanceof LivingEntity){
        living.applyKnockback(10, 20, 20);
        System.out.println("i print");
    }
}

```

# Answer
Use the `AttackEntityEvent` instead. Here's an example:

```
@SubscribeEvent
public void onPlayerAttack(AttackEntityEvent event) {
    PlayerEntity attacker = event.getPlayer();
    Entity target = event.getTarget();
}

```

Hope this helps!
> 0 votes

---
Tags: java, minecraft-modding
---


title: Java Simple 2D Grid Pathfinding

text:
# Question
Title: Java Simple 2D Grid Pathfinding
I want to code some basic pathfinding for my bot in Java. Below is a 2D grid representation of the 3D world. **0**s being the places you can go, and **1**s being the places that you cannot go.

```
int[][] data = {
            {0, 0, 0, 0, 0},
            {0, 0, 1, 0, 1},
            {1, 0, 0, 1, 1},
            {0, 0, 0, 1, 0},
            {1, 1, 0, 0, 1}
    };

```

How can I write a simple pathfinder in Java, where if I say that I'm currently at (2D coords) and I want to go to (2D coords), it will generate the shortest path there. I don't need a fancy cost system, because each move will have the same cost, and each **1** will have the same danger level. There are already some posts about this online that I've seen, but most of them look a little too overkill for my simple project.

**EDIT:** The cost can be decided by how many moves are necessary to get to the player. The best path is the shortest; least moves necessary. In the best case scenario, the path finder will return a list of all the coordinates I have to walk on to get to the target.

Thank you for all the help!

# Answer
This is a typical example of using something like Dijkstra's algorithm or A\* to find a path.

Both will work for what you're describing and you can pick either one, there are plenty of online examples of both.

Very simplified the algorithms works by finding the next available step that is available and not yet tried, and then repeating that step until there are no more available steps or the destination is reached.

A simple version might look like:

```
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {
    public static class Point {
        public int x;
        public int y;
        public Point previous;

        public Point(int x, int y, Point previous) {
            this.x = x;
            this.y = y;
            this.previous = previous;
        }

        @Override
        public String toString() { return String.format("(%d, %d)", x, y); }

        @Override
        public boolean equals(Object o) {
            Point point = (Point) o;
            return x == point.x && y == point.y;
        }

        @Override
        public int hashCode() { return Objects.hash(x, y); }

        public Point offset(int ox, int oy) { return new Point(x + ox, y + oy, this);  }
    }

    public static boolean IsWalkable(int[][] map, Point point) {
        if (point.y < 0 || point.y > map.length - 1) return false;
        if (point.x < 0 || point.x > map[0].length - 1) return false;
        return map[point.y][point.x] == 0;
    }

    public static List<Point> FindNeighbors(int[][] map, Point point) {
        List<Point> neighbors = new ArrayList<>();
        Point up = point.offset(0,  1);
        Point down = point.offset(0,  -1);
        Point left = point.offset(-1, 0);
        Point right = point.offset(1, 0);
        if (IsWalkable(map, up)) neighbors.add(up);
        if (IsWalkable(map, down)) neighbors.add(down);
        if (IsWalkable(map, left)) neighbors.add(left);
        if (IsWalkable(map, right)) neighbors.add(right);
        return neighbors;
    }

    public static List<Point> FindPath(int[][] map, Point start, Point end) {
        boolean finished = false;
        List<Point> used = new ArrayList<>();
        used.add(start);
        while (!finished) {
            List<Point> newOpen = new ArrayList<>();
            for(int i = 0; i < used.size(); ++i){
                Point point = used.get(i);
                for (Point neighbor : FindNeighbors(map, point)) {
                    if (!used.contains(neighbor) && !newOpen.contains(neighbor)) {
                        newOpen.add(neighbor);
                    }
                }
            }

            for(Point point : newOpen) {
                used.add(point);
                if (end.equals(point)) {
                    finished = true;
                    break;
                }
            }

            if (!finished && newOpen.isEmpty())
                return null;
        }

        List<Point> path = new ArrayList<>();
        Point point = used.get(used.size() - 1);
        while(point.previous != null) {
            path.add(0, point);
            point = point.previous;
        }
        return path;
    }

    public static void main(String[] args) {
        int[][] map = {
                {0, 0, 0, 0, 0},
                {0, 0, 1, 0, 1},
                {1, 0, 0, 1, 1},
                {0, 0, 0, 1, 0},
                {1, 1, 0, 0, 1}
        };

        Point start = new Point(0, 0, null);
        Point end = new Point(3, 4, null);
        List<Point> path = FindPath(map, start, end);
        if (path != null) {
            for (Point point : path) {
                System.out.println(point);
            }
        }
        else
            System.out.println("No path found");
    }
}

```

The above will print the path as a solution from (0, 0) to (3, 4):

```
(0, 1)
(1, 1)
(1, 2)
(1, 3)
(2, 3)
(2, 4)
(3, 4)

```
> 2 votes

---
Tags: java, mathematics, path-finding
---


# Question
Title: Unity InputSystem using Unity Events not maintaining values
I am testing out using the new Input System and cannot get the values from `context.ReadValue<Vector2>()` to pass into a private variable.

The simple setup is below:

```
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    Vector2 leftThumbstickValues;

    void Start()
    {
        leftThumbstickValues = Vector2.zero;
    }

    void FixedUpdate()
    {
        Debug.Log("FixedUpdate: " + leftThumbstickValues); //Always displays "FixedUpdate: (0.0, 0.0)"
    }

    public void Move(InputAction.CallbackContext context)
    {
        leftThumbstickValues = context.ReadValue<Vector2>();
        Debug.Log("Move: " + leftThumbstickValues); //Displays correct values
    }
}

```

As you can see, in the `Move` function it correctly pulls the values from the thumbstick, but when it tries to use the values in `FixedUpdate` it always equals `Vector2.zero`. It seems like it should just work, but I think I must have overlooked something very simple.

Player Input Settings

Input Action Move Properties

Input Action Left Stick Properties

**EDIT:** I decided to remove the Player Input component and subscribe to the events in code:

```
 controls.Player.Move.performed += cntxt =>
 {
     Move(cntxt);
 };
 controls.Player.Move.canceled += cntxt =>
 {
     leftThumbstickValues = Vector2.zero;
 };

```

This now works as expected. I'm not sure I should mark this as the answer though as it doesn't explain why it doesn't work with the original setup, just offers an alternative solution.

# Answer
I had this exact same issue. The problem was that the Unity Editor got into a state where the *Player Input* component in the inspector was referring to a different instance of the *Player* than what was in the scene. This was easy to confirm by printing out the hashcode of the *GameObject* in both the input callback and in the `FixedUpdate()` block, which showed two different IDs!

This was fixed by re-assigning the *Player Input* callbacks in the Editor Inspector to the *Player* object in the scene. I have no idea what causes these to unsync in the first place. I hope this helps someone in the future.
> 2 votes

---
Tags: unity, input, events, callbacks
---


# Question
Title: Do external graphics cards for laptops help decrease compilation time?
Can modern compilers use the power of a graphics card to shorten compilation time?

Or is this solely based on the CPU and RAM?

For example, can GCC utilize an external graphics card connected via a thunderbolt cable when compiling C++ source code?

# Answer
> 2 votes
No, it won't.

I have never heard of a compiler which uses GPU acceleration, and I don't think it would make sense to try to develop one. Compiling is one of those kinds of tasks where CPUs easily beat GPUs in performance.

But if you want to improve your compilation times without investing in a new computer: I do know of a couple technology stacks which offer "cloud build services". Like Unity, for example. The idea is that there is a powerful server on the Internet which does the compiling for you. You send your sourcecode to the server. The server compiles it for you, and sends you the compiled binary.

You could also set up something like that of your own with a bit of tinkering and an AWS on-demand high performance instance.

Or you could try to look into programming techniques which reduce the compilation times of your C++ code. Like compiler firewalls to reduce the amount of code which needs to be recompiled after each code change. Or try to implement as much as you can in your game using data files, configuration files or scripts instead of hardcoding stuff, so that you can iterate on your game design without recompiling each time you adjust a number.

---
Tags: c++, graphics, hardware-acceleration
---


# Question
Title: Trying To Restart My Shooting Arrow With Overlap
I am trying to restart my shooting arrow if the arrow hits the roof but the bool is not changing \[and giving a\] cast failed \[error\] this is my shooter character shooting arrow

```
 void AShooterCharacter::BeginPlay()
{
   Super::BeginPlay();

}

// Called every frame
void AShooterCharacter::Tick(float DeltaTime)
{
   Super::Tick(DeltaTime);

}

// Called to bind functionality to input
void AShooterCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
   Super::SetupPlayerInputComponent(PlayerInputComponent);

   PlayerInputComponent->BindAxis("MoveRight", this, &AShooterCharacter::MoveRight);
   PlayerInputComponent->BindAction("Shoot", IE_Pressed, this, &AShooterCharacter::Shoot);

}
void AShooterCharacter::MoveRight(float value)
{
   AddMovementInput(FVector(0.f, -1.0f, 0.f), value);

}
void AShooterCharacter::Shoot()
{
   UWorld* const world = GetWorld();
   if (world != nullptr)
   {
       if (bCanIShoot)
       {
           FVector location = GetActorLocation();
           world->SpawnActor<AArrow_Weapon>(Arrow, location, FRotator::ZeroRotator);
           ;
           bCanIShoot = false;
       }

   }
}

```

this is my arrow actor

```
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
    box = CreateDefaultSubobject<UBoxComponent>(TEXT("Box"));

}

// Called when the game starts or when spawned
void AArrow_Weapon::BeginPlay()
{
    Super::BeginPlay();
    box->OnComponentBeginOverlap.AddDynamic(this, &AArrow_Weapon::OvarlabBegin);
}

// Called every frame
void AArrow_Weapon::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    FVector newLocation = GetActorLocation();
    newLocation.Z += Speed * DeltaTime;
    SetActorLocation(newLocation);
}

void AArrow_Weapon::DesctroyArrow()
{
    Destroy();
}
void AArrow_Weapon::OvarlabBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
    if (OtherActor != nullptr)
    {
        if (OtherActor->ActorHasTag("TopRoof"))
        {
            iAShooterCharacter* player = Cast<AShooterCharacter>(OtherActor);

            if (player)
            {
                player->bCanIShoot = true;;
            }
            UE_LOG(LogTemp, Warning, TEXT("arrowHit11111"));

        }
    }
}

```

# Answer
> 0 votes
I think you said you are getting a failed cast error. This is because you are trying to cast the OtherActor to a `AShooterCharacter`. The `OtherActor` however is not the player, it is the roof. This is ensured by the `ActorHasTag("TopRoof")`. So you should remove the line setting `player` to a casted `OtherActor`.

You can't get the player that shot the arrow from the ceiling it hits. Instead, you should have the player that shot the arrow as a field in the `AArrow_Weapon`. When you spawn it you should pass in `this`(the player) to the constructor.

Then you can just set `player->bCanIShoot`.

Edit: Okay, so it looks like there's not a way to directly pass another parameter through the constructor. So instead, we'll set it right after it is spawned.

On the arrow class, add a field like `AShooterCharacter* ShotBy`. Then have a setter like

```
AArrow_Weapon::SetShotBy(AShooterCharacter* ShotBy){
    this->ShotBy = ShotBy;
}

```

Keep constructing it like you were before, but keep the pointer returned by `SpawnActor`. Use it to set the value.

```
AArrow_Weapon* justShot = SpawnActor<AArrow_Weapon>(Arrow, location, FRotator::ZeroRotator);
justShot->SetShotBy(this);

```

# Answer
> 0 votes
```
FActorSpawnParameters Params;
Params.Owner = this;
world->SpawnActor<AArrow_Weapon>(Arrow, location, FRotator::ZeroRotator,Params);

```

Then

```
if (OtherActor->ActorHasTag("TopRoof"))
{
   AShooterCharacter* player = Cast<AShooterCharacter>(GetOwner());

```

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


# Question
Title: Why is the derivative important in game development? How did you use it in a real scenario?
I'm really eager to know how a programmer finds useful a derivative in game development, using a real scenario as an example. Also I plan to use this question to understand the importance of derivatives more!

# Answer
> 1 votes
Derivatives (and integrals) come up everywhere in game physics!

Consider the static force diagram for a ball rolling down a ramp. You need to know the gravity vector, the mass of the ball, and the angle of the ramp (its normal vector); Then you can calculate the net force on the ball and determine the acceleration of the ball in that frame. On the next frame you calculate that all over again for the new conditions and apply acceleration again.

**These acceleration value are the derivative of the ball's velocity**. To phrase it another way, that acceleration value determined every frame is the rate of change of the velocity of the ball. And the velocity is the rate of change of the ball's position every frame too. To implement these physics you will need to keep track of all 3 vectors every frame and add acceleration to velocity, then add velocity to position. And ta-da, you have a rudimentary physics engine using discrete calculus!

---

Derivatives can also be used in logical problems like pathfinding, AI, and other kinds of solving for optimal solutions.

An example of this may be generating rivers in a terrain generator. Rivers always flow downhill, so if you randomly select an origin point for a river you will need to calculate what direction is downhill, and usually the *steepest* downhill direction; This is done with partial derivatives by treating the terrain as a mathematical surface.

# Answer
> 0 votes
I actually did use the derivative once. No, actually it was the integral. But w/e.

Basically I had this inertial scrolling system (in one dimension so a line) and I wanted it so when you stopped scrolling the inertia would move the camera so that it stopped exactly over a selectable option.

The way I did this was you use the normal scroll equations when you're moving your finger. But as soon as you release, it stops using the normal equations and switches to using an integral of the normal equation. From the integral we can easily see the exact spot the camera will stop moving and can modify the equation so that we stop earlier or later.

# Answer
> -1 votes
I will give it to you straight: Unless you are making you own engine, you will almost never use them. Off-the-shelf engines and libraries (which you should be using anyway if you actually want to ship your game before the next decade) usually do a very good job of hiding complex mathematics behind intuitive APIs.

---
Tags: mathematics, optimization
---


# Question
Title: Odd behaviour when changing rigid body velocity inside OnCollisionEnter2D
This is the code I'm using to make an object bounce across the scene:

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

public class Enemy2 : MonoBehaviour
{
    [SerializeField] private float _speed;

    private Rigidbody2D _rb;

    private Vector2 _velocity;

    private void Awake()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    // Start is called before the first frame update
    void Start()
    {
        Vector2 dir = Random.insideUnitCircle;
        if (_rb.velocity.x == 0 && _rb.velocity.y == 0)
            dir = new Vector2(0.5f,0.5f);

        _velocity = dir.normalized * _speed;
        _velocity = new Vector2(0, -1);
        _rb.velocity = _velocity;

        FaceDirection();
    }

    private void FixedUpdate()
    {

    }

    // Update is called once per frame
    private void OnCollisionEnter2D(Collision2D other)
    {
        Debug.Log("Collision: "+_rb.velocity);
        _velocity = new Vector2(0, +1);//Vector2.Reflect(_velocity, other.contacts[0].normal);
        _rb.velocity = _velocity;
    }

    private void FaceDirection()
    {
        transform.localScale = new Vector2(Mathf.Sign(_velocity.x),1);
    }
}

```

I have hardcoded the initial and Reflect directions just to make sure it wasn't my fault and it produces same behaviour: The object gets stuck when colliders with a collider instead of "rebound".

I'm using a dynamic rigid body with trigger set to false and no linear drag.

Can anybody guess what's hapenning here?

# Answer
In general you should not set a rigidbody’s velocity directly, as it often results in weird behavior, per the docs:

Rigidbody2D.velocity

Instead, try AddForce(), AddTorque() or AddForceAtPosition()
> 1 votes

---
Tags: unity, 2d, physics
---


# Question
Title: What color format, depth buffer should I use in a RenderTexture for WebGL screen output in Unity? Is NPOT ok? MipMaps?
Today I learned about a technique for forcing uniform resolution in a Unity WebGL build, as described here in the answer by DMGregory. Yay! I'm experimenting with implementing this technique on a large ongoing project and am seeing promising results so far. However, I am a little bit baffled as what color format I should choose for the RenderTexture. It seems to me it would be most efficient to choose something without an Alpha channel, but that's just a hunch. There are seemingly zillions of formats (not all supported on WebGL):

With the build-test cycle on WebGL being slow as it is, I'm looking for some insight as to how to choose the most efficient color format. And what about the depth buffer setting?

Finally, does it matter if the RenderTexture is NPOT? Again my hunch is to have it be as few pixels as possible, even if NPOT, but ¯\*(ツ)*/¯ Same goes for MipMaps -- seems like wasted memory space but I'm guessing here.

**Edit:** I found this, which does explain the nomenclature at least, but I'm still unsure how I should be thinking about this.

# Answer
> 1 votes
After a great deal of trial and error I have learned a few things.

### Methodology

For each permutation of the factors described in the original question, I created a build using a RenderTexture and tested it at four points in the game for average fps over 10s. I did not test every permutation! Only those that seemed to offer a glimmer of insight. The control was a build that used a main camera rendering directly, rather than to a RenderTexture. The test platform was WebGL as loaded into Chrome v.94 on a MacBook Pro 2012 Retina with 16GB Ram, runnning MacOS 10.12.6 at full screen which equates to 2360 x 1474 after subtracting the browser's chrome.

### Color Format

As near as I can tell, color format made zero difference on frame rate or build size. A great many of the color formats are not valid with WebGL builds, and of those that do, only a few make sense. The default R8G8B8A8\_UNORM gave the same performance as all the other options I tried.

### NPOT

I thought maybe there might be a performance penalty for using a NPOT format, but as near I can tell -- for instance, comparing 960 x 600 vs 1024 x 512 performance -- there is little to go on here. 960 x 600 is slightly more pixels but the relative performance was a draw suggesting this is not an issue.

### MipMaps

MipMap settings appear to make no difference to RenderTexture visual output, even at lowest quality settings where one might expect 1/2 size textures would be substituted (per default Unity Quality settings). No difference in build size either -- I guess not surprising.

### AA settings

Ditto for AA settings -- made no discernible difference to visual quality or fps on their own.

### Size

Indeed, the only factor that seemed to have an effect on fps was the size of the RenderTexture (X * Y) and it was fairly profound.

With the resolution set to 960 * 600 (the target for HTML container) I saw a 38% increase in frame rate. With it set to the nearest POT, 1024 * 512, I saw a 35% increase in frame rate over the baseline.

---
Tags: unity, resolution, rendertexture, unity-webgl
---


# Question
Title: Design patterns for non-modal (in-game) dialogues/cutscenes in a game engine
I want to create a scripted dialogues/sequences between NPCs and/or PC during the game.

I have a DSL to configure a PC's dialogue with one NPC, inspired by Inkle and Twine.

Now, I need a dialogue between 2+ NPCs, where the PC can also participate.

Question: the dialogue object of PC-to-NPC dialogue is owned by that NPC, can receive all necessary events that drive the scripted dialogue/scene. But who should own a dialogue between multiple NPCs? This somebody should receive and handle events related to all the participants, check if the NPCs are still friendly and alive, and a few other things that wouldn't be a problem if it was a single NPC.

How is it done in the well-designed engines? I know you can attach a script object to a game entity in Unity, for example. Does the script get attached to location itself, or be standalone? How does this fit into event distribution mechanism?

I don't want to replace NPCs with a scripted sequence, I want them to maintain their normal properties during the scene.

# Answer
> 2 votes
In game development, there is never just one solution to any given problem.

But one solution could be to create each active dialog as a separate, independent, invisible entity which references all participants of the conversation.

That entity would then be responsible to check if the conditions for starting the scene are met (the player entered the trigger area, both NPCs are alive and within certain areas, both NPCs are in a state which allows them to start a conversation, neither is involved in a different conversation right now, etc.). It would then keep checking the state of the characters involved in the scene to make sure the conditions for continuing the scene are still met. The entity would also decide when to show the next line of the conversation and be responsible for displaying it.

# Answer
> 1 votes
There are much smarter people here than me, but I'll pitch in with my $.02.

You asked about how others would approach this problem building a game in an engine like Unity. While I have not built a game with multiple NPCs talking to the player at once, I have built games where players can interact and converse with individual NPCs, and I think my approach to the former would be similar.

First of all, I usually start out with a basic class structure where all or at least most of the games' 'entities' derive from a pair of abstract base classes which I usually call `Item` and `ItemRuntime`.

`Item` derives from the Unity class `ScriptableObject` and defines the immutable data for that entity. `ItemRuntime` doesn't derive from anything, and will hold runtime data for each generated item instance as well as a few methods that would be awkward to keep in the immutable.

Everything else descends from these two base classes in a cascading manner. For instance, `Vehicle`, `Character` and `Loot` might be the base classes for things you can move around in, the various kinds of NPCs you find in the game, and the stuff you collect, respectively. More specific types can then derive from these. One such type might be a "Sentient NPC," an interactable character that can converse. The class definition would include a list of all the Items that character knows about (here shown as Awareness), as well as a list in the runtime that keeps track of what that character has already told the player about. Going backwards, each item type could define certain ways in which a character could speak about it, for instance, Loot might be "precious" or "rare," a vehicle might be "fast" or "rugged," a character might be "wise" or "combative" etc.

\[

A master controller would keep track of what the player knows about so that conversations with NPCs have context, while the scripts for the SentientNPCs regarding the various items they are aware of would be defined within the SentientNPC class.

---
Tags: architecture, design-patterns, dialogue-tree
---


# Question
Title: Unity keyboard state issue between scene loads
I'm facing an issue when loading scenes in unity.

My game is composed of full screen levels where players exit to the next level when touching the edges. So, when the player touches an edge I load next level and position the player at the correct position to start traversing the new scene. For example if I'm exiting Level1 from the right side, I load Level2 and I position player on the left.

Player is a "DonDestroyOnLoad" game object.

The problem is that unity seems to only keep last key pressed between scene loads. For example if I walk to the right in level1 and reach the edge of level, second level is loaded and player keeps moving to the right because the key is still pressed. But, If I walk to the right in level1 and jump (while pressing right arrow key) and I touch the edge of the screen, level2 is loaded but the Right key is lost (the first I pressed in level one).

I have found this here at stackexchange -\> Why doesn't Unity keep keydown states between scenes, and how can I change that? but it seems very hacky.

# Answer
This appears to be a bug wherein even a keyboard polling gameObject loses track of second keypresses across scene loads. One workaround is to keep a minimal main level that keeps track of all the inputs, scores, handles basic mechanics etc, and loads and unloads scenery overlays additively, so those controllers always persist.

Here's a simplistic script that illustrates this:

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

public class KeyPressTest : MonoBehaviour
{
    float timer;
    bool nextSceneLoaded;
    public string nextScene;

    void Update()
    {
        timer += Time.deltaTime;
        if(timer > 2 && !nextSceneLoaded)
        {
            SceneManager.LoadScene(nextScene,LoadSceneMode.Additive);
            nextSceneLoaded = true;
        }
        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("A " + timer.ToString());
        }
        if (Input.GetKey(KeyCode.S))
        {
            Debug.Log("S " + timer.ToString());
        }
    }
}

```

Put this in a start scene and provide a second scene name. Hold down the A & S keys and you'll see they continue to both be polled after the second scene loads.

**EDIT** Note -- editted intro to this answer per @Notbad's clarifying comment below, as after further experimentation it does appear that even if a gameObject is marked as `DontDestroyOnload` it will lose the second keypress when a new scene is loaded in single mode. To illustrate this, here is the above script modified so the start scene is discarded and only the poller persists. Sure enough, after the second scene loads, only one key will still be polled...

<pre><code>// Doesn't Work!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class KeyPressTest : MonoBehaviour
{
    float timer;
    bool nextSceneLoaded;
    public string nextScene;

    private void Start()
    {
        DontDestroyOnLoad(gameObject);
    }

    void Update()
    {
        timer += Time.deltaTime;
        if(timer > 2 && !nextSceneLoaded)
        {
            SceneManager.LoadScene(nextScene,LoadSceneMode.Single);
            nextSceneLoaded = true;
        }
        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("A " + timer.ToString());
        }
        if (Input.GetKey(KeyCode.S))
        {
            Debug.Log("S " + timer.ToString());
        }
    }
}
```
</code></pre>
> 1 votes

# Answer
Just for reference I ended doing this in my game controller:

```
void Start()
{
    DontDestroyOnLoad(gameObject);
}

void OnEnable()
{
    SceneManager.sceneLoaded += OnSceneLoaded;
}

void OnDisable()
{
    SceneManager.sceneLoaded -= OnSceneLoaded;
}

public void MoveToNextScene(string sceneName, ExitType exitType)
{
    _lastExitType = exitType;
    SceneManager.LoadScene(sceneName, LoadSceneMode.Additive);
}

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

// Update is called once per frame
IEnumerator _OnSceneLoaded(Scene scene)
{
    var asyncOperation = SceneManager.UnloadSceneAsync(0);
    while (!asyncOperation.isDone)
        yield return asyncOperation;
    ...
}

```

Thanks to @Acme Nerd Games instructions. It felt a bit hacky to me but well, it at least works and I can move to other more important subjects.

The only thing that I don't like is that I could end with both screens loaded for a litle period of time and the player could notice it. But it is easy fixable with a quick fade out effect.
> 0 votes

---
Tags: unity, keyboard, scene
---


# Question
Title: OpenXR device not present in Start or Awake methods in Unity C# script
I'm developing a VR game using OpenXR in Unity (specifically developing on a Valve Index). When I try to access the input devices through the `InputDevices.GetDevices()` function, I get 0 devices back when I call this function from my script's `Awake()` or `Start()` methods. But when I call the same function from my script's `Update()` method, I see all the devices (e.g. head set, left controller, right controller).

Why can't I see the devices in the `Awake()` or `Start()` methods?

# Answer
> 2 votes
It turns out that some devices, like the Valve Index, don't initialize until you pick them up. Which can happen *after* the `Start()` method runs.

So to solve this, you need to write a function that is called later on during the `Update()` method until you have the device object(s) you need.

For example, if you want to find the left controller, you would run something like the following:

```
using System.Collections;
using System.Collections.Generic;
using UnityEditor.PackageManager;
using UnityEngine;
using UnityEngine.XR;

public class HandPresence : MonoBehaviour
{
    private InputDevice _targetDevice;

    void Start()
    {
        TryInitialize();
    }

    void TryInitialize()
    {
        var inputDevices = new List<InputDevice>();
        InputDeviceCharacteristics rightControllerCharacteristics =
            InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller;
        InputDevices.GetDevicesWithCharacteristics(rightControllerCharacteristics, inputDevices);

        if (inputDevices.Count == 0)
        {
            return;
        }

        _targetDevice = inputDevices[0];
    }

    void Update()
    {
        if (!_targetDevice.isValid)
        {
            TryInitialize();
        }
        else
        {
            // Do what you would like with _targetDevice here
        }
    }
}

```

In this case, we use the `TryInitialize()` function to save the device into a private class variable. We run this function in the `Start()` method, but then check if we actually saved a device (by checking if the private class variable is valid) in the `Update()` method, and call `TryInitialize()` again if we did not.

This was tested and works in Unity 2020.2.7f1, with OpenXR 1.02.

# Answer
> 2 votes
A bit better solution with Coroutine and reusable code for multiple controllers.

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

public class HandPresence : MonoBehaviour
{
    private InputDevice _rightController;
    private InputDevice _leftController;

    void Start()
    {
        var characteristics = InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller;
        StartCoroutine(RepeatGetDevice(_rightController, characteristics));

        characteristics = InputDeviceCharacteristics.Left | InputDeviceCharacteristics.Controller;
        StartCoroutine(RepeatGetDevice(_leftController, characteristics));
    }

    private IEnumerator RepeatGetDevice(InputDevice device, InputDeviceCharacteristics characteristics )
    {
        var devices = new List<InputDevice>();

        do
        {
            yield return null;
            InputDevices.GetDevicesWithCharacteristics(characteristics, devices);
            if (devices.Count > 0)
                device = devices[0];
        } while (devices.Count == 0);

        Debug.Log($"{device.name} : {device.characteristics}");
    }
}

```

---
Tags: unity, c#, virtual-reality, valve
---