# Question
Title: How do I add a delay in a switch statement?
```
    float distance = Vector3.Distance(transform.position, player.position);
    var State = distance > 10 ? AIState.TowardsPlayer : AIState.Right;
    Debug.Log(distance);

    switch (State)
    {
        case AIState.TowardsPlayer:
            transform.LookAt(player.transform);
            transform.position += transform.forward * approaching * Time.deltaTime;
            break;
        case AIState.Right:
            transform.position += transform.right * 1f * Time.deltaTime;
            Invoke("AIState.TowardsPlayer", 2f);
            break;

```

I want it to have a slight delay after AIState.Right finishes its execution before moving onto AIState.TowardsPlayer. I put Invoke but it didn't work.

# Answer
You're trying to add a delay like this:

```
Invoke("AIState.TowardsPlayer", 2f);

```

This does not work because `AIState.TowardsPlayer` is an enum value. `Invoke()` is used to call *functions*.

You probably want to use a coroutine, something like this:

```
private IEnumerator UpdateState() {
    while (true) {
        float distance = Vector3.Distance(transform.position, player.position);
        var state = distance > 10 ? AIState.TowardsPlayer : AIState.Right;

        switch (state) {
            case AIState.TowardsPlayer:
                transform.LookAt(player.transform);
                transform.position += transform.forward * approaching * Time.deltaTime;
                break;
            case AIState.Right:
                transform.position += transform.right * 1f * Time.deltaTime;
                yield return new WaitForSeconds(2f);
                break;
        }

        //wait one frame before next loop iteration, so we never hang the application
        //in an infinite loop
        yield return null;
    }
}

void OnEnable() {
    StartCoroutine(UpdateState());
}

```

Here we have a `yield return new WaitForSeconds(2f);` statement to pause for two seconds after the `AIState.Right` condition occurs.

If you're not familiar with Coroutines, make sure to read up on them, as they can make your life a lot easier.
> 1 votes

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


# Question
Title: Score won't save to Android in Game Maker Studio 1.4
I have oController as the first object to run when the game is opened. In oController's **Game Start** event I have the following code:

```
ini_open(working_directory + "SavedScores.ini");
var highscores = ini_read_real("Highscores", "Score", 0);
ini_close();

global.LastScore = highscores;

```

When the player has gotten their score, I use this code to save it:

```
if global.gameOver {

    if global.LastScore == 0 {
        global.LastScore = global.currentScore;

        ini_open(working_directory + "SavedScores.ini");
        ini_write_real("Highscores", "Score", global.LastScore);
        ini_close();
    } else {
        if global.currentScore > global.LastScore {
            global.LastScore = global.currentScore;

            ini_open(working_directory + "SavedScores.ini");
            ini_write_real("Highscores", "Score", global.LastScore);
            ini_close();
        }
    }
}

```

Whenever I relaunch the game on my phone, it won't load the score I got when I previously launched the game. Idk why it's not saving?

# Answer
I load the file in my player's creation event and it has solved my problem. :)

Put this in your controller object create event:

```
//Create save directory
global.dir = working_directory+"/Saves/"

```

I ran this code in the player create event:

```
if (file_exists(global.dir + "Score.ini")) {
    ini_open(global.dir + "Score.ini");
    global.LastScore = ini_read_real("Highscores", "Score", 0);
    ini_close();
}

```
> 0 votes

---
Tags: android, game-maker, savegame
---


# Question
Title: Non-rectangular collision detection in Python and Pygame
I am programming a ray tracer in python, and I have gotten as far as making a character that can move across a 2d plane and change direction of movement when needed. The problem is this: I want to be able to use an image with transparency as the maze that the player travels through, and use transparent parts as parts that aren't walls, where as every thing else is a wall. The way I am using collision detection is by using the `pygame.sprite.spritecollide` method, which takes in a Sprite, and a Sprite Group. So I first add the map sprite object to the group, and then in the main while loop, it checks for collision. Here is a small snippet of what that might look like:

```
map = Map("map1.png") # "Map" class is regular sprite class but with "image" and "rect"
group = pygame.sprite.Group()
group.add(map)
# inbetween stuff would be here
# while loop \/
running = True
while running:
    # event handling stuff would be here
    if pygame.sprite.spritecollide(player, group, False):
        print True
    # screen drawing routines would be here

```

As I mentioned, the image has transparency. But nevertheless, the image rect sticks to the non transparency position that it was, so I have to move the player off screen to get the console to stop saying "True".

So what I ask, is there a way that I can check for sprite collision but with transparency?

# Answer
> 1 votes
This is an interesting question. It's *possible* to do this with a huge sprite representing the maze, using a sprite mask to ensure only the walls are part of collision. I'm not sure that's a good way to go, but it is relatively simple.

When the sprite is created, you must be sure to create the mask:

```
self.image = pygame.image.load( maze_image ).convert_alpha()
self.mask  = pygame.mask.from_surface( self.image )

```

Then when the collision is checked, you must also ensure it's using the mask. This I must admit, left me a bit confused. I was under the impression that if a sprite has a `.mask` member it was *always* used for collisions. Perhaps it's just the function `pygame.sprite.spritecollide()` that doesn't use it automatically, since it does have the optional 'collided' parameter. /me shrugs.

Anyway, this leads to the collision call:

```
if ( pygame.sprite.spritecollide( maze, alien_group, False, collided=pygame.sprite.collide_mask ) ):

```

Where `maze` is the Maze sprite, and `alien_group` is a sprite `GroupSingle` containing only the single Player's alien sprite. The aforementioned extra parameter to force with-mask collisions is last. This collision function returns a list of what's collided with the `maze` sprite, but given there's only one alien, there's no need to check *with what*. The list can only be empty, or contain the alien.

The game checks for collision, and if found, changes the window background colour to red. Probably in your code, it needs to block the player, or whatever.

green\_alien.png

hexmaze.png (has a transparent background)

Reference Code:

```
import pygame

# Window size
WINDOW_WIDTH  = 800
WINDOW_HEIGHT = 690
FPS           = 60

# background colours
INKY_BLACK = (   0,  0,  0 )
FIREY_RED  = ( 203, 49,  7 )

class MazeSprite( pygame.sprite.Sprite ):
    """ A maze with a transparent background as a *huge* sprite """
    def __init__( self, maze_image ):
        pygame.sprite.Sprite.__init__( self )
        self.image = pygame.image.load( maze_image ).convert_alpha()
        self.mask  = pygame.mask.from_surface( self.image )
        self.rect  = self.image.get_rect( topleft=(0,0) )

class AlienSprite( pygame.sprite.Sprite ):
    """ A tiny little alien hoardette """
    def __init__( self, alien_image , x=50, y=50 ):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load( alien_image ).convert_alpha()
        self.mask  = pygame.mask.from_surface( self.image )
        self.rect  = self.image.get_rect( center=( x, y ) )

    def moveBy( self, dx, dy ):
        self.rect.move_ip( dx, dy )
        #print("Now at %s" % ( str( self.rect.center ) ) )

### MAIN
pygame.init()
pygame.font.init()
SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF
window  = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), SURFACE )
pygame.display.set_caption("Maze Sprite-Collision Example")

# Make some sprites to hold the Maze background and Player's Alien
maze  = MazeSprite( 'hexmaze.png' )
alien = AlienSprite( "green_alien.png", 283, 155 )

sprite_group = pygame.sprite.Group()        # All sprites for updating and drawing
sprite_group.add( maze )
sprite_group.add( alien )
alien_group = pygame.sprite.GroupSingle()   # Just for the alien collisions
alien_group.add( alien )

clock = pygame.time.Clock()
done  = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

    # Handle continuous-keypresses
    keys = pygame.key.get_pressed()
    if ( keys[pygame.K_UP] ):
        alien.moveBy( 0, -1 )
    elif ( keys[pygame.K_DOWN] ):
        alien.moveBy( 0, 1 )
    elif ( keys[pygame.K_LEFT] ):
        alien.moveBy( -1, 0 )
    elif ( keys[pygame.K_RIGHT] ):
        alien.moveBy( 1, 0 )

    # has the alien hit the walls?
    background = INKY_BLACK
    # NOTE: Ensure we use "mask" collision
    #       It's not used (here) automatically
    if ( pygame.sprite.spritecollide( maze, alien_group, False, collided=pygame.sprite.collide_mask ) ):
        # returned list is not empty
        background = FIREY_RED

    # Repaint the screen
    sprite_group.update()          # re-position the game sprites
    window.fill( background )
    sprite_group.draw( window )    # draw the game sprites

    pygame.display.flip()
    clock.tick_busy_loop( FPS )

pygame.quit()

```

---
Tags: collision-detection, python, pygame
---


# Question
Title: How would I have multiple keys control one bool in the Animator Control?
I have been working on an update to my game. I want to add a Third Person Character Controller. I have the basic Third Person Character Controller and a basic script that works with the Animator Controller to change the state to "isWalking" when the player presses the 'W' key. Here is the code so far:

animationStateController.cs |

```
using UnityEngine;

public class animationStateController : MonoBehaviour
{
    Animator animator; // References the Animator component.
    int isWalkingHash; // Variable for the simplification of the 'If' statements in void update.
    int isRunningHash; // Variable for the simplification of the 'If' statements in void update.

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>(); // Get's the animator component from the attached character.
        isWalkingHash = Animator.StringToHash("isWalking"); // Converts the string "isWalking" (the name of the bool in the Animator Controller) to a simpler data type.
        isRunningHash = Animator.StringToHash("isRunning"); // Converts the string "isRunning" (the name of the bool in the Animator Controller) to a simpler data type.
    }

    // Update is called once per frame
    void Update()
    {
        bool forwardPressed = Input.GetKey("w"); // Set's the bool "forwardPressed" to equal the "W" key.
        bool runPressed = Input.GetKey("left shift"); // Set's the bool "runPressed" to equal the "Left Shift" key.
        bool isWalking = animator.GetBool(isWalkingHash); // Set's the bool "isWalking" to equal the "isWalkingHash" integer.
        bool isRunning = animator.GetBool(isRunningHash); // Set's the bool "isRunning" to equal the "isRunningHash" integer.

        // If the player is not walking and the 'W' key is pressed then:
        if (!isWalking && forwardPressed)
        {
            // Set the "isWalking" bool to true.
            animator.SetBool(isWalkingHash, true);
        }
        // If the player is walking and the 'W' key is not pressed then:
        if (isWalking && !forwardPressed)
        {
            // Set the "isWalking" bool to false.
            animator.SetBool(isWalkingHash, false);
        }

        // If the player is not running and the 'W' and the 'Left Shift' keys are pressed then:
        if (!isRunning && (forwardPressed && runPressed))
        {
            // Set the "isRunning" bool to true.
            animator.SetBool(isRunningHash, true);
        }
        // If the player is running and the 'W' and the 'Left Shift' keys are not pressed then:
        if (isRunning && (!forwardPressed || !runPressed))
        {
            // Set the "isRunning" bool to false.
            animator.SetBool(isRunningHash, false);
        }
    }
}

```

My question is how would I use the 'W', 'A', 'S', and 'D' keys to control the books "isWalking" all at once? Like I can move forward walking and yes that is good, but I have a ThirdPersonCamera and Control script. Here is the ThirdPersonControl script below, it only covers the movement of the player using the keyboard. Camera movement is done with Cinemachine:

ThirdPersonMovement.cs |

```
using UnityEngine;

public class ThirdPersonMovement : MonoBehaviour
{
    /// <summary>
    /// controller - The reference to the Character Controller component attached to the "ThirdPersonController" Game Object.
    /// cam - References the Main Camera.
    /// speed - The walking speed of the player.
    /// runSpeed - The running speed of the player.
    /// turnSmoothTime - The time it takes to smooth the player rotation.
    /// turnSmoothVelocity - The smoothing velocity for the Atan2 used later.
    /// </summary>
    public CharacterController controller;
    public Transform cam;
    public float speed = 4f;
    public float runSpeed = 8f;
    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;

    // Update is called once per frame
    void Update()
    {
        /// <summary>
        /// horizontalInput get's the Raw Horizontal Input, this way we don't get any type of input smoothing.
        /// verticalInput get's the Raw Vertical Input, this way we don't get input smoothing.
        /// heading Is the direction the player will move in, basically.
        /// </summary>
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        float verticalInput = Input.GetAxisRaw("Vertical");
        Vector3 heading = new Vector3(horizontalInput, 0f, verticalInput).normalized;

        /// <summary>
        /// Below are two bools for determining whether or not the player is walking or is running.
        /// </summary>
        bool isWalking = Input.GetKey("w");
        bool isRunning = Input.GetKey("left shift");

        // If the direction of the player has a value greater than or equal to 0.1f then:
        if (heading.magnitude >= 0.1f)
        {
            /// <summary>
            /// Returns the arc tangent of the values assigned to 'X' and 'Y'. This will equal the float variable "targetAngle".
            /// Mathf.Rad2Deg converts the radians (the number given by the previous equation) to degrees.
            /// </summary>
            float targetAngle = Mathf.Atan2(heading.x, heading.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            // Assigns the values and calculates smoothing.
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);

            // Calculates the rotation of the player than assigns the value to the players Transform Rotation.
            transform.rotation = Quaternion.Euler(0f, angle, 0f);
            // Assigns moveDir the information needed to make the player move in the cameras orientation.
            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            // Move the "controller" towards the heading multiplied by speed multiplied by Time.deltaTime;. Time.deltaTime makes the movement frame rate independent.
            controller.Move(moveDir.normalized * speed * Time.deltaTime);

            // If both bools are true then:
            if (isRunning && isWalking)
            {
                // Increase the speed to equal the 'runSpeed' variable.
                controller.Move(moveDir.normalized * runSpeed * Time.deltaTime);
            }
        }
    }
}

```

A video showing my problem

The above video demonstrates the problem. I can walk perfectly fine forward, but if I try and walk left, right, or backward I get nothing. I tried multiple things previously. None of which worked. Here is what I have tried:

1. I tried changing the 'If' statement on line 26 to say `if (!isWalking && (forwardPressed || leftPressed || rightPressed || backwardPressed)) {` added the extra variables as well, but the result I received was the animator controller switching quickly between Idle and Walk. I also added to line 32 respectively.
2. I searched for tutorials, all of which (that I found) only dealt with singular animations such as how to go from idle to crouch.

I wish I could remember exactly what else I have tried, but I can't remember that. Any help with this would be gladly appreciated. Thank you for taking the time to read this. I am still fairly new to Unity and Programming so forgive me please if I overlook something.

# Answer
While not the most elegant solution, you can simply check for all your input keys. `|` returns true if at least one of the conditions is true.

```
 bool isWalking = Input.GetKey("w") | Input.GetKey("a") | Input.GetKey("s") | Input.GetKey("d");

```

Maybe later you want to switch it for your query against the input manager. Hard coded values are usually not best practice and the player won't be able to change his control to arrow keys or joystick.

```
 bool isWalking = (horizontalInput != 0) | (verticalInput != 0);

```
> 0 votes

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


# Question
Title: Unity Animation Controller and walking diagonally keeps switching between the two diagonals?
Using Unity 2019.4.1f1 Personal.

I have the above Animation Controller. When only walking in one direction at a time and when you stop you stay facing that direction, this works as planned.

All of the transitions do not have an exit time and have a fixed duration of 0. I don't know what info to give as this is the first time I've used animation. Let me know and I'll add relevant details.

Here's my update function that updates the variables in the animator:

```
void Update() {
  float h = Input.GetAxisRaw("Horizontal");
  float v = Input.GetAxisRaw("Vertical");

  animator.SetFloat("Horizontal", h);
  animator.SetFloat("Vertical", v);

  if (Mathf.Abs(v) < Mathf.Abs(h)) {
    // flips the renderer to reuse other handed image
    spriteRenderer.flipX = h > 0;
  }

  // no actual movement until I figure this out
}

```

What I'm experiencing that I want to fix is when running diagonally:

It seems that when walking diagonally then the animator variables for `Horizontal` and `Vertical` are both either 1 or -1 and this causes the alternating of the sprites. What I'd like to happen is that the state machine would deterministically pick either N/S sprites or E/W sprites when moving diagonally. Turning on "Can Transition To Self" seems to properly pick a direction and stick to it but it fails to animate when only moving in a single direction. It looks like it's constantly transitioning to itself which starts over the cycle so I've left that unchecked on all transitions.

I'm not sure what the best way to fix this is. Most attempts I've tried so far complicate the state machine to the point it's unmaintainable. I also couldn't find anything about introducing priorities in a way that fixed the jitter.

What's the idiomatic Unity way to achieve clean diagonal movement in 2D?

# Answer
# The cause

Now you have selected that walk in some direction can be triggered from *Any State*. Thus, if you have `vertical = 1` and `horizontal = 1` in *WalkingNorth* state, your transition to *WalkingEast* is triggered (it meets the condition for `horizontal = 1`) and vice versa (transition to *WalkingNorth* is triggered when in *WalkingEast* state because of `vertical = 1`).

# Solution

Consider changing your animation state transitions, so that *Entry* points to *IdleSouth* \- this will be your initial state. Then, make transitions from every *Idle\_* state to every *Walking\_* state based on triggers. Leave *Walking\_* -\> *Idle\_* transitions intact. This will prevent you from going from *WalkingNorth* to *WalkingEast* when `horizontal = 1` and `vertical = 1`.
> 1 votes

# Answer
You can add a condition as when any one of the input is not 0 then randomly assign a value to the animator.

If(h==1){ If(y==1){ Anim.SetFloat("Horizontal",0); Anim.SetFloat("Vertical",1); }else if(y==-1){ Anim.SetFloat("Horizontal",0); Anim.SetFloat("Vertical",-1); }}

Same could be done with h = -1
> 0 votes

---
Tags: unity, 2d, animation, sprites
---


# Question
Title: Determining bordering irregular shapes from an image
Given only an image, I have to find a way of determining whether any two irregular bodies in that image are bordering one another. This is a map of districts, each with their own name, and my goal is to build a database which stores, for each district, which districts border it. I could manually create an entry for each district, and simply list which districts are bordering them. There are hundreds of districts, however, and I'm sure there's some way to automate this process. Not to mention, this map of districts is subject to change.

I've tried so far by defining a central point for a handful of districts, then testing if a line could be drawn between a pair of points and only cross over a border line once. This would mean the two districts were bordering, but this solution only works with districts that have simple geometry.

Any help here would be much appreciated!

# Answer
(Assuming your borders are only 1-pixel wide. If they're thicker, do a pre-process to thin the borders/expand their regions until there's only a 1 pixel separation between regions)

1. Prepare an array of region IDs as large as your image, initialized with a default "unassigned" value.
2. Iterate over the pixels of your image in some order.
3. If you come to a pixel that is an interior (not a border), and the corresponding entry in your region ID array is unassigned, assign it the next unused region ID, and start a flood fill from that location.
4. The flood fill will spread over all connected interior pixels, marking them as your newly-chosen region ID in your array.
5. When your flood fill reaches a border pixel, check if any of its neighbouring cells has a different region ID (that's not unassigned). If so, you've discovered a place where a different region meets this one. Check if you've already recorded this other region as a neighbour of this one. If not, add it, and add this region as a neighbour of the other one.
6. Once you run out of interior pixels to fill or border pixels to check, you're done exploring this region. Resume your orderly iteration over the remaining pixels, skipping over any you've already assigned to a region.
> 2 votes

---
Tags: geometry, maps
---


title: HTML5 - check if font has loaded

text:
# Question
Title: HTML5 - check if font has loaded
At present I load my font for my game in with `@font-face`

For instance:

```
@font-face {
    font-family: 'Orbitron';
    src: url('res/orbitron-medium.ttf');
}

```

and then reference it throughout my JS implementation as such:

```
ctx.font = "12pt Orbitron";

```

where ctx is my 2d context from the canvas.

However, I notice a certain lag time while the font is downloaded to the user. Is there a way I can use a default font until it is loaded in?

---

Edit -

I'll expand the question, because I hadn't taken the first comment into account. What would the proper method of handling this be in the case that a user has disabled custom fonts?

# Answer
I am not sure if it is possible to detect this, the browser will download the font when it see's the CSS. You could draw the text using a default font, then use something like this to detect if the font has loaded outside your canvas. If it is detected as having loaded, you could then refresh your canvas.

Edit; "What would the proper method of handling this be in the case that a user has disabled custom fonts" - You would have to let the default parent font remain present

**EDIT:**

OK, So after digging into this further (and playing alot with this), it would appear it is not as simple to handle this as first thought. However, after searching for a solution as if this were my own problem, I have located the following which is what I recommend using to detect if the browser supports font face. If the browser doesn't support font face, just set it to use a standard local font, otherwise the user would have to wait for the font to load, unfortunately any delay you may be experiencing is most likely down to file size and really isn't is something I can help you with, other than by advising you load the font at the start of your page, and assign it at the end of the page.

detect HTML5 and CSS3 features (search for tests\['fontface'\])

Also take a look at these: http://paulirish.com/2009/font-face-feature-detection/ http://news.ycombinator.com/item?id=1347011

I hope you find this more useful.

Regards,Chris
> 3 votes

# Answer
Here's accurate, but heavy solution. You can use this in addition to previous answers, to be 100% sure.
Let's quess that the font hasn't been loaded yet. What we'll get in case of drawing it? There're two possible options:

* **Nothing**.
It's easy to check - draw it on blank space, and use `getImageData` to ensure it's totally empty.
* **Default or another\* font**.
First, draw some letter ("a", for example) with *this font* at blank space and remember it's image data. Then, draw the same letter at very same position with your custom font. Finally, use `getImageData` to compare images data.

\*By another font I meant possibility of using 2nd font, like `ctx.font = "12px MyCustomFont Arial;"`. I'm not sure how browser will react in this case - will it use default font untill *MyCustomFont* gets loaded or will it use 2nd specified *Arial* instead.

**UPD** Just checked - my chrome v22, windows x64, shows **nothing** for unloaded font here.
> 2 votes

# Answer
The JavaScript FontFace class is (as of July 2020) still a working draft, but already supported by all browsers except (as usual) Internet Explorer.

It can be used to load a font via JavaScript and provides a Promise-based API which allows to execute a callback function if/when the font is actually loaded:

```
let myFont = new FontFace("myFont", "url(fonts/MyReallyCoolFont.ttf)");
myFont.load().then(
    font => {
        // your font is now loaded.
        // Now you just need to make it available to the DOM:
        document.fonts.add(font);
        // and then you can refer to it by name:
        ctx.font = '12px myFont';
    },
    error => {
        // your font could not be loaded.
        console.log(error);
    }
)

```
> 2 votes

# Answer
This answer about a similar question on StackOverflow gives a detailed solution to detecting when the font has loaded. It repeatedly draws a character in the font that should be loaded, and when it notices that the number of pixels suddenly changes it knows the font has been loaded and invokes a callback. The detection function is written for FontAwesome and similar fonts, but you can adjust it to suit your needs.
> 0 votes

---
Tags: javascript, html5
---


# Question
Title: Sprites don't become lit when installing Universal RP package
I want to implement 2D lights in Unity. So, I downloaded the **Universal RP** package from the Package Manager.

I created renderers as shown here, then I created a light object (Point Light 2D) in a new project.

What should happen: After this last step, the scene should become black.

What happened in my case: There scene is same as before plus a warning message popped up in the other project, and when I place any object from my game, only that object appears black.

> **WARNING:**
>
> *FlowerM\_03 material was not upgraded. There's no upgrader to convert Unlit/Transparent shader to selected pipeline UnityEditor.Rendering.Universal.UniversalRenderPipelineMaterialUpgrader:UpgradeProjectMaterials() (at Library/PackageCache/com.unity.render-pipelines.universal@7.4.1/Editor/UniversalRenderPipelineMaterialUpgrader.cs:25)*

Videos I took reference from:-

https://www.youtube.com/watch?v=nkgGyO9VG54

https://www.youtube.com/watch?v=F5l8vP90EvU

# Answer
> 0 votes
The warning message tells you that the package doesn't know how to automatically upgrade the materials that your existing sprites are using. So, it's up to you to change their material to the one you want.

If you have a sprite that's already behaving the way you want, take the material it's using and apply it to the others.

If not, you can create a new material and set its shader to `Universal Render Pipeline > 2D > Sprite-Lit-Default`

Then select each sprite that's not behaving, and set it to use this new material.

This is covered about 4 minutes into one of the videos you linked, so please be sure you're making full use of the references available to you when troubleshooting problems in your game.

---
Tags: unity, 2d, rendering, lighting
---


# Question
Title: How can I make sure the rotation has finished or the transform is facing the target?
```
void FixedUpdate()
    {
        LiftProcess();
        MoveProcess();
        TiltProcess();

        if (hasRotate == true)
        {
            Vector3 targetDirection = helicopterPlatform.transform.position - transform.position;
            Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, lookAtSpeed * Time.deltaTime, 0.0f);
            transform.rotation = Quaternion.LookRotation(newDirection);
        }
    }

```

I want ot make a check IF transform.rotation has finished and the transform is facing the newDirection then change the flag hasRotate to false. What check and how should I apply ?

# Answer
You can check `if ( Vector3.Angle(newDirection, targetDirection) < thresholdDegrees)`, where you can set the threshold in degrees as tight as you like.
> 1 votes

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


# Question
Title: How do I stop my player or camera from jittering during player movement?
In my game, I have a third person character. The player moves with a rigidbody and has `isKinematic` set off with interpolate on. In the script, it moves with `Rigidbody.MovePosition` with the y position froze. Here's my player script:

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

public class PlayerController : MonoBehaviour
{
   public float speed;

   public Rigidbody rb;

   public Transform camPos;

   // Start is called before the first frame update
   void Start()
   {
       rb = GetComponent<Rigidbody>();
       camPos = Camera.main.transform;
   }

   private void FixedUpdate()
   {
       if (Input.GetKey("w"))
       {
           rb.MovePosition(transform.position + (camPos.forward * speed * Time.fixedDeltaTime));
       }
       if (Input.GetKey("s"))
       {
           rb.MovePosition(transform.position + (-camPos.forward * speed * Time.fixedDeltaTime));
       }
       if (Input.GetKey("d"))
       {
           rb.MovePosition(transform.position + (camPos.right * speed * Time.fixedDeltaTime));
       }
       if (Input.GetKey("a"))
       {
           rb.MovePosition(transform.position + (-camPos.right * speed * Time.fixedDeltaTime));
       }

       rb.velocity = Vector3.zero;
   }
}

```

For my camera, I have it lookat the player and lag behind smoothly. Here's that script:

```
//Hakeem Thomas
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamPos : MonoBehaviour
{
    public Transform target;
    public float smoothTime = 0.5F;
    private Vector3 velocity = Vector3.zero;

    public GameObject player;

    private float mouseX, mouseY;
    public int mouseX_Speed, mouseY_Speed;

    //mouseSensitivity
    public int turnSpeed;

    void getMouseXY()
    {
        mouseX += Input.GetAxis("Mouse X") * smoothTime;
        mouseY -= Input.GetAxis("Mouse Y") * smoothTime;
    }
    void LateUpdate()
    {
        getMouseXY();
        // Define a target position above and behind the target transform
        Vector3 targetPosition = target.TransformPoint(new Vector3(0, 1.5f, -2.5f));

        // Smoothly move the camera towards that target position
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
        transform.LookAt(target);

        target.rotation = Quaternion.Euler((mouseY * mouseY_Speed), (mouseX * mouseX_Speed), 0);
        player.transform.rotation = Quaternion.Euler(0, (mouseX * turnSpeed), 0);

    }
}

```

My issue is that whenever the player moves either the camera/player jitters.

I have debugged the player transform y position to make sure it wasn't moving up or down (it doesn't). To help with this issue I have either turned down the `Fixed Timestep` under Time in the project settings or put the code in the camera script is fixed update instead of late update (which is an issue based on my research).

I know `MovePosition` for the player isn't the right way to move, but I don't know how to make the player move in the direction the camera is facing with `rb.velocity`. I suspect the issue may lay in the player script with variable `camPos`. Either way, I would like to stop the jittering.

# Answer
I made this mistake too:

```
target.rotation = Quaternion.Euler((mouseY * mouseY_Speed), (mouseX * mouseX_Speed), 0);
player.transform.rotation = Quaternion.Euler(0, (mouseX * turnSpeed), 0);

```

When you write to any part of the transform - including rotation - you disable rigidbody interpolation for that frame. The physics engine is bypassed, so it treats it as though the object has teleported, and tries to resume physics-driven, interpolated movement next frame.

If your object has a rigidbody, ensure you're routing *all* changes to its transformation, both position and rotation, through that body. That way the physics engine remains in control and you get the full benefit of its interpolation.

You're already using `MovePosition()` instead of `transform.position = ...`, so you should use `MoveRotation()` instead of `transform.rotation = ...`.
> 1 votes

# Answer
Another common cause of jitter is combining movement code in `Update()` with movement code in `FixedUpdate()`.

The default physics step is 0.02 seconds, which is 50 updates per second. That's slightly less than the typical monitor refresh rate of 60fps. This means every tenth of a second, you can expect an update sequence that looks sort of like this:

```
FixedUpdate
Update
FixedUpdate
Update
FixedUpdate
Update
FixedUpdate
Update
Update   <--------
FixedUpdate
Update

```

Because we have 5 physics updates for every 6 screen updates, about 10 times a second we're going to have a frame where the camera moves but the target didn't move. This causes very noticeable jitter.

There are two easy solutions, each which has its own downsides:

1. Reduce the physics update timestep (increase the number of physics updates per second). This increases the performance cost of running physics, and may not help on devices where the monitor refresh rate is much higher (e.g. on a 120hz or 240hz monitor).
2. Move the camera during FixedUpdate. Users with high-refresh-rate monitors may be able to tell that the camera motion isn't as smooth as it should be (since the camera is moving at 50hz but rendering at 120/240hz), but at least it shouldn't jitter.

I just made a simple test project to reproduce your issue. I saw major jitter when moving the camera in `Update()/LateUpdate()`, and no jitter when moving the camera in `FixedUpdate()`.
> 0 votes

---
Tags: unity, camera, movement, rigidbody, third-person-view
---


# Question
Title: Finding all possible paths from one hexagon to another
I got a hexagonal grid (cube coords)

In hex (0,0,0) there is a soldier and in another (distance == 4 hexes) a target:

i need to find all possible pathes from soldier hex to a target :

1)Length of path should be no more then 6 hexes

2)Not including those which returning to already visited tiles

3)Including those that are longer than the shortest possible path .

Though i need to solve it on javascript, but even pseudocode or just some thougths would be helpful

Thank you !

# Answer
> 0 votes
I did this :

```
function search(from,to,i) {

if(i == 1){
    if (isHexNear(from,to) || JSON.stringify(from) == JSON.stringify(to)){
        return [[from, to]]
    }
    return []
}

let all_paths = []

let neighbors = nearestHexesArr(from)
neighbors.push(from)

for (let node of neighbors) {

    let neighbor_all_paths = search(node,to,i-1)
    for( let path of neighbor_all_paths){
        all_paths.push([from, node].concat(path))
    }
}

return all_paths
}

```

Though it got some issues (resulting paths got duplicate hexes) , still after some cleaning of result it works.

isHexNear(from,to) and nearestHexesArr(from) are helper functions not hard to create.

Algorithm used is here: search Algo answer

# Answer
> 1 votes
Some pseudo brute force that just goes into all direction and stops on either length \> 6 or repeated field

```
function searchPath(x, y, z, gamefield, pathlength, pathtaken) {
 if (tile[x, y, z] == destination) {
  solutions.add(pathtaken);
 } else
 if (pathlength < 6) {
  if (gamefield[x, y, z] = false) {
   gamefield[x, y, z] = true;
   pathtaken.add(tile[x, y, z]);
   searchPath(x + 1, y - 1, z, gamefield, pathlength + 1, pathtaken);
   searchPath(x - 1, y + 1, z, gamefield, pathlength + 1, pathtaken);
   searchPath(x, y + 1, z - 1, gamefield, pathlength + 1, pathtaken);
   searchPath(x, y - 1, z + 1, gamefield, pathlength + 1, pathtaken);
   searchPath(x - 1, y, z + 1, gamefield, pathlength + 1, pathtaken);
   searchPath(x + 1, y, z - 1, gamefield, pathlength + 1, pathtaken);
  }
 }
}

```

A simple recursion that does not care about bounds. x, y z are the coordinates and hold your current position, gamefield is an array of bools that hold if you visited the place already, pathlength how many fields you walked and pathtaken is a list of tiles you walked. Make sure that they get their own instance of the passed parameters.

# Answer
> 0 votes
This reminds me of a problem I did on Google Foobar recently. It's dynamic programming. Basically first compute every path where you can get to the destination in exactly 1 move (from any tile location). Then compute every path that you can get to the destination in exactly 2 moves (this is done by computing every path that can reach a tile in the previous step in 1 move) that do not reuse nodes. Keep on doing this recursively until you reach the max distance, in this case 6. Then your result is all possible paths that start at the start node with distance 6 or less.

Here's some psuedocode:

```
public List<List<Tile>> getAllPaths(Tile origin, Tile destination, int maxDistance) {
    List<List<Tile>>[] allPaths = new List<List<Tile>>[maxDistance]();

    // Add everything adjacent to destination
    allPaths[0] = new List<List<Tile>>();
    for (int i = 0; i < destination.edgeNeighbours.Count; i++) {
        List<Tile> newPath = new List<Tile>();
        newPath.Add(destination.edgeNeighbours[i]);
        allPaths[i].Add(newPath);
    }

    // Compute paths recursively
    for (int distanceMinusOne = 1; distanceMinusOne < maxDistance; distanceMinusOne++) {
        for (int subPath = 0; subPath < allPaths[distanceMinusOne - 1].Count; subPath++) {
            for (int nextTile = 0; nextTile < allPaths[distanceMinusOne - 1][subPath][0].edgeNeighbours.Count; nextTile++) {

                // Check for duplicate tiles.
                if (allPaths[distanceMinusOne - 1][subPath].Contains(allPaths[distanceMinusOne - 1][subPath][nextTile])) {
                    break;
                }

                List<Tile> newPath = new List<Tile>();
                newPath.Add(allPaths[distanceMinusOne - 1][subPath][0].edgeNeighbours[nextTile]);
                newPath.AddAll(allPaths[distanceMinusOne - 1][subPath]);
                allPaths[distanceMinusOne].Add(newPath);
            }
        }
    }

    // Get all the paths
    List<List<Tile>> finalPaths = new List<List<Tile>>();
    for (int distanceMinusOne = 0; distanceMinusOne < allPaths.Count; distanceMinusOne++) {
        for (int path = 0; path < allPaths[distanceMinusOne].Count; path++) {
            if (allPaths[distanceMinusOne][path][0] == origin) {
                finalPaths.Add(allPaths[distanceMinusOne][path]);
            }
        }
    }

    return finalPaths;
}

```

---
Tags: javascript
---


# Question
Title: What is the "Unity" way to approach tech design for a 2D game like this?
So I come from C++ land where I've always done every little thing myself. Now I'm getting into Unity and C# and I'm ironically overwhelmed with the domain. I'm starting off with this simple little 2D game and I'm wondering... if someone can point me to the correct tools that would lead to a successful implementation of this game. Here is a quick mock up I did in paint:

These are the parts of Unity I've investigated:

* Tilemap
* Canvas
* GridLayout
* Prefabs
* GameObjects (these seem fundamental to Unity, heh).

After researching these topics, and playing around a bit, here are my initial questions:

**How do you approach Canvases in Unity?** I could see this being split into 5 separate Canvases, one for each local body of UI. Or 1 Canvas for the game board, and 1 canvas that contains a single overlay with all of the other UI components. But then how do those components typically get positioned? **Is it common practice to place by absolute coordinates?**

I guess I'm getting hung up on.. how do I place my canvas for the game board in that position relative to all the other UI elements? I'm a C++ application developer so if I'm doing UI at all I'm used to layout systems. I'm not sure how common that is in this ecosystem.

**Should I even use TileMap for this?** It doesn't seem like I need that kind of power. My grid is finite and fits on screen. My gut reaction is that I should just instantiate a bunch of colored squares at first. But I'm not really sure the best approach to that either. GridLayout on a canvas? Absolute coords? TileMap?

**What other tools should I be looking at?** By tools I mean Unity concepts I didn't mention above. My initial thought is to just have a backing data structure that holds all the data for the grid, and then I just render... prefabs? based on that data? Maybe I just want someone to tell me I'm on the right track or "no you're doing it totally wrong use this other thing", heh.

# Answer
> How do you approach Canvases in Unity?

It's possible to use more than one screen-space canvas in Unity, but it's uncommon. There is usually no reason to do that, unless you want different UI elements to use different basic canvas settings.

If you want your game to support multiple resolutions, then you want to avoid absolute positioning. You usually anchor UI elements to the closest corner or the edge of their parent. That way those elements stay relative to their corners / edges when you resize the UI. This is easy to forget and hard to spot while you are using in a constant screen resolution. So when I design UIs, I usually undock the game window and frequently drag the lower-right corner of that window around to check if the UI handles that gracefully.

On the other hand, if you decided that your game will only run in one resolution, then you can of course ignore anchors and just place objects where you want them to. You can save a lot of work that way. But designing for a fixed resolution impacts the user experience on some platforms (like PC) and can make your game almost impossible to play on others (like mobile).

> Should I even use TileMap for this?

The general rule of thumb in Unity is that you should use a canvas for the UI and non-canvas objects for the actual game. This is of course a rule you can break in either direction if you want to, but as a beginner you would be well-advised to work with the conventions of the engine instead of against them.

The Unity tilemap is more than just a way to arrange rectangles in a grid. It offers you:

* A handy map editor
* Collision detection between gameObjects and tiles in a very efficient way
* A lightweight way to implement tiles with game mechanics
* Pretty well-optimized rendering

These are all very useful when you have a game where the player navigates the grid in a physical manner (like in a platformer or a top-down action-adventure). But if I interpret your mockup correctly, then the game you seem to want to make seems more like a turn-based strategy game. This is a genre which *usually* uses more abstract game mechanics. It's also a genre which does not fit particularly well into the Unity architecture. I created a turn-based strategy game in Unity before, and compared to more action-oriented games it at times felt a bit like trying to fit a square peg into a round hole. You likely won't use the Unity physics engine and collision detection that much anyway. So yes, I guess you *could* implement this using a GridLayout on the UI if you wanted to.

But representing the actual game with sprite game-objects on a tilemap would likely be a much cleaner solution.
> 6 votes

# Answer
You would usually use the canvas for UI elements. You can anchor your elements relative to positions and it should take care of your scaling for different dimensions if done correctly.

A gameobject and prefab are almost the same. A gameobject basically is a container of something. It can hold multiple scripts, your sprites, colliders, etc. Take a look at your (3), one of them would be basically a gameobject. A prefab is a copy template of it. You would not create 3 times the same thing, just instantiate it and assign the values to it (like image, number values, etc)

Now a tilemap just makes your life easier but you can achieve the same with a grid or even just placing multiple sprites on the board. You can find some more examples for 2D from Unity at https://github.com/Unity-Technologies/2d-extras

Additional things you might want to take a look at are scenes but basically you are good and just need to get a feel for things. If you have any problem implementing a specific part, don't hesitate to describe the problem - best with what you tried and how it failed.
> 4 votes

# Answer
# Disclaimer

I myself am a noob working on my first Unity game. However, like you, mine is a 2D game with no aspirations for a 3rd dimension (a typical puzzle game).

# Use the UI

Like you, I struggled to understand whether it is better to use the world space or the UI space. Everyone said to use the world, so I started out with that. After playing around with things a fair amount, especially trying to make things pixel-perfect, I realized that the Unity world is really 3D, whether you pretend it is 2D or not, and this is simply more firepower than you need for purely 2D apps. On the one hand, setting the game scale to world units and setting the world unit to be the size of your tile makes for very nice, very convenient coordinates. On the other hand, if you want things pixel-perfect, this route will make you pull your hair out. That's because if you end up drawing a line between two pixels, Unity will very helpfully interpolate for you, drawing the line two pixels wide and adjusting the color accordingly (I want to call it "anti-aliasing", but this effect happens even if you explicitly turn anti-aliasing off, so I think that refers more to curves than simple straight rectilinear lines).

What I did is switch entirely to UI elements: `Panels`, `Buttons`, `ScrollView`, etc. This means that everything you do is now in screen coordinates, which is both good and bad. The good thing is, it is trivial to make things pixel-perfect. The bad thing is, screen resolutions. If you only want to target a single resolution, life is easy. Of course, if you were going to do that, why are you using Unity? So, the best way to go is to create a `Canvas` set to "Screen Space - Overlay" and set the `Scaler` to "Scale With Screen Size". I also set the scaling to 0.5, so it accounts for both horizontal and vertical changes evenly. This will mostly make your game scale appropriately from tiny phones up to massive 4K TV displays.

# Custom Scaling

My situation is unique in that I want the puzzle board to remain close to a fixed physical size (so zoomed in on tiny displays and zoomed out on big ones), which implies "Constant Physical Size". However, I also want to be able to zoom in and out under user control. So I removed the `Canvas Scaler` entirely and I simply resize the main `Panel` to zoom. Note that the Camera is almost completely irrelevant with this style, and you should basically ignore it.

The next issue is that I have menus which I *do* want to scale to the screen size. So I created a *second* `Canvas` which has the `Scaler` set as mentioned above. This causes my menus to always be visible at an appropriate size for the display, while letting the puzzle board expand and contract as necessary.

In this style, there are no "world coordinates". There are just screen coordinates, determined by your `Canvas Scaler` or your `Canvas`. Layering is sometimes achieved by setting the Z order, but mostly by ordering your `GameObjects` (rendering goes from top to bottom, so the last object drawn will always be "on top"). Of course, my Canvases also render in list order, so the Menu Canvas is drawn last, and overlays everything else.

# Widgets

I suspect you can get far by using `Panels` for most of your controls. A button provides a very convenient `OnClick()` event to hook into, but I use `OnPointerClick()` from the EventSystem, and find out which panel the mouse is over via eventData.pointerEntered. This way, you have a single entry point for click handling, and you can get at the object clicked without having to compute its coordinates on the screen. If you are generating your tiles programmatically, I don't see a need for a `GridLayout` (although, I haven't used it, so take that with a grain of salt).

It looks like Area 1 on your drawing is a "game map", and Area 2-5 are what I would call the "UI" proper. If you want the game map to be scrollable, you can probably just create a `ScrollRect` and lay down the entire map at once, using the `ScrollRect` to mask all but the visible area. You should be able to lay out all the UI elements statically in the designer, so you can get the controls pixel-perfect. Note that "Pixel Perfect" is actually an option on your `Canvas`, which will snap objects to integer screen coordinates so you don't get the anti-aliasing problem I mentioned above. Definitely check this box if you want crisp edges.

Every widget that you create more than 1 of, you should create as a Prefab first. Make the Prefab have the properties which will be most common, and then create all the instances from the Prefab by dragging the Prefab onto your object tree. This will make all your tiles have the same size, anchors, etc. However, note that once you override a Prefab, it will stop auto-updating when you change the Prefab properties. So, you can make each object constructed from a Prefab different from the Prefab (reflected as overrides), but there is the cost to doing so, which is that it disconnects the object from Prefab updates.

# Scripts

Yes, all your game logic should live in scripts. There should be \[at least\] one for your map, one for your characters, one for game items, one for menu actions, etc. The scripts can use dependency injection by declaring public data members which you bind in the Unity Editor (drag a game object onto the field in the property page). This makes it easy to refer to other Unity objects inside your script without making global references to the object hierarchy.

You'll notice that every script gives you a `Start()` and `Update()` method for free. This is a reminder to NOT USE THE CONSTRUCTOR. The c'tor will get called multiple times because of serialization. You want initialization to be done in `Awake()` or `Start()`. This is unfriendly to `#nullable enabled` code, unfortunately, but such is life.
> 0 votes

---
Tags: unity, 2d, html-canvas, grid
---


# Question
Title: How can I use Drag handlers (IBeginDragHandler, IEndDragHandler, IDragHandler) with a 2D sprite renderer instead of a UI Image?
In my game, I assigned all of the blocks to be 2D sprites so that they could be easily converted into prefabs:

However, when designing the drag and drop scripts, I noticed that all of the drag and drop handlers such as IBeginDragHandler, IEndDragHandler, IDragHandler, etc. weren't working at all. I later noticed that these were intended to be used by UI Images.

Now I am left wondering what I can do to make these 2D Sprites be usable by these functions for UI Images. Do I have any other options other than to start from scratch by making new UI Images?

Here's the small amount of code needed to create a reproducible example:

```
Public class DragDrop : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
    [SerializeField]
    private Canvas canvas;
    private CanvasGroup canvasGroup;

    private RectTransform rectTransform;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        canvasGroup = GetComponent<CanvasGroup>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        canvasGroup.alpha = 0.6f;
        canvasGroup.blocksRaycasts = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        canvasGroup.alpha = 1f;
        canvasGroup.blocksRaycasts = true;
    }
}

```

# Answer
> 2 votes
Make sure that:

1. You have a `Collider2D`(`BoxCollider2D` etc.) added.
2. `Physics2DRaycaster` added to your camera.
3. `EventSystem` in your scene.
4. Nothing is blocking the `Raycast` to this `SpriteRenderer`.

---

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

[RequireComponent(typeof(Collider2D))]
public class DraggableSpriteRenderer : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    [SerializeField] private SpriteRenderer _spriteRenderer;
    public SpriteRenderer _SpriteRenderer => this._spriteRenderer;

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");

        Vector3 movement = new Vector3(
            x: eventData.delta.x * Time.deltaTime,
            y: eventData.delta.y * Time.deltaTime
        );

        this.transform.localPosition += movement;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
    }

#if UNITY_EDITOR
    private void Reset()
    {
        this._spriteRenderer = this.GetComponent<SpriteRenderer>();
    }
#endif
}

```

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


title: Count Unity terrain size In blender?

text:
# Question
Title: Count Unity terrain size In blender?
My unity terrain size is 150\*150, and I want to create a plane in blender have the same size. How to figure the correct size ?

# Answer
> 2 votes
According to answer in Unity forums (link):

> ...
>
> it's best to have 1 Blender Unit = 1 Unity Unit = 1 meter.
>
> If you create your Blender model, and it's scaled 1:1:1, and on import it's very teeny tiny...
>
> Check your import settings for that model.
>
> If you are using a targeted save pipeline and are saving the .blend file directly to your Assets Directory of your project, the import settings should be set to 1.
>
> If you are using an export import pipeline and are exporting to .fbx and importing the .fbx file into Unity, you may find that the import settings default to 0.01.
>
> I believe this is because Maya (and perhaps other) packages that save to .fbx use centimeters by default for scale, rather then meters.

---
Tags: unity, blender, terrain
---


# Question
Title: Convert shader that uses a texture array to ShaderGraph
I am working on procedural generation in Unity, and am now a bit stuck. I am using Perlin noise to generate a heightmap, including lacunarity, persistence, octaves and frequencies.

Today I have been working on adding a custom shader for water to make everything look a lot prettier. I followed this tutorial, in which he used a Shader Graph. Thank god these exist, because they are so much nicer than Unity's default ShaderLab/HLSL code.

Speaking of Unity's default shader code, the shader that I wrote for the proc gen mesh blends different textures together (sand, grass, rocks, snow etc.) together based on values from the heightmap. Here is the code from the shader that I am looking at converting.

```
Shader "Custom/TerrainShader" {
    Properties {
        testTexture("Texture", 2D) = "white"{}
        testScale("Scale", Float) = 1

    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        const static int maxLayerCount = 8;
        const static float epsilon = 1E-4;

        int layerCount;
        float3 baseColours[maxLayerCount];
        float baseStartHeights[maxLayerCount];
        float baseBlends[maxLayerCount];
        float baseColourStrength[maxLayerCount];
        float baseTextureScales[maxLayerCount];

        float minHeight;
        float maxHeight;

        sampler2D testTexture;
        float testScale;

        UNITY_DECLARE_TEX2DARRAY(baseTextures);

        struct Input {
            float3 worldPos;
            float3 worldNormal;
        };

        float inverseLerp(float a, float b, float value) {
            return saturate((value-a)/(b-a));
        }

        float3 triplanar(float3 worldPos, float scale, float3 blendAxes, int textureIndex) {
            float3 scaledWorldPos = worldPos / scale;
            float3 xProjection = UNITY_SAMPLE_TEX2DARRAY(baseTextures, float3(scaledWorldPos.y, scaledWorldPos.z, textureIndex)) * blendAxes.x;
            float3 yProjection = UNITY_SAMPLE_TEX2DARRAY(baseTextures, float3(scaledWorldPos.x, scaledWorldPos.z, textureIndex)) * blendAxes.y;
            float3 zProjection = UNITY_SAMPLE_TEX2DARRAY(baseTextures, float3(scaledWorldPos.x, scaledWorldPos.y, textureIndex)) * blendAxes.z;
            return xProjection + yProjection + zProjection;
        }

        void surf (Input IN, inout SurfaceOutputStandard o) {
            float heightPercent = inverseLerp(minHeight,maxHeight, IN.worldPos.y);
            float3 blendAxes = abs(IN.worldNormal);
            blendAxes /= blendAxes.x + blendAxes.y + blendAxes.z;

            for (int i = 0; i < layerCount; i ++) {
                float drawStrength = inverseLerp(-baseBlends[i]/2 - epsilon, baseBlends[i]/2, heightPercent - baseStartHeights[i]);

                float3 baseColour = baseColours[i] * baseColourStrength[i];
                float3 textureColour = triplanar(IN.worldPos, baseTextureScales[i], blendAxes, i) * (1-baseColourStrength[i]);

                o.Albedo = o.Albedo * (1-drawStrength) + (baseColour+textureColour) * drawStrength;
            }

        }

        ENDCG
    }
    FallBack "Diffuse"
}

```

The Texture data is communicated to the shader through this code here:

```
public void UpdateMeshHeights(Material material, float minHeight, float maxHeight)
{
    material.SetInt("layerCount", layers.Length);
    material.SetColorArray("baseColours", layers.Select(x => x.tint).ToArray());
    material.SetFloatArray("baseStartHeights", layers.Select(x => x.startHeight).ToArray());
    material.SetFloatArray("baseBlends", layers.Select(x => x.blendStrength).ToArray());
    material.SetFloatArray("baseColourStrengths", layers.Select(x => x.tintStrength).ToArray());
    material.SetFloatArray("baseTextureScales", layers.Select(x => x.textureScale).ToArray());
    Texture2DArray texturesArray = GenerateTextureArray(layers.Select(x => x.texture).ToArray());
    material.SetTexture("baseTextures", texturesArray);

    savedMinHeight = minHeight;
    savedMaxHeight = maxHeight;

    material.SetFloat("minHeight", minHeight);
    material.SetFloat("maxHeight", maxHeight);
}

```

Where `layers` is an array of a Layer objects, here

```
public class Layer
{
    public Texture2D texture;
    public Color tint;
    [Range(0, 1)]
    public float tintStrength;
    [Range(0, 1)]
    public float startHeight;
    [Range(0, 1)]
    public float blendStrength;
    public float textureScale;
}

```

The water shadergraph works all fine and dandy (tested in its own scene) and I am very pleased with the outcome. However, when brought together with the custom shader above, the water renders, but the mesh is left with an unwieldy pink colour for its material.

I understand it is something to do with the Render Pipelines; the .shadergraph files use the Universal Render Pipeline and the .shader files lie somewhere else. Is there any way to convert between the two, whether that be converting the .shader into a .shadergraph or vice versa? I can't seem to find any details on it anywhere.

If there is no way to convert, can someone talk me through how I can blend textures together based on heightmap data? At the moment the data about where the textures begin and end are held in FloatArrays, which there isn't an equivalent to using ShaderGraphs, from what I can see? I may be wrong, and there is probably a much better way of doing it.

If you want to look specifically at the code for the rest of the project, it can be found on my GitHub.

Thank you to anyone who can help or point me in the right direction!

# Answer
ShaderGraph generates sourcecode which you can view, copy and paste into a code-based shader, so converting or integrating a ShaderGraph shader into a code-based one is possible. However, the other way around isn't. If you want to convert a code-based shader into ShaderGraph, you either have to convert it into a custom function and integrate it into a shadergraph as a black box (as explained in the answer by DMGregory) you you have to manually rebuild it from scratch.

> can someone talk me through how I can blend textures together based on heightmap data?

You can do that with a Blend Node. This node can perform various image blending algorithms between two textures which you might recognize from image editors like Photoshop. If you want to interpolate linearly between the two textures, then "Overwrite" is the mode you are looking for. But some of the other modes might also give you interesting results, so it might be worth experimenting a bit. This is the workflow to build such a shader in ShaderGraph:

* Create 3 SampleTexture nodes for the two textures and the heightmap
* Create the Blend node
* Feed the two textures into the first two input nodes of the Blend node
* Feed the heightmap into the 3rd input node
* Feed the output into the masters albedo/color node

Shader Graph (I omitted the vertex displacement which is based on the same heightmap multiplied by 5):

Result:

The opacity input of the Blend node expects a value between 1 and 0 which determines the ratio between the two textures. If you only want a small band within the range of the heightmap to be blended, then you might have to send the output of the heightmap through a couple math nodes first.

For example, if you want the heightmap values between 0.5 and 0.6 to blend between the two textures and everything below that band to be texture A and everything above it to be texture B, then:

* Subtract 0.5 (lower bound of blending zone)
* Divide by 0.1 (width of the blending zone)
* Clamp the results to a range of 0 to 1

Graph:

Result:
> 2 votes

# Answer
Here's a quick stab at how to convert your shader code to a custom function node we can apply in a Shader Graph.

First, we'll make a new text file to hold the shader code. I called mine "shaderGraphArray.cginc"

```
const static int maxLayerCount = 8;
const static float epsilon = 1E-4;

int layerCount;
float3 baseColours[maxLayerCount];
float baseStartHeights[maxLayerCount];
float baseBlends[maxLayerCount];
float baseColourStrength[maxLayerCount];
float baseTextureScales[maxLayerCount];

float3 triplanar(float3 worldPos, float scale, float3 blendAxes, Texture2DArray textures, SamplerState ss, int textureIndex) {
    float3 scaledWorldPos = worldPos / scale;
    float3 xProjection = SAMPLE_TEXTURE2D_ARRAY(textures, ss, float2(scaledWorldPos.y, scaledWorldPos.z), textureIndex) * blendAxes.x;
    float3 yProjection = SAMPLE_TEXTURE2D_ARRAY(textures, ss, float2(scaledWorldPos.x, scaledWorldPos.z), textureIndex) * blendAxes.y;
    float3 zProjection = SAMPLE_TEXTURE2D_ARRAY(textures, ss, float2(scaledWorldPos.x, scaledWorldPos.y), textureIndex) * blendAxes.z;
    return xProjection + yProjection + zProjection;
}

void layer_terrain_float(float3 worldPos, float heightPercent, float3 worldNormal, Texture2DArray textures, SamplerState ss, int layerCount, out float3 albedo) {
    float3 blendAxes = abs(worldNormal);
    blendAxes /= blendAxes.x + blendAxes.y + blendAxes.z;

    albedo = 0.0f;

    for (int i = 0; i < layerCount; i ++) {
        float drawStrength = inverseLerp(-baseBlends[i]/2 - epsilon, baseBlends[i]/2, heightPercent - baseStartHeights[i]);

        float3 baseColour = baseColours[i] * baseColourStrength[i];
        float3 textureColour = triplanar(worldPos, baseTextureScales[i], blendAxes, textures, ss, i) * (1-baseColourStrength[i]);

        albedo = albedo * (1-drawStrength) + (baseColour+textureColour) * drawStrength;
    }
}

```

Things to note here:

* I refactored the main workhorse of iterating through the layers into a `void` function that takes all its inputs as arguments and puts its output into an `out` argument.
* I changed the texture-sampling macros from the old, pre-scriptable-render-pipeline `UNITY_SAMPLE_TEX2DARRAY` to the new D3D11+ style `SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index)`. Based on this thread, I was able to find a list of all these macros here.
* These macros now want a sampler state, so I included that as another argument to pass down.

The rest should be a pretty straightforward conversion.

Then I called this custom function from a shader graph as shown here:
> 2 votes

# Answer
I'm working on make custom shader working on lwrp 4.10.0, and my way is custom node, here is sample code:

```
[Title("Custom", "TerNode")]
public class TerNode : CodeFunctionNode
{
    public TerNode()
    {
        name = "TerNode";
    }

    protected override MethodInfo GetFunctionToConvert()
    {
        return GetType().GetMethod("MyCustomFunction", BindingFlags.Static | BindingFlags.NonPublic);
    }

    static string MyCustomFunction(
         [Slot(0, Binding.MeshUV0)] Vector2 uv,
         [Slot(1, Binding.None)] Texture2DArray _SplatTexArray,
         [Slot(2, Binding.None)] SamplerState _SplatIdSampler,
         [Slot(3, Binding.None)] out ColorRGB Out)
    {
        Out = new ColorRGB();
        return "{ ... }"; // Shader code here
    }
}

```

\`

Also i tried to write a lwrp-compatiable shader directly, i used

`Texture2DArray _SplatTexArray; SamplerState _SamplerState_Linear_Repeat_sampler_splat;`

to replace UNITY\_SAMPLE\_TEX2DARRAY(\_SplatTexArray), but finally i gave up this method because i can not make it lighting.
> 1 votes

---
Tags: unity, c#, shaders, hlsl, unity-shader-graph
---


# Question
Title: Maya name clash with FBX motion capture file and FBX avatar on the 'root'
I'm attempting to re-target motion capture data from radical motion to an avatar I created with Character Creator. After creating a character definition for one, I import the other and it appears they are merging their 'roots'. Both their hierarchies contain a `:root` with no namespace. I tried modifying namespaces before importing but that isn't working either.

Any thoughts?

# Answer
I had to change my import settings for my FBX files. Under Include -\> File Content, I needed to select Add. More info can be found here.
> 0 votes

---
Tags: character, maya, motion-capture
---


# Question
Title: Correct way to project a texture with alpha and colors onto surfaces in Unity
I am experimenting with Unity and wanted to project a unit circle beneath a unit and my very first naive approach was to create a child plane below the unit, assign the material to it and stretch it using the Pro Builder UV editor but it looked horrible:

In order to figure out what's wrong I read a lot of various approaches to "fix" that issue which were mostly the following:

* use a higher resolution for the texture
* do not use any compression
* do not use a POT resolution
* change the filtering option from bilinear to point
* ...

Eventually I figured that I have to do something completely different and that is how I stumbled upon the idea to use a shader attached to a projector game object in order to project a material. Unfortunately though it turns out the shader expects a grayscale image and only tints the projection based on a parameter. For reference this is the shader I have just copied from the web (source):

```
Shader "Projector/AdditiveTint" {
    Properties {
        _Color ("Tint Color", Color) = (1,1,1,1)
        _Attenuation ("Falloff", Range(0.0, 1.0)) = 1.0
        _ShadowTex ("Cookie", 2D) = "gray" {}
    }
    Subshader {
        Tags {"Queue"="Transparent"}
        Pass {
            ZWrite Off
            ColorMask RGB
            Blend SrcAlpha One // Additive blending
            Offset -1, -1

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct v2f {
                float4 uvShadow : TEXCOORD0;
                float4 pos : SV_POSITION;
            };

            float4x4 unity_Projector;
            float4x4 unity_ProjectorClip;

            v2f vert (float4 vertex : POSITION)
            {
                v2f o;
                o.pos = UnityObjectToClipPos (vertex);
                o.uvShadow = mul (unity_Projector, vertex);
                return o;
            }

            sampler2D _ShadowTex;
            fixed4 _Color;
            float _Attenuation;

            fixed4 frag (v2f i) : SV_Target
            {
                // Apply alpha mask
                fixed4 texCookie = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
                fixed4 outColor = _Color * texCookie.a;
                // Attenuation
                float depth = i.uvShadow.z; // [-1 (near), 1 (far)]
                return outColor * clamp(1.0 - abs(depth) + _Attenuation, 0.0, 1.0);
            }
            ENDCG
        }
    }
}

```

With that shader I was able to render the following effect:

Since I have no experience with shaders at all I just blatantly copy & pasted it and do not know (yet) how to customize them or even write custom ones in the first place.

Assuming my approach to combine a projector with such a shader is the way to go, I'd like to know whether there is any shader you can share that allows me to project an unlit texture with transparency and its own color such as the following example:

# Answer
After a lot of research I finally found a shader, that for the time being, does what I want to which was described in the Unity forums. The corresponding shader code is the following:

```
Shader "Projector/Tattoo" {
    Properties {
        _ShadowTex("Cookie", 2D) = "white" {}
    }

    Subshader {
        Tags {
            "RenderType" = "Transparent"
            "Queue" = "Transparent+100"
        }
        Pass {
            ZWrite Off
            Offset -1, -1

            Fog{ Mode Off }

            ColorMask RGB
            Blend OneMinusSrcAlpha SrcAlpha

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_fog_exp2
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
            };

            sampler2D _ShadowTex;
            float4x4 unity_Projector;
            float4 _Color;

            v2f vert(appdata_tan v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = mul(unity_Projector, v.vertex);
                return o;
            }

            half4 frag(v2f i) : COLOR
            {
                half4 tex = tex2Dproj(_ShadowTex, i.uv);
                tex.a = 1 - tex.a;
                if (i.uv.w < 0)
                {
                    tex = float4(0,0,0,1);
                }
                return tex;
            }
            ENDCG
        }
    }
}

```

Since I don't know anything about shaders I'd appreciate if you have optimziation suggestions.
> 2 votes

# Answer
Well, for my bullet hole shader I find the issue to remove the transparent alpha effect by changing my "Blend" with your "Blend OneMinusSrcAlpha SrcAlpha".

```
// Upgrade NOTE: replaced '_Projector' with 'unity_Projector'
// Upgrade NOTE: replaced '_ProjectorClip' with 'unity_ProjectorClip'

Shader "Projector/Multiply" {
    Properties {
        _ShadowTex ("Cookie", 2D) = "gray" {}
        _FalloffTex ("FallOff", 2D) = "white" {}
    }
    Subshader {
        Tags {"Queue"="Transparent"}
        Pass {
            ZWrite Off
            ColorMask RGB
            Blend OneMinusSrcAlpha SrcAlpha
            Offset -1, -1

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fog
            #include "UnityCG.cginc"

            struct v2f {
                float4 uvShadow : TEXCOORD0;
                float4 uvFalloff : TEXCOORD1;
                UNITY_FOG_COORDS(2)
                float4 pos : SV_POSITION;
            };

            float4x4 unity_Projector;
            float4x4 unity_ProjectorClip;

            v2f vert (float4 vertex : POSITION)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(vertex);
                o.uvShadow = mul (unity_Projector, vertex);
                o.uvFalloff = mul (unity_ProjectorClip, vertex);
                UNITY_TRANSFER_FOG(o,o.pos);
                return o;
            }

            sampler2D _ShadowTex;
            sampler2D _FalloffTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 texS = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
                texS.a = 1.0-texS.a;

                fixed4 texF = tex2Dproj (_FalloffTex, UNITY_PROJ_COORD(i.uvFalloff));
                fixed4 res = lerp(fixed4(1,1,1,1), texS, texF.a);

                UNITY_APPLY_FOG_COLOR(i.fogCoord, res, fixed4(1,1,1,1));
                return res;
            }
            ENDCG
        }
    }
}

```
> 0 votes

# Answer
The unity standard assets contains a projector game object, material, and shader. Just drag into your scene, reposition, drag material into projector, and drag image into shader “cookie” field.
> 0 votes

# Answer
The former additive shader wasn't working for me, so I made the working version. This is my first ever shader, I don't even know what this script language is called and never read any doc about shaders, but hey it's working, so feel free to grab :)

```
Shader "Projector/AdditiveTint" {
    Properties{
        _Color("Tint Color", Color) = (1,1,1,1)
        _ShadowTex("Cookie", 2D) = "white" {}
    }

        Subshader{
            Tags {
                "RenderType" = "Transparent"
                "Queue" = "Transparent+100"
            }
            Pass {
                ZWrite Off
                Offset -1, -1

        //Fog{ Mode Off }

        ColorMask RGB
        Blend One One

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma fragmentoption ARB_fog_exp2
        #pragma fragmentoption ARB_precision_hint_fastest
        #include "UnityCG.cginc"

        struct v2f
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
        };

        sampler2D _ShadowTex;
        float4x4 unity_Projector;

        v2f vert(appdata_tan v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv = mul(unity_Projector, v.vertex);
            return o;
        }

        fixed4 _Color;
        half4 frag(v2f i) : COLOR
        {
            half4 tex = tex2Dproj(_ShadowTex, i.uv);
            tex.a = 1 - tex.a;
            if (i.uv.w < 0)
            {
                tex = float4(0,0,0,1);
            }
            return _Color * tex;
        }
        ENDCG
    }
    }
}

```
> 0 votes

---
Tags: unity, shaders, textures
---


# Question
Title: Why does the keyboard continue to control disabled buttons?
Having the whole panel with all its children including buttons disabled by simple `gameObject.SetActive(false)` doesn't prevent the buttons from interacting (navigation and clicks) with the keyboard. What could be the reason?

# Answer
> 1 votes
I tried `CanvasGroup.interactable` but it didn't help. Then I looked closely at the UI elements and found a *custom component* on them made by the previous developer - something like a custom `EventSystem`. I have no idea what was the need to write a custom event system, but after deleting it everything works as expected.

---
Tags: unity
---


# Question
Title: Android Build Failing Game Maker Studio 1.4
In Game Maker Studio 1.4 I'm trying to export my game to Android API 29. Whenever I start to compile, the build fails because the API 28 support library is too low for the Target API 29. I have the latest Android Studio and SDK's installed. I don't know how to fix it.

**Here's a pic of my target sdk settings:**

**Here's my lint file saying what the error is:**

# Answer
> 1 votes
I found out that to export to API 29 and above; Android support libraries are no longer supported for those API's. You have to merge your project over to Androidx. You have the target SDK settings look like mine above. Then you open your Root gradle.properties file and paste the following lines of code:

Example Location: **D:\SteamLibrary\steamapps\common\gamemaker\_studio\Android\runner\RootFiles**

```
android.useAndroidX=true

android.enableJetifier=true

```

Then you add some code to the Android module gradle.build file **not** the Root gradle.build file. You add this to the gradle file in the ProjectFiles folder:

```
lintOptions {
   abortOnError false
}

```

Which will make game maker ignore the build failure and will then build successfully. The location for the build.gradle file is your Game maker studio install location for example:

**D:\SteamLibrary\steamapps\common\gamemaker\_studio\Android\runner\ProjectFiles\build.gradle**

Your file should look like this under the android section after you've enter the code above:

```
android {
    compileSdkVersion ${YYAndroidCompileSDKVersion}
    buildToolsVersion '${YYAndroidBuildToolsVersion}'

    ${YYAndroidJavaMaxHeapSize}

    defaultConfig {
        applicationId "${YYAndroidPackageName}"
        minSdkVersion ${YYAndroidMinSDKVersion}
        targetSdkVersion ${YYAndroidTargetSDKVersion}
        multiDexEnabled true
    }
    lintOptions {
        abortOnError false
    }

    signingConfigs {
        release {
            storeFile file("${YYAndroidKeyStoreFile}")
            storePassword "${YYAndroidKeyStoreFilePassword}"
            keyAlias "${YYAndroidKeyAlias}"
            keyPassword "${YYAndroidKeyPassword}"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.release
        }
    }

    ${YYAndroidSplits}
}

```

It's possible to export to newer API's in Game maker studio 1.4 you just won't be able to put advertisements in your game. You'll have to make a full game and sell it if you want to make money off of it.

---
Tags: android, game-maker, gradle
---


# Question
Title: How can I not infringe on another game, while having a similar concept to that game?
The Call Of Duty game (Black Ops) has its story revolving around number stations, Mk-ultra brainwashing, black operations and Soviet biochemical weapons. I want to have my story's concept pretty much similar like that with some differences, but I don't want to infringe on the original story; does anyone have any ideas for my story to not be a ripoff, but can give off a similar atmosphere?

# Answer
> 0 votes
First of all, keep in mind that CoD did not invent most of these things. They are either things which actually exist or popular myths. Often a mix of both. They can hardly monopolize these story elements.

So a good start is to do your own research. When you dive down the rabbit hole on your own, you will find that there are a lot of interesting facts and myths around these topics which the CoD developers did *not* put in their game. And don't just focus on the Soviet Union. There are also some pretty interesting secret projects *other* states won't confirm or deny they might or might not have done during the cold war. And considering that your game is fiction, and that most of what you are going to find during your research will *also* be fiction invented by some conspiracy theorists, you can also extrapolate from what you find and invent your own.

---
Tags: copyright, storyboard
---


# Question
Title: Calculating the flavour of a dish in a cooking game
I'm currently working on a game that sees players cook dishes and are scored on their performance. To determine whether a dish is good or not, I will be looking to see if these elements are balanced:

* Salt
* Fat
* Acid

A dish is made up of multiple ingredients and each ingredient will have its own salt, fat and acid levels. Adding too much or too little of an element (e.g. over-salting) results in a weaker score for the player.

There are also a few other factors that affect the salt, fat and acid balance:

* The number of ingredients (adding more ingredients should reduce saltiness, fattiness and acidity)
* Acid can reduce the saltiness and fattiness of a dish.
* Salt can reduce the acidity of a dish.

This idea comes from Samin Nosrat's book Salt, Fat, Acid Heat. Below is an image from her book where she breaks down 4 popular salads and shows how each of the ingredients affects each element. If the player was to recreate "The Caesar" salad, they should get a perfect score for balancing all those ingredients but if they created a salad with just bacon and anchovies it should be considered too salty.

Texture is another element that the player needs to balance but this won't need to be calculated in the same way as the other elements. My plan here is to check if the player is making a salad it should have some crunch to it, whereas if they are making a roast the meat should be tender.

Given a set of ingredients, I would like to calculate whether the dish is balanced or not. The game will probably have 100s of ingredients and I would like some advice on how to best calculate these elements, score the player and balance the many ingredient combinations a player can come up with.

# Answer
I would first model this by creating a table which includes the taste components (and perhaps far more data) of each ingredient per unit. This table could look something like this:

```
Ingredient | Salt   | Fat   | Acid   | Crunch | Umami  |
--------------------------------------------------------
Bacon      |    5   |     6 |      3 |      7 |      8 |
Lettuce    |    0   |     0 |      1 |      3 |      1 |
Vinegar    |    0   |     0 |      9 |      0 |      2 |
Cheese     |    3   |     7 |      1 |      1 |      6 |

```

<sub>(this is just an example, please don't nail me down on those numbers)</sub>

When the player creates their dish from multiple ingredients, just add them up. So when the player creates a bacon salad from 2 units of bacon, 3 units of lettuce and one unit of cheese, then the final sum for "umami" would be:

```
2 * 8 = 16
3 * 1 =  3
1 * 6 =  6
----------
        25

```

When the player just adds twice as many ingredients, then they of course don't get a dish which tastes twice as intense, they get twice as much food of the same taste. So to calculate the final taste, you should divide the sum by the total units of ingredients in the dish to get the average umami value of the dish, which would in this case be `25 / 6 =`  4.17.

Do this with each taste-component and you got the average taste of the dish on each component.

Now what combination of these values is a "balanced" taste and what isn't is more of a topic for cooking stack exchange. But your implementation will likely boil down to finding target values for each taste component and grade the player by how close they got to the target values.
> 2 votes

---
Tags: game-design, algorithm, balance, scoring
---


# Question
Title: Efficient way to implement a lot of singletons
I just came upon programming patterns and learned about singleton. I'm in the process of creating my first game and it contains several managers:

I wanted to implement singleton on each of the managers,but the only way I can think is copy pasting the singleton pattern on each awake method script attached to each manager.

Is there a more efficient way to do it rather than pasting the pattern on each awake method?

# Answer
I have to say this question doesn't demonstrate much research. If you plug "unity singleton" into a search engine, the very first result is the Unify Community Wiki where they show how to make a reusable Singleton via the Curiously Recurring Template Pattern.

Here's a simplified version closer to the Awake style you're describing:

```
public abstract class Singleton<T> : MonoBehaviour where T :Singleton<T>
{
    public static T Instance { get; private set; }

    private void Awake() {

        if(Instance != null) {
            Debug.LogErrorFormat("Two copies of singleton {0} in the scene: ({1}, {2}). Please ensure only one is present.",
                (typeof(T)).FullName, Instance.name, name);
            Destroy(gameObject);
            return;
        }

        Instance = (T)this;
    }
}

```

You can then apply this singleton behaviour to any MonoBehaviour type by deriving from the template:

```
public class SomeManager : Singleton<SomeManager>
{
}

```

Then access its instance with `SomeManager.Instance`

That said, as Vaillancourt points out, you can skip having many singletons by just having one overall manager that holds references to the others. In this way it behaves like a version of the Service Locator pattern, giving you a common place to re-hook the references if you ever need to change the sub-managers or have more than one:

```
public class GameManager : Singleton<GameManager> {

    public AudioManager audioManager;
    public PuzzleManager puzzleManager;
    // ...
}

```

This can help you avoid a common problem we run into with Singletons, where we add multiplayer and suddenly all the systems that used to be globally unique for the only player, now need multiple instances, one for each player. The "manager of managers" gives you a convenient place to parcel out which references to use for each player, and you can look them up with something like `GameManager.Instance.GetInventoryForPlayer(2)`.
> 3 votes

# Answer
An effective way to achieve this is to *not do it*.

You can create a single singleton that will be the entry point and owner of all the other managers. This way, you don't need to add the singleton infrastructure to all of your managers, just to one.
> 2 votes

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


title: Visualizing NavMesh to Camera

text:
# Question
Title: Visualizing NavMesh to Camera
When Unity builds a NavMesh, you can see it in the scene view if you have the Navigation window open and select "Show NavMesh" in the Navmesh Display box. I'd like to use the exact same overlay in a camera view. Is this accessible in any way? Can it be rebuilt during runtime? Since the navMesh isn't an actual mesh, I can't seem to find a way to make this happen.

EDIT: This is what I'm trying to work with right now:

```
public class NavMeshToCamera : MonoBehaviour {

    NavMeshTriangulation triangles;
    Mesh mesh;

    void Awake () {
        triangles = NavMesh.CalculateTriangulation();
        mesh = new Mesh();

        mesh.vertices = triangles.vertices;
        mesh.triangles = triangles.indices;
    }
}

```

I have this script attached to a secondary camera that will be enabled while holding down a button to see an overlay of a minimap of the current dungeon. I'm not quite sure what to do with the mesh data to provide a mesh visible to the camera. Since no mesh exists initially, I suppose I'd have to take the new mesh, apply a layer to it, and have only that layer visible to the camera. But I'm having some difficulties with this.

# Answer
> 2 votes
This should be possible by optaining the triangles from the generated NavMesh. So first you need to bake the NavMesh and then call CalculateTriangulation. This gives you a NavMeshTriangulation object which contain a list of vertices and indices. From there it should be fairly easy to transform them into a Unity Mesh. The only problem is, that the generated size of the triangulation doesn't match the size of your objects, so you have to scale the generated mesh. Strangely the scale is not uniform for all axis so for me a scalation for the x axis of 1 / 30 and for the z axis of 1 / 40 worked best. So your code should look something like this:

```
  var triangles = NavMesh.CalculateTriangulation ();
  Vector3[] vertices = triangles.vertices;
  for (int i = 0; i < vertices.Length; ++i) {
    vertices [i].x *= 1.0f / 30.0f;
    vertices [i].z *= 1.0f / 40.0f;
  }

  Mesh mesh = new Mesh ();
  mesh.vertices = vertices;
  mesh.triangles = triangles.indices;
  GetComponent<MeshFilter>().sharedMesh = mesh;

```

# Answer
> 2 votes
Just want to add to the answer above, if your NavMesh consists of different Areas, you can actually assign your triangle indices to different submeshes using `Mesh.SetTriangles()` and `Mesh.subMeshCount`, so that they will use different indexes from the Mesh Renderer's Materials array.

I've attached my code snippet demonstrating that below. If you want a more detailed explanation, you can refer to my article on it here: https://blog.terresquall.com/2020/07/showing-unitys-navmesh-in-game/

```
using UnityEngine;
using UnityEngine.AI;

public class ShowNavmesh : MonoBehaviour
{
    void Start()
    {
        ShowMesh();
    }

    // Generates the NavMesh shape and assigns it to the MeshFilter component.
    void ShowMesh()
    {
        // NavMesh.CalculateTriangulation returns a NavMeshTriangulation object.
        NavMeshTriangulation meshData = NavMesh.CalculateTriangulation();

        // Organise the NavMeshTriangulation data into Dictionary key-value pairs.
        // In this Dictionary, each area in the NavMesh will have its own list of triangles
        // that belong to the area. Each of these lists of triangles will be rendered as
        // a submesh later below.
            Dictionary<int,List<int>> submeshIndices = new Dictionary<int,List<int>>();

        // <meshData.areas> is an int[] that contains an entry for every triangle in
        // <meshData.indices>. The entry helps to identify which Navigation Area each
        // triangle belongs to.
            for(int i = 0;i < meshData.areas.Length;i++) {
                    // If a list hasn't already been created for this area index, do so.
                if(!submeshIndices.ContainsKey(meshData.areas[i])) {
                        submeshIndices.Add(meshData.areas[i],new List<int>());
                    }

            // Because a triangle contains 3 points, <meshData.indices> will always be exactly 3 times
            // the size of <meshData.areas>. Each index on <meshData.areas> identifies 3 items in <meshData.indices<,
            // so we have to identify the 3 items that each <meshData.areas< item is referring to.
                    submeshIndices[meshData.areas[i]].Add(meshData.indices[3 * i]);
                    submeshIndices[meshData.areas[i]].Add(meshData.indices[3 * i + 1]);
                    submeshIndices[meshData.areas[i]].Add(meshData.indices[3 * i + 2]);
            }

        // Create a new mesh and chuck in the NavMesh's vertex and triangle data to form the mesh.
        Mesh mesh = new Mesh();
        mesh.vertices = meshData.vertices;

        // Tell our mesh how many submeshes it contains, and use SetTriangles() to assign
        // triangles to the different submeshes in the mesh object.
        mesh.subMeshCount = submeshIndices.Count;
        int index = 0;
        foreach(KeyValuePair<int,List<int>> entry in submeshIndices) {
            mesh.SetTriangles(entry.Value.ToArray(),index++);
            }

        // Assigns the newly-created mesh to the MeshFilter on the same GameObject.
        GetComponent<MeshFilter>().mesh = mesh;
    }
}
```

---
Tags: unity, camera, navmesh
---


# Question
Title: How to change the geometry of the scene in Unity?
I'm trying to experiment with 3D spherical geometry in Unity, but it seems like Unity objects are inherently set in flat space. My first idea was to create a class inheriting from `Transform` that would override most of the methods, but I discovered that the `transform` member of a game object is read only so I cannot replace it with my custom class. I know this sort of thing is possible because the game Hyperbolica is being built in Unity using curved space. I have the math all figured out, I'm just not experienced with Unity. Anyone have other ideas for things I could try?

# Answer
> 2 votes
The editor coordinate system will always be in 3D Cartesian coordinates in a flat Euclidean spacetime, but you're under no obligation to use those coordinates for evaluating your game logic or rendering.

You can add an additional `Transform4D` component to your objects/entities, and refer to its custom coordinate values instead.

Each frame, you can set the position/orientation/scale of the built-in `Transform` component to a 3D projection of your `Transform4D` from your player's current viewpoint to handle the local neighbourhood around the player where space is "almost flat"

Or you can use your `Transform4D` to compute 4-dimensional positions for each of your mesh's vertices, and send them to the GPU as a texture coordinate channel. A custom shader then reads these and projects your 4D object using this channel, instead of the 3D position values provided by the engine.

I played around with some hypersphere exploration back in the Flash days and the situation was similar: the native coordinate system was only flat Euclidean (and 2D!), but if you're willing to compute your own vertex positions you can project any arbitrary space you can think of into that canvas.

---
Tags: unity, rotation, transformation
---