# Question
Title: How to batch coroutines (IEnumerators) in parallel
We are working in a context where multithreading is not an option, so we're using coroutines to handle our loads. Often there are multiple things that need to be downloaded, leading to a pattern like this:

```
// set up multiple downloads
dataToDownload = 3;
StartCoroutine(ReadDataCoroutine1(OnDataRead));
StartCoroutine(ReadDataCoroutine2(OnDataRead));
StartCoroutine(ReadDataCoroutine3(OnDataRead));

// handle each of the loads completed
private void OnDataRead()
{
    // nasty and error prone way to check completion of all data
    dataToDownload--;
    if (dataToDownload > 0) return;

    DoStuffNowThatDataIsAllLoaded();
}

```

So I thought I would build a helper class to batch the downloads:

```
public BatchDownloader(
    IEnumerable<Func<IEnumerator>> downloadFuncs,
    Action<int, int> onDownloadComplete = null,
    Action<int> onAllDownloadsComplete = null)
{
    this.downloadFuncs = downloadFuncs;
    this.onDownloadComplete = onDownloadComplete;
    this.onAllDownloadsComplete = onAllDownloadsComplete;
    totalDownloads = downloadFuncs.Count();
}
public IEnumerator DownloadBatch()
{
    completedDownloads = 0;
    foreach (var downloadFuncs in downloadFuncs)
        yield return ProcessDownload(downloadFuncs);
    onAllDownloadsComplete?.Invoke(totalDownloads);
}
private IEnumerator ProcessDownload(Func<IEnumerator> downloadFunc)
{
    yield return downloadFunc();
    onDownloadComplete?.Invoke(totalDownloads, ++completedDownloads);
}

```

Used something like this:

```
public IEnumerator LoadAllTheThings()
{
    Func<IEnumerator>[] downloadFuncs = new Func<IEnumerator>[]
    {
        ReadDataCoroutine1,
        ReadDataCoroutine2,
        ReadDataCoroutine3
    };

    BatchDownloader batchDownloader = new BatchDownloader(downloadFuncs);

    yield return batchDownloader.DownloadBatch();

    DoStuffNowThatDataIsAllLoaded();
}

```

Now that is much cleaner, more flexible, and it all works a treat, except that no load starts until the previous finishes. This obviously has a huge effect on load time. So in an attempt to have the coroutines run simultaneously, I'm trying the following:

```
public IEnumerator DownloadBatch()
{
    completedDownloadsCount = 0;

    var activeDownloads = new List<IEnumerator>();
    foreach (var downloadFunc in downloadFuncs)
    {
        activeDownloads.Add(downloadFunc());
    }

    while (activeDownloads.Count > 0)
    {
        yield return null;
        for (int i = activeDownloads.Count - 1; i >= 0; --i)
        {
            var download = activeDownloads[i];
            if (!download.MoveNext())
            {
                onDownloadComplete?.Invoke(totalDownloadsCount, ++completedDownloadsCount);
                activeDownloads.RemoveAt(i);
            }
        }
    }

    onAllDownloadsComplete?.Invoke(totalDownloadsCount);
}

```

Now while this correctly kicks off the coroutines, and runs them "in parallel", any code *after* the last yield in a coroutine is not executed. So in a method like the following:

```
private IEnumerator ReadDataCoroutine1()
{
   yield return WaitForStuffToDownload();

   DoPostDownloadStuff();
}

```

`DoPostDownloadStuff()` is never called.

What am I misunderstanding here about stepping through these IEnumerators? Is there a way to do what I'm trying to, without introducing `StartCoroutine` into the batch downloader? (that is my solution for now, but idealy I'd like to not have to)

# Answer
> 1 votes
For completeness sake, here is the version that uses a passed in MonoBehaviour to run the downloads.

\[Edit\]: I've settled for this solution, I haven't had any success with a version that does not use StartCoroutine. \[/Edit\]

Note also the fix in `ProcessDownload`, for the case where no `onDownloadComplete` delegate was provided (whoops).

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

namespace MB.Other
{
    public class BatchDownloader
    {
        private readonly IEnumerable<Func<IEnumerator>> downloadFuncs;
        private readonly Action<int, int> onDownloadComplete;
        private readonly Action<int> onAllDownloadsComplete;
        private readonly int totalDownloadsCount;

        private int completedDownloadsCount;

        public BatchDownloader(
            IEnumerable<Func<IEnumerator>> downloadFuncs,
            Action<int, int> onDownloadComplete = null,
            Action<int> onAllDownloadsComplete = null)
        {
            this.downloadFuncs = downloadFuncs;
            this.onDownloadComplete = onDownloadComplete;
            this.onAllDownloadsComplete = onAllDownloadsComplete;
            totalDownloadsCount = downloadFuncs.Count();
        }

        public IEnumerator DownloadBatch(MonoBehaviour coroutineRunner)
        {
            completedDownloadsCount = 0;

            foreach (var downloadFuncs in downloadFuncs)
                coroutineRunner.StartCoroutine(ProcessDownload(downloadFuncs));

            while (totalDownloadsCount != completedDownloadsCount)
                yield return null;

            onAllDownloadsComplete?.Invoke(totalDownloadsCount);
        }

        private IEnumerator ProcessDownload(Func<IEnumerator> downloadFunc)
        {
            yield return downloadFunc();

            completedDownloadsCount++;

            onDownloadComplete?.Invoke(totalDownloadsCount, completedDownloadsCount);
        }
    }
}

```

---
Tags: unity, coroutines
---


# Question
Title: Persistent variable for all list members inside a loop called every frame
I'm trying to add a sort of manager to handle all objects in a list and increase a float value that each individual member of the list has given a condition every single frame. I'm having some trouble wrapping my head around the actual code I need though.

So say I've got an OverlapCircleAll or trigger checking for tagged objects in a certain radius. These objects are then added to a List (`foo`).

Then, I go through `foo` with a for loop and declare a float value `x` for each object.

What I need is for each object's `x` to increase when the object is also on another list, `bar`.

So something like this:

```
for (int i = 0; i < foo.Count; i++)
{
     float x;
     //or float x = 0;?

     if (bar.Contains(foo[i]))
     {
          x += 1f;
     }
}

```

The problem is, I can't figure out how to make the value of `x` persist each loop. This function is called in Update() so the idea is that the longer an object is in both `foo` and `bar`, the higher its value of `x` is. I don't know how to save the value of `x` for the next loop though. Ideally something like:

```
for (int i = 0; i < foo.Count; i++)
{
     float x;

     if (lastX != null)
     {
          x = lastX;
     }
     else
     {
          x = 0;
     }

     if (bar.Contains(foo[i]))
     {
          x += 1f;
     }

     float lastX = x;
}

```

But I don't know a) how to save `lastX` for each object in the list and b) set `x` to `lastX` (because for each loop it creates a `lastX`).

I thought about storing each `x` in an array of floats and calling the corresponding `array[i]` to `foo[i]` to get `x`, but if I remove something from the list then the array will become desynchronised with the list and all the `x` values will get muddled up.

What is the correct way to go about this?

# Answer
> 0 votes
The *correct way* is very different at times.

## Change variable scope

In the first part of the code you use `float x;` inside the for loop. This means `x` is in the *scope* of the for loop block, it is recreated every loop.

You can change the scope by declaring x outside of the loop, then it is recreated each (assumed) `Update` call. Since you would want x to persist between calls to `Update` you need to move it outside of it (change scope). This makes `x` a class variable (there are different names for that too) and looks like this:

```
public class Example : MonoBehaviour
{
    private float x = 0f;

    void Update()
    {
        for(...) {...}
    }
}

```

## Keeping values where they belong to

Your second problem is a different story. For each element in your list you need a value x bounded to that element. This strongly suggests that x is part of that element. A good way to solve this is to add the `float x` to whatever type your elements are. If the elements are objects of one of your own classes, you can just add a new variable x to this class. Then access it using

```
foo[i].x

```

If the elements are objects of built in unity classes you can create a *Wrapper class* along the lines of:

```
public class MyElements
{
    public float x;
    public GameObject originalElement; // assumption...
}

```

Then when filling your list/array you fill it with `MyElements`.

All in all this is a basic C#/programming problem which is not related to game development. You can learn how to do this in various tutorials/books or other resources. If you need assistance, update your question or post a new one (preferrably on a suitable stackexchange site).

### Final note

As you realized, it is difficult to properly handle a parallel list of `x`. No question it can be done but it is very error prone.

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


# Question
Title: What category would this asynchronous production economy game fall under?
I'm thinking of getting into game development and my friend and I have this idea for a game. We want to do some research on similar games, and I have noticed that games seem to fall under certain categories like "platformer", "shooter", "racing games" or similar.

Our idea is a multiplayer, mobile game where you and around 4-5 other players are placed in a session.

Every player is given a different role in a market (like a farmer to grow crops, miller to make flour out of crops, baker to bake bread, etc.). The players are supposed to sell goods to each other in order to earn money (or similar). The resources are produced/generated over time, so it's like Travian and other city building games when it comes to stuff happening over time.

You own a production facility (like a farm, mill, etc.) and if you have enough resources/money it produces some good every 10 min (arbitrary time for the example).

This happens even when the user is not playing. Then once in a while, you can check in, put some of your goods up for sale that others can purchase.

So it's a passive loop that simply generates resources every x minutes, and in addition, the players can put up their goods for sale when they feel like it.

But the game is not "infinite". When one of the players reaches a certain goal, the game session ends and the players are ranked (or something, it's still a rough idea).

So in this regard, it's more like Wordfeud or Chess where your next move depends on what the other players do and there is a way to win the game (be it a winning condition or time running out).

So the question is, does this kind of game fall under a specific category that we can research?

# Answer
Games where the core gameplay loop is to just let the game play itself in the background for longer stretches of time and only occasionally returning to the game and making decisions are referred to as "idle games".

Games which focus on trading, managing a company and making business decisions are usually called "tycoon games" or "economy simulations".

When it comes to growing crops, farming games have developed into a whole genre of its own. That genre has often thematic overlap with the two categories mentioned above.

I am looking forward to playing your unique take on these genres.
> 0 votes

---
Tags: game-design, game-mechanics, terminology
---


# Question
Title: Difference between CC BY-SA 3.0 and CC BY 3.0
Comparing CC BY-SA 3.0 and CC BY 3.0, both permits that you share ou even modify the material, under the term that you give credit, link the license and inform in case of any changes.

But in CC BY-SA, if you transform the material, those modifications should be distributed under the same license (or a compatible one, if I got it right). CC BY does not have such a term.

So, what's that mean? If someone got my game under CC BY, can they change it and distribute it under a different license, even a closed-source license?

In the case of CC BY-SA, in the same scenario, this version should be distributed as CC BY-SA as well?

# Answer
> 2 votes
I have recently seen this discussion on the topic: https://discuss.okfn.org/t/reasons-to-use-a-cc-by-sa-licence-instead-of-cc-by/1765

So yes, as your questions suggests, if licensed under CC BY, closed source redistribution is possible. If the license includes a -SA (share alike) clause, the same license has to be used for redistribution.

In both cases, the copyright/credits and indication of changes must stay.

Disclaimer: I am no expert on the subject

This answer provides useful details too: https://opensource.stackexchange.com/a/1718

---
Tags: licensing
---


# Question
Title: Moving camera vertically only after player is too high or too low
In my 2D platformer game, I find it very exhausting for the player if the camera follows the player all the time. So, I looked up for some tricks to make camera movement feel more natural.

The first trick is from James Doyle, where the camera follows a target instead of the player itself. Thus, I can safely use `Mathf.Lerp` for the target, and avoid having jitters.

The second thing I want to do is to limit the vertical movement of the camera. That is, I don't want the camera to move up and down whenever the player jumps. It is dizzying. Instead, I want camera to follow the player only if player is vertically too high or too low.

Here is roughly what I do:

```
\\PlayerController.cs

    public Transform cameraTarget;
    private void FixedUpdate()
    {
       if(Mathf.Abs(transform.position.y - cameraTarget.position.y) > verticalLimit )
         cameraTarget.position = new Vector3(cameraTarget.position.x, Mathf.Lerp(cameraTarget.position.y, transform.position.y, Time.fixedDeltaTime), cameraTarget.position.z);
        if (Input.GetAxisRaw("Horizontal") != 0)
        {
            cameraTarget.localPosition = new Vector3(Mathf.Lerp(cameraTarget.localPosition.x, Input.GetAxisRaw("Horizontal")* cameraAheadAmount, 0.8f * Time.fixedDeltaTime), cameraTarget.localPosition.y, cameraTarget.localPosition.z);
        }

    }

```

The problem for this approach is that whenever the vertical distance between the player and the camera target is less than the limit, the camera does not follow the player anymore. So, what I get is basically a camera following the player from down below, again, all the times.

I thought of using a boolean flag to tell the camera follow the player when vertical limit is exceeded, but then when do I set and unset the flag?

I am new to Unity's `Update()` and `FixedUpdate()` logic, so I cannot somehow design a workaround. Is there a simple way to do this?

# Answer
> 0 votes
Thanks to the comment of DMGregory (once more!), I could find what I wanted in this video.

Instead of making the camera follow the `cameraTarget` using

```
transform.position = new Vector3(target.position.x, target.position.y, transform.position.z);

```

I used the trick that was shown in the video. This is not **exactly** what I wanted, but even a better considering my problem.

```
transform.position = new Vector3(
(transform.position.x * .8f) + (target.position.x * .2f),
(transform.position.y*.95f) + (target.position.y*.05f),
transform.position.z);

```

---
Tags: unity, camera, algorithm
---


# Question
Title: Unity 2019.3 - Player getting stuck on wall
# Problem

I have a wall made with a Tilemap and a Tilemap Collider 2D. Sometimes, when the player jumps against the walls, it seems to get stuck. You do not need to be pressing the directional button, when pressing jump, for this to happen. Just being pressed against the wall, and then pressing the jump button alone, reproduces the error.

# Demo

# What I have tried

I applied a Physics collider to the Walls with friction set to 0. It didnt solve the issue.

# Info that might be relevant to solve this

This is the player controller for the movement. Notice the FixedUpdate method, to see how I control the velocity of the Rigidbody2D.

```
using UnityEngine;
using UnityEngine.InputSystem;

namespace Notan
{
    public enum Direction3 { Left, Right, Still }

    [RequireComponent(typeof(Rigidbody2D))]
    public class PlayerMovement : MonoBehaviour
    {
        [SerializeField, Range(0f, 100f)] float speed = 10f;
        [SerializeField, Range(1f, 20f)] float jumpForce = 3f;

        Rigidbody2D body;
        Direction3 direction;
        bool jumpScheduled;

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

        void Update()
        {
            UpdateDirection();
            UpdateJump();
        }

        void FixedUpdate()
        {
            UpdateVelocity();
        }

        bool LeftPressed() => Keyboard.current.leftArrowKey.isPressed;

        bool RightPressed() => Keyboard.current.rightArrowKey.isPressed;

        bool SpacePressed() => Keyboard.current.spaceKey.wasPressedThisFrame;

        void UpdateDirection()
        {
            direction = LeftPressed() ? Direction3.Left : RightPressed() ? Direction3.Right : Direction3.Still;
        }

        void UpdateJump()
        {
            if (SpacePressed()) jumpScheduled = true;
        }

        // Left is -1
        // Right is 1
        // Still is 0
        int GetHorizontalDirection() => direction == Direction3.Left ? -1 : direction == Direction3.Right ? 1 : 0;

        void UpdateVelocity()
        {
            var velocity = body.velocity;
            velocity.x = GetHorizontalDirection() * speed;
            if (jumpScheduled)
            {
                velocity.y = jumpForce;
                jumpScheduled = false;
            }

            body.velocity = velocity;
        }
    }
}

```

This is the configuration of the players Rigidbody2D

# Unity version

I am using Unity 2019.3.9f1.

# Answer
> 6 votes
This is a common physics engine artifact caused by considering each tile's collider separately. Bennett Foddy illustrates why it happens in this GDC talk. It means your falling object can catch on the lip of the next tile down and be stopped from falling, before the tile to the side pushes it back out sideways, just due to bad luck in the order the collisions were evaluated.

We can fix it by adding a CompositeCollider2D component to the tilemap, and ticking the "used by composite" box on the TileMapCollider2D.

What this does is combine all the physics shapes of all the connected tiles into one big polygon, without internal edges to get snagged on. Since collision with the whole shape is considered at once, you don't run into the same ordering artifacts.

There's a cost to this, which is why Unity doesn't apply it by default. Not every tilemap needs it, but if you want to smoothly slide along continuous walls/floors then it's worthwhile to add.

---
Tags: unity, physics
---


title: What is the use of FBX files in Unity?

text:
# Question
Title: What is the use of FBX files in Unity?
I downloaded the Space Kit from Kenney's assets and imported it to my project. I saw a subfolder called Models, with many files with .fbx extension (e.g. "alien.fbx", "astronaut.fbx", etc.). When I dragged them into the scene, I saw objects with some sub-objects (e.g. alien object with head and legs as sub-objects), but they seem just static objects - they have only renderers. Is this what these .fbx files are all about? Or maybe I am using these assets incorrectly?

# Answer
The use of FBX files in Unity is the same as the use of FBX files anywhere else. Searching for FBX leads you to sites like this one that explain it in detail:

> The Autodesk FBX file format is a popular **3D data interchange format** utilized between 3D editors and game engines. It was originally created as the native file format for Kaydara’s Filmbox motion capture tool.
>
> ...
>
> FBX supports **3D models**, **scene hierarchy**, materials lighting, **animations**, **bones**, **skinning** as well as **blend shapes**.

(So don't discount your ability to find your own answers with a simple search!)

As you can see, this is a format commonly used to store 3D meshes, like the ones used by the MeshFilter/MeshRenderer components in Unity to draw 3D characters.

If you drag just the FBX file containing the mesh into your scene, then Unity knows only the mesh you want to use. It doesn't know what gameplay scripts or physics shapes etc. you might want to use with it, so by default it just creates a game object with a MeshRenderer to draw that mesh. You can add your own additional components to it to customize it further.

Alternatively, asset packs like those from Kenney will often contain both the raw FBX asset that stores the mesh *and* a Unity prefab file that represents an already-configured game object, with the mesh and other relevant components/materials/etc. attached. You still need to keep the FBX file in your Assets folder hierarchy in this case (the prefab references it to get its mesh), but for setting up your scene you'll more often want to use the prefab that's packaged it up for you already.
> 2 votes

# Answer
FBX is indeed a file format for 3d models. Besides mesh data and materials it can also contain an animation rig and animation sequences for that rig.

However, the models from this asset pack do not seem to contain an animation rig. So if you want to animate them, you have two options:

* Import the models into a 3d animation program of your choice and add a rig to them
* Animate them in Unity by adding an Animator component to the root object, creating an animation controller and creating animation clips which manipulate positions and rotations of the sub-objects.
> 3 votes

---
Tags: unity, fbx
---


# Question
Title: Handling rotation interpolation at 180 degrees
I currently have a scene where 3d a gents move throughout a grid, each time they move that can pick a random cardinal direction up,down,left or right. They then rotate to face that direction using `Quaternion.Slerp`. However I noticed there were some edge cases where the agents didn't move at all, and found out the problem was being caused during rotations at 180 degrees. Doing some reading on this I found that Slerp and Lerp dont handle rotations at this degree very well if at all and now I'm at a loss on how to proceed. I tried using `transform.rotateAround()` to rotate the character around the Y axis to the direction, but again at 180 degrees the agents start to just spin in circles forever.

Here's my current rotate code:

```
IEnumerator rotate(){
        while(Quaternion.Angle(transform.rotation,direction) > 0.3){
            var tempRotation = Quaternion.Slerp(transform.rotation, direction, Time.deltaTime * rotateSpeed);
            this.transform.rotation = tempRotation;
            yield return null;
        }
        this.transform.rotation = direction;
    }

```

Heres the code that handles picking where to go:

```
int choice = Random.Range(0,4);
        prevPos = pos;
        if((choice == 0) && pos.x < gs.maxX){
            pos.x += 1;
            direction = Quaternion.AngleAxis(-90,Vector3.up);
            }
            else if((choice == 1) && pos.x > 0){
            pos.x -= 1;
            direction = Quaternion.AngleAxis(90,Vector3.up);
            }
            else if((choice == 2)&& pos.y < gs.maxY){
            pos.y += 1;
            direction = Quaternion.AngleAxis(180,Vector3.up);
            }else if((choice == 3) && pos.y > 0){
            pos.y -= 1;
            direction = Quaternion.AngleAxis(0,Vector3.up);
        }

```

If someone could point me in the right direction on how to handle this gracefully I'd really appreciate it!

# Answer
> 1 votes
Using `Quaternion.RotateTowards()` fixed my issue. Here's the new code:

```
IEnumerator rotate(){
        while(Quaternion.Angle(transform.rotation,direction) > 0.3){
            transform.rotation = Quaternion.RotateTowards(transform.rotation,direction,rotateSpeed*Time.deltaTime);
            yield return null;
        }
        this.transform.rotation = direction;
    }

```

Turns out upon further testing, this does not work. I have tried to modify it so that it will rotate around the Y axis in increments until the angle between agentPosition and the new destination is less than 180 degrees:

```
 IEnumerator rotate(){
          angle = Quaternion.Angle(transform.rotation,direction);
            while(angle > 0.3){
                if(angle >= 180){
                    //There's problem with Slerp at angles >= 180 degrees so manually
                    // rotate around Y axis until Slerp can be used
                    transform.RotateAround(transform.position,Vector3.up,15*Time.deltaTime*rotateSpeed);
                    angle = Quaternion.Angle(transform.rotation,direction);
                }else{
                    transform.rotation = Quaternion.RotateTowards(transform.rotation,direction,Time.deltaTime*(rotateSpeed*90));
                }
                angle = Quaternion.Angle(transform.rotation,direction);
                yield return null;
            }
        this.transform.rotation = direction;
    }

```

This however still does not work.

---
Tags: unity, rotation, quaternion
---


title: Correctly done level scaling?

text:
# Question
Title: Correctly done level scaling?
A lot of role playing games have a system where npcs scale with the player level and become stronger, on the surface it might seem genial but in most games either it doesn't change anything or it makes low levels enemies ridiculously hard to beat or sometimes impossible, like in oblivion.

I came up with the idea of making nps not scale with the level of the player but scale with stats.

For example a level 1 wolf has a base attack that deals 5% of the players maximum HP as damage with each hit, but is mitigated by defense. Therefore the attack will remain consistent in strength even when the player is max level but can be blocked by sacrificing damage to build a lot of denfese or by becoming better at parrying attacks.

Is there any other mechanism I can implement to make the npcs stronger through all the levels without making them ridiculously invincible or giving them one hit mechanics that instantly kill the player?

# Answer
> 4 votes
When enemies scale with the player in a way that the game experience of fighting them stays exactly the same throughout the game, then the question is why you have player progression *at all* in your game. You are really fighting yourself here.

If you want to retain player progression as a **meaningful** reward mechanic but without sacrificing the open world, then there are other ways to achieve that.

* Keep the power-by-level curve flat. Emphasize **horizontal progression over vertical progression**. Avoid giving nummerical advantages. Unlock new abilities and game mechanics instead. These should make the game more interesting and offer new ways to play the game, but shouldn't make the player any stronger than they were before.
* Instead of scaling the world with the player level, **scale the world with player achievements**. The further the player advances the major story arcs of your game, the more dangerous the game world becomes. This still gives you the "rise to continuously increasing challenges" mechanic which RPGs used successfully for decades, but without sacrificing the ability to explore the world in any order.
* Use **dynamic difficulty**. Analyze how successful the player is in combat. When they beat enemies while taking barely a scratch, spawn stronger enemies. When the player struggles, spawn weaker enemies. That way the game does not just adapt to the players nominal power level, but also to their personal skill.
* This is a very bold one, but I have seen it employed successfully in the later games of the Disgaea franchise. **Let the player choose the power level of the enemies**. This only works under some conditions:

1. It must be presented in a way which works within the fiction of your game. If it's an immersion breaker (like a easy-medium-hard selector in your options menu), then players will ignore it. That's why it works in Disgaea. The world of that game is so over-the-top wacky and self-aware that really anything goes.
    2. All rewards must match the risks. If you want the player to go to the limit of their abilities, then you must reward them appropriately for doing that.
    3. The player must not reach the ceiling. Better rewards means that the player's power will also grow faster and eventually out-scale the current power level. This is a feedback cycle you can't easily break. So make sure that either there is no highest power level, or that the player won't realistically be able to reach it before they completed all your story content and explored your whole game world and are now only playing your game to grind for grinding sake (a playstyle which only appeals to a small minority of players).

---
Tags: game-design, rpg, progression
---


# Question
Title: How to rotate libGDX particle to face the direction of movement
I'm creating spark particle effect so I created simple horizontal spark texture.

Here is what I currently have

If I change rotation property, I get this

But i want to rotate particle to face the direction of movement. How can I achieve it?

I use libGDX Particle Editor.

# Answer
> 1 votes
Assuming you're using a Vector2 for your motion (or an x-speed and a y-speed variable), you just need to do a little trigonometry. To find the angle of travel, you take the arctangent of the y-speed divided by the x-speed. Let's call your motion vector "velocity." You can derive the angle by taking atan(velocity.y/velocity.x).

# Answer
> 0 votes
It works with "aligned" option, but you need to set only one value in angle settings chart.

---
Tags: libgdx, particles
---


# Question
Title: How to apply a texture to an object by face rather than the entire object? (unreal 4)
I am trying to apply different textures to a model I have by face rather than the entire object. I am only able to add one material to the entire object. How can I apply different textures to different faces of my model separately? I imported my model from blender. For reference, I have a detailed building with a roof, windows, etc. that is all one object and I would like to texture different parts of the building with different megascans separately. Would appreciate any advise.

# Answer
> 1 votes
**TL;DR**

For various technical reasons we won't go into here, the underlying technology does not allow this by default. That is to say, without modelling the mesh(es) correctly, you will not be able to just drag-drop textures/materials to individual faces. Essentially, your mesh has to be *built* to support that.

**Solution #1: separate models**

Break your model up into separate models for each face. This is tedious, but for a beginner, allows you to drag-drop textures individually to faces. However, you will have to re-assemble each face in its correct position in relation to other faces, in UE4... which could be very tedious depending on the model's complexity.

I wouldn't really recommend this unless your model is *very* simple indeed.

**Solution #2: separate sub-meshes**

Remodel the object by breaking it up in your favourite modelling tool (Blender, Sketchup, 3DS Max, or what have you) into distinct sub-meshes or even distinct objects to be reassembled in UE4.

Remember, sub-meshes will need to be able to be *recognised as distinct by UE4* for this to work, otherwise you will need to use whole separate models (#1); I suggest doing a couple of simple tests first, a few minutes modelling each, using a simple cube to check whether you can get the faces recognised as separate by UE4 on import, before spending hours remodelling your whole building only to find it doesn't work.

Note that with separate objects, you can move each one distinctly (e.g. opening the roof of your building) so for maximum flexibility, this is the best approach to take.

**Solution #3: UV painting & mapping a single model**

Alternatively, keep your existing model and learn UV unwrapping/painting from a single albedo texture, e.g. Quake. This will require you to select seams of your 3D object (just like seems on a piece of clothing) where the surface can be split and opened when you paint the 2D representation, and will then be "sewn up" at runtime.

This is a useful technique to know for games, but generally takes a couple of weeks to learn.

The downside to this solution is that it is harder to animate individual elements discretely, as you have to do what's called *vertex-weighting* in order to perform animations. Not the best solution for buildings, but very good for animated characters.

# Answer
> 0 votes
Select the object/face which you want to be a different material and scroll down to Polygon Material ID, choose a different one. When you do this your Unreal will have a materials list for you.

---
Tags: unreal-4, blender
---


title: Flexible Message

text:
# Question
Title: Flexible Message
I'm looking to create a way to show messages to the player. The message should be able to have pictures, different options and outcomes.

What's the best way to design this?

# Answer
# Anatomy of the message popup

My approach would be to create a UI canvas with a single panel "message box" which can be toggled on and off by a script.

In order for the message box to always arrange all its content vertically it has a VerticalLayoutGroup with "Child-Alignment: Middle Center". I switched off "Force Child Expand" in the vertical layout group because I want the children to control their own size. That way the panel can adjust to the size of the children instead of the other way around.

In order for the panel to adjust its size to the amount of content it holds, I gave it a ContentSizeFitter. Both horizontal and vertical fit are set to "Preferred Size". (You will see a warning "Parent has a type of layout group component" in these content size fitters. This is not a problem in this case, because we are not using "Control Child Size" in the parent).

Both the headline text and the body text of the message also have a ContentSizeFitter with "Horizontal Fit: Unconstrained" and "Vertical Fit: Preferred Size". This makes the text box shrink and grow vertically depending on the amount of text in it. You might also notice that I am using Text Mesh Pro for all text elements. This is just a personal preference. I find TMP to be superior to the default text in several regards. But it works just as well with regular text.

# Adding logic

The buttons don't do anything yet. So I will add a script to the basic panel which has a method to handle button clicks. It takes the number of the button that was clicked as a parameter.

```
using UnityEngine;

public class MessageBoxHelloWorld : MonoBehaviour
{
    public void OptionClick(int optionNumber) {
        switch(optionNumber) {
            case 0:
                Debug.Log("You saved the world");
                break;
            case 1:
                Debug.Log("You conquered the world");
                break;
            case 2:
                Debug.Log("You destroyed the world");
                break;
        }
        Destroy(gameObject);
    }
}

```

As you can see, these just post a message to the console and then makes the message box disappear by destroying it. Adding more game-specific logic to these three options would be up to you.

Then I link each of the three buttons to the method in this script. Remember to add the number of the button to the text input below the method, so it knows which button the player pressed:

# Making it reusable

Ok, now we created *one* message box, but you wanted to have several different messages.

## Prefabs

One option would be to just make this message box a prefab. You can then create a prefab variant of it for every message in your game. This gives you a workflow which is actually pretty similar to scriptable objects: Every message is an asset. But you now have a lot of flexibility regarding the design of each message, because you can add any UI elements you want to a message and change any of their settings. And you even get WYSIWYG editing for messages.

When it comes to implementing the logic for handling the player choices, then you will have to write a separate script for every message. In order to avoid code duplication, you might want to use object-oriented inheritance. Create a base-class which derives for MonoBehaviour and then have the classes which implement the events inherit from that class. That allows you to move common logic to the base class. When you notice that you have a lot of options in a lot of different messages which do exactly the same thing (like closing the message without doing anything), then you could move the onclick-handler method for those buttons to the base class. That way you don't need to program it individually for each message.

## The universal message box

But what if we want to make the message box entirely code-driven? There can be a lot of reasons for that. Perhaps you want some messages which are created entirely from code at runtime. Or perhaps you want to move the messages to an external file. Whatever your reason might be to not use prefabs, this should work for you.

Now we no longer have an unique script for each message, we have a script which can be used to display any message. It needs public method which allows us to set:

* The headline
* The image
* The text
* Any number of buttons and what happens when the player clicks on them.

The programming for this gets a bit more convoluted, but shouldn't be too difficult to implement on your own. The only thing which could get a bit more tricky is implementing the logic for the buttons. One thing you should know about here is how to set the event of a button at runtime. You can do that with the method `button.onClick.AddListener`. That method requires a `UnityAction`. What is a UnityAction? It's a delegate. Or in other words, an object which wraps a call to a method. So you can write code like that:

```
private void CloseMessageBox() {
    gameObject.SetActive(false);
}

/* ... */

    button.onClick.AddListener(this.CloseMessageBox);

```

Or you can create an anonymous method in-place in form of a lambda expression:

```
button.onClick.AddListener(
    () => {
        gameObject.SetActive(false);
    }
);

```
> 0 votes

---
Tags: unity, architecture
---


# Question
Title: Unity 2019.3 - Tilemap colliders 2D + Componsite colliders + Platform effectors
I am using tilemaps to create my own platform game. This is what I had in the first place.

This was working fine in first place, but is an issue. Sometimes, the enemies get stuck while running along the platforms. This was probably due to a similar issue that I had, when the player was getting stuck on the walls. It was solved by adding a composite collider. So I did the same to solve this problem. With the composite, it was looking like this:

This solved the issue too. But now comes the catch. Those elements are also platforms, meaning that I have to add a platform effector. And while this works, there is a small edge case...

If I am in a height where I do not reach the top of the platform, but can reach the bottom part, somehow it can stand on it. This was not happening before using the composite collider 2D.

Why is this happening? How can avoid this issue?

I am using Unity 2019.3.9f1

# Answer
> 1 votes
I find my solution activating an option in the Platform Effector 2D called "Use one way grouping". I have to say that I have no idea what it does, even after reading its documentation, but it seems to have done the trick. If anyone wants to expand on this, and add a more comprehensive answer, I would be happy to know about it.

---
Tags: unity, physics, platformer
---


# Question
Title: How can I add Y-axis/Pitch/Vertical to LineTraceByChannel Raycast with Unreal Blueprints?
I am using LineTraceByChannel to cast a ray and return the name of the object it hits in my game world. It works but I am having trouble working out how to add the Y-axis (Up/Down) value. At the moment the ray is only cast horizontal to the ground, regardless of whether the player is looking up or down.

I tried adding a Pitch variable and getting the y-axis value but haven't worked out how exactly to use this. I followed a tutorial to get this far so any further advice is much appreciated.

This is my blueprint currently

The 'Selection Beam' component is attached to the character mesh, facing forwards:

This is where I get the input from the Mouse Y axis, if that helps:

# Answer
> 1 votes
I found the solution. Double-click your character to edit it. Look at the details panel on the right. Check the box next to 'Use Controller Rotation Pitch'. Thats it, simple!

---
Tags: raycasting, unreal, blueprints
---


title: Reset Polygon Collider Runtime (Unity)

text:
# Question
Title: Reset Polygon Collider Runtime (Unity)
I've created an animation by using different frames. Then applied polygon collider on that object. Problem is that when frame changes in animation, it does not reset collider. I've searched for resetting polygon collider as sprite gets change. One solution I've found is like following : Destroying existing collider & Adding new collider to the object. http://answers.unity3d.com/answers/723811/view.html I've applied this on the object. But it hangs the game. Is there any another way to reset polygon collider from c#.

# Answer
> 1 votes
Use combination on colliders in a child object. Animate enable-disable which collider you need or not in which frame with the main animation.

You can't animate similar collider used over once. But you can use multiple child objects containing similar collider.

# Answer
> 1 votes
I've got an solution for this problem from below link : http://answers.unity3d.com/answers/1135594/view.html

# Answer
> 1 votes
I know this is old but I was recently looking for something like this. Anyway, I figured it out: you could pull the physics shape directly from the sprite, then shove it straight into the polygoncollider, so the code below is all you need to do that. This gives you the benefit of being able to directly customise the colliders directly in the sprite editor custom physics collider tab, and late update means it's always frame perfect.

```
PolygonCollider2D col;
SpriteRenderer spriteRenderer;
List<Vector2> physicsShape = new List<Vector2>();
// Start is called before the first frame update
void Start()
{
    col = GetComponent<PolygonCollider2D>();
    spriteRenderer = GetComponent<SpriteRenderer>();
}
void LateUpdate()
{
    spriteRenderer.sprite.GetPhysicsShape(0, physicsShape);
    col.SetPath(0, physicsShape);
}

```

---
Tags: unity
---


title: Problem with handling key input C#

text:
# Question
Title: Problem with handling key input C#
I am attempting to make a game in C# in windows forms, and need for the character to react to key input. I have implemented a very basic code which changes the position of a picture box on key pressed, and then displays the picture box in a new position:

```
    public Form1()
    {
        InitializeComponent();

        KeyDown += new KeyEventHandler(keyDown);
    }
    void keyDown(object sender, KeyEventArgs e)
    {
        int x = SpriteCharacter.Location.X;
        int y = SpriteCharacter.Location.Y;

        if (e.KeyCode == Keys.Right) x += 1;
        else if (e.KeyCode == Keys.Left) x -= 1;
        else if (e.KeyCode == Keys.Up) y -= 1;
        else if (e.KeyCode == Keys.Down) y += 1;
        else if (e.KeyCode == Keys.Escape) Close();

        SpriteCharacter.Location = new Point(x, y);
    }

```

The problem you can probably immediately spot is that this script cannot handle user input if two keys are pressed at the same time. E.g. if you press right and down, the character will not move diagonally, but will either go right or down, depending on which key was pressed last.

What would be a more advanced way to handle key input, to make something like this possible? Is these anything I could read up on?

# Answer
> 1 votes
The main problem here is that you don't have some sort of game loop. You record the keypress, but not the continious keydown (thus, if the letter 'A' is pressed for 10 seconds, only 1 event is triggered). Now this could be expected behaviour (only move one square one keypress at a time). With a gameloop you can have the object moving independant of the keypress events.

Here is a solution: Create a moveX and a moveY global variable.

Add the event **OnKeyDown**: if the Left key is pressed, set the moveX to -1, if the Right key is pressed set the moveX to +1. Do the same for the vertical movements.

Add the event **OnKeyUp**: if the Left key is let go, set the moveX to 0, same for the other keys.

What you now have, is a moveX and moveY that hold the direction the player wants to go.

Now, add a **timer** that elapses every 1/60th second (for 60 frames per second). When that timer expires, update the gameobject position according to the set moveX and moveY variables. This timer is effectively providing you a gameloop, in which you can do many other things; such as moving the enemies or other things that need to happen continiously.

# Answer
> 0 votes
When you use `else` you are preventing two `if` blocks to be evaluated at the same time. For your code you should use `else` only for the opposing axes, for example:

```
if (e.KeyCode == Keys.Right) x += 1;
else if (e.KeyCode == Keys.Left) x -= 1;

if (e.KeyCode == Keys.Up) y -= 1;
else if (e.KeyCode == Keys.Down) y += 1;

if (e.KeyCode == Keys.Escape) Close();

```

# Answer
> 0 votes
If you wanted to know if the user held CTRL, SHIFT or ALT down whilst pressing another button then you could check the Modifiers:

```
            if(e.KeyCode == Keys.Up && e.Modifiers == Keys.Control)
                Debug.WriteLine("Up and Ctrl");

```

But your question is about right and down, if the user presses both at the same time one will trigger first and then the other, which will result in a diagonal move but via two moves instead of one. Is that what you want to achieve...a diagonal move in one? If so I'd use something other than the arrows, ideally the number pad if that's an option, then 3 is diagonal down/right in one move, 6 being move right.

The KeyDown event will only give you one key down at a time, unless the 'other' key is a modifier such as CTRL, SHIFT or ALT. So unless you want to write in some kind of delay and also hook into the KeyUp event (so you know they have released the key) so that...if the user clicks right and down fast enough then they move diagonally...your best bet is to have different keys to move diagonally...assuming that's what you want to achieve...

# Answer
> 0 votes
What you can do is create separate timers for each movement instance.

For example, for going up, down, right and left, you can create a timer that goes like:

```
private void up_Tick(object sender, EventArgs e)
        {
            //this makes the player go up
            player.Top -= 3;
        }
 private void down_Tick(object sender, EventArgs e)
        {
            //this makes the player go down
            player.Top += 3;
        }
 private void left_Tick(object sender, EventArgs e)
        {
            //this makes the player go left
            player.Left -= 3;
        }
 private void right_Tick(object sender, EventArgs e)
        {
            //this makes the player go right
            player.Left += 3;
        }

```

After creating the timers, you can create key up and key down events to handle the movement with keys -

```
private void yourFormName_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.W)
    {
    \\this starts the timer to go up and if you press the W key then the player goes up
    up.Start();
    }
    if (e.KeyCode == Keys.S)
    {
    \\this starts the timer to go down and if you press the S key then the player goes down
    down.Start();
    }
    if (e.KeyCode == Keys.D)
    {
    \\this starts the timer to go right and if you press the D key then the player goes right
    right.Start();
    }
    if (e.KeyCode == Keys.A)
    {
    \\this starts the timer to go left and if you press the W key then the player goes left
    left.Start();
    }

}

```

Hope this helped!

---
Tags: c#
---


title: Security in Unity

text:
# Question
Title: Security in Unity
I have a public int variable in my game for number of coins. It's public because it must be accessed in other scripts and scenes (for when you want to buy levels, character,etc). I want to use anti-cheat toolkit and as I'm new to unity I don't know whether it's safe.

# Answer
Public or private doesn't matter to cheaters.

Access control modifiers like that are just a fiction, a polite agreement between coders and the IDE to pretend that private members are inaccessible, to make the program easier to reason about.

It's trivial to work around them as a coder if you want to do so, and for hackers they're all just bytes in memory, as easy to read or change as any others.

When thinking about security in a client-side application like a game, it's important to remember: "Your code is in the hands of the enemy"

No amount of obfuscation or added complexity in your game client code will stop a determined hacker. They can decompile your code and remove or neutralize whatever extra checks you've put in place, or snoop the information out of system memory.

The *only* way to be truly secure is to put the sensitive information on a server that you or a trusted party controls, behind a strict set of rules on what transactions can be done on it. (eg. If it's entitlements to in-app purchase content, validate that they're only ever unlocked when spending the required amount of currency or a valid & unused voucher code)

Everything else just gives the hackers a slightly higher hurdle to vault. If your game gets popular, trust that a skilled hacker *will* vault it, and turn their exploit into a script that even unskilled hackers can use to accomplish the same feat.
> 3 votes

---
Tags: unity, software-engineering
---


# Question
Title: Unity: Render 1st Texture to 2nd Texture
I want to pass the first texture through a shader and render it to a second texture.

The actual task is bit more complicated, as I then want to render the second texture back to the first texture also using a shader.

I have a terrible solution at the moment involving two cameras, two quads and two materials and two rendertextures. The output of Cam1 is rendered to Texture1 used in Material1 applied to Quad1. Quad1 is in the view of Cam2 rendered to Texture2 used by Material2 applied to Quad2. Quad2 is of course in the view of Cam1. I then have to alternate turning on and off the Cameras and the Quads. It works, but the solution is terribly complicated.

Please tell me there is a better solution. With WebGL I could do this simply by swapping source and target for the shader. I'm sure this can be done in Unity too, but I have no clue what to look for.

# Answer
Turns out it's simple, if you get great advice from DMGregory.

```
Graphics.Blit(sourceRenderTexture, targetRenderTexture, unlitMaterial, -1);

```

is the answer. I'm using an Unlit Material with Shader and that's it. If you need to set a sprite to your rendertexture, this also works with Blit

```
Graphics.Blit(sprite.texture, renderTexture);

```
> 1 votes

---
Tags: unity, rendering, rendertexture
---


# Question
Title: Unity Performance: Recycling Pooled Objects OR Re-Instantiating?
* Re-using pre-instantiated objects in a pool.
* Destroying then re-instantiating objects in a pool.

Both pools are limited.

When creating loads of objects which is better for performance?

# Answer
> 3 votes
When you instantiate a new object, a whole bunch of stuff needs to happen:

* The engine has to allocate memory to hold its native/unmanaged representation (the guts of the object inside the engine itself)
* The .Net runtime has to allocate memory to hold its managed representation (the parts visible to your C# scripts, and any C#-based components), and register them with the garbage collector (GC alloc)
* The new objects need to be constructed in that allocated memory.
* The deserializer has to copy the data from the prefab you're instantiating into this new memory space, and wire-up any internal references between objects/components in the new copy.
* The new object needs to be added into the engine's various update lists for scripting callbacks, physics, rendering, etc.
* Components' Awake, OnEnable, and Start methods need to be run.

This takes time. Not a lot individually, but it adds up. When you Destroy an object, all this work needs to be undone, and that takes time too.

The "GC alloc" bit also means you're using up some of your garbage collection headroom. Once you run out, the runtime puts your scripts on hold to do a full mark & sweep pass and clear out any unused objects, and compact the used memory to free up space. This can cause a noticeable hitch in your framerate, so it's best if we don't trigger the garbage collector too frequently in the thick of play.

When you keep objects in a pool, deactivate them instead of destroying them, and re-activate them to recycle them instead of spawning new ones, you get to skip doing almost all of this work, and you create no new work for the garbage collector.

So pooling/recycling is definitely more efficient than instantiating/destroying, for objects that you're spawning & despawning frequently. Don't worry about it for objects you spawn only a handful of times in your level, but things like bullets or particle effects that you use by the dozens or hundreds, that might spawn & despawn every few seconds, are prime candidates for this kind of optimization - especially if you're targeting mobile.

---
Tags: unity, performance, object-pools
---


# Question
Title: How do I not let my explosion go through the walls like bomberman?
I have this problem that I want to fix. Every time I place a bomb it goes pass through the wall even if I added a Layermask to tell if it's a wall or not.

##

```
public LayerMask levelMask;
public GameObject explosion;

void Start()
{
    Invoke("Explode", 1f);
}

void Explode()
{
    Instantiate(explosion, transform.position, Quaternion.identity);

    StartCoroutine(CreateExplosions(Vector2.up));
    StartCoroutine(CreateExplosions(Vector2.down));
    StartCoroutine(CreateExplosions(Vector2.right));
    StartCoroutine(CreateExplosions(Vector2.left));

    GetComponent<SpriteRenderer>().enabled = false;
    Destroy(gameObject, .3f);
}

```

---

```
private IEnumerator CreateExplosions(Vector3 direction)
{

    for (int i = 1; i < 3; i++)
    {

    RaycastHit hit;

    Physics.Raycast(transform.position + new Vector3(0,.5f,0), direction, out
    hit, i, levelMask);

    if (!hit.collider)
    {
    Instantiate(explosionPrefab, transform.position + (i * direction),
    explosionPrefab.transform.rotation);
    }
    else
    {
    break;
    }
    yield return new WaitForSeconds(.05f);

    }
}

```

# Answer
I just fixed my problem.

```
//I changed the vector to vector2
private IEnumerator CreateExplosions(Vector2 direction)
{

    for (int i = 1; i < 3; i++)
    {
        //I made the 'RaycastHit2D hit' to be the return value of 'Physices2D.Raycast'
        //and sending the information to the 'hit'.
        //I also casted it to vector2 because transform.position was
        //returning a vector3
        RaycastHit2D hit = Physics2D.Raycast((Vector2)transform.position + new
        Vector2(0, .5f), direction, i, levelMask);

        if (!hit.collider)
        {
            //I also casted it to vector2 because transform.position was
            //returning a vector3
            Instantiate(explosion, (Vector2)transform.position + (i * direction),
            explosion.transform.rotation);
        }
        else
        {
            break;
        }

        yield return new WaitForSeconds(.05f);
    }
}

```
> 1 votes

---
Tags: unity, c#, collision-detection, physics, raycasting
---


# Question
Title: How can I prevent a component from handling collision events?
In Unity, I can set the `enabled` flag of a component to `false`, and this prevents Unity from running the `Update` method of the component. However, Unity still runs other methods of the component, such as `OnTriggerEnter2D`. Is there a way to completely disable a component (without removing it), such that it does not get any events at all?

Of course I can manually add a flag to my component, and check this flag from within the event handlers, but I would like to know if there is a built-in solution.

# Answer
The engine will always send these collision messages, by design:

> Collision events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.

If you don't want your script to process the event when it's disabled, that's in your control to express in your script:

```
void OnCollisionEnter(Collision collision) {
    if(!enabled) return;

    // ...the rest of your collision response goes here.
}

```

Philipp's recommendation to put the script on a separate object you can deactivate as a whole is also a good one, if you need a more blanket-level shutdown rather than surgically disabling just specific handlers.
> 2 votes

---
Tags: unity, events
---


# Question
Title: How do I check if there is already an object in this scene with the same name upon reloading the scene?
If the title wasn't clear enough (I don't really know how to explain it), basically I have an Audio Manager that is DontDestroyOnLoad. I also have a pause menu, that takes me back to the main menu, and in the main menu, I can reload the scene again. The problem is, upon reloading the scene, multiple copies of AudioManager is created in DontDestroyOnLoad, and I don't know how to solve it. My AudioManager script to give you a reference (only the important parts):

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

public class AudioManager : MonoBehaviour
{
    #region Instances
    private static AudioManager instance;
    public static AudioManager Instance
    {
        get
        {
            if (instance == null) //if instance doesn't exist, find an AudioManager
            {
                instance = FindObjectOfType<AudioManager>();

                if (instance == null) //if instance still doesn't exit, then it will create a new one
                {
                    instance = new GameObject("Spawned AudioManager", typeof(AudioManager)).GetComponent<AudioManager>();
                }
            }

            return instance;
        }
        private set
        {
            instance = value;
        }
    }
    #endregion

    #region Fields
    //the audio source can only play one looping sound at a time
    private AudioSource musicSource;
    private AudioSource musicSource2; //purpose of having 2 musicSources is that we can use them to achieve effects like CrossFade
    private AudioSource sfxSource;

    private bool firstMusicSourceIsPlaying;
    #endregion

    private void Awake()
    {
        //Make sure we don't destroy this instance
        DontDestroyOnLoad(this.gameObject);

        //Create audio sources, and make them as references
        musicSource = this.gameObject.AddComponent<AudioSource>();
        musicSource2 = this.gameObject.AddComponent<AudioSource>();
        sfxSource = this.gameObject.AddComponent<AudioSource>();

        //loop musicSource
        musicSource.loop = true;
        musicSource2.loop = true;
    }

```

If you are reading this, thanks for taking your time and try to help me!

# Answer
> 1 votes
This is often handled by having the object check for an existing instance of itself in Awake, and self-destructing if one already exists:

```
private void Awake()
{
    // If there's already a copy of me, self-destruct and abort!
    if(instance != null && instance != this)
    {
        Destroy(gameObject);
        return;
    }
    /* // In your current code, the instance is populated via a static getter,
       // but you could instead choose to populate it here in Awake:
    else
    {
        instance = this;
    }
    */

    // Otherwise, keep me around forever and do my other Awake stuff...
    DontDestroyOnLoad(gameObject);

    // ...other Awake stuff goes here...
}

```

Personally though, I like another approach:

* Put your long-lived manager objects in a scene of their own.
* Load that scene additively when they need to be created for the first time.
* When you need to change/reset levels, unload the previous level scene and load the next, additively.

This won't destroy or recreate the objects in your manager scene, which get to stay around unaffected the whole time, until you choose the right time to unload them.

This means no duplicate objects that need to fight for dominance, and no inefficiency of spawning copies only to destroy them.

---
Tags: unity, audio
---


# Question
Title: Unity - Pixels, Units, Sprites and Pixels per unit - Setting a relationship between sprites and screen size
I don't get how units and pixels work in Unity. For instance:

Here I have a camera with size 5. This means that there are 5 units from the center of the camera to either the top or bottom border. This means too that the total height of the camera are 10 units.

At the same time we have a "Display 1" set to 1920x1080. If the height of the screen in pixels is 1080, and there are 10 units, this would mean that every unity will be 108 pixels, right?

On the other hand, if I set the resolution of "Display 1" to 2560x1440, this would mean that every unit would draw 144 pixels, right?

Now, I have my sprite, a 35x37 pixels image.

Since I want my game to be a pixel art, I want the pixels to be more prominent. To do this, I would like to upscale it 4 times, meaning that instead of 35x37, I want to draw 140x148 pixels, right?

But if I go to the settings of my sprite, I find the following settings:

There is a field calles "pixels per unit". Which means that I have to manually the calculation between the resolution of my display and the size of my camera. So in this case set the "Pixels per unit" to 108.

But then, if I want to allow to have different resolutions in my game, say 1440p, this means that the "Pixels per unit" for my sprite must be 144, instead of 108. Since this setting is not automatic, and cannot be changed on runtime (I think), does this mean that I have to duplicate the same sprite and set every file with different PPU, depending on all the resolutions I want to support, and then in runtime select the appropiate sprite? Because that doesn't seem right.

Is there some concept I am not properly grasping about Units and Pixels?

# Answer
Generally you want to keep your Pixels per Unit setting constant for a set of assets you use together. It's the conversion factor between the texture resolution and the coordinate space of your gameplay logic.

For example, if you're making a tile-based game with 32x32 tiles, a PPU of 32 would make good sense. Then it's easy to write say a dash move that travels 3 tiles: it moves 3 units in world space. If you later go and make an "HD" version of your game with 64x64 tiles, you can replace the assets with PPU 64 versions, and none of your gameplay logic has to change, because the logical coordinate system is still the same: 1 unit = 1 tile.

To adapt to different display sizes, the main thing you want to change is your camera.

Let's start with your 1920 x 1080 example with camera size 5, and call that our baseline. As you worked out, that means each unit of world space maps to 108 display pixels. To draw the character at a 4x scale, 140x148 pixels, then it needs to be 1.370370... world units tall. That's a PPU of 27.

Okay, now let's lock-in that PPU, and use it for all our assets, so everything has the same degree of "chunkiness" to its pixels for stylistic consistency, at a constant 4x display-pixel-to-source-texel ratio, a nice integer that helps us avoid rounding artifacts.

Now if we display on a 2560 x 1440 monitor without changing anything, our formerly 148-pixel-tall character is now drawn 197.333 pixels tall, a 5.33333 pixel-to-texel ratio, and that trailing decimal is going to cause unsightly distortions.

But we don't want to change the logical size of all our game content by changing the PPU - then we have to re-calibrate all the distances, velocities, and forces used in our gameplay scripts, so it would be a terrible mess.

So we change the camera. 5.3333 is pretty close to 5, so let's see what happens when we adjust our camera cropping to make our pixel-to-texel ratio that nice integer:

```
5 pixels per texel = 1440 display pixels of screen height / (camera size * 2 * 27 PPU)

```

Rearranging:

```
camera size = 1440 display pixels of screen height / (5 pixels per texel * 2 * 27 PPU)
            = 5.333333...

```

Running the math with these numbers, we get a camera size of 5.333333. Increase your camera size to that value, and boom, we're back to a nice neat integer pixel-to-texel ratio, without changing any of our texture assets or gameplay scripts.

This means that the player on the 1440 screen sees slightly more area than the player on the 1920 x 1080 version, just because of how integer division works when we want to display whole, non-fractional pixels.

For many games, a 6.667% change in the display area is trivial and won't alter gameplay, so we can ship with as simple a solution as this.

For other games, seeing that extra 0.6 of a world unit is a problem: it breaks the intended framing of the level, or lets the player glimpse things they shouldn't, like a secret that was supposed to be hidden juuuust off-screen. For cases like that, there are two main things you can do:

1. Add letterboxing or a frame to keep the cropped view of your gameplay the same (on mobile games, this is often a great place to stick on-screen controls or stat displays)
2. Include an alternative set of assets that are painted at a different resolution and use a different PPU, as described in this article.

For this example, you'd make an alternate set of assets with a PPU of 36 instead of 27, to match the 4/3 ratio between 1440 and 1080, so you can display it at the same 4 display-pixels-per-source-texel as your 1080p version. Your alternate character sprite would be 49 texels tall, so it still boils down to the same logical size in your game, and no gameplay logic needs to change.

You don't need to create new assets for every screen size, just ones that force you into a fractional scale that you can't solve with camera sizing/framing. So for instance, once you have these alternate assets for 1440p, you can support 720p with the very same setup, just at 2x scale instead of 4x.

But again, many games won't need to go to those lengths. If you design your game such that a ~6% change in the view area doesn't ruin the gameplay, or find an art style that lets you frame it in a way that's visually pleasing, then you can get by without the complexity of full asset swaps.

See also this previous answer where I look at this from another angle, reviewing options for scaling a game up from 720p to 1080p.
> 4 votes

---
Tags: unity, resolution, pixel-art
---


title: How to make a character sit in Unity?

text:
# Question
Title: How to make a character sit in Unity?
So I've got the animation, it has root motion but activating it in the settings doesn't seem to do much.

What would be a good **optimized** way to have the character sit on the stool with the animation matching the movement? Would I need to do it through code?And if that's the case, could I specify in which frame do the movement? Or add a second animation that is in charge of Root Motion?

I know either of these two options I give could work but I'm checking to see if there is a better way or if I'm missing something here.

Thanks!

**EDIT**: Following DMGregory's comment I disabled the collider to see if it improved... it did change, but it isn't much better:

**EDIT 2**: This is how the animation preview looks like (what I'm expecting)

Then I just hold the last frame while they're sitting and play the animation backwards for when they're getting off - this is just while I get it to work.

# Answer
This video helped me a lot: https://youtu.be/7JEoG4xubP8?t=1319

So what I did was move the character through the script doing a lerp of translation and rotation and turning off all the root motion options EXCEPT in the Animation tool tip of the FBX, scrolling off to almost the end of it and under Motion set the Root Motion Node as `<Root Transform>`.
> 2 votes

---
Tags: unity, animation
---


# Question
Title: Why do some games use such misleading ads?
Here is an image from 9GAG that shows how misleading ads for Gardenscapes are

The ad looks like simpler game. Why don't they just make games based on those ads? Why advertise a game that's totally different from what the ad is for?

# Answer
> 2 votes
I did not talk to the people who made the marketing campaign for that game. I do not even know that game. I have not even seen this advertisement in the wild. So I can only guess wildly what their motive might have been to do this advertisement campaign.

But my theory is that the concept for the left game is:

* Easy to represent in marketing - the customer immediately sees (or has a theory) how the game works and is intrigued by it.
* Difficult to develop - designing puzzles like that takes a lot of time. You need a smart game designer to come up with the puzzles and a good artist to create the assets for it. But such puzzles have no replay value, so you get relatively little playtime out of all that effort.
* Difficult to monetize - there is no good obvious way to add microtransactions to such a game. And as a game which consists mostly of content, it's not good for long-time player retention either.

The game on the right, on the other hand:

* Hard to represent in marketing - it looks really complicated and cluttered. The customer can't make any sense of that screenshot. They have no idea what's the goal of the game or how it plays. Some customers will recognize it as a match-3 game, but now you are facing the difficulty to show how your match-3 game is different from all the others they already played.
* Easy to develop - Match-3 puzzle games are a tried and true formula. They are not difficult to make, the graphical assets are mostly static images and yet they provide hours upon hours of gameplay.
* Easy to monetize - Candy Crush has already figured out how to turn a match-3 game into a gold mine, so you can simply copy their monetization strategy.

So what we have here is one game idea which is easy to promote but not profitable and one game idea which is profitable but not easy to promote. This is a problem. So why not make the second game, but use screenshots from the prototype of the first game to trick people into playing it? Probably because it is unethical and might even violate laws about misrepresenting a product, but it's profitable nevertheless.

---
Tags: advertisements
---


# Question
Title: How to start a coroutine that will finish after the object is destroyed
I have a simple game in which the player can collect power-ups. Each power-up gives the player a temporary advantage for several seconds. The power-up should disappear immediately after the player collects it.

My current implementation of the power-up logic is:

```
[SerializeField] float duration;

private void OnTriggerEnter2D(Collider2D other) {
    if (other.tag == "Player") {
            StartCoroutine(GiveTemporaryPowerup(other.gameObject));
            Destroy(gameObject);
    }
}

private IEnumerator GiveTemporaryPowerup(GameObject gameObject) {
    gameObject.ActivatePowerupFunction();
    yield return new WaitForSeconds(duration);
    gameObject.DeactivatePowerupFunction();
}

```

This does not work: the powerup is activated but not deactivated. Deactivation does work when I remove the line "Destroy(gameObject)". However, without this line the player can collect the same powerup several times, which I want to avoid.

I tried to put the coroutine on a component attached to the player object (rather than the power-up object), but this did not solve the problem - deactivate was not called. Here is the updated code on the power-up:

```
private void OnTriggerEnter2D(Collider2D other) {
    if (other.tag == "Player") {
            var playerComponent = other.gameObject.GetComponent<Player>();
            StartCoroutine(playerComponent.GiveTemporaryPowerup(duration));
            Destroy(gameObject);
    }
}

```

And the code on the Player component:

```
public IEnumerator GiveTemporaryPowerup(float duration) {
    ActivatePowerupFunction();
    yield return new WaitForSeconds(duration);
    DeactivatePowerupFunction();
}

```

What is the correct way to implement this?

# Answer
> 0 votes
My mistake was that I thought that StartCoroutine is a global function, and only the coroutine itself should belong to a living object. In fact, it is the other way around. The following code solves the problem:

```
[SerializeField] float duration;

private void OnTriggerEnter2D(Collider2D other) {
    if (other.tag == "Player") {
          other.GetComponent<Player>().StartCoroutine(GiveTemporaryPowerup(other.gameObject));
          Destroy(gameObject);
    }
}

private IEnumerator GiveTemporaryPowerup(GameObject gameObject) {
    gameObject.ActivatePowerupFunction();
    yield return new WaitForSeconds(duration);
    gameObject.DeactivatePowerupFunction();
}

```

---
Tags: unity, coroutines
---


# Question
Title: How to choose what to use in Java: Enums or Objects?
I'm in a dilemma over using Enum Types or using class objects in that particular part of my java project.

Let's suppose I have an array where I constantly add and remove things from it, but I also render textures from that array via accessing the texture with an enum type from its class like:

```
public static Texture requestTexture(Type type){
    if(type == Type.One){
        return textureOne;
    }
}

```

`// can be improved with hashmap`

I wonder if I can use classes instead of enums? Will it slow down my performance since I will be constantly creating new objects and deleting them since they leave the stack, but on the other hand, it will be more cleaner and structured code?

# Answer
Given that your proposed logic would typically look something like this...

```
public static Texture requestTexture(TextureType type)
{
    switch(type)
    {
        case TextureType.Undefined:
            return new Texture(); //class type used to create object
        break;
        case TextureType.Small:
            return new Texture(32,32); //class type used to create object
        break;
        case TextureType.Large:
            return new Texture(128, 128); //class type used to create object
        break;
    }
}

```

...you won't have a class instance (object) by the time you have to make this decision. This is what enum types are typically used for: rapidly switching on some minimal data item. That is exactly what you have to do here, *in order to be able* to construct from the associated class type.

Think of the enum as a phone book; the `switch` / `case` block as an old-fashioned telephone switchboard - and the object like the person you are trying to call; while the class is just a plan for creating that specific callee (your mom, your uncle, or your best friend).

`enum`s are not at all the same as classes, which provide program logic; instead they are small data-related types used to define valid options. A common example of enum use is when you are asked to choose your country when signing up for webmail account; the entry is not the country, nor is the list of entries; instead it is like a telephone directory, representing a list of options in the real world. You just can't pick or enter a country that doesn't exist in that list.
> 1 votes

---
Tags: java, performance, software-engineering
---


# Question
Title: how do i make it so you can hold down a key to keep moving
so I am trying to make my first working game and it is not working. There is no error message, it just does nothing. I want the box guy to move right or left when you hold down left or right arrow key, it was working before, but you could not hold it, you would have to spam the button. now nothing happens can u help.

```
import pygame, sys
import time
from threading import Thread
pygame.init()
display_width = 800
display_height = 600
green = (0, 255, 0)
blue = (0, 0, 255)
greenblue = (0, 200, 255)
black = (0,0,0)
white = (255,255,255)
pygame.init()
x =  (display_width * 0.45)
y = (display_height * 0.8)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
clock = pygame.time.Clock()
pygame.display.set_caption('game1(name later)')
skyimg =  pygame.image.load('sky.png')
boxImg = pygame.image.load('Bbigbox.png')
x_change = 0
leftpress = False
rightpress = False
def loadbox(x,y):
    gameDisplay.blit(boxImg, (x,y))

px = 40

py = 40

def new():
    if event.type == pygame.QUIT:
                pygame.quit()
                pg.quit()
                sys.exit()
                stop()
def keycheck():
    global px
    if leftpress == True:
        px -= 5
    elif rightpress == True:
        px += 5

def main():
    global px
    global leftpress
    global rightpress
    while True:

        for event in pygame.event.get():

            if event.type == pygame.KEYDOWN:

                        if event.key == pygame.K_LEFT:
                            if px < 800 and px > 0:
                                leftpress == True
                        elif event.key == pygame.K_RIGHT:
                            if x < 800 or x > 0:
                                rightpress == True

                        if event.key == pygame.K_SPACE:
                            print("test")

            if event.type == pygame.KEYUP:

                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:

                    leftpress = False
                    rightpress = False

        keycheck()
        gameDisplay.fill(greenblue)
        loadbox(px, py)
        pygame.display.update()
main()

```

pictures and code: https://drive.google.com/open?id=1-uu4wk2JMG-OjSHoXBkBtuHOxq1GEBO1

# Answer
> 0 votes
I fixed it this is the part of my code I changed

```
                if event.key == pygame.K_LEFT:

                    xchange += -10
                elif event.key == pygame.K_RIGHT:
                    xchange += 10

        if event.type == pygame.KEYUP:
            xchange = 0

    print(xchange)
    px += xchange

```

---
Tags: python
---


# Question
Title: Improving Rigidbody collision between real-time movable object and other Rigidbodies
I have a cube that has been scaled to be rectangular (controlled by a remote Raspberry Pi gyro/accelerometer/magnetometer) and am translating its orientation into Unity via calls to `transform.localEulerAngles = new Vector3(...)`. This works wonderfully (the cube object modeled to be a Pi rotates perfectly), however now I'm running into issues with the actual physics.

GIF of successful roll

Initially the ball will land on and roll around the Pi object, however when I start to increase the speed of my movements the ball will sometimes fall through the Pi.

The cube has a Rigidbody (no gravity, is kinematic) and Box collider (not triggered), and the sphere has a Rigidbody (has gravity, not kinematic) and Sphere collider (not triggered) attached. I've tried varying the collision detection from discrete to continuous on both objects and have noticed similar behaviors.

The intent is to turn this into a marble maze type game, and the issue that I have is similar. If I roll the ball into the joint between a wall and the floor (both stretched cubes), rotate it down, and then rotate it up, the ball will fall through the joint. I have the same movement code attached to the `GameArea` object below. Again, same issue with various types of collision detection applied.

My assumption is that this is a quickness of movement thing, as the cubes overlap each other (there's not a space for the ball to sneak through).

For reference, in the physics colliders section of the project preferences, all relevant layers are supposed to collide with each other. I don't mind getting into code-based collision detection, but this seemed fairly trivial for Unity to take care of so I was wondering if I was missing something obvious.

# Answer
> 1 votes
If you have an object with a Rigidbody, you should avoid moving it with its Transform.

That includes setting `transform.position`, `transform.rotation`, `transform.localEulerAngles`, or calling `transform.Translate`, `transform.Rotate`, etc. All of these rip the object out of the physics engine's control, and are treated like an instantaneous teleportation - allowing it to skip over collisions that should have happened in-between.

Basically, treat your Transform as read-only. Any and all changes should be applied via the Rigidbody.

You can replace your localEulerAngles code with something like...

```
Quaternion targetOrientation = transform.parent.rotation * Quaternion.Euler(inputEulerAngles);

```

(You can skip the multiplication by the parent rotation if you're already at the root level of the hierarchy)

Then you can either apply that rotation directly:

```
rigidbody.MoveRotation(targetOrientation);

```

Or, in FixedUpdate, you can apply a torque to reach that target for the next timestep:

(If I recall correctly, you'll need to make your body dynamic rather than kinematic for this approach, but it can play nicer with the rest of your physics world)

```
// Compute the change in orientation we need to impart.
Quaternion rotationChange = targetOrientation * Quaternion.Inverse(rigidbody.rotation);

// Convert to an angle-axis representation.
rotationChange.ToAngleAxis(out float angle, out Vector3 axis);
// I can't remember the range of the returned angle, so you might not need this.
if (angle > 180f)
    angle -= 360f;

// If you need to, you can enforce a cap here on the maximum rotation you'll
// allow in a single step, to prevent overly jerky movement from upsetting your sim.
// angle = Mathf.Clamp(angle, -90f, 90f);

angle *= Mathf.Deg2Rad;

// Compute an angular velocity that will bring us to the target orientation
// in a single time step.
var angularVelocity = axis * angle / Time.deltaTime;

// You can reduce this parameter to smooth the movement over multiple time steps,
// to help reduce the effect of sudden jerks.
float catchUp = 1.0f;

// Apply a torque to finish the job.
rigidbody.AddTorque(catchUp * angularVelocity - rigidbody.angularVelocity, ForceMode.VelocityChange);

```

Note that even when we do our best to give the physics engine full control over the situation, rotational collisions are kind of hard to detect efficiently. If you have a long skinny object, a small rotation can make its distant end jump all the way from one side of an object to another. So other things we can do to reduce tunnelling:

* Expand the collider of your floor and walls to give them some extra padding out to the sides and underneath. You can use layers or `Physics.IgnoreCollision()` to make sure your expanded floor collider and wall colliders don't interfere with one another if they're not part of the same body (not sure if you move them as one unit, or if you have a moving floor inside stationary walls)

As long as your ball stays on top, this extra padding won't be noticeable to the player, but it can give the collision resolution system more margin for error so it can still determine the side to push the object out through. The thinner your object is, the more chance that a collision ends up slightly past the middle plane and gets pushed out the wrong side.

This change is very cheap, and surprisingly robust, so I'd make it your first option.
* Set the ball's collision detection mode to Continuous Dynamic, and the moving part of the maze to use Continuous Speculative collision detection.

These modes are much more expensive than the default discrete mode, but they catch more potential tunnelling cases for fast-moving objects. If you have only a small number of colliders interacting, it might not be too heavyweight.
* Shorten your fixed timestep, so you simulate physics more frequently at smaller steps, making it less likely for one object to teleport through another.

This too is expensive, so be sure to profile here.

A combination of these strategies should let you tame your rotational collisions and keep your ball behaving plausibly.

---
Tags: unity, collision-detection
---


title: What is the use case for slerp in 2D?

text:
# Question
Title: What is the use case for slerp in 2D?
When searching for slerp, I get this text:

> Slerp is shorthand for spherical linear interpolation, introduced by Ken Shoemake in the context of quaternion interpolation for the purpose of animating 3D rotation.

As far as I understand it, slerp is important for rotations in 3D, since the rotation is composed of multiple angles and it's important to consider the whole structure rather than each number individually.

However, I've also heard of people choosing between lerp and slerp for a single angle for rotation in 2D (where lerp is done with a lerp\_angle method takes into account rotations in both directions). I don't understand what slerp would mean in 2D or how it would be different. Is there some case in which lerp doesn't work right in 2D? Is the behavior different, how?

# Answer
> 1 votes
What happens if you do a linear interpolation of 0.5 between the angles 359° and 1°? you get 180°. But what you really wanted is 0°, since it lies on the shortest path between both angles. So you get some kind of "wrapping problem". It is nothing you can't fix with some branches, but it gets messy. Since you don't want to repeat all those special case treatments, every time you interpolate 2 angles, you will probably write a function that handles this. How would you call this one? Maybe SLERP ;) SLERP is just a term and not strictly bound to quaternions. Wikipedia says:

> It refers to **constant-speed motion along a unit-radius great circle arc**, given the ends and an interpolation parameter between 0 and 1.

So a LERP with angles and some special case correction will also behave like this. I don't know for sure if you can really call this SLERP or if the term has some more constraints on the algorithm, but "from the outside" they behave the same.

If you don't like those branches and you think quaternions are too much dead weight in 2D, there is an article I found addressing this problem: click me

In case the link expires and for future reference: The article talks about using "spinors" in 2D similar to quaternions in 3d.

---
Tags: 2d, mathematics, lerp
---


# Question
Title: How can I create noises when character is running using this audio manager script?
So I used this tutorial: https://www.youtube.com/watch?v=tLyj02T51Oc, to create an AudioManager that can be easily called from other scripts, and can fade sound effects. One thing I do not know how to do is how to play a sound when let's say the player is running. I only have a function that plays an sfx, but all the SFX have looped equal to false, and I know that a running noise will need the SFX to loop. How can I add a function to this script so that running noises can be correctly implemented? The script:

using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    #region Instances
    private static AudioManager _instance = null;
    public static AudioManager Instance
    {
        get
        {
            if (_instance == null) //if instance doesn't exist, find an AudioManager
            {
                _instance = new AudioManager();
            }
            return _instance;
        }
        private set
        {
            _instance = value;
        }
    }
    #endregion

    #region Fields
    //the audio source can only play one looping sound at a time
    private AudioSource musicSource;
    private AudioSource musicSource2; //purpose of having 2 musicSources is that we can use them to achieve effects like CrossFade
    private AudioSource sfxSource;

    private bool firstMusicSourceIsPlaying;
    #endregion

    private void Awake()
    {
        if(_instance == null)
        {
            //Set this instance as the instance reference
            _instance = this;
        }
        else if(_instance != this)
        {
            //If the instance reference has already been set, and this is not the instance reference, destroy the game object
            Destroy(gameObject);
        }

        //Make sure we don't destroy this instance
        DontDestroyOnLoad(_instance);

        //Create audio sources, and make them as references
        musicSource = this.gameObject.AddComponent<AudioSource>();
        musicSource2 = this.gameObject.AddComponent<AudioSource>();
        sfxSource = this.gameObject.AddComponent<AudioSource>();

        //loop musicSource
        musicSource.loop = true;
        musicSource2.loop = true;
    }

    //plays the music
    public void PlayMusic(AudioClip musicClip)
    {
        //Determine which source is active (if the boolean is true, play musicSource, else play musicSource2)
        AudioSource activeSource = (firstMusicSourceIsPlaying) ? musicSource : musicSource2;

        activeSource.clip = musicClip;
        activeSource.volume = 1; //volume is between 0 and 1
        activeSource.Play();
    }

    //fade out the first music, fade in the second (new) music
    public void PlayMusicWithFade(AudioClip newClip, float musicVolume, float transitionTime = 1.0f)
    {
        //Determine which source is active (if the boolean is true, play musicSource, else play musicSource2)
        AudioSource activeSource = (firstMusicSourceIsPlaying) ? musicSource : musicSource2;

        StartCoroutine(UpdateMusicWithFade(activeSource, newClip, transitionTime, musicVolume));
    }

    public void StopMusicWithFade(float musicVolume, float transitionTime = 1.0f)
    {
        //Determine which source is active (if the boolean is true, play musicSource, else play musicSource2)
        AudioSource activeSource = (firstMusicSourceIsPlaying) ? musicSource : musicSource2;

        StartCoroutine(UpdateStopMusicWithFade(activeSource, transitionTime, musicVolume));
    }

    public void PlayMusicWithCrossFade(AudioClip musicClip, float musicVolume, float transitionTime = 1.0f)
    {
        //Determine which source is active
        AudioSource activeSource = (firstMusicSourceIsPlaying) ? musicSource : musicSource2;
        AudioSource newSource = (firstMusicSourceIsPlaying) ? musicSource2 : musicSource;

        //Swap the source
        firstMusicSourceIsPlaying = !firstMusicSourceIsPlaying;

        //Set the fields of the audio source, then start the coroutine top crossfade
        newSource.clip = musicClip;
        newSource.Play();
        StartCoroutine(UpdateMusicWithCrossFade(activeSource, newSource, transitionTime, musicVolume));
    }

    //Update the volume overtime to achieve a fade effect
    private IEnumerator UpdateMusicWithFade(AudioSource activeSource, AudioClip newClip, float transitionTime, float musicVolume)
    {
        //Make sure that the source is active and playing
        if (!activeSource.isPlaying)
        {
            activeSource.Play();
        }

        //transition float
        float t = 0.0f;

        //fade out
        for (t = 0; t < transitionTime; t += Time.deltaTime)
        {
            //Music clip's volume is going to be reduced a bit every second
            activeSource.volume = (musicVolume - ((t / transitionTime) * musicVolume));

            //Makes sure this is updated over multiple frames
            yield return null;
        }

        //transition to new clip
        activeSource.Stop();
        activeSource.clip = newClip;
        activeSource.Play();

        //fade in
        for (t = 0; t < transitionTime; t += Time.deltaTime)
        {
            //Music clip's volume starts at 1, and for every second it is going to be reduced a bit
            activeSource.volume = (t / transitionTime) * musicVolume;

            //Makes sure this is updated over multiple frames
            yield return null;
        }
    }

    private IEnumerator UpdateStopMusicWithFade(AudioSource activeSource, float transitionTime, float musicVolume)
    {
        //transition float
        float t = 0.0f;

        //fade out
        for (t = 0; t < transitionTime; t += Time.deltaTime)
        {
            //Music clip's volume is going to be reduced a bit every second
            activeSource.volume = (musicVolume - ((t / transitionTime) * musicVolume));

            //Makes sure this is updated over multiple frames
            yield return null;
        }

        //stops music
        activeSource.Stop();
    }

    private IEnumerator UpdateMusicWithCrossFade(AudioSource original, AudioSource newSource, float transitionTime, float musicVolume)
    {
        float t = 0.0f;

        for (t = 0.0f; t <= transitionTime; t += Time.deltaTime)
        {
            original.volume = (musicVolume - ((t / transitionTime) * musicVolume));
            newSource.volume = (t / transitionTime) * musicVolume;
            yield return null;
        }

        original.Stop();
    }

    //plays the SFX
    public void PlaySFX(AudioClip clip)
    {
        //if we just use Play, let's say we have two SFX overlapping, Play will just mute the previous audio clip
        sfxSource.PlayOneShot(clip);
    }

    //plays the SFX, but allows to change the volume
    public void PlaySFX(AudioClip clip, float volume)
    {
        sfxSource.PlayOneShot(clip, volume);
    }

    //good for options menu
    public void SetMusicVolume(float volume)
    {
        musicSource.volume = volume;
        musicSource2.volume = volume;
    }

    public void SetSFXVolume(float volume)
    {
        sfxSource.volume = volume;
    }
}
```

# Answer
> 0 votes
Probably the easiest and best way to go is with animation events. There is actualy a video tutorial covering that. I recommend you watch this and follow along.

---
Tags: unity, audio
---


# Question
Title: In unreal engine, what's the difference among "set global time dilation" and "set current time dilation" and "set custom time dilation"?
what's the different effect of these three functions, thanks!

# Answer
> 3 votes
Sorry im not programmer but ill explain the easiest way i can. Global Time dilation scales time for all objects in the scene that use time, custom time dilation scales time relative to the global time dilation. For example you are making the Flash game. When running fast the world goes into slow motion. so global time dilation could be 0.1 but flash custom time dilation set to 10

---
Tags: unreal-4, unreal, blueprints
---


# Question
Title: How do I sense when the player collides with a door in a GameController script?
I want to be able to sense when the player collides with a door from my GameController script. The player is a public GameObject and doors are tagged as such. Here is psuedo code for what I'm looking for:

```
public class GameController : MonoBehaviour
{
   public GameObject player;

   void Update()
   {
      if(player collides with game object tagged "Door")
         do something
   }
}

```

# Answer
> 1 votes
Thank you @schneebuzz for helping me to fix this issue. With his advice I was able to find a function to manually check for collision with a rigidbody.

```
public class GameController : MonoBehaviour
{
    public GameObject player;
    public float collisionCheckDistance;

    private Rigidbody rigidbody;

    void Start()
    {
        rigidbody = player.GetComponent<Rigidbody>();
    }

    void Update()
    {
        RaycastHit raycastHit;

        if (rigidbody.SweepTest(rigidbody.transform.TransformDirection(Vector3.forward), out raycastHit, collisionCheckDistance))
        {
            if (raycastHit.transform.tag == "Door")
            {
                DoorController doorController = raycastHit.transform.gameObject.GetComponentInParent<DoorController>();
                doorController.openDoor();
                doorController.closeDoor();
            }
        }
    }
}

```

# Answer
> 0 votes
You need a collider (e.g. BoxCollider, CapsuleCollider etc.) on both the player and door and a script component on your Player:

```
public class MyPlayer : MonoBehaviour
{

   void OnCollisionEnter(Collision collision)
   {
        if(collision.gameObject.CompareTag("Door")
        {
            Debug.Log("Player Hit door, do something!");
        }
   }
}

```

As noted by @DMGregory: One of the two colliding components need an attached Rigidbody or CharacterController, in your case this is most likely the player.

---
Tags: unity, collision-detection
---


# Question
Title: looking for a system for writing branching dialog
I'm creating an HTML5 RPG and need to write NPC dialog. In my beta, I wrote the dialog in spreadsheets and assigned lines to NPC by ID. Branching required writing a complicated flag system. It was impossible for anyone to read through it and understand what was going on.

I'm looking for a better alternative to writing branching story dialog. The dialog will require some degree of in-text `markdown` support (so I can be sure which text to highlight with CSS). In the spreadsheet, that looked like

> "Hello, my name is \[name: John\]. Welcome to \[location: Aragon\]. Please fetch the \[keyword: sword\]"

Would would appear as:

> "Hello, my name is `John`. Welcome to **Aragon**. Please fetch the *sword*"

These would be higlighted/handled differently in code.

# Answer
I find the actual editing and management prohibitively hard when the tool itself doesn't allow hypertext.

I'd start with something like Twinery: https://twinery.org/

You can then devise a way to import your Twines as e.g. XML or Markdown text files into your game. At least you will know that the data is properly set up because a tool like Twinery visualizes the branches.
> 1 votes

---
Tags: rpg, dialogue-tree, storyboard
---