# Question
Title: Why the text in the ui texts values are all the same 9,9?
At the top :

```
public List<Text> texts = new List<Text>();

```

Than when creating a grid :

```
IEnumerator CreateGrid()
{
    gridBlocks = new Transform[gridWidth, gridHeight];

    for (int x = 0; x < gridWidth; x++)
    {
        yield return new WaitForSeconds(spawnSpeed);

        for (int z = 0; z < gridHeight; z++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
            block.transform.parent = transform;
            block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
            block.tag = "Grid Block";
            texts.Add(block.GetComponentInChildren<Text>());
            gridBlocks[x, z] = block.transform;
            gridBlocksPositions.Add(block.transform.position);
            if ((x == 0) || (x == gridWidth - 1) || (z == 0) || (z == gridHeight - 1))
            {
                gridOuterBlocks.Add(block.transform.position);

                var cubeRenderer = block.GetComponent<Renderer>();
                cubeRenderer.material.SetColor("_Color", Color.red);
            }
        }
    }

    if (Random.Range(0, 2) == 0)
    {
        var blockRenderer = gridBlocks[0, Random.Range(0, gridHeight)].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
        startBlockPOs = blockRenderer.transform.position;
        blockRenderer = gridBlocks[gridWidth - 1, Random.Range(0, gridHeight)].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
        endBlockPos = blockRenderer.transform.position;
    }
    else
    {
        var blockRenderer = gridBlocks[Random.Range(0, gridWidth), 0].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
        startBlockPOs = blockRenderer.transform.position;
        blockRenderer = gridBlocks[Random.Range(0, gridWidth), gridHeight - 1].GetComponent<Renderer>();
        blockRenderer.material.SetColor("_Color", Color.blue);
        endBlockPos = blockRenderer.transform.position;
    }
    gridGenerated = true;

    Test();
}

```

Inside the CreateGrid method I'm getting the text from each block :

```
texts.Add(block.GetComponentInChildren<Text>());

```

Than inside Test I loop over the texts and writing to each text the x and y of each block. It should show me the text 0,0 than 0,1 then 0,2 and so on... Instead it's showing on all the texts 9,9

The grid in this case height and width are 10.

```
private void Test()
{
    for (int i = 0; i < texts.Count; i++)
    {
        for (int x = 0; x < gridHeight; x++)
        {
            for (int y = 0; y < gridWidth; y++)
            {
                blocksX.Add(x.ToString());
                blocksY.Add(y.ToString());

                texts[i].text = x.ToString() + ", " + y.ToString();
            }
        }
    }
}

```

# Answer
> 1 votes
This should work:

```
private void Test()
{
    for (int x = 0; x < gridHeight; x++)
    {
        for (int y = 0; y < gridWidth; y++)
        {
            blocksX.Add(x.ToString());
            blocksY.Add(y.ToString());

            int index = y + x * gridWidth;
            texts[index].text = x.ToString() + ", " + y.ToString();
        }
    }
}

```

In your code, all steps of your inner 2 loops run for all steps of your outermost loop. Therefore you are running the innermost loop body 100 (10 * 10) times for all your texts. Only the last steps of your inner loops persist before the outermost loop moves forward, leaving all your texts at (9, 9).

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


# Question
Title: How can I rotate my player towards a target without rotating the player to face the target?
In my code I play animation that make the player walking backward. Once the player is walking backward I want it to reach a target but not to be facing the target but to keep walking backward to the target.

In the Update()

```
private void Update()
    {
        var distance = Vector3.Distance(crate.position, player.position);
        if (distance < 1.7f && crateOpenOnce == false && unlockCrate.HasOpened())
        {
            rb.isKinematic = false;
            crateOpenOnce = true;
        }

        if(startSpeedUp)
        {
            animator.Play("Walk Backward");
            SpeedUp();

            float step = movementSpeed * Time.deltaTime;
            player.position = Vector3.MoveTowards(player.position, target.position, step);
        }
    }

```

The Vector3.MoveTowards doesn't seems to be working not affecting the player he keep walking backward straight.

"Walk Backward" is the animation and inside SpeedUp I slowly increasing the speed.

The "Walk Backward" inside the SpeedUp() is a float parameter from the Animator Controller I might have to give it some other name.

```
private void SpeedUp()
    {
        if (timeElapsed < lerpDuration)
        {
            timeElapsed += Time.deltaTime;
            valueToLerp = Mathf.Lerp(endValue, startValue, timeElapsed / lerpDuration);
            animator.SetFloat("Walk Backward", valueToLerp);
        }
    }

```

The player is start walking slowly and speeding up backward while his head is watching another object that move both are moving at the same time :

The player is walking backward and looking at the rolling object and you can see on the left a bit top a very small cube and this is should be the target where the player should move to.

The player should not rotating facing the cube but moving to the cube while he is moving backward also to move to the cube but the player is keep moving backward and never getting close to the cube.

Updating about what I tried :

Because I'm adding speed to the backward animation I don't want to MoveTowards the player to the target but to RotateTowards the target :

```
private void Update()
    {
        var distance = Vector3.Distance(crate.position, player.position);
        if (distance < 1.7f && crateOpenOnce == false && unlockCrate.HasOpened())
        {
            rb.isKinematic = false;
            crateOpenOnce = true;
        }

        if(startSpeedUp)
        {
            animator.Play("Walk Backward");
            SpeedUp();

            Vector3 targetDirection = target.position - player.position;
            // The step size is equal to speed times frame time.
            float singleStep = playerRotatingSpeed * Time.deltaTime;
            // Rotate the forward vector towards the target direction by one step
            Vector3 newDirection = Vector3.RotateTowards(player.forward, targetDirection, singleStep, 0.0f);
            player.rotation = Quaternion.LookRotation(newDirection);
        }
    }

```

The problem now is that the player is rotating facing the target and I don't want it to face the target but to keep walking backward to the target the rotation should be maybe only on the Y.

This line make the player facing the target and I don't want it ! I don't want that behaviour.

```
player.rotation = Quaternion.LookRotation(newDirection);

```

# Answer
The answer at least it's working for me :

To add minus to the lookPos :

```
if(startSpeedUp)
        {
            animator.Play("Walk Backward");
            SpeedUp();

            var lookPos = target.position - player.position;
            lookPos.y = 0;
            var rotation = Quaternion.LookRotation(-lookPos);
            player.rotation = Quaternion.Slerp(player.rotation, rotation, Time.deltaTime * rotationSpeed);

        }
    }

```
> 0 votes

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


title: Making a billboard shader in Unity

text:
# Question
Title: Making a billboard shader in Unity
I followed this guy's tutorial on making a billboard shader, and it works great, except if you are billboarding things that are tall, like a tree, it looks weird, to put it simply.

When the camera's horizontal rotation is zero, it looks fine, as you can see: the trees up close are models the ones far away are billboards

But when you rotate to look up or down, the tree billboards rotate with the camera, this is particularly apparent when the up close 3D trees are pointing the correct way but the billboards in the distance are not.

So I just need to know how to get it to rotate in the way I want but not in the way I don't want:

```
            float4 worldOrigin = mul(UNITY_MATRIX_M, float4(0, 0, 0, 1));
            float4 viewOrigin = float4(UnityObjectToViewPos(float3(0, 0, 0)), 1);
            float4 worldPos = mul(UNITY_MATRIX_M, v.vertex);

            float4 viewPos = worldPos - worldOrigin + viewOrigin; // the tutorial's way of doing it for billboarding

            //float4 viewPos = mul(UNITY_MATRIX_V, worldPos); // the normal way, basically turns it into an unlit shader

            float4 clipsPos = mul(UNITY_MATRIX_P, viewPos);
            o.vertex = clipsPos;

```

I've tried a million things, like seeing what it looks like when you multiply some of the vectors in the UNITY\_MATRIX\_V matrix by 0 or by another vector before using mul() on it. So is there anyway for them to behave when the camera rotates up and down as well as have them always face the player? Thank you, here is the full code just in case: thank you!

```
Shader "Billboard"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Color("Color", Color) = (1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent+500" }
        LOD 100

        Pass
        {

            ZTest Off
            Blend SrcAlpha OneMinusSrcAlpha
            Cull Off

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_instancing
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float4 color : COLOR;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
                float4 color : COLOR0;
                UNITY_VERTEX_INPUT_INSTANCE_ID // necessary only if you want to access instanced properties in fragment Shader.
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            UNITY_INSTANCING_BUFFER_START(Props)
            UNITY_DEFINE_INSTANCED_PROP(float4, _Color)
            UNITY_INSTANCING_BUFFER_END(Props)

            v2f vert (appdata v)
            {
                v2f o;

                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_TRANSFER_INSTANCE_ID(v, o); // necessary only if you want to access instanced properties in the fragment Shader.

                float4 worldOrigin = mul(UNITY_MATRIX_M, float4(0, 0, 0, 1));
                float4 viewOrigin = float4(UnityObjectToViewPos(float3(0, 0, 0)), 1);
                float4 worldPos = mul(UNITY_MATRIX_M, v.vertex);

                float4 viewPos = worldPos - worldOrigin + viewOrigin; // the tutorial's way of doing it for billboarding

                //float4 viewPos = mul(UNITY_MATRIX_V, worldPos); // the normal way, basically turns it into an unlit shader

                float4 clipsPos = mul(UNITY_MATRIX_P, viewPos);
                o.vertex = clipsPos;

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = UNITY_ACCESS_INSTANCED_PROP(Props, _Color) * tex2D(_MainTex, i.uv);

                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);

                UNITY_SETUP_INSTANCE_ID(i); // necessary only if any instanced properties are going to be accessed in the fragment Shader.

                return col;

                //return col;
            }
            ENDCG
        }
    }
}

```

# Answer
> 0 votes
So obviously you just don't take out the camera rotation part of the matrix that the code above takes out, I just didn't know what the various parts of the matrix meant and through a long time of trial and error nothing seemed to make sense but this guy on Reddit explained everything perfectly and even wrote shader code which works. After adding his code my shader now looks like this:

```
Shader "Billboard"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Color("Color", Color) = (1,1,1,1)
    }
    SubShader
    {
        Tags { "IGNOREPROJECTOR" = "true" "RenderType"="Transparent" "Queue"="Transparent+500" } //"LIGHTMODE"="FORWARDBASE" "QUEUE"="AlphaTest" "IGNOREPROJECTOR"="true" "SHADOWSUPPORT"="true" "RenderType"="TransparentCutout" "DisableBatching"="LodFading"
        LOD 100

        Pass
        {

            //ZTest Off
            Blend SrcAlpha OneMinusSrcAlpha
            Cull Off

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_instancing
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float4 color : COLOR;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
                float4 color : COLOR0;
                UNITY_VERTEX_INPUT_INSTANCE_ID // necessary only if you want to access instanced properties in fragment Shader.
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            UNITY_INSTANCING_BUFFER_START(Props)
            UNITY_DEFINE_INSTANCED_PROP(float4, _Color)
            UNITY_INSTANCING_BUFFER_END(Props)

            v2f vert (appdata v)
            {
                v2f o;

                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_TRANSFER_INSTANCE_ID(v, o); // necessary only if you want to access instanced properties in the fragment Shader.

                //copy them so we can change them (demonstration purpos only)
                float4x4 newViewMatrix = UNITY_MATRIX_V;

                //break out the axis
                float3 right = normalize(newViewMatrix._m00_m01_m02);
                float3 up = float3(0, 1, 0);
                float3 forward = normalize(newViewMatrix._m20_m21_m22);
                //get the rotation parts of the matrix
                float4x4 rotationMatrix = float4x4(
                    right, 0,
                    up, 0,
                    forward, 0,
                    0, 0, 0, 1);

                //the inverse of a rotation matrix happens to always be the transpose
                float4x4 rotationMatrixInverse = transpose(rotationMatrix);

                //apply the rotationMatrixInverse, model, view and projection matrix
                float4 pos = v.vertex;
                pos = mul(rotationMatrixInverse, pos);
                pos = mul(UNITY_MATRIX_M, pos);
                pos = mul(newViewMatrix, pos);
                pos = mul(UNITY_MATRIX_P, pos);
                o.vertex = pos;

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = UNITY_ACCESS_INSTANCED_PROP(Props, _Color) * tex2D(_MainTex, i.uv);
                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                UNITY_SETUP_INSTANCE_ID(i); // necessary only if any instanced properties are going to be accessed in the fragment Shader.
                return col;
            }
            ENDCG
        }
    }
}

```

---
Tags: unity, shaders
---


# Question
Title: How do I load scene content but not show it until later?
In my game, I have

1. A start up scene that has a 1 script. This script loads
2. The inventory scene
3. The first level

I don't want to show the inventory scene, I just want to pre-load it. Therefore I have put all the objects in the inventory scene into an empty game object named "InventoryRoot". I have called DontDestroyOnLoad on it. I want to disable this gameobject after the scene has loaded. This way, the inventory scene is not shown, but it is "there". When I want to show the inventory scene, I will call InventoryRoot.setActive(true);

However, I don't know how to set it non-active from the outside.

My current code is this:

```
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("InventoryScene");

// Wait until the asynchronous scene fully loads
while (!asyncLoad.isDone)
{
    yield return null;
}

//now I would like to do something like this (pseudo-code):
asyncLoad.getScene().getRootObject().setActive(false);

```

Edit:

Later, when I want to show the inventory, I would simply call

```
_InventoryScene.getRootObject().setActive(true);

```

I would also like to pass variables to the \_InventoryScene and not use playerprefs or similar.

That is why I wanted to learn how to access the rootobject of another scene. I thought I could then in the same way also access scripts in the other scene and pass data to it, for example like this:

```
_InventoryScene.showInventory(MyPlayer.CurrentInventory);
_InventoryScene.getRootObject().setActive(true);

```

# Answer
> 1 votes
Unfortunately this does not work. Setting .allowSceneActivation = false puts the entire app into a holding state: Scenes do not stop showing "(is loading)"

An alternative approach using a singleton would look like this:

Create a GameManager script of type Singleton. It's code is stated on the bottom of this posting.

Instead of using global variables and access them directly (like PlayerHealther = 50), you call it like this:

```
GameManager.Instance.PlayerHealth = 50;

```

Keeping everything in a single class makes using it fun and keeps everything nicely organized.

In your GameManager, at startup, you load the scenes that you require to be permanently available, additively.

You put all of your scene object in an empty gameobject called "...Root". For example, the inventory screen scene's root gameobject would be called "InventorySceneRoot".

You would load it like this:

```
private GameObject _InventoryRoot = null;

public void StartUp()
{
     pGetOrLoadInventoryWithoutActivating();
}

private void pGetOrLoadInventoryWithoutActivating()
{
    if (_InventoryRoot != null)
    {
        return;//already loaded
    }

    _InventoryRoot = GameObject.Find("InventoryRoot");

    if (_InventoryRoot != null)
    {
        return;//already loaded
    }

    StartCoroutine(pLoadInventoryWithoutActivating());
}

IEnumerator pLoadInventoryWithoutActivating()
{
    AsyncOperation nAsyncLoad = SceneManager.LoadSceneAsync("InventoryScene");

    // Wait until the asynchronous scene fully loads
    while (!nAsyncLoad.isDone)
    {
        yield return null;
    }

    _InventoryRoot = GameObject.Find("InventoryRoot");

    if (_InventoryRoot == null)
    {
        Debug.Break();
    }
    DontDestroyOnLoad(_InventoryRoot);//make it so that the InventoryRoot is not destroyed when we load other scenes. But setting the root object to DontDestroyOnLoad, we protect the entire scene of being unloaded

    _InventoryRoot.SetActive(false);//make the inventory scene disactive at first

    pCheckStarted();
}

```

Then if you later want to show or hide the inventory scene, you call the following function:

```
public void ShowOrHideInventory(bool uActivate)
{
    _InventoryRoot.SetActive(uActivate);
}

```

like this:

```
GameManager.Instance.ShowOrHideInventory(true); //do this to show the inventory

```

You would do the level loading in the GameMananager as well, for example like this:

```
public void LoadLevel1()
{
    if (_Level1Root != null)
    {
        return;//already loaded via StartCoroutine(pLoadSceneAsync("Level1Scene"));
    }

    _Level1Root = GameObject.Find("Level1Root");

    if (_Level1Root != null)
    {
        return;//already loaded
    }

    StartCoroutine(pLoadLevel1Async("Level1Scene"));
}

private IEnumerator pLoadLevel1Async(string u)
{
    AsyncOperation nAsyncLoad = SceneManager.LoadSceneAsync(u);

    while (!nAsyncLoad.isDone)
    {
        yield return null;
    }
    _Level1Root = GameObject.Find("Level1Root");

    if (_Level1Root != null)
    {
        Debug.Break();//must be present
    }
}

```

That's the basic concept. You have to understand it and adapt it to your project because not all games have the same architecture, but for the start, it will work.

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

using UnityEditor;
using UnityEngine.SceneManagement;

public class GameManager : Singleton<GameManager>
{
    private GameObject _InventoryRoot = null;
    private GameObject _HUDRoot = null;
    private GameObject _Level1Root = null;

    private HUDanimator _HUD = null;

    private bool _bPrerequisitesLoaded = false;

    public bool PrerequitesLoaded()
    {
        return _bPrerequisitesLoaded;//In my game, the HUD is in a scene of its own. However, Level1 uses this HUD via GameManager.Instance.getHUD(). There are situations where the Level1 has been loaded before the HUDScene, and the HUD is not available yet. Instead of letting it throw an error, I check in LateUpdate, Update, OnGUI, etc. of Level1 if all the necessary stuff (inventory and HUD) have already been loaded (hasStarted=
    }

    // Add your game manager members here
    public void Pause(bool paused)
    {
    }
    public void SaySomething(string u)
    {
        if (EditorUtility.DisplayDialog("Ok :-)", u, "Ok"))
        {

        }
    }
    public HUDanimator getHUD()
    {
        if (_HUD == null)
        {
            GameObject nGo = GameObject.Find("TheHUDCanvas");
            if (nGo == null)
            {
                Debug.Break();//the HUDScene is not loaded yet. This may not happen! We need to make sure that HUDScene has already been loaded
            }
            _HUD = nGo.GetComponentInChildren<HUDanimator>();
            if (_HUD == null)
            {
                Debug.Break();
            }
        }
        return _HUD;
    }
    public void ShowOrHideInventory(bool uActivate)
    {
        _InventoryRoot.SetActive(uActivate);
    }
    public void StartupLoadInventoryAndHUD()
    {
        GameObject nGo = GameObject.Find("Level1Root");
        if (nGo != null)
        {
            DontDestroyOnLoad(nGo);//we are calling this script from Level1Scene. So before we load HUD and Inventory, we need to protect this scene
        }

        pGetOrLoadInventoryWithoutActivating();
        pGetOrLoadHUD();
    }
    private void pGetOrLoadHUD()
    {
        if (_HUDRoot != null)
        {
            return;//already loaded
        }

        _HUDRoot = GameObject.Find("HUDRoot");

        if (_HUDRoot != null)
        {
            return;//already loaded
        }

        StartCoroutine(pLoadHUDWithoutActivating());
    }
    private void pGetOrLoadInventoryWithoutActivating()
    {
        if (_InventoryRoot != null)
        {
            return;//already loaded
        }

        _InventoryRoot = GameObject.Find("InventoryRoot");

        if (_InventoryRoot != null)
        {
            return;//already loaded
        }

        StartCoroutine(pLoadInventoryWithoutActivating());
    }
    private void pCheckStarted()
    {
        if (_HUDRoot != null)
        {
            if (_InventoryRoot != null)
            {
                _bPrerequisitesLoaded = true;
            }
        }
    }
    public void LoadLevel1()
    {
        if (_Level1Root != null)
        {
            return;//already loaded via StartCoroutine(pLoadSceneAsync("Level1Scene"));
        }

        _Level1Root = GameObject.Find("Level1Root");

        if (_Level1Root != null)
        {
            return;//already loaded
        }

        StartCoroutine(pLoadLevel1Async("Level1Scene"));
    }
    private IEnumerator pLoadLevel1Async(string u)
    {
        AsyncOperation nAsyncLoad = SceneManager.LoadSceneAsync(u);

        while (!nAsyncLoad.isDone)
        {
            yield return null;
        }
        _Level1Root = GameObject.Find("Level1Root");

        if (_Level1Root != null)
        {
            Debug.Break();//must be present
        }
    }

    IEnumerator pLoadInventoryWithoutActivating()
    {
        AsyncOperation nAsyncLoad = SceneManager.LoadSceneAsync("InventoryScene");

        while (!nAsyncLoad.isDone)
        {
            yield return null;
        }

        _InventoryRoot = GameObject.Find("InventoryRoot");

        if (_InventoryRoot == null)
        {
            Debug.Break();
        }
        DontDestroyOnLoad(_InventoryRoot);//make it so that the InventoryRoot is not destroyed when we load other scenes. But setting the root object to DontDestroyOnLoad, we protect the entire scene of being unloaded

        _InventoryRoot.SetActive(false);//make the inventory scene disactive at first

        pCheckStarted();
    }

    IEnumerator pLoadHUDWithoutActivating()
    {
        AsyncOperation nAsyncLoad = SceneManager.LoadSceneAsync("HUDScene");

        // Wait until the asynchronous scene fully loads
        while (!nAsyncLoad.isDone)
        {
            yield return null;
        }

        _HUDRoot = GameObject.Find("HUDRoot");

        if (_HUDRoot == null)
        {
            Debug.Break();
        }
        DontDestroyOnLoad(_HUDRoot);

        // _HUDRoot.SetActive(false);//make the HUD scene disactive at first

        pCheckStarted();
    }
}

```

And this is the singleton class:

```
using UnityEngine;

/// <summary>
/// Inherit from this base class to create a singleton.
/// e.g. public class MyClassName : Singleton<MyClassName> {}
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    // Check to see if we're about to be destroyed.
    private static bool _bShuttingDown = false;
    private static object _bLock = new object();
    private static T _Instance;

    /// <summary>
    /// Access singleton instance through this propriety.
    /// </summary>
    public static T Instance
    {
        get
        {
            if (_bShuttingDown)
            {
                Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
                    "' already destroyed. Returning null.");
                return null;
            }

            lock (_bLock)
            {
                if (_Instance == null)
                {
                    // Search for existing instance.
                    _Instance = (T)FindObjectOfType(typeof(T));

                    // Create new instance if one doesn't already exist.
                    if (_Instance == null)
                    {
                        // Need to create a new GameObject to attach the singleton to.
                        var singletonObject = new GameObject();
                        _Instance = singletonObject.AddComponent<T>();
                        singletonObject.name = typeof(T).ToString() + " (Singleton)";

                        // Make instance persistent.
                        DontDestroyOnLoad(singletonObject);
                    }
                }

                return _Instance;
            }
        }
    }

    private void OnApplicationQuit()
    {
        _bShuttingDown = true;
    }

    private void OnDestroy()
    {
        _bShuttingDown = true;
    }
}

```

# Answer
> -1 votes
You could use `SceneManager.LoadSceneAsync` in conjunction with `AsyncOperation.allowSceneActivation = false` to load basically everything and then wait to activate until you're ready for it. Details on that here. Since `AsyncOperations` are executed in a queue that is suspended by this flag, you should enqueue scenes for async loading in the order that you intend to show them. The last thing in the queue is the one you can delay showing using `allowSceneActivation = false`.

You could also try what you had planned but load behind a splash so players don't see the scene pop in, then disable once it's active using your root object. While the scene has not yet been loaded, I don't know how you can get your root object to turn it on or off.

As with all things performance, before opting for a complicated loading system, you should profile to make sure it's worth your time.

---
Tags: unity, scenemanager
---


# Question
Title: SpriteAtlas's sprites not initialized in ScriptableObject?
I am trying to implement a simple abstraction over `SpriteAtlas` where I can simply request texture coordinates for a certain `BlockType` (each `BlockType` has associated texture with it that is packed inside a `SpriteAtlas`. Imagine dirt, stone, water etc.). To achieve just that, I've created a simple `ScriptableObject` class that is given a reference to the `SpriteAtlas` and in its `OnEnable` method it tries to extract all of the texture coordinates from the sprite atlas:

```
    [SerializeField] private SpriteAtlas spriteAtlas;

    private readonly Dictionary<BlockType, Vector2[]> _blockTypeToTextureCoordinates = new Dictionary<BlockType, Vector2[]>();
    private Sprite[] _sprites;

    private void OnEnable()
    {
        LoadAllSpritesFromSpriteAtlas(); // This method works perfectly fine.
        ExtractTextureCoordinatesFromEachSprite(); // This method has a problem in it.
    }

    private void LoadAllSpritesFromSpriteAtlas()
    {
        _sprites = new Sprite[spriteAtlas.spriteCount];
        spriteAtlas.GetSprites(_sprites);
    }

    private void ExtractTextureCoordinatesFromEachSprite()
    {
        foreach (var sprite in _sprites)
        {
            if (!Enum.TryParse(sprite.texture.name, out BlockType blockType))
            {
                Debug.LogError($"'{sprite.texture.name}' could not be converted to a block type.");
                continue;
            }

            // I've been in debugger and sprite is not yet packed.
            _blockTypeToTextureCoordinates[blockType] = sprite.uv;
        }
    }

```

The problem lies in the last method `ExtractTextureCoordinatesFromEachSprite`, where when I am trying to get sprite texture coordinates (uv), it always returns `{(0, 0), (0, 1), (1, 0), (1, 1)}`, which is a full sprite atlas texture, instead of only a small portion of it (some small texture coordinate numbers between 0 and 1). I used debugger and it said that `sprite.packed` variable is set to `false` (meaning the sprites are not yet packed at this point in time). However, if I would do exactly the same code in `MonoBehaviour` class' `Awake` method, everything would work fine and sprites would be packed when accessed and appropriate UV coordinates would get returned.

However, I'd really love if I could do it inside a `ScriptableObject` and it really makes no sense that sprites are not initialized at that point since this information could easily be created even before the game is run. Can anyone help me understand why the sprites are not packed when accessed in `OnEnable` method of `ScriptableObject` and is there a way to make it work somehow?

# Answer
Will switching this to use lazy initialization help?

```
// No OnEnable method anymore. Instead, when a sprite UV is requested,
// we check whether we've loaded all the sprite texture coordinates,
// and if not, then we load them "just in time".

public Vector2[] GetUVsForBlockType(BlockType blockType) {
    if (_blockTypeToTextureCoordinates.Count == 0) {
        LoadAllSpritesFromSpriteAtlas();
        ExtractTextureCoordinatesFromEachSprite();
    }

    return _blockTypeToTextureCoordinates[blockType];
}

```
> 1 votes

---
Tags: unity, sprites, texture-atlas
---


# Question
Title: Pygame logic to make a player stop at obstacles without overlapping them
what's the best logic to force the player to change its direction when he's just next to an obstacle (building, rock, tree..) ?

I know this is related to collision detection but maybe my logic isn't as good as needed or maybe it needs some improvements.

Here is the pseudocode for it :

```
for obstacle in obstacles:
    if player.mask.overlap(obstacle.mask, offset):
        blocked_dir = player.direction
    else:
        blocked_dir = ''

# movement
if key_pressed[K_d] and blocked_dir != 'right':
    player.x += player.speed
elif key_pressed[K_z] and blocked_dir != 'up':
    player.y -= player.speed
elif key_pressed[K_q] and blocked_dir != 'left':
    player.x -= player.speed
elif key_pressed[K_s] and blocked_dir != 'down':
    player.y += player.speed
# There are also other 4 directions (topright, topleft, bottomleft, bottomright) and they all have the same logic.

```

So the problem with this code is that it's not accurate : sometimes the player glitches and overlaps the obstacle a bit and sometimes he can't move in a direction other than the blocked one since he's still in collision with the obstacle. (that other direction in this case becomes the blocked one).

So is there a better logic ? If not, how can I fix my own ?

# Answer
> 0 votes
After taking a look at the comments of a similar post, I could fix the issue.

My logic of detecting collision with map obstacles was not wrong, but it was missing something : preventing the player from getting stuck at the obstacle just after colliding with it.

The lack of this feature in my game made the player overlap with obstacles once he hits them and made the game look unrealistic.

So I had to push the player back once he collides with an obstacle depending on his last direction.

Here is the code for that :

```
def push_backwards(self):
    if self.blocked_dir == 'up':
        self.y += 5
    elif self.blocked_dir == 'down':
        self.y -= 5
    elif self.blocked_dir == 'right':
        self.x -= 5
    elif self.blocked_dir == 'left':
        self.x += 5
    ...

for obstacle in obstacles:
    if player.mask.overlap(obstacle.mask, offset):
        player.blocked_dir = player.direction
        player.push_backwards()
    else:
        player.blocked_dir = ''

```

---
Tags: collision-detection, movement, pygame, masking
---


title: Having an Audio Atlas?

text:
# Question
Title: Having an Audio Atlas?
**Problem**

I have 100 textures and I want to easily load them all without writing 100 lines of code loading them all.

**Solution**

Use a texture atlas. Use this to pack them. Use pixijs or something like that as it has native support for texture atlas

**Problem**

The same problem but with audio.

**My Proposed Solution**

Use a sound atlas. Merge all the audio into one, have a json recording the time stamps to beginning and end.

However, this solution has flaws. How will I update the sound to know whenever to stop the sound without going slightly under or over the time? Is this solution even reliable? Is there a tool that we can use for this? Are there better solutions than what I proposed?

# Answer
> 4 votes
Why would you write individual lines of code for loading each texture/sound?

That sounds like something you should load from a manifest file, so that adding/changing assets is just a data change, not a code change - no need to recompile. Your loading code then just loads the manifest, and loops through loading the assets identified inside.

You can take this a step further with data baking, where you combine the manifest and all its referenced files into one binary, load it as one big blob, then walk through the manifest portion to find the memory offsets within for each contained asset. This is mostly an optimization for loading speed, since it combines many small reads into one big read, and you can "pre-digest" the data into whatever binary representations your game uses internally, rather than decoding them on load.

Even with the data baking approach, each sound asset still retains its own identity as a separate data object, rather than being a set of timecodes in a single massive audio stream, so you should not have to modify the code that plays/interacts with individual sounds.

# Answer
> 1 votes
The main reason you use a texture atlas is not because you want to reduce the amount of lines of code to define or use multiple small textures. If you have a lot of textures, all that information will likely be in a data file, or automatically generated code anyways.

We use texture atlases because when you're drawing stuff on the screen, it is much faster to draw a lot of sprites with one draw call, where each sprite takes from a different area of a large atlas, than to draw each sprite with a different texture, and therefore a different draw call. The trade in simplicity vs performance is generally acceptable, so atlasing textures, especially for GUI elements is a very common operation nowadays (don't forget to turn mipmapping off).

With audio, this doesn't really apply. Audio mixing is performed in regular (not GPU) memory, so it doesn't really matter if multiple audio clips are separate, or in a single large audio "atlas". Furthermore, it can add a bit of complexity, since there is an additional seek operation for every clip that you want to play.

If you want to do an audio atlas, go ahead. It will most likely not affect performance, but if you find that it makes managing your audio files easier, then it might be a good idea for your use case.

As to how to go about making an audio atlas, I'm not aware of many tools that do this for you, but I think it should be relatively easy to hack a quick tool, for example in C#, with NAudio to read, write and manipulate audio files. You can add padding between the audio files if you think that is necessary, and output your data in Json, or whatever file format you want.

---
Tags: audio
---


# Question
Title: Our designer refuses to work because of job official title
Our game contains comics to tell part of the story, and our comic designer says that he is not responsible for designing the characters in the comics because it is the job of the character designer. Is what he said true? As far as I know the comic designer is responsible for everything that is in the comics, regardless of the design content. Excuse me if I'm not using official job titles here (like a "comic designer"?! is there even such title) Thanks in advance.

# Answer
> 4 votes
Job titles and responsibilities vary greatly from one place to the next. The duties for a particular role at a particular place depend on what the two relevant parties have agreed upon. The particulars of that (such as authority of a manager to assign additional responsibilities, legal ramifications, and so forth) extend beyond the bounds of game development.

Game development teams often have overlapping roles and require a certain amount of fluidity, especially on small teams.

Both options you described sound reasonable. That is to say, designing characters for the comic content could reasonably be assigned to either role, or possibly even both.

Game development roles are not externally regulated. As such, "known title duties" only makes sense in the context of a contract of some kind. For instance, hiring documents, certain verbal agreements or task assignments from a manager. That's not something we can arbitrate.

# Answer
> 2 votes
Most job descriptions include a final catch-all clause that says something like "and any other duties as assigned or required."

It is one thing to say, "I don't have the skillset to do that job, and I am concerned about producing a quality product." It's another thing to just outright refuse to do something just because they don't want to do it.

Someone refusing to do work because it doesn't align with their job title or exactly matches their job description is a problematic employee and should be replaced. That person is not looking out for the company's best interests.

---
Tags: character, project-management, teamwork
---


# Question
Title: Are MMORPG servers and clients usually developed in isolation?
As with the title, are they usually developed together in a custom engine, or are they mostly developed independantly of each other? e.g. the server and client as completely different projects that would just share the engine as a DLL or something?

# Answer
> 3 votes
It's fair to say that for the sort of authoritative server / pure client which nearly all MMORPGs use for unavoidable security reasons, the server is typically developed with the specific purpose of serving that specific data which the client engine needs to consume in order to function.

This works much the same for highly visual business applications, which at some point early in development, if not right at the start, split out the business logic and develop that as the backend. This development process tends to be highly parallel with much ongoing feedback between client & server devs (can occur rapidly early on, if the same dev works on both). You can generally rest assured that though there may be shared components, the two projects will be kept as distinct source repositories, at the very least. Git submodules are often used for shared components.

Besides security concerns, remember that games are quite complex both design-wise and technically, and are usually on tight development budgets; we generally do not have the resource to make a server so generalised that it could be used with multiple clients; highly generalised code penalises us in terms of code comprehension (thus maintainability) and performance. It's a rare case to see multiple front-ends / clients for the same server.

(Dwarf Fortress is one such case, probably this was possible because the *vast* majority of its code was anyway non-rendering code, since its base renderer is very simple, the process of separating that out was probably fairly trivial and could have been done quite late into the project's lifetime).

# Answer
> 2 votes
This is too context-dependent.

Some MMORPG games that I had a chance to look at in terms of source code preferred to develop the server and the client as separate codebases. Some of them didn't even share any code between the two. If it was a custom engine I too would probably prefer them to be separate.

But if you are using an already established game engine for your client (such as Unity or Unreal), you might as well use the engine in headless mode for your server too, just for the sake of development speed.

# Answer
> 2 votes
Warning: Sweeping generalizations will be made here.

Client and server development (for the most part) is written in languages suitable to the task. The client will (most likely) be C++, C#, or mobile native. The server will again most likely be written in a "web-friendly" language. You will not write your server in C++ when Java, Python, Ruby, Go, Node, C#(?) are available and come with lots of APIs for web/cloud services like load balancers, databases, API gateways, serverless functions.

The important part is that the server and client are doing very different jobs. They have particular anxieties. You can always throw more or larger hardware at a server problem - very hard to do that on the client!

You can share (note: can and not will) the DTO's (Data Transfer Objects). This is incredibly natural if you are using the same language on the front and backend. This is what I do with C# and Unity and C# with NancyFX on the server. Both share a single classlib containing all our DTO's.

But again, I've seen just as many folks write their own DTO's in Java while the client folks write theirs in Swift or Kotlin.

I've also seen generators where you write the DTO's once in your own DSL, and your own tool/preprocess-step generates the DTO in the correct language for client and server.

There is no "right way" because every situation is different. Maybe you just can't hire any C# backend developers, and now your backend is in Java because you only have Java devs available (this has happened to me at LEAST once, I'm a Unity & C# fanboy after all).

Whatever you choose to do, make sure it works for your situation and your team.

# Answer
> 1 votes
The answer is, it depends. My MMO is a separate development stack. My client is developed in Unity, and my server is .NET so they necessarily must be developed separately.

However, Unity for example allows for developing server code and client code right alongside each other. When you are done you end up compiling both the client and the server, OR each instance is both client and server and you tell it which it is.

---
Tags: architecture, client-server, mmo, server, client
---


# Question
Title: UI detects different resolution after second app launch
I'm encountering the strange behaviour that my UI (canvas with some buttons) is looking differently after the second launch on mobile. Restart of the phone does not help. This does not happen in play mode. This does not happen in play mode and only einstalling the app results again in the correct view. (installation is done via transfer of apk to phone and installing it). There are no errors in the console and everything works on the first start. The version used is 2021.1.15

In the editor the screen resolution is set to the same as the phone, the canvas scaler script is deactivated, there is no script that scales or adds elements dynamic or from a save file. All elements are places via the inspector.

I created a new project with the canvas and some buttons, looking like this .

When I first time start the app, it looks exactly as in play mode:

On second app launch, it looks like this:

The numbers on the button are the position and size

```
GetComponentInChildren<Text>().text =
            transform.position.ToString() + GetComponent<RectTransform>().sizeDelta.ToString();

```

The button itself is default button added over the menu with no layout at all, values adjusted over the inspector. The original scene had more objects in the scene itself which where not affected by the second launch, only the UI gets messed up. The button has still the same reported size on the second launch but the position is way smaller.

Now if I add the canvas scaler, set it to scale with screen size and enter the same values as my phone uses, I'm getting a slightly different behaviour. The first launch is still exactly the same, on the second launch the buttons are still similar to the first launch but all the numbers are still from the second screenshot. While the UI displays all element, they are not as sharp as on the fist launch.

Why would the canvas think the phone has a resolution of 1493x720 on the second launch instead of the correct 2240x1080?

Update:

Here are the numbers between the two launches.

# Answer
I still have not figured out what this is causing this, at least it is possible to force the game to use the correct resolution by just setting the resolution back.

```
void Start() {
    Screen.SetResolution(2240, 1080, true);
}

```

https://docs.unity3d.com/ScriptReference/Screen.SetResolution.html
> 1 votes

---
Tags: unity
---


# Question
Title: How do I get the main camera from a root object?
In my scene, all objects are children of game object named "SceneRoot".

The main camera is a child somewhere in this hierarchy, for example at

```
SceneRoot->Hero->Model->MainCamera;

```

I need to attach a raw image to it using code.

To do that, I first need to find this camera.

I have tried

```
GameObject go = SceneRoot.GetComponentsInChildren<Camera>();

```

But that throws the error

```
Type "UnityEngine.Camera[]" can't be converted to "UnityEngine.Camera".

```

How could I get the camera object in order to attach a raw image to it?

Thank you!

# Answer
> 1 votes
Did you mean `GetComponentInChildren`, without the "s"?

When you use the plural, you're saying "give me ALL the cameras you find," so it has to return an array `Camera[]` to hold potentially multiple cameras.

When you use the singular, you're saying "give me the FIRST camera you find," so it's able to return either a single valid `Camera` or `null` if it can't find any.

Your compiler error describes this exact problem, so please be sure to read these messages carefully and investigate what they're telling you.

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


# Question
Title: how to get current zoom level from scene window
I want to show some label on some rect transforms using `Handles.Label()`. it shows the text with a default font size regardless of the zoom level in the scene window.

```
public class NodeWrapper : MonoBehaviour {

    public Node node;

    void OnDrawGizmos()
    {
        Handles.Label(transform.position + new Vector3(-.9f, .5f), node.Name);
        Handles.Label(transform.position + new Vector3(-.9f, .4f), node.Info);
        ...
    }
}

```

So when I zoom out in the scene window, the labels get closer and at some point they become unreadable. I want to show/hide some lines when zoom level changes. How can I achieve that? Is it possible to get the current zoom level of the scene?

## edit

PS. I'm developing a node editor for another game, I use scene window to create and serialize some objects. My target is only **Scene window** which uses **2D** config.

# Answer
> 3 votes
To get the `Handles.Label` function to work in different zoom levels you need to change two things:

1. Use the function signature that accepts `GUIStyle`
2. Calculate the `fontSize` while considering the `orthographicSize` of the scene camera.

For example:

```
// this is the internal camera rendering the scene view, not the main camera!
float zoom = SceneView.currentDrawingSceneView.camera.orthographicSize;

// the style object allows you to control font size, among many other settings
var style = new GUIStyle();

// this value depends on your scene, tweak it to match the other objects
int fontSize = 70;

// as you zoom out, the ortho size actually increases,
// so dividing by it makes the font smaller which is exactly what we need
style.fontSize = Mathf.FloorToInt(fontSize / zoom);

Handles.Label(transform.position + new Vector3(-.9f, .5f), node.Name, style);

```

# Answer
> 1 votes
docs.unity3d.com/ScriptReference/Camera-orthographicSize.html , orthographicSize value is your zoom, make a script to get that value from the main.camera and manipulate the labels according to that value.

small example,

```
public Camera cam;
private float orthoZoom;

void Update() {
  orthoZoom = cam.orthographicSize;
}

```

# Answer
> 0 votes
I tested, and it worked!

```
float zoom = SceneView.currentDrawingSceneView.size;
float fontSize = 300f;
var style = new GUIStyle();
style.fontSize = Mathf.FloorToInt(fontSize / zoom);

```

---
Tags: unity, editors
---


# Question
Title: How to best deal with percentage from gear and skills when stacking
I have a issue I am unsure the best way to go about solving. Developing a game I store all the "percentage boosts" a character could get either from skills, equipment, quest items or whatnot as decimals (lowest being 0.0001 all the way to 1.0+).

This might not be the proper way in relation to my question but, without radically changing a game that's already live (web game), it's the way I have to work with.

What I normally do is look at all your equipment, boons, skills and so on that affect this stat and add them all together:

```
loop
    equipmentBonus += slot->bonus // where equipBonus = 0.0 to start.

```

Do the same things for boons, skills and so on.

Now we have this number, lets say its 1.87 (187% to this stat) One might think:

```
Stat * Bonus // (10 * 1.87 = 18.7)

```

Seems straight forward. But what if that total bonus is a flat 1.0; now it's just 10. In my mind it should double it, so:

```
Stat * (1 + Bonus) // (10 * 2.87 = 28.7)

```

Ok so now if their bonus is above 1 we double it.

New issue: `Bonus is now 3.6 (+1 = 4.6)`

This is where I am having issues, because in my mind 3.6 (360%) (same base stat of 10) is now 36, where as 4.6 (1 + Bonus) = 46.

The only solution I could think of was to stop the addition of 1 once we reach higher then 2, but again that poses issues because 1 is now 2, 2 is now 3, 3 is now 3 ... (hundred percent).

Can some one help me understand the best way to apply these stat bonuses? Would it be as simple as:

```
Stat + (Stat * Bonus)// But what if the bonus is higher then 1?

```

Thoughts?

**I am not looking for code, but a better understanding oh how to handle percentages both above and below 100%, without fundamentally changing how they are stored (i.e., 0.0001 -\> 1.0) in a way where they stack in an additive way (I believe is above) as opposed to multiplicative way)**

# Answer
> 3 votes
I think you have two concepts mixed up: A percentage multiplier and a percentage bonus.

A percentage multiplier can decrease your stats below their original value. If you have a debuff that says "attack stat reduced to 20%", then that means you'll have stat\*0.2 afterwards. If, on the other hand, you have a buff that says "attack stat tripled", then you'll have stat\*3.

However, if you have percentage *bonuses*, it adds to the stats you already have. Before bonuses you have 100% of your base stats. After a +10% bonus you'll have 110% of your base stats. This is true regardless of how big the bonus is. Maybe this makes it more intuitive: If you have a "+200% bonus", this means you gain 2x your stats *on top of* your existing stats. Meaning that you'll have 3x your original stats in the end.

The two formulas you came up with intuitively are actually identical. Quick mathematical proof:

```
finalStat = stat * (1 + bonus); //Multiply it out
finalStat = stat * 1 + stat * bonus; //*1 is trivial, get rid of it
finalStat = stat + stat * bonus; //Here we are!

```

As long as you add all percentage numbers together before calculating the final stats, the bonuses will be additive, not multiplicative. You can achieve this easily by ensuring that you only do the `finalStat = stat + stat * bonus` calculation exactly once in your code.

Also, be careful that you don't have different systems in your game with bonuses that stack by multiplication (unless intended). Players are very efficient at finding and exploiting these to push their stats to the moon.

---
Tags: mathematics, rpg
---


# Question
Title: How do I change gravity of box2d world after world is created?
I want to modify the world of box2d after creating it, namely to change the gravity vector. Is there a way to do this?

# Answer
> 2 votes
`world.setGravity(b2Vec2(0.0, 0.0));`

# Answer
> 0 votes
Or use `world.SetGravity(new b2Vec2(0.0, 10.0));`

Note the capital `S` and the `new` command. It may depend on what version, language, etc. - not sure.

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


title: How do I sort canvas UI?

text:
# Question
Title: How do I sort canvas UI?
I have a HUD on the UI layer.

It looks like this:

This HUD overlays the scene.

There are situations where I need to fade out the screen (including the HUD).

To do that, I have added a black image on the UI layer whose alpha value I change.

This fades out the scene, but not the HUD.

What could I do in order to make it so that the HUD is also affected / overlaid by the black image?

This is what the black image looks like:

# Answer
> 2 votes
I got it:

I have to set the HUD-\>Canvas-\>Sort Order to -1.

---
Tags: unity
---


# Question
Title: How to map texture pixels to the corresponding 3D positions?
I have a mesh stored in .obj format with a texture image in .png format. For any "defined" pixel in the texture image, I'd like to compute the corresponding 3D coordinates when the texture image is mapped to the 3D mesh. For "defined" pixels, I mean the texture pixels that correspond to points on the surface of the mesh, not the texture pixels between the texture patches.

The .obj file format is as follows:

```
v 0.123 0.234 0.345 1.0
v ...
...
vt 0.500 1
vt ...
...
vn 0.707 0.000 0.707
vn ...
...
f 1/1 2/2 3/3
f ...
...

```

# Answer
> 1 votes
**This answer only covers Affine Texture Mapping. Consider this a partial solution.**

---

I'll be assuming you can process your obj to a list of triangles. Each triangle having three vertex. And each vertex having their 3D space coordinates (x, y, z) and their texture coordinates (u, v).

---

For each triangle, sort the points by one texture coordinate - let us say -`u`. Once sorted, let us call these points `A`, `B`, and `C`.

You are going to define - at most - two ranges: The range from `A.u` to `B.u`, and the range from `B.u` to `C.u`. And I say at most, because perhaps some of these coordinates are equal. If they are, you don't need that range.

The start and end of each range define two lines, which constraint the texture space on the `u` axis. On The `v` axis, you will constraint the texture space by two line equations of the form `v = mu + n`.

For the first range, the lines equations correspond to the lines `l_AB` and `l_AC`. For the second range, the lines are `l_AC`, `l_BC`.

You can figure out the line equations with a little algebra. The slope is the good old formula:

```
m = (B.v - A.v)/(B.u - A.u)

```

And for the intercept, we can replace one of the points:

```
A.v = m(A.u) + n

=>

n = A.v - m(A.u)

```

Remember that we are doing the lines `l_AB` and `l_AC` for the first range, which cross at the point `A`. And the lines `l_AC` and `l_BC` for the second, which cross at the point `C`. Thus, we can use the `v` coordinates of the other points to determine which line has lower values in each range.

Now, you can iterate over the texture. For example, for the first range:

```
if (B.v < C.v)
{
    l_1 = l_AB
    l_2 = l_AC
}
else
{
    l_1 = l_AC
    l_2 = l_AB
}

for (int u = (int)floor(A.u); u <= (int)ceil(B.u); u++)
{
    for (int v = (int)floor(l_1(u)); v <= (int)ceil(l_2(u)); v++)
    {
        // Something with u and v
    }
}

```

*I don't know how you want to handle texels that are partially on a triangle. However, I'm suggesting you include them. Which is the reason behind the rounding (`floor` and `ceil`) above.*

---

We need to convert these coordinates to 3D, of course. For that we will have to express these `u` and `v` coordinates as a linear combination of the lines of the triangle.

We can use a single conversion for the whole triangle - being the points of a triangle always coplanar. Let us base it on the point `A`. So we will work assuming `A = 0`.

We will define vectors in texture space: `dB = B - A`, `dC = C - A` and `d = uv - A`. So we could say:

```
p * dB + q * dC = d

```

Which is actually two equations:

```
p * dB.u + q * dC.u = d.u
p * dB.v + q * dC.v = d.v

```

Since we have two linear equations and two unknown (`p`, `q`) we can solve the system. Let us do elimination, Gauss-Jordan style:

```
   p     q
┌                  ┐
│ dB.u  dC.u │ d.u │
│            │     │
│ dB.v  dC.v │ d.v │
└                  ┘

Divide the first equation by dB.u =>

     p      q
┌                         ┐
│  dB.u    dC.u  │  d.u   │
│ ------  ------ │ -----  │
│  dB.u    dB.u  │  dB.u  │
│                │        │
│  dB.v    dC.v  │  d.v   │
└                         ┘

=>

   p      q
┌                       ┐
│        dC.u  │  d.u   │
│  1    ------ │ ------ │
│        dB.u  │  dB.u  │
│              │        │
│ dB.v   dC.v  │  d.v   │
└                       ┘

Subtract from the second equation the first equation dB.v times =>

     p                    q
┌                                                       ┐
│                        dC.u       │        d.u        │
│    1                  ------      │       ------      │
│                        dB.u       │        dB.u       │
│                                   │                   │
│                             dC.u  │             d.u   │
│ dB.v -(dB.v)1  dC.v -(dB.v)------ │ d.v -(dB.v)------ │
│                             dB.u  │             dB.u  │
└                                                       ┘

=>

  p              q
┌                                              ┐
│              dC.u       │        d.u         │
│ 1           ------      │       ------       │
│              dB.u       │        dB.u        │
│                         │                    │
│            dB.v * dC.u  │        dB.v * d.u  │
│ 0  dC.v - ------------- │ d.v - ------------ │
│               dB.u      │          dB.u      │
└                                              ┘

Divide the second equation by dC.v - (dB.v * dC.u)/dB.u =>

  p               q
┌                                                   ┐
│               dC.u        │         d.u           │
│ 1            ------       │        ------         │
│               dB.u        │         dB.u          │
│                           │                       │
│             dB.v * dC.u   │         dB.v * d.u    │
│     dC.v - -------------  │  d.v - ------------   │
│                dB.u       │           dB.u        │
│ 0  ---------------------- │ --------------------  │
│             dB.v * dC.u   │          dB.v * dC.u  │
│     dC.v - -------------  │  dC.v - ------------- │
│                dB.u       │             dB.u      │
└                                                   ┘

=>

  p    q
┌                                   ┐
│     dC.u  │         d.u           │
│ 1  ------ │        ------         │
│     dB.u  │         dB.u          │
│           │                       │
│           │         dB.v * d.u    │
│           │  d.v - ------------   │
│           │           dB.u        │
│ 0    1    │ --------------------  │
│           │          dB.v * dC.u  │
│           │  dC.v - ------------- │
│           │             dB.u      │
└                                   ┘

=>

  p    q
┌                                             ┐
│     dC.u  │               d.u               │
│ 1  ------ │              ------             │
│     dB.u  │               dB.u              │
│           │                                 │
│           │    dB.u * d.v     dB.v * d.u    │
│           │   ------------ - ------------   │
│           │        dB.u          dB.u       │
│ 0    1    │ ------------------------------- │
│           │   dB.u * dC.v     dB.v * dC.u   │
│           │  ------------- - -------------  │
│           │        dB.u          dB.u       │
└                                             ┘

=>

  p    q
┌                                           ┐
│     dC.u  │              d.u              │
│ 1  ------ │             ------            │
│     dB.u  │              dB.u             │
│           │                               │
│           │    dB.u * d.v - dB.v * d.u    │
│           │   -------------------------   │
│           │              dB.u             │
│ 0    1    │ ----------------------------- │
│           │   dB.u * dC.v - dB.v * dC.u   │
│           │  ---------------------------  │
│           │              dB.u             │
└                                           ┘

=>

  p    q
┌                                         ┐
│     dC.u  │             d.u             │
│ 1  ------ │            ------           │
│     dB.u  │             dB.u            │
│           │                             │
│           │   dB.u * d.v - dB.v * d.u   │
│ 0    1    │ --------------------------- │
│           │  dB.u * dC.v - dB.v * dC.u  │
└                                         ┘

Subtract from the first equation the second equation dC.u/dB.u times =>

  p         q
┌                                                                    ┐
│     dC.u     dC.u  │  d.u       dB.u * d.v - dB.v * d.u      dC.u  │
│ 1  ------ - ------ │ ------ - --------------------------- * ------ │
│     dB.u     dB.u  │  dB.u     dB.u * dC.v - dB.v * dC.u     dB.u  │
│                    │                                               │
│                    │            dB.u * d.v - dB.v * d.u            │
│ 0         1        │          ---------------------------          │
│                    │           dB.u * dC.v - dB.v * dC.u           │
└                                                                    ┘

=>

  p  q
┌                                                      ┐
│      │  d.u       dB.u * d.v - dB.v * d.u      dC.u  │
│ 1  0 │ ------ - --------------------------- * ------ │
│      │  dB.u     dB.u * dC.v - dB.v * dC.u     dB.u  │
│      │                                               │
│      │            dB.u * d.v - dB.v * d.u            │
│ 0  1 │          ---------------------------          │
│      │           dB.u * dC.v - dB.v * dC.u           │
└                                                      ┘

=>

  p  q
┌                                    ┐
│      │   dC.v * d.u - dC.u * d.v   │
│ 1  0 │ --------------------------- │
│      │  dB.u * dC.v - dB.v * dC.u  │
│      │                             │
│      │   dB.u * d.v - dB.v * d.u   │
│ 0  1 │ --------------------------- │
│      │  dB.u * dC.v - dB.v * dC.u  │
└                                    ┘

This last simplification was computer assisted. Thanks Wolfram|Alpha.

```

So we have:

```
k = dB.u * dC.v - dB.v * dC.u
p = (dC.v * d.u - dC.u * d.v) / k
q = (dB.u * d.v - dB.v * d.u) / k

```

We can incorporate that to our code, and use those components to find the 3D coordinates.

```
VectorUV dB = B.uv - A.uv
VectorUV dC = C.uv - A.uv

if (B.v < C.v)
{
    l_1 = l_AB
    l_2 = l_AC
}
else
{
    l_1 = l_AC
    l_2 = l_AB
}

k = dB.u * dC.v - dB.v * dC.u
for (int u = (int)floor(A.u); u <= (int)ceil(B.u); u++)
{
    for (int v = (int)floor(l_1(u)); v <= (int)ceil(l_2(u)); v++)
    {
        VectorUV d = new VectorUV(u - A.u, v - A.v)
        p = (dC.v * d.u - dC.u * d.v) / k
        q = (dB.u * d.v - dB.v * d.u) / k
        coords = A.xyz + (B.xyz - A.xyz) * p + (C.xyz - A.xyz) * q
        // …
    }
}

```

*I remind you that the code above only handles the first range of a triangle. For the other range you need another for loop. And, of course, you would be doing that for all triangles.*

---

You would have an array where you can store those coordinates. Make it an array of sets, because you may find that the same texel is mapped to one position in 3D, multiple, or none. *And you might find a texel has a position multiple times, in particular on the edges.*

---

By the way. We have a division by zero if `k = dB.u * dC.v - dB.v * dC.u = 0`. I believe this happens if the shape in texture space does not make a triangle. I suggest you consider these cases as pathological.

---
Tags: textures, mesh, uv-mapping, texture-atlas
---


title: Custom build failure callback

text:
# Question
Title: Custom build failure callback
I've been working on some custom build scripts, which will manipulate the references of certain MonoBehaviours.

I'm using `IPreprocessBuildWithReport` to do the manipulation, and I want to reset the references when the build completes. Even if the build fails, I want to do the operation, but I want to do some additional stuff if it fails. I'm also using `IPostprocessBuildWithReport` and `IProcessSceneWithReport` as well.

I've tried putting a Debug.Log in `OnProcessScene` and `OnPostProcessBuild`. I'm building without JAVA path defined, for Android, or without the Keystore password, which fails the build. The `IPreprocessBuildWithReport` correctly prints the Debug, but the others don't.

Is there any class or interface which has a callback for Build Failure which I can use? I've tried to get the summary from the `BuildReport` in `OnPreprocessBuild`, but the result is always returning `Unknown`.

Edit: I would also like to make the same changes if the Build was cancelled, rather than just if it was failing.

Platforms: Windows, Android

Unity 2019.3.7f1

# Answer
> 1 votes
We started to use CompilationPipeline to detect the errors and trigger some custom actions. Here is the script template:

```
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.Compilation;
using UnityEngine;

namespace Fiftytwo.BuildTools
{
    internal class BuildPreprocessor : IPreprocessBuildWithReport
    {
        private static object _compilationContext;
        private static int _compilationErrorCount;

        public int callbackOrder => 0;

        public void OnPreprocessBuild ( BuildReport report )
        {
            _compilationContext = null;
            _compilationErrorCount = 0;

            CompilationPipeline.compilationStarted += CompilationPipelineOnCompilationStarted;
            CompilationPipeline.assemblyCompilationFinished += CompilationPipelineOnAssemblyCompilationFinished;
            CompilationPipeline.compilationFinished += CompilationPipelineOnCompilationFinished;
        }

        private static void CompilationPipelineOnCompilationStarted ( object compilationContext )
        {
            _compilationContext = compilationContext;
            _compilationErrorCount = 0;
        }

        private static void CompilationPipelineOnAssemblyCompilationFinished ( string path, CompilerMessage[] messages )
        {
            for( int i = messages?.Length ?? 0; --i >= 0; )
            {
                if( messages[i].type == CompilerMessageType.Error )
                    ++_compilationErrorCount;
            }
        }

        private static void CompilationPipelineOnCompilationFinished ( object compilationContext )
        {
            if( compilationContext != _compilationContext )
                return;

            _compilationContext = null;

            CompilationPipeline.compilationStarted -= CompilationPipelineOnCompilationStarted;
            CompilationPipeline.assemblyCompilationFinished -= CompilationPipelineOnAssemblyCompilationFinished;
            CompilationPipeline.compilationFinished -= CompilationPipelineOnCompilationFinished;

            if( _compilationErrorCount > 0 )
            {
                Debug.LogError( $"Compilation finished with errors ({_compilationErrorCount})" );
                // Custom compilation failure processing
            }
        }
    }
}

```

# Answer
> 0 votes
You can use a custom build handler and invoke the unity default build process from there. For post-processing use `BuildHandler.OnBuildCleanup`, which is called when a build completes **or** fails.

[InitializeOnLoad]
public class BuildHandler : MonoBehaviour
{
    public static event Action OnBuildStarted;
    public static event Action OnBuildCleanup;

    static BuildHandler()
    {
        BuildPlayerWindow.RegisterBuildPlayerHandler(Build);
    }

    private static void Build(BuildPlayerOptions buildOptions)
    {
        try
        {
            BuildStarted();

            //now start Unity's default building procedure
            BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(buildOptions);
        }
        catch (BuildPlayerWindow.BuildMethodException) { } //logged internally
        catch (Exception ex)
        {
            Exception log = ex.InnerException == null ? ex : ex.InnerException;
            Debug.LogException(log);
            Debug.LogErrorFormat("{0} in BuildHandler: '{1}'", log.GetType().Name, ex.Message);
        }
        finally
        {
            BuildCleanup();
        }
    }

    private static void BuildStarted()
    {
        try
        {
            if (OnBuildStarted != null)
                OnBuildStarted.Invoke();
        }
        catch (Exception ex)
        {
            throw new Exception("OnBuildStarted failed", ex);
        }
    }

    private static void BuildCleanup()
    {
        if (OnBuildCleanup != null)
        {
            foreach (Action cleanupBuild in OnBuildCleanup.GetInvocationList())
            {
                try
                {
                    cleanupBuild.Invoke();
                }
                catch (Exception ex)
                {
                    Object context = cleanupBuild.Target as Object;
                    Debug.LogException(ex, context);
                    Debug.LogWarning("Caught exception while BuildHandler.OnBuildCleanup... Continuing");
                }
            }
        }
    }
}
```

---
Tags: unity, build-process
---


# Question
Title: Best way to implement a to hit formula based on provided stats
There are a ton of these questions, some can get really mathy - which is fine, but I am looking for a simple way based on a few stats, I thought I came up with one, so I will share it in hopes that someone can tell me where I might be going wrong.

The goal is that the monster should, depending on how powerful you are, be able to have a chance to hit. Weaker monsters instant death to them, harder monsters possible instant death to you.

**I also realize these are hard questions to answer because it is game dependant. I hope I have provided enough info for you to give some guidance.**

Lets get the stats out the way:

* To Hit Stat (Character): base stat / modded stat (ie: 12/100)
* Accuracy / Dodge (Character): between 0.0001 - 1.0 (0.01% - 100% (can be higher))
* Enemy Dodge / Enemy Accuracy: Between 0.0001 - 0.85 (0.01% - 85%)
* To Hit (Monster): Dex / 10,000 - where 10k is 1k higher then max stats (9k) for monsters
* Monsters do have a max level (if that will help)

When a character levels they get 1 point into their base stat - which is then used in conjunction with all equipment and so on to increase the modded stat additively (base stat + base stat * bonuses = modded stat)

Characters can cap out (Modded stat) Higher then 10K which might pose issues for a to hit formula. How ever at that point I would assume your skills are 100% as max level is 1000 - thus you should always be hitting

The idea I had was (based off another question asked):

```
(stat / modded stat) + (((accuracy - dodge) / accuracy) * 100)

```

Some assumptions I made based on how I built the system:

* Accuracy at 100%+ means you always hit
* Dodge at 100%+ Means you always dodge.
* Enemies dodge and accuracy do not go above 85% (they can start at 0.01% for both)
* Monsters always use their dex (ie 12/max cap), monsters do not have modded stats
    + All Monster stats are the same, IE: if Dex is 9k all other stats, such as str, int, chr ... are also 9k

There are some issues with this formula though:

* If stat and stat mod are the same (no equipment or bonus for character only) I chose to use the stat (as opposed to stat / modded stat) so, if 11 === 11 - well, use 11. For the character (see below for example)
* Because a character might never train (I don't know why) Accuracy or Dodge their bonus might be 0.01% (there are equipment bonuses that can increase this to a max of 30% across all equipment with another 5% for boons (135% max) how ever in the following example we will assume you have nothing)

So:

```
   Level 1 (Character) = (11) + ((0.0001 - 0.0001) / 0.001) * 100) = 11 // Nothing equipped no bonuses

   vs.

   Rat (Enemy) = (8/10000) + ((0.0001 - 0.0001) / 0.001) * 100) = 0.0008

```

This doesn't seem right, so the player has a 11% to hit and the rat has a 0.0008% chance to hit?

Character : 100 - 11 = 82% chance to hit Rate : 100 - 0.0008 = 99.9992% chance to hit?

This doesn't make sense to me. For context here's a high level monster with a character that has a 95% dodge chance:

```
 (9000/10000) + ((0.75 - 0.95) / 0.75) * 100) = -25.7666666667

```

That does not look right.

# Answer
> 2 votes
I'm going to give you a few options to handle `accuracy` and `dodge`, pick the one that better suits you. *I have no idea about the other stats.*

---

## Accuracy is paramount

For our first option, if an attack has 100% `accuracy`, `dodge` does not matter. Even if `dodge` is 100%, when `accuracy` is 100%, `dodge` does not matter.

In fact, the probability of hitting are at least `accuracy`. That is, the formula will be `accuracy` plus some other term.

This is the formula:

```
probability = accuracy + (100% - accuracy) * (100% - dodge)

```

Of course, the second term is a function of `dodge`. I made it `100% - dodge` because less `dodge` should be easier to hit. Also, it has a factor of `100% - accuracy`. The idea is to scale down the effect of the second term as `accuracy` increases.

With this formula, the only case where it is impossible to hit is when `accuracy` is 0%, and `dodge` is 100%. Furthermore, you get perfect chance of hitting when either `accuracy` is 100% or `dodge` is 0%.

---

**Notes**:

* If you use `1/x` instead of `1-x` your distribution will be asymptotic (probabilities approach infinity, and of course you have division by 0). Don't do that.
* The formula might have problems when a variable goes over 100%. Because `1-x` would be negative. If `accuracy` is less or equal to 100%, clamp `dodge` to 100%. If `accuracy` is greater than 100%, you can either clamp both to 100%, or only clamp `dodge` to `100% - accuracy/(100% - accuracy)`, which allows values of `dodge` over 100% result in less probability than `accuracy`.

---

## Dodge is paramount

When `dodge` is 100%, there is no chance of hitting. Even if `accuracy` is 100%, when `dodge` is 100%, `accuracy` does not matter.

For this formula, `accuracy` means more chance of hitting, insofar `dodge` allows it. In fact, the probability of hitting will never be greater than `100% - dodge`. And we accomplish that by using it as a factor for `accuracy`.

This is the formula:

```
probability = accuracy * (100% - dodge)

```

Here the only way to have perfect chance of hitting is when `dodge` is 0% and `accuracy` is 100%. If either `dodge` is 100%, or `accuracy` is 0% it is impossible to hit.

---

**Note**: Here we also have a case of `1-x`. However, being a formula of a single term, your options are to clamp both variables to 100%, or clamp the result (which is how you would handle negatives).

---

## Generalization

So, you want something kind of in the middle?

This is the difference of the two formulas:

```
nuonce = accuracy * dodge + (100% - accuracy)(100% - dodge)

```

Now you can explore a continuum between the two formulas like this:

```
probability = accuracy * (100% - dodge) + nuonce * f

```

Where `f` goes from 0 to 1.

Regardless of `f`. When `accuracy` is 100% and `dodge` is 0%, it always hits. And when `accuracy` is 0% and `dodge` is 100%, it is impossible to hit.

When `f = 1` you get the first formula, and when `f = 0` you get the second. Furthermore, `f` is the probability when `accuracy` and `dodge` are both 0% or when they are both 100%.

---

There is an special case: When `f = 0.5`, the formula is a plane (for all other values, we have an hyperbolic paraboloid a.k.a. a saddle). For `f = 0.5` the formula simplifies to this:

```
probability = 50% * (accuracy - dodge + 100%)

```

As you can see, in this special case, you get 50% whenever `accuracy` and `dodge` are equal (not only when they are both 0% or both 100%, which is true for any value of `f`).

---

## Skewing

If you want to control the probability when both `dodge` and `accuracy` are 0% independently of the probability when both `dodge` and `accuracy` are 100%, there is a way. Notice that the formula I gave you for nuonce has two terms:

```
nuonce = accuracy * dodge + (100% - accuracy)(100% - dodge)

```

I could have expressed the difference multiple ways, but this terms has a meaning. It will be clearer here:

```
probability = accuracy * (100% - dodge)
    + p * accuracy * dodge
    + q * (100% - accuracy)(100% - dodge)

```

Now `p` is the probability when both `accuracy` and `dodge` are 100%. And `q` is the probability when both `accuracy` and `dodge` are 0%.

*All that is missing is for you to decide.*

---
Tags: mathematics, game-design, rpg, browser-based-games
---


# Question
Title: How to properly get the x-axis value among the data of the smartphone's gyro sensor in Unity
I want to load x, y, z data using the IMU sensor of the smartphone.

```
Input_gyro_attitude_eulerAngles = Input.gyro.attitude.eulerAngles - Offset; // gyro angle

```

Through the code above, the y and z axes are loaded well even though there is a little error.

But For the x-axis, only values within the range of 270 to 90 degrees are recorded, and values between 90 and 270 are not recorded as shown in the photo.

1. How can I get it to load properly?
2. And why are only the values on the x-axis appearing strangely?

# Answer
> 1 votes
```
D = Quaternion.Euler(T, 0, 0)

```

This creates a unit quaternion, a point on a four-dimensional sphere with three of those dimensions being imaginary numbers. The four components of the quaternion x, y, z, and w are NOT angles.

```
D.x * 360f

```

This takes one of those imaginary axis values and multiplies it by 360. This does NOT make it an angle. It's geometrically meaningless.

`D.x` is the *sine* of an angle, but it may not be exactly the angle that you want at the end of the day. Because the total angle in the quaternion will always be -180 to +180, and that means if you have rotation on the y or z axes, the x alone won't hit those extremes.

To extract out "I just care about the rotation angle in this specific plane," you can do something a bit like this:

```
// Turn your Euler angle offset into a quaternion.
var offset = Quaternion.Euler(offset_angles);

// Reverse this quaternion to "undo" the offset.
var correction = Quaternion.Inverse(offset);

// Apply the correction to the quaternion - this behaves more consistently
// than trying to add/subtract Euler angles.
var correctedAttitude = Input.gyro.attitude * correction;

// Now we can use this attitude to transform the world up vector
// into the phone's local coordinate system.
var sensedUp = Quaterntion.Inverse(correctedAttitude) * Vector3.up;

// And you can use the components of that vector to discern an orientation
// angle in the plane of your choosing.
var degreeAngle = Mathf.Atan2(sensedUp.y, sensedUp.x) * Mathf.Rad2Dag;

```

Depending on which axis of rotation you care about, whether you want clockwise or counterclockwise rotation to be positive, and where you want 0 degrees to sit within the circle, you might choose a different reference vector or use different components inside `Atan2`.

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


# Question
Title: Map() fails when reading back GPU Texture
I need to read back a GPU texture (stored in the GPU as `D3D11_USAGE_DEFAULT`). I am doing this via creating a staging ID3D11Texture. The whole application is running in a Microsoft Store application.

I am starting from a D3D11ShaderResourceView defined in the `cResourceShaderView` variable below. Code follows:

```
ID3D11Texture2D* pTextureInterface = 0;
ID3D11Resource* res;
HRESULT hr = 0;

ID3D11Texture2D* tx = 0;

ID3D11Device* dv;
deviceContext->GetDevice(&dv);

cResourceShaderView->GetResource(&res);
hr = res->QueryInterface<ID3D11Texture2D>(&pTextureInterface);
D3D11_TEXTURE2D_DESC desc;
pTextureInterface->GetDesc(&desc);

desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.BindFlags = 0;

hr = dv->CreateTexture2D(&desc, nullptr, &tx);
deviceContext->CopyResource(tx, pTextureInterface);

D3D11_MAPPED_SUBRESOURCE mapped = { 0 };
hr = deviceContext->Map(tx, 0, D3D11_MAP_READ, 0, &mapped);

```

The `Map()` function fails with an `E_INVALIDARG`.

I have turned on Debug Layers and there are no specific warnings nor errors in the Visual Studio Window for all these code above.

If I try to save this texture using the `DirectX::SaveWICTextureToFile` function which uses this same method in the sample, inside this function the `Map()` function call here fails as well with an `E_INVALIDARG` and without any debug warnings nor errors.

The `GetDesc()` function gives me a valid `D3D11_TEXTURE2D_DESC` for that texture.

What could be wrong?

# Answer
You can't read back from a texture using `Map()` on a deferred context:

> If you call Map on a deferred context, you can only pass D3D11\_MAP\_WRITE\_DISCARD, D3D11\_MAP\_WRITE\_NO\_OVERWRITE, or both to the MapType parameter. Other D3D11\_MAP-typed values are not supported for a deferred context.

As to why, you have to keep in mind how the copy and map operations work inside the system. When you call `CopyResource()`, you are not copying the resource. You are just telling Direct3D to record a command that issues a copy operation from one memory area to another. When you call `Map()`, Direct3D inserts a read fence in the command buffer.

Now, the difference between immediate and deferred contexts is as to when the commands are submitted to the GPU.

With an immediate (non-deferred) context, Direct3D submits commands as you record them, so the GPU is running in parallel with your CPU program, and it is possible for the CPU program to wait on a fence to read from some memory.

With a deferred context, as its name suggests, you are only recording the command buffer contents. They are later submitted if/when you call `ExecuteCommandList`, so waiting on the fence while the command buffer is merely being created doesn't make any sense. Therefore it's forbidden by the API.

So in general, you have two choices:

* Do this in the immediate context instead. You can still use secondary deferred contexts, but this type of operations can only be done on the immediate context.
* If you definitely must do this from another thread, use Direct3D 12 instead, where you have full control over command buffer creation, submission, you can put whatever fences you want wherever you want, at the cost of dramatically increased complexity. There's no immediate, nor deferred context. In fact, the concept of "context" no longer even exists.

Direct3D 11 deferred contexts are in my opinion, an inelegant hack. If you need simplicity, use Direct3D 11 immediate contexts. If you need full control, use Direct3D 12.
> 2 votes

---
Tags: directx11, gpu, cpu
---


# Question
Title: How can I find if there is a gap/s between transforms array?
```
for (int i = 0; i < cubes.Length; i++)
{
    if(bricks[i].transform.position.z == 1)
    {
        var distance = Vector3.Distance(bricks[i].transform.position, )
    }
}

```

I want to find all the places where the distance between two cubes is \> 0. For example if there is a gap between index 6 and index 7, then give me the gap position it's empty space, but give me this position where there was should be a cube.

Each couple of cubes check if there is a gap between them and return the gap position.

I have a maze randomly generated and there are some entrances I want to find the entrances by checking for gaps each gap position is entrance.

This is the maze create class:

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

public class Maze
{
    //Grid size
    public int width;
    public int height;

    //Store grid
    private bool[,] grid;
    //Generate random directions to move
    private System.Random rg;

    //Start position
    public int startX;
    public int startY;

    //Public getter
    public bool[,] Grid
    {
        get { return grid; }
    }

    //Constructor of the grid for setting values
    public Maze(int width, int height, System.Random rg)
    {
        this.width = width;
        this.height = height;

        this.rg = rg;
    }

    //Generate the grid
    public void Generate()
    {
        grid = new bool[width, height];

        startX = 1;
        startY = 1;

        grid[startX, startY] = true;

        MazeDigger(startX, startY);
    }

    void MazeDigger(int x, int y)
    {
        int[] directions = new int[] { 1, 2, 3, 4 };

        //We create random array of directions
        HelpingTools.Shuffle(directions, rg);

        //We are looping over all the directions
        for (int i = 0; i < directions.Length; i++)
        {
            if (directions[i] == 1)
            {
                if (y - 2 <= 0)
                    continue;

                if (grid[x, y - 2] == false)
                {
                    grid[x, y - 2] = true;
                    grid[x, y - 1] = true;

                    MazeDigger(x, y - 2);
                }
            }

            if (directions[i] == 2)
            {
                if (x - 2 <= 0)
                    continue;

                if (grid[x - 2, y] == false)
                {
                    grid[x - 2, y] = true;
                    grid[x - 1, y] = true;

                    MazeDigger(x - 2, y);
                }
            }

            if (directions[i] == 3)
            {
                if (x + 2 >= width - 1)
                    continue;

                if (grid[x + 2, y] == false)
                {
                    grid[x + 2, y] = true;
                    grid[x + 1, y] = true;

                    MazeDigger(x + 2, y);
                }
            }

            if (directions[i] == 4)
            {
                if (y + 2 >= height - 1)
                    continue;

                if (grid[x, y + 2] == false)
                {
                    grid[x, y + 2] = true;
                    grid[x, y + 1] = true;

                    MazeDigger(x, y + 2);
                }
            }
        }
    }
}

```

And this is the maze generate script

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

public class MazeGenerator : MonoBehaviour
{
    public Maze maze;
    public int mazeWidth;
    public int mazeHeight;
    public string mazeSeed;
    public GameObject wallPrefab;

    private GameObject wall;
    private GameObject wallCorner;
    private System.Random mazeRG;

    // Use this for initialization
    void Start ()
    {
        mazeRG = new System.Random();

        if (mazeWidth % 2 == 0)
            //mazeWidth++;

        if (mazeHeight % 2 == 0)
        {
            //mazeHeight++;
        }

        maze = new Maze(mazeWidth, mazeHeight, mazeRG);
        GenerateMaze();
    }

    public void GenerateMaze()
    {
        maze.Generate();
        DrawMaze();
    }

    void DrawMaze()
    {
        for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == true)
                {
                    CreateMaze(position, transform, 0, mazeRG.Next(0, 3) * 90);
                }
            }
        }

        var bricks = GameObject.FindGameObjectsWithTag("MazeBrick");

        bricks[bricks.Length - 1].GetComponent<Renderer>().material.color = Color.red;

        //bricks[Random.Range(0, bricks.Length - 1)].GetComponent<Renderer>().material.color = Color.red;

        for (int i = 0; i < bricks.Length; i++)
        {
            if (bricks[i].transform.position.x == maze.startX &&
                bricks[i].transform.position.z == maze.startY)
            {
                bricks[i].GetComponent<Renderer>().material.color = Color.red;
            }

            if(bricks[i].transform.position.z == 1)
            {
                var distance = Vector3.Distance(bricks[i].transform.position, )
            }
        }
    }

    void CreateMaze(Vector3 position, Transform parent, int sortingOrder, float rotation)
    {
        GameObject mazePrefab = Instantiate(wallPrefab, position, Quaternion.identity);
        mazePrefab.transform.SetParent(parent);
        mazePrefab.transform.Rotate(0, 0, rotation);
        mazePrefab.tag = "MazeBrick";
    }

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

    }
}

```

And the HelpingTools script :

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

public class HelpingTools : MonoBehaviour
{
    public static T[] Shuffle<T>(T[] array, System.Random rg)
    {
        for (int i = 0; i < array.Length - 1; i++)
        {
            int randomIndex = rg.Next(i, array.Length);

            T tempItem = array[randomIndex];

            array[randomIndex] = array[i];
            array[i] = tempItem;
        }

        return array;
    }
}

```

The maze is generate randomly. with random entrances/exits depending on what you are define as entrances or exits but for this example lets say they are all entrances.

I positioned the main camera in one of the entrances but I want that after the maze has generated to position the camera automatic randomly on one of the entrances.

Later on I want the camera to enter the selected entrance and travel through the maze. but for now first I want to find all the entrances and position the camera in front of one of them.

I tried this to fill the gaps between the bricks of the grid but it's not working.

```
for (int i = 0; i < bricks.Length; i++)
{
    var brick = bricks[i];

    for (int x = 0; x < bricks.Length; x++)
    {
        if (brick.transform.position.z == 1)
        {
            var distance = Vector3.Distance(brick.transform.position, bricks[x].transform.position);
            if (distance > brick.transform.localScale.x)
            {
                continue;
            }
            if(distance == 1f)
            {
                // josh.position.x + (mark.position.x - josh.position.x) / 2;

                var block = Instantiate(wallPrefab, new Vector3(bricks[x].transform.position.x + 1,0,brick.transform.position.z), wallPrefab.transform.rotation);
                block.GetComponent<Renderer>().material.color = Color.green;
            }
        }
    }
}

```

If I'm trying this loop :

```
for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == false)
                {
                    var t = Instantiate(wallPrefab, position, Quaternion.identity);
                    t.GetComponent<Renderer>().material.color = Color.yellow;
                }
            }
        }

```

Then it will fill all gaps in yellow and also will fill the surrounding of the maze. How do I fill only the gaps of the outer of the maze ?

This is is not working either :

```
for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                if (x == mazeWidth - 1 || y == mazeHeight - 1)
                {

                    Vector3 position = new Vector3(x, 0.5f, y);

                    if (maze.Grid[x, y] == false)
                    {
                        var t = Instantiate(wallPrefab, position, Quaternion.identity);
                        t.GetComponent<Renderer>().material.color = Color.yellow;
                    }
                }
            }
        }

```

Updating with my last testing :

```
for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == false)
                {
                    if (x == mazeWidth - 1 || x == 1 || y == mazeHeight - 1 || y == 1)
                    {
                        var t = Instantiate(wallPrefab, position, Quaternion.identity);
                        t.GetComponent<Renderer>().material.color = Color.yellow;
                    }
                }
            }
        }

```

but still the result is not good enough.

And another update, I'm almost there.

I still don't get it yet if the maze size is 30 on 30 why when I click on bricks that on the outer of the maze the Z position is 27 and not 30 ?

And why some bricks are out of the outer of the maze ?

```
for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == false)
                {
                    if (x == 27 || x == 1f || y == 27 || y == 1f)
                    {
                        var t = Instantiate(wallPrefab, position, Quaternion.identity);
                        t.GetComponent<Renderer>().material.color = Color.yellow;
                    }
                }
            }
        }

```

The result is :

In this screenshot the top show a brick outside the maze what is this ? X is at 1 but Z is at 29 than on the bottom I clicked on a brick in the outer maze area and it is the z on 27.

So why its coloring some on z 29 ? and why the maze is size 27 on 27 but I set it to be 30 on 30 ?

And maybe the maze is 30 on 30 but all the rows and columns from 30 to 27 are empty gaps ?

I don't understand it yet.

# Answer
Lets address your points one by one and a possible missconception of your maze

* Your start index is wrong. The array is zero based but you set the start point to 1 in the Maze script line 40 and 41.
* I might be wrong here but to me your maze looks inverted. That means you do not travel between the blocks but the path it meant to be the blocks that are generated. Assuming this is true, that brings us to the next point (even if it was not true, the next point is still valid)
* Now you should know the reason for line 23 and 27 in the MazeGenerator. You can't generate a maze with an even side. If you have a maze by the size of 5, you have wall-space-wall-space-wall, but if it is size 6, you are not ending on the same kind of tile as you are starting.
> 0 votes

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