# Question
Title: How to get chunks in a sphere rather than cuboid
I have a chunk system to load stars around the player. It takes a given "real" loading range (aka Unity-units of range), calculates the necessary chunk loading range (as integer), creates star GameObjects within the loading range on screen, and stores stars in cache which are within chunk loading range but outside of real loading range.
Chunks are stored in a dictionary with the key being a struct consisting of x,y,z integer coordinates. Available data are:

* Real position of the player
* Current chunk of the player
* Center point and size of each chunk (same size for all)
* I know when the player steps into another chunk

A quick calculation revealed that if I'd be able to load chunks spherically instead of cubically, I would be able to load ~40% less chunks. The amount of chunks I have to grab (currently) can vary, ranging from a range of 3 to ~8 (meaning minimum of (2\*3+1) 7\*7\*7=343 to (2\*8+1) 17\*17\*17=4913). Current Code:

```
    public Chunk[,,] GetChunksInCuboid (Coordinate coords, int range)
    {
        return GetChunksInRectangle (new Coordinate (coords.x - range, coords.y - range, coords.z - range), new Coordinate (coords.x + range, coords.y + range, coords.z + range));
    }

    public Chunk[,,] GetChunksInCuboid (Coordinate min, Coordinate max)
    {
        int xLen = max.x - min.x + 1;
        int yLen = max.y - min.y + 1;
        int zLen = max.z - min.z + 1;

        Chunk[,,] A = new Chunk[xLen, yLen, zLen];

        for (int x = 0; x < xLen; x++)
        {
            for (int y = 0; y < yLen; y++)
            {
                for (int z = 0; z < zLen; z++)
                {
                    A[x, y, z] = GetChunk (x + min.x, y + min.y, z + min.z);
                }
            }
        }

        return A;
    }

```

My question is the following: Is it possible, and if yes, how can I performantly load chunks in a sphere?

# Answer
> 2 votes
Once I faced this particular problem. My approach was to make the code dumber.

I hard baked the precomputed offsets for different load distances. And then I would just go over them, and add the offset to the coordinates of current chunk where the player is located. I had not to worry about any distance check because the offsets were precomputed for that.

I think we can do better, actually. If we know that all the chunks near the last position of the player loaded, we only need to load the chunks that are near the new position that were not near the old position. We could have precomputed offsets for those sections.

*I suggest to use code generation for that.*

# Answer
> 0 votes
Now, while I wrote the question I had an idea and the solution was actually simple. But I thought I'd still throw it up here in case someone has a similar challenge. Be reminded, I selected the most optimal data structures - but if you find something to improve *here*, feel free to inform me!

The solution is: Get all chunks in a rectangle as described in the question, but filter them based on their 'coordinate' distance. Here is a SE answer to how to calculate distance in a 3D sphere. One additional optimization comes from not applying square root to the distance, but just comparing the distance by using their "squared" form.

Meaning: If a² \> b² then |a| \> |b|.
Concluding: If a \> b and a \> 0 and b \> 0, then a^n \> b^n with n \>= 1.
By *not* square rooting the distance, you can save one relatively cost heavy computation for every chunk's distance check.

```
    public Chunk[,,] GetChunksInSphere (Coordinate coords, int range, float radius)
    {
        Coordinate min = new Coordinate (coords.x - range, coords.y - range, coords.z - range);
        Coordinate max = new Coordinate (coords.x + range, coords.y + range, coords.z + range);

        int xLen = max.x - min.x + 1;
        int yLen = max.y - min.y + 1;
        int zLen = max.z - min.z + 1;
        float r = radius / (float) ChunkSize;
        float sqRadius = r * r;

        Chunk[,,] A = new Chunk[xLen, yLen, zLen];

        for (int x = 0; x < xLen; x++)
        {
            for (int y = 0; y < yLen; y++)
            {
                for (int z = 0; z < zLen; z++)
                {
                    Coordinate c = new Coordinate (x + min.x, y + min.y, z + min.z);
                    if (Coordinate.RealSquareDistance (coords, c) <= sqRadius) A[x, y, z] = GetChunk (c);
                }
            }
        }

        return A; // Beware that the array will be filled will 'null's!
    }

```

The formulas for getting the distance in the Coordinate struct:

```
    /// <summary> More performant for comparing distances. </summary>
    public static double RealSquareDistance (Coordinate a, Coordinate b)
    {
        int xDis = a.x - b.x;
        int yDis = a.y - b.y;
        int zDis = a.z - b.z;
        return xDis * xDis + yDis * yDis + zDis * zDis;
    }

    public static double RealDistance (Coordinate a, Coordinate b)
    {
        int xDis = a.x - b.x;
        int yDis = a.y - b.y;
        int zDis = a.z - b.z;
        return Math.Sqrt (xDis * xDis + yDis * yDis + zDis * zDis);
    }

```

These will return the distance in "Coordinate" size. For checking the distance with real ranges, simply divide it with your chunk size.

## Result

This optimization cut computation time almost **in half** and it reduced the cached stars
from ***~2000 to ~70*** \- which means we got a ~40% performance increase and ~95% less data to cache (depends on chunk size, bigger chunks have more to store). Further improvements to performance come by having to check much less cached data (the cached stars are expected to be manifested as GameObjects at any time).

This is because all chunks at the edges between the loading range distance sphere and the cube around it, which had previously loaded 0 stars and just cached everything, were no longer being loaded. The only cached stars now are those which are just outside the loading range sphere, but still inside the loaded chunks on the edges.

I was quite surprised about the result, but it all makes sense.

---
Tags: mathematics, performance
---


title: Changing sprites on trigger collision

text:
# Question
Title: Changing sprites on trigger collision
Sitting here at a game jam trying to make a game where i need to change a sprite when the ball hits a trigger. If anyone could help me with some of the coding needed you would have my sincerest thanks.

# Answer
> 0 votes
check this out: https://www.hackingwithswift.com/read/11/5/collision-detection-skphysicscontactdelegate

was not so hard to find: google for spritekit collision

---
Tags: sprites
---


title: Raycast wrong direction

text:
# Question
Title: Raycast wrong direction
I use `Physics.Raycast` and `transform.forward` to shoot a ray in front of my gameobject, but the ray gets cast downwards instead.

```
if (Physics.Raycast(transform.position, transform.forward, out var hit, range))
{
   Debug.Log(hit.transform.name);
}

Debug.DrawRay(transform.position, transform.forward * 50, Color.green);

```

What's wrong with my code?

# Answer
Currently your raycasting happens relative to your **transform**. Your transform is currently rotated so "forward" is now pointing downwards. If you want your raycasting to happens relative to the **global** space, you could can change your code to use `Vector3.forward` instead. I have also changed your hard coded `50` to `range` so that it will draw your debug ray the same distance as the actual physics ray.

```
    if (Physics.Raycast(transform.position, Vector3.forward, out var hit, range))
    {
        Debug.Log(hit.transform.name);
    }

    Debug.DrawRay(transform.position, Vector3.forward * range, Color.green);

```

If you want to visually see what the ray hits, you could change your code like this:

```
    if (Physics.Raycast(transform.position, Vector3.forward, out var hit, range))
    {
        Debug.Log(hit.transform.name);
        Debug.DrawLine(transform.position, hit.point, Color.green);
    }
    else
    {
        Debug.DrawRay(transform.position, Vector3.forward * range, Color.red);
    }

```

The last code snippet will draw a red line when it missed the target and a green line to (not through) the target when it got hit.
> 2 votes

---
Tags: unity, transformation, raycasting, direction
---


# Question
Title: Player must places the object in the preset position
I want to know how to do like this video: https://youtu.be/6gouxqSxeG8 At the minute 3:09, the player can put the street vendor in the predetermined location (with the green arrow show that place).

Please tell me some keyword about this or video tutorial about how to implement it in unity 2d.

Thanks.

# Answer
There is never just one solution for a problem in Unity. But I would approach this problem as follows:

1. Add a collider to each "drop zone".
2. When the player selects an object to place, create a sprite and make it follow the mouse cursor. You can use `Camera.ScreenToWorldPoint` to convert a mouse position to a world position.
3. When the player clicks, use `Camera.ViewportPointToRay` to get a ray which you can then feed into `Physics.Raycast` to detect the collider under the player's mouse cursor. You might want to use layer masks to restrict the raycast to drop zones only (improves performance and avoids hits with objects you didn't want).
4. When the raycast finds a drop zone (and not perhaps some other object which is in the way), replace the drop zone with a new instance of your street vendor prefab. Place the prefab at the coordinates of the drop zone.
> 1 votes

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


# Question
Title: How to prevent OnCollisionEnter2D calling a function again and again?
My current code makes a ball keep jumping whenever it hits the ground. But when it hits a vertical ground it keeps calling the jump function again and again. That is because OnCollisionEnter2D makes the isGrounded bool true as long as it is in touch with a vertical collider. I tried several ways for example this didn't work for me:

```
void FixedUpdate()
{

    if(isGrounded == true){
    Verticaljump();
    isGrounded = false;
    }
}
void OnCollisionEnter2D(Collision2D collision) {
    if(collision.gameObject.CompareTag("H-Ground")){
        isGrounded = true;
    }
}

```

As shown in the picture the OncollisionEnter2D starts and keep adding force on y-axis.Is there any way I can call a function only once even if the gameObject keeps colliding with a surface.

OnCollisionExit2D also does not work. So how can I call a function only once as it collides with ground and even if it keeps colliding with the ground?

# Answer
> 0 votes
If I've understood your question correctly you have an issue in a situation where the ball touches the "ground" from a side?

Like there (consider `=` to be ground and `o` to be a ball)

```
     o=====

===========

```

One solution which comes to my mind is to add a small invisible object with rigidbody/collider on the bottom of the ball which will handle `isGrounded` situation. Then if the rest of the ball touches the ground you just do whatever else you want as grounded situation is already handled by other object (of course you will have to pass that `isGrounded` to the ball object itself.

Another solution is to check if the `transform.position` of the platform is actually below the `transform.position` of the ball. Like that

```
void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("H-Ground") && (collision.gameObject.transform.position.y < this.transform.position.y))
    {
        isGrounded = true;
    }
}

```

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


# Question
Title: Even if one client port will be simple to write without it, should I still use an engine?
So the idea is to create a **TRUE REAL TIME** strategy game that is working as android and IOS app, and also as web browser game. Players should be able to play on all their devices.

There will not be any physics but there will be alot of data transfering, many diferent calculations, settings. There will not be client to client direct connection, everything should go trough servers. Graphics will be simple Menus/ different pictures. Player interactions will not be graphically presented. More like raw data.

Friend's chat, team chat, Maybe global chat. Facebook/Google connection/authorization. Notifications... etc

Now after I explained the idea here are the question:

Given that the browser client will be relatively simple to write without an engine (using javascript/html/sql), should I still use a game engine to write the different clients (browser, iOS, Android); if I can avoid using an engine for one port, should I avoid using an engine at all? And, more importantly, why?

# Answer
The fact that *one* client will be "simple" to write natively is not a good reason to not use an engine; in fact you should use an engine for all of your ports.

* One codebase to write.
* One codebase to maintain.
* One, unified, user interface for your clients.
* One way to pass data around.

The use of the engine will abstract a lot of particularities of the different platforms you'll work with. This means that you'll get the content in the hands of your users faster, in a more unified and reliable way.
> 3 votes

---
Tags: software-engineering
---


# Question
Title: How to instantiate new GameObject at position of old GameObject onAnimationComplete
I have a GameObject that is a Farmer that plants Seeds. The Seeds will animate into Plants. Once that animation is complete, I'd like to replace my Seed with a Plant. This happens hundreds of times per game at arbitrary positions. I've tried this as something I built off of this question: Unity: detect animation's end

```
public class SeedScript : StateMachineBehaviour {
[SerializeField] private GameObject seed;
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
    Destroy(this);
    animator.GetComponent<TreeScript>().GrowTree(seed);
    Instantiate (tree, this.position,  this.rotation);
}

```

}

Obviously, this doesn't work at all. Doesn't even compile.

I've also looked at these co-routines: https://answers.unity.com/questions/981948/statemachinebehaviour-startcoroutine.html but again, I need to get position data from the animating object.

Yes, I could just merge my Seed and Plant classes together, let's pretend I cannot do that and MUST instantiate some arbitrary new object at the position of another object on some animation completion.

# Answer
> 1 votes
`this` in your code would refer to the StateMachineBehaviour so if you `Destroy(this)` you try to destroy the wrong object.

Rather add an event to your animation timeline that calls a method on your Seed GameObject (attach the script to your GameObject). The benefit of this approach is you can move your event to any position on your timeline, for example you might want to show the seed and plant simultaneously so that it looks like the plant is coming out of the seed.

Inside that method (on your Seed GameObject), you can Instantiate your Plant script (attach the script to your Plant GameObject) and copy your variables from the Seed GameObject to your Plant GameObject.

```
public class Seed : MonoBehaviour
{
    public Plant plantPrefab;

    public void GrowPlant()
    {
        Plant plant = Instantiate<Plant>(plantPrefab);
        plant.transform.SetParent(transform.parent);
        plant.transform.SetPositionAndRotation(transform.position, transform.rotation);

        // Whatever else you want to copy...
    }
}

```

---
Tags: unity, animation-states
---


# Question
Title: Excluding geometry from a shadow casting light in deferred rendering
Is it possible to exclude geometry from a particular shadow casting light in a deferred rendering pipeline? If yes, can it be done *correctly* or are there limitations? This is mainly to reduce the rendering cost of each shadow casting light.

In UE4 this is currently not possible and one of the staff members simply replied with a rather cryptic message:

> "Unfortunately, this is not possible with Deferred Rendering."

Since we are rendering the depth map from the light's perspective, we *should* be able to exclude geometry from that render pass...? Are there edge cases that I am not thinking of when combining shadow casting lights with deferred rendering?

Link to forum post (and screenshot to follow in case the link goes down): https://forums.unrealengine.com/unreal-engine/feedback-for-epic/35667-exclude-object-from-a-specific-light

# Answer
At a conceptual level, yes, the decision of what gets rendered into a shadow map is entirely yours. You can choose to include or exclude whatever geometry you want from the shadow map generation process, and this will mean that the generated shadow map will make it so that any visible objects not in the shadow map will not cast shadows. You can even make invisible objects cast shadows if you like.

But the answer you found was not about the *idea* of shadow maps; it was specifically about whether Unreal 4's implementation was capable of doing this. According to the reply you were given, the UE4 scene graph system is not capable of doing this, of having there be a difference between which objects in the scene are shadow casters and which objects are part of the visuals of the scene.

You could probably modify the engine to allow this, but the point of the response is that this is not a feature of the engine as it stood in 2015.
> 1 votes

---
Tags: unreal-4, optimization, shadow-mapping
---


# Question
Title: Set the LineTraceByChannel to use my custom created channel? C++
I want to use LineTraceSingleByChannel function for my SightRay component which will be used for my adventure game. I want to mark certain objects in game as 'Viewable' in Trace Channel. Then the ray will only be true if it hits a 'Viewable' object.

I have created the Viewable trace channel in the Collision settings of Project Settings. But I have two problems now.

1. In the actual c++ code I am writing, how do I reference this new 'Viewable' channel in the ECollisionChannel parameter of the method?
2. How do I assign this channel to each object in the scene?

I have been trying to figure this out for hours, I've read many Unreal documentation pages and forum threads but can't get a straight answer, particularly without using Blueprint nodes.

Here is my code:

```
bool USightRay::GetLineTraceHit(FHitResult &OutHit)
{

FVector LineStart = UGameplayStatics::GetPlayerCameraManager(this, 0)->GetCameraLocation();
FVector LineEnd = LineStart + UGameplayStatics::GetPlayerCameraManager(this, 0)->GetCameraRotation().Vector() * LineTraceLength;
//ECollisionChannel viewable =  WHAT CAN I PUT HERE?????
if (GetWorld()->LineTraceSingleByChannel(OutHit, LineStart, LineEnd, viewable))
{
    UE_LOG(LogTemp, Warning, TEXT("HIT ME WITH YOUR RHYTHM STICK!"));
    return true;
}

return false;
}

```

I actually thought this would be simple before I started to code it. I've used it before but I just used ECollisionChannel::ECC\_Visibility in place of 'viewable'. This time I want to learn to filter the collisions and traces properly.

Thank you for any help.

# Answer
Well I kind of figured it out, but thought I can post here for any comments in case I am doing anything wrong. Also this might help someone who reads this with same problem.

Basically, I had created the custom trace as mentioned, but I didn't really know how to access it in code. After hours of reading I found you must go to your projects DefaultEngine.ini file , in there search "ECC" and it will tell you which one it is.

Then you can put something like:

```
#define COLLISION_VIEWABLE ECC_GameTraceChannel2

```

at top of your cpp file, and in the method parameter use ECollisionChannel::COLLISION\_VIEWABLE , this now raycasts only on my specified channel.
> 4 votes

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


# Question
Title: Custom functionality for content saved to database
I'm creating a turn-based game where I store most of my content in a database (enemies, items, npcs, location data, etc). This allows me to update the content easily without needing to rebuild anything.

I'm wondering if there is a way to safely link something like an enemy db instance to some hardcoded custom functionality. For example, maybe at the start of combat a certain enemy casts a specific spell or yells something.

I could look up a custom behavior file based on an enemy name or db id, but then if it changed that functionality would break. I could have a field for uploading a custom behavior script but that could introduce a slew of issues.

tl;dr; Are there standard patterns for adding custom functionality to content that is saved/loaded from a database?

# Answer
> 1 votes
Have a field dedicated to store the name of the script, and lookup the script by that.

Unlike finding the script by the name or id of the entity, you will be able to have multiple that use the same script. Plus, you can change the name of the entity without unlinking the script.

# Answer
> 0 votes
What Theraot said is basically true. You are putting data first in your game. The entities: monsters, items and weapons are defined by their data and, their attributes. Now if you want to add "special attributes", you could simply list those by name in a comma separated string. If I totally agree with Theraot answer why did I bother to write one?

1. You should make a tool for adding and removing these behaviors. If you do this by hand you might have very strange typos and annoying behaviors.
2. You could consider using reflection to load the scripts/class/method by name.
3. Consider using snail case naming for these like `yell_horde` or `attack_kick` so you'll know what type of behavior you want to add to the entity.

---
Tags: databases
---


# Question
Title: Attempting to have a group of units create random values independently in python 3 for a salvage loot system
I am working on creating a salvage mechanic for my game. I want different units to calculate salvage after an encounter to randomly determine how much each one was able to scavenge from fallen allies or attackers.

As I have it setup up now its calculate as a group.
IE: If I have group of units whom collectively can salvage value of 5 and for each point of salvage I can potentially gain 1-4 piece of salvage then I have a range of 5-20 pieces of salvage (provided there are 20 or more pieces of salvage to collect). I am simply multiplying the total salvage value of the group by a randomly determined number in a range of 1-4.

My question is, how can I get each unit to calculate its salvage individually from its own range, rather than as a group as I'm doing now to give greater variance in the amount of salvage generated?

I am rather new and any suggestion or insight would be appreciated.

Below is the code for a demo I setup for the salvage system:

```
import random

parts_inventory = 0
undif_unit_count = 999
haulers = 2
foragers = 1
salvage_value = (haulers * 2) + foragers
temp_salvage = 0
salvage_random = random.randint(1, 4)

attack = random.randint(1, 6)
fatalities = attack
salvage_pool = fatalities * 4

print("There were {} units destroyed resulting in {} pieces of potential salvage".format(attack, salvage_pool))
print("Your units can haul away {} peice of salvage".format(salvage_value))

def salvage_operation(parts_inventory=parts_inventory):
    print("Encounter Haul {}".format(salvage_value))
    if salvage_value <= salvage_pool:
        print("You gained {} salvaged parts.".format(salvage_value))
        parts_inventory = parts_inventory + salvage_value
    if salvage_value > salvage_pool:
        print("You gained {} salvaged parts.".format(salvage_pool))
        parts_inventory = parts_inventory + salvage_pool
salvage_operation()

```

# Answer
> 0 votes
this is not how you would normally write Python

```
from random import randint

def units_scrap_rolls(current_salvage, haulers, foragers):
  rolls = [(haulers, 6), (foragers, 4)]
  for unit_count, roll_max in rolls:
    for i in range(unit_count):
      current_salvage += randint(1, 6)
  return current_salvage

salvage
salvage = print(units_scrap_rolls(salvage, 2, 1))
print(salvage)

```
* Notice the function has a return value
* Using Python range() instead of while
* Concise code
* No default values for the variables if they aren't used

# Answer
> 0 votes
Here is a solution I managed to come up with after talking with a friend involving making a function to essentially roll dice for each unit via a loop.

```
import random

haulers = 2
foragers = 1
temp_salvage = 0
count = 0

def units_scrap_rolls(temp_salvage=temp_salvage, haulers=haulers, foragers=foragers, count=count):
    if haulers > 0:
        number_of_rolls = haulers
        count = number_of_rolls
        while number_of_rolls >= count and count > 0:
            temp_salvage = temp_salvage + random.randint(1, 6)
            count = count - 1
        print ("After the Haulers were done, you had {} salvage.".format(temp_salvage))
    if foragers > 0:
        number_of_rolls = foragers
        count = number_of_rolls
        while number_of_rolls >= count and count > 0:
            temp_salvage = temp_salvage + random.randint(1, 4)
            count = count - 1

    print("In total you gained {} pieces of salvage.".format(temp_salvage))

units_scrap_rolls()

```

---
Tags: python
---


# Question
Title: LWRP Custom Shader Graph material casts no shadow
I created an empty Shader Graph by clicking Create -\> Shaders -\> PBR Graph.

I created the material for this shader and assigned it to my game object, but the object does not cast a shadow.

If I assign the default LWRP Lit material, then everything works and the shadows are dropped, but with a custom shader there is no shadow.

How can I make my custom shader material cast shadows?

# Answer
> 1 votes
This fixed it for me:

If you use a transparent surface type on standard LWRP or UniversalRP (that does not cast shadows), then change that material to a custom shadergraph's shader, you lose shadow casting. Just use a lit shader for the new pipelines, set it to Opaque, then change it to your custom shader.

e.g. set it to Lit (universal Render Pipeline/Lit)
and change it back to your custom shader afterwards

---
Tags: unity, shaders, shadows
---


# Question
Title: How to calculate the post Rigidbody2D velocity vector before applying a specific force in Unity?
I am trying to implement a space rocket in 2D. Whenever the player presses a button, a constant force (Both vertical and horizontal) is being added to that rocket. What I want to add is a maximum speed, the rocket cant exceed as the rocket will continue accelerating to infinity. The player can also choose not to accelerate, which can lead to the rocket starting to fall down due to gravity. Thus, I cant just Clamp the rigidbody.velocity of the rocket whenever the magnitude of it exceeds max speed as it will also limit the fall velocity which is not as limited. Thus, I am trying to predict whether the player will exceed the maximum velocity when trying to accelerate, in order not to add the force.

So far, I have tried doing this but the velocity vector does not seem to change immediately, so vel is equal to postVel:

```
Vector2 vel = rigidbody.velocity;
rigidbody.AddRelativeForce(Force); // Add force
Vector2 postVel = rigidbody.velocity;
rigidbody.AddRelativeForce(-Force); // Undo force

```

# Answer
Adding forces to a rigidbody won't change its velocity until the phyiscs engine runs another update, which happens betweeen two calls to a FixedUpdate method in your own code.

But if you want to predict the velocity of a body after applying a force, you can do so using Newton's formula `force = mass * acceleration`, or `acceleration = force / mass`.

```
Vector3 newVelocity = body.velocity + (Force / body.mass) * Time.deltaTime;

```

But keep in mind that drag, other forces and collisions with other bodies might cause the velocity on the next frame to be different than you predicted.
> 1 votes

# Answer
Remmber: *F=MA*

When you add force you are modifying the acceleration, which will in turn change velocity as time progresses.

You have added and subtracted force in the same instant, without allowing time for the newly changed rate of acceleration to modify the velocity. Add some brief sleeps in your code and you will see the change in velocity.
> 0 votes

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


# Question
Title: How do rendering pipelines improve the performance of updating all the vertices every frame?
Let's say I am implementing a simple game engine, particularly the rendering part. From the high-level view we have some vertices which are copied to the graphics card alongside shader information etc.

I do not really understand how this is done in a performant manner: Consider a basic OpenGL program (and all the tutorials or whatever I could find out there) which copies all the vertices to the graphics card at each draw call. This seems to be a lot of work.

And as far as I understand if I am doing some kind of third person game, for example, I have to copy every vertex of the character at each draw call (and possibly more). Even though the world is static and the character is representing only a small amount, this still seems to be a lot.

Do game engines apply some kind of "caching" here, to make sure they only copy what has actually changed, or is this a rather mindless copy of everything, and the performance is not such a big deal?

Essentially I want to learn about some kind of architectural choices concerning this vertex copy operation, however I cannot seem to find the right resources. Thank you for any input you could provide.

# Answer
> 1 votes
Usually games and game engines will upload vertices, textures and other render-relevant data to the graphic card once by putting it into buffers. Those then stay in the GPU RAM until the game tells the GPU it won't need that data anymore. This is the reason why graphic cards require several GB or RAM: So games do *not* need to pass all the vertices through the PCIe bus on every single frame.

When the game wants the GPU to render something, it just tells it which vertex- and pixel shader programs to run and which previously uploaded buffer(s) to use for that run. Position and orientation of the object(s) are usually communicated to the GPU by sending a projection matrix for that draw-call.

Skelettal animation is often also handled on the GPU. The CPU only tells the GPU the bone rotations and IK target locations for each frame. The GPU will then use that information to transform the mesh vertices before rendering the mesh.

---
Tags: opengl, architecture, graphics, vertex-buffer
---


# Question
Title: Performance cost of creating local variables just for 'readability'?
I am learning C++ and Unreal Engine. I'm wondering if creating local variables inside functions purely to help me read the function later will cost my game/code in performance (assuming if I carry on this practise over hundreds/thousands of functions/variables).

Eg:

```
void APostie::MoveForward(float Value)
{
FVector Delta = GetActorForwardVector() * BaseWalkSpeed * Value * GetWorld()->GetDeltaSeconds();
FRotator NewRotation = GetActorRotation();
FHitResult Hit;
GetCharacterMovement()->SafeMoveUpdatedComponent(Delta, NewRotation, true, Hit);
}

```

Here the 'NewRotation' variable is completely useless. But I am intending to copy-paste this function and use it in similar input functions that will require the NewRotation to have a calculation on it.

So is it much better peformance-wise to have the function like this instead (again, imagine there are several hundred similar situations in a code solution)

```
void APostie::MoveForward(float Value)
{
FVector Delta = GetActorForwardVector() * BaseWalkSpeed * Value * GetWorld()->GetDeltaSeconds();
FHitResult Hit;
GetCharacterMovement()->SafeMoveUpdatedComponent(Delta, GetActorRotation(), true, Hit);
}

```

As you see in the second version the Rotation is set directly. Does this make any difference to game performance (including Networked games) ? Thanks

# Answer
> 5 votes
This depends on how good the compiler is at optimizing the code. I'm inclined to say it is good if not very good.

However, if you want to be sure, you got to do the experiment. Measure both versions with a profiler and see what comes up on top.

---

Your job is not to optimize code, it is to make a system (a game in this case). If you go ahead and do that, and it turns out that it is slow... well, you are going to get the most performance improvements per effort if you focus on the bottlenecks and the hot paths.

Those bottlenecks and hot paths are probably going to be some computation or some interaction with an external system, not some local variable.

*Yes, learn to use the profiler, it will tell you where the hot paths are.*

---

What I'm saying that you are probably worrying too much about this. Let the good people who work in creating compilers figure where inlining a local variable is a good idea, and you can figure out how to make a good game.

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


# Question
Title: How do 3D rendering pipelines render light effects?
How does 3D software like Blender, Maya, Unity, or Houidini etc. render the effects of lights illuminating a 3D scene?

# Answer
> 2 votes
Not all of the software you listed calculates lighting the same way, or the same in all circumstances. There are a few different approaches:

* **Offline raytracing / path tracing** are used by 3D modelling software like Maya/Blender/Houdini when you want to output a high-quality final render, or a frame for something like an animated film.

In these techniques, the software traces the actual paths taken by each ray of light departing a light source or arriving at the camera, as it bounces around your scene or gets diffused by your materials.

This can produce highly accurate, photorealistic results, including detailed reflections, but it can be extremely performance intensive. A single frame might take seconds, minutes, or even hours to compute in full, depending on the complexity of the scene and the target resolution/quality. 3D film studios and effects houses frequently have render farms full of high-powered computers to chew through all the raw computation required.

So this often can't keep up for the purposes of realtime interaction, and the apps will fall back on iterative approximations or rasterization techniques to keep the editing views and preview panes responsive.

* **Realtime rasterization** is the family of techniques at the heart of most modern games and interactive 3D apps.

It flips the question from "for each ray of light, what surfaces does it hit in my scene?" to "for each surface in my scene, how does the light illuminate it?"

Typically we draw the scene triangle by triangle of each mesh, projecting the corners of that triangle onto the screen, then filling each pixel between those corners with a colour.

To find the right colour, we run what's called a pixel shader or surface shader, a small program that your GPU executes for every pixel it draws. This program figures out which way that bit of the surface is facing — based on the mesh's normals, or a normal map texture it looks up into, then evaluates how much that direction is pointing toward or away from the light source. Places where the surface points directly at the light get drawn bright, while places that face perpendicular or away from the light get drawn black. (Plus some extra considerations for specular reflection that depends on the view direction)

By adding up these colours, computed for each light source in range, we get the net illumination of the pixel.

The trouble with this approach is it's only an approximation of the most direct light path from the light to the surface to the eye. It doesn't take into account anything else in the scene — like objects that sit between our triangle and the light source and should block the light, casting a shadow, or nearby illuminated surfaces that should bounce light onto the surface we're drawing.

So we have to approximate these effects, like drawing a shadow map to estimate which scene pixels are actually occluded from the light's perspective, or adding ambient terms or other tricks to simulate bounced light and reflections. Modern rendering in games uses many sophisticated approaches to fill in for these interactions and get a more natural look.

This rasterization technique can get us fast, plausible results for a high framerate, but it can sometimes show artifacts that can reveal the trick or make the result look lower quality than raytracing.

* **Hybrid "baked" solutions** are often used to increase the fidelity of lighting in realtime apps and games, while keeping framerates high.

In these models, an offline "baking" pass uses raycasting-style techniques to calculate bounce light interactions in the scene, then stores that information to a light map or lighting/reflection probe data structures. This can also be done at runtime, by an asynchronous background thread that updates slowly-changing illumination information periodically.

At runtime, light that can change quickly (as on moving objects or lights that move and change) is rendered with traditional rasterization techniques so it updates instantly, while the bounced light or light on static objects is looked up from the data structures. This sampling process is often lossy and not perfectly accurate, but it can go a long way to make the scene look more like an offline render, with convincing bounced lighting.
* **Realtime ray-tracing** is an emerging technique leveraging new and more powerful graphics cards with built-in hardware acceleration for common raycasting approaches. While it's still out of reach to render a AAA game completely with raytracing at an acceptable framerate, games can use this hardware selectively, to do things like mapping more convincing reflections on shiny surfaces, or sparsely sampling a scene with rays and using temporal filtering or neural networks to up-rez this low resolution coverage to a convincing full-resolution image.
* **Raymarching** is a more exotic technique not often seen in mainstream games and apps, but popular in "demoscene" creations or playgrounds like ShaderToy. In this technique, the content of the scene is expressed as a signed distance field, and for each pixel we draw, we "march" a ray through this field, one step at a time, until it hits something.

It's conceptually similar to raytracing, but expressing it as an iterative stepping through a distance field lets us leverage conventional rasterization hardware to accelerate it on the GPU. Some games will mix rasterization with raymarched height/displacement maps to make surfaces look more detailed than the underlying geometry (popular for things like bricks and cobbled roads).

It's difficult to use this with conventional animated meshes, but can be effective for games that use procedural geometry, like Claybook.

---
Tags: rendering, lighting
---


# Question
Title: Why is the timer not calling the function?
I am trying to call a function every 30 seconds. I have used this before without issues so I'm not sure why it isn't working now. Any ideas? Has something changed in 4.24 maybe?

.h I have tried both public and private

```
UFUNCTION()
void Ping();

```

And the .cpp I see both logs in the output so I know its getting there. Also the ensure passes. I have also tried GetWorld which is null in a UObject and GWorld which also works but has the same problem of the ping function not being called at all.

```
UE_LOG(LogTemp, Warning, TEXT("start ping"))
if (ensure(GEngine))
{
    UWorld* World = GEngine->GetWorldContexts()[0].World();
    UE_LOG(LogTemp, Warning, TEXT("start ping has gworld"))
    World->GetTimerManager().SetTimer(PingTimerHandle, this, &UGameJoltApi::Ping, 30, true, 30);
}

```

And here is the ping function. Its not called even once. I never see the log in the output.

```
UE_LOG(LogTemp, Warning, TEXT("ping"))
FString Url = URLBaseApi + URLSessions + "ping/?game_id=460364&username=" + Username + "&user_token=" + UserToken;

TSharedRef<IHttpRequest> Request = FHttpModule::Get().CreateRequest();
Request->SetVerb("POST");
Request->SetHeader("Content-Type", "application/json");
Request->SetURL(GenerateUrl(Url));
Request->OnProcessRequestComplete().BindUObject(this, &UGameJoltApi::OnStartSessionResponse);
Request->ProcessRequest();

```

# Answer
> 0 votes
I havent found an answer but I found a workaround. I moved the code in the `UObject` that starts the timer to my `GameInstance` and everything works as it should. I have no idea why I couldn't do this in the `UObject` but this is probably better design wise anyway as the API shouldn't have to worry about timers and such.

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


# Question
Title: How can I get the Launch dynamic link in Unity?
I have integrated firebase dynamic link sdk in my app and it is working perfectly fine,

I can generate dynamic links, and when clicked on them if the app is not installed it redirects me to the playstore and if installed open up the link in app.

My question is how can I get that generated link when I open the app through it, I just could not able to find anything in docs

the code I am using to listen for link clicks is as follows

```
void Start()
{
    DynamicLinks.DynamicLinkReceived += OnDynamicLink;
}

// Display the dynamic link received by the application.
private void OnDynamicLink(object sender, EventArgs args)
{
    var dynamicLinkEventArgs = args as ReceivedDynamicLinkEventArgs;
    Debug.LogFormat("Received dynamic link {0}", dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString);
    // Above line gets me the original base link,
    // But I want the link which I clicked
}

```

# Answer
> -1 votes
Try putting the code as below:

```
void Start()
{
    DynamicLinks.DynamicLinkReceived += OnDynamicLink;
}

private void OnApplicationFocus(bool focus)
{
    DynamicLinks.DynamicLinkReceived += OnDynamicLink;
}

```

---
Tags: unity, firebase
---


# Question
Title: Performance of Tristrip vs Indexed Triangles in OpenGL
Let's say that I want to take advantage of GPU transform cache and use tristrips for that purpose. In the first case we have three triangles: 012, 213, 234. In the second case we used tristrip topology and passed indices to GPU: 0 1 2 3 4. In both cases all vertices will be cached on GPU. The only difference is the size of index buffer. In the first case (triangle topology) the size is 9. In the second case the size is 5. Even if we get 2x-3x size reduction, the index buffer is usually not the bottleneck. So, the question is why we get performance boost when using triangle strip vs indexed triangles in OpenGL?

# Answer
**Trianlge strips don't necessarily give increased performance**

In the old days (pre-1998/99) GPU vendors used to recommend triangle strips as the optimal primitive type, but that was in a very specific case - non-indexed triangle strips using the GL\_TRIANGLE\_STRIP mode via glDrawArrays or glBegin/glEnd.

In 1998/99 something happened - Quake III Arena was launched. Back in those days the latest id Software game was *the* benchmarking tool of choice, and magazines and other publications used to regularly list performance figures. If you were a hardware manufacturer you needed to have this game run as fast as possible.

John Carmack wrote a note entitled Optimizing OpenGL drivers for Quake3 which contains the following little snippet:

> Quake3’s rendering architecture has been defined with the primary goal of minimizing API calls and focusing as much work as possible in a single place to make optimization more productive.
>
> During gameplay, 99.9% of all primitives go through a single API point:
>
> ```
> glDrawElements( GL_TRIANGLES, numIndexes, GL_UNSIGNED_INT, indexes );
>
> ```

This was the beginning of indexed *triangles* (rather than strips) being the preferred performance path, although it's reasonable to assume that this was the result of back-and-forth discussion between Carmack and hardware manufacturers rather than something he pushed himself.

If you see anything recommending strips as the optimal primitive type then you need to look at the date it was published; the probabilitity is that it is something from 1998 or before.
> 2 votes

---
Tags: opengl, rendering
---


title: Slerp to slerp smoothing

text:
# Question
Title: Slerp to slerp smoothing
```
p0 ------- p1 ------- p2

```

I am successfully slerping between 2 points (p0-p1; p1-p2). But the transition between two slerped angles (p1\_in-p1\_out) do not match, and it looks jarring

Video of how it looks:

green squares are points, the position and angle between each are interpolated.

The issue is most visible at second 6.00

https://gfycat.com/unhealthygraveduckling

I tried hermite splines, although it reduces the effect, it's still visible.

I tried converting Catmull-Rom to use with quaternions by just adding the 4th index to the vector functions. This works perfectly except on some occasions, where some are interpolated from the wrong (long) "way", causing the view to flip between those points. I tried aligning, did not help.

Other questions on SO related to slerp don't ask this question, and I could not get any usable answers from some questions on 4 point slerps.

Is this a common issue, am I overseeing something?

Thanks

# Answer
> 2 votes
I hadn't actually aligned in CatmullRom, it was one of my other tests. It got lost in all the messy code. The problem was solved by aligning the start and end points of the spline input. (params: pre, start, end, post)

The issue could also be solved by using circular blending, which I hadn't know, but it works as well. This video demonstrates my problem and the solution pretty well.

Quaternion aligning makes sure the quaternions are within 180 degrees of each other, if they're not, reverses one. This is the code I used:

void AlignQuaternions( const Quaternion &in1, const Quaternion &in2, Quaternion &out )
{
    float a = 0.0;
    float b = 0.0;

    // dot product of in1 - in2
    a += (in1.x-in2.x) * (in1.x-in2.x);
    a += (in1.y-in2.y) * (in1.y-in2.y);
    a += (in1.z-in2.z) * (in1.z-in2.z);
    a += (in1.w-in2.w) * (in1.w-in2.w);

    // dot product of in1 + in2
    b += (in1.x+in2.x) * (in1.x+in2.x);
    b += (in1.y+in2.y) * (in1.y+in2.y);
    b += (in1.z+in2.z) * (in1.z+in2.z);
    b += (in1.w+in2.w) * (in1.w+in2.w);

    if ( a > b )
    {
        out.x = -in2.x;
        out.y = -in2.y;
        out.z = -in2.z;
        out.w = -in2.w;
    }
    else
    {
        out.x = in2.x;
        out.y = in2.y;
        out.z = in2.z;
        out.w = in2.w;
    }
}
```

---
Tags: quaternion, interpolation, angles
---


# Question
Title: Adding a time-delay without changing the function signature
I have written a simple generic implementation of the BFS algorithm, which I intend to use in several places in my Unity game. A simplified version of the class is:

```
class BFS {
     public abstract void OnNewNodeDiscovered(Node node);

     public void FindPath(Node start, Node end) {
         // Implementation of the algorithm.
         // Calls OnNewNodeDiscovered whenever a new node is discovered.
     }
}

```

I added the method OnNewNodeDiscovered so that users of this class can do custom actions, such as logging, changing the colors of things in the scene, etc., during the algorithm.

This works fine, but now I want to create a sub-class which also, in the function OnNewNodeDiscovered, adds a time-delay, so that the progress of the algorithm can be displayed to the player. The problem is that, the only way I know for adding a time delay in Unity is to convert the function to a coroutine, which returns IEnumerator, and then "yield return new WaitForSecods(delay)". But this breaks my design of having a generic OnNewNodeDiscovered function.

My quesion is: is there an alternative way to add a time-delay inside a function that will be called from Unity? Can't I just say something like "sleep(duration)" to sleep for the specified duration and return later to the next statement point, without having to change the return type to IEnumerator?

# Answer
Based on your comments, I think you are actually looking for the thing you said you were not looking for. Below an example of how you could implement something you want, the idea is that FindPath is run like a CoRoutine, and it yields OnNewNodeDiscovered (which is an IENumerator)

Now I used an example that draws a line that alternates colors every 0.1 seconds to test whether it works as intended, but I think you should be able to convert this to your own needs.

```
public class Example : MonoBehaviour
{
    public void Start()
    {
        StartCoroutine(FindPath(Vector3.zero, new Vector3(100, 0, 0), 100));
    }

    public virtual IEnumerator FoundNode(Vector3 from, Vector3 to)
    {
        Debug.DrawLine(from, to, Color.red, 0.1f);
        yield return new WaitForSeconds(0.1f);
        Debug.DrawLine(from, to, Color.green, 0.1f);
        yield return new WaitForSeconds(0.1f);
    }

    public IEnumerator FindPath(Vector3 start, Vector3 end, int steps)
    {
        Vector3 step = (end - start) / steps;

        Vector3 pos = start;

        for (int i = 0; i < steps; i++)
        {
            Vector3 next = pos + step;
            yield return FoundNode(pos, next);
            pos = next;
        }
    }
}

```

And if you in some cases don't want a delay in OnNewNodeDiscovered, calling `yield break;` instead of `yield return something;` makes it yield immediatly (so without a delay)
> 1 votes

# Answer
My method would be to add a separate function in your subclass to achieve this.

```
class BFS {
     public abstract void OnNewNodeDiscovered(Node node);

     public void FindPath(Node start, Node end) {
         // Implementation of the algorithm.
         // Calls OnNewNodeDiscovered whenever a new node is discovered.
     }
}

class BFS_SubClass {
    public void OnNewNodeDiscovered(Node node) {
        ...
        // Implementation
        ...
        TimeDelay(time);
        ...
        // More implementation
    }

    private IEnumerator TimeDelay(float time) {
        yield return new waitforseconds(time);
    }
}

```

Calling the IEnumerator as a function should allow you to retain single thread-ness and achieve a time delay.

Disclaimer, it's been a while since I did unity c#
> 0 votes

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


# Question
Title: Is it a good option to simultaneously work on a game and a game engine?
I'm considering this, now I work on 3d game but I want also to make in slow tempo, iteratively a game engine is it a good choice?
The game what I working on is with non custom engine (Unity, Unreal Engine 4 - I not yet selected, switching from engine to engine) and also I want to develop a custom 3d engine but this engine will not be heavy but lightweight so with selected features. So I'm not talking about making Unity like engine but still 3D thank you for answer :)
And this engine will contain:

* c#
* opengl
* existing physics engine (Bullet or sth)
* ...

what I not considering:

* editor
* multiplayer
* characters

so just API
Additionally I have linear algebra background but no experience with shaders
edit: currently I want to make game in existing game engine
but in future I want to migrate with game to custom game engine

# Answer
> 19 votes
Consider using a framework, like MonoGame.

It is a kind of a middle ground between "nothing" and a full-blown engine like Unity or Unreal.

It saves you from the really finicky implementation details (3d games are especially math heavy, both for graphics and physics), without dictating too much how things should be done.

Adopt a modular system - this will let you reuse parts of your game in other projects, disregarding others you may not need.

Add features to your engine incrementally as your game requires them - you can strike a balance between having your engine become the game (too specific) and having no game (too generic).

Last, but not the least, in the hopes that it would be useful, I will link my GitHub repository for a 3D game project with goals similar to yours, even if the exact game type is different. It is in no way meant as an example of a decent complete solution - but you can see it has multiple modules with common functions and solves a few common problems engines usually do for you. Consider it more of a heap of stuff to sift through and help you along an idea.

Here it is, some lines are even commented. Note that implementing your own model system is probably not a good idea, but my terrain implementation (based on Riemers old XNA tutorials but heavily expanded) is very solid and provides nearly triangle-perfect terrain collision for cheap performance cost.

Good luck!

# Answer
> 16 votes
You, of course, can use a third party solution. You can develop C# games with (in decreasing complexity) Unity, Godot, Monogame, OpenTK, among other solutions.

**Making a game without a third party game engine** is perfectly viable. You can work with a window toolkit library, a graphics library, and so on. You will have a lot of flexibility... Yet, it is a lot of work. Because of that, it usually only makes sense for small-ish projects.

**Making a game and a game engine at the same time** is possible. You are not braking any law of physics or anything like that. However, you are likely to lose focus. The requirements of the game engine and the requirements of the game are not the same. *In particular if you are making an editor.*

I want to note that there are game framework and game IDEs. So a game framework is a game engine in the sense that it is the software component that makes the game run. *You know, like an engine.* However, often when people think about getting a "game engine", they are thinking about an editor where they can make a game, that is the game IDE.

A game IDE, a.k.a Game Engine, will allow you to build games that use a game framework, a.k.a game engine.

Thus, there are three components:

* The game
* The framework
* The IDE

You do not deploy the IDE. You deploy the game with its framework, the game won't work without the framework (they may or may not be separable on the release build).

---

Now, if you develop a game without a third party game engine. You would arguably be making the framework and the game at the same time. The problem is separating them.

You have knowledge of the game you are making while writing framework code. You could end up in a situation where the engine is not useful for a different (kind of) game, and tweaking it to be would break your old game. This happens because game specific abstractions made their way into the framework code. The more of them you put in the framework, the easier it is to make the game, and the harder it is to adapt the framework for a different game.

*The flip side is that without a game, it is hard to pin down the requirements for the framework.*

For a commercial game engine, the framework was built before the game. Thus, it does not know anything about the game. This leads naturally to a situation where the game is a plugin for the framework... and thus, switching from one game engine to another is hard. *Oh, and the companies that produce the game engines like that.* It also leads naturally to very a versatile framework. This is the state of the art. *Although not every commercial game engine is like this.*

---

Good software architecture will dictate to decouple the game. For instance, changes in the framework should not propagate to game logic. *Because of this, I’m against the framework requiring to inherit from its classes to use it.* You want to be able to make adapters with the right abstractions for the game at hand. Any change to the framework will only propagate to the adapters, and not any further. *Of course, if the framework wants inheritance, you can make the adapter inherit, and avoid placing game logic inside them.*

*Will come back to the idea of adapters.*

---

> editor

I would argue against an editor. It does not come naturally to write an IDE, unless you want to release it. What comes naturally is to make a set of tools. Each one for a specific task (such as a terrain editor, for example). And in that, you can often rely on third party solutions.

---

> multiplayer

Oh dear...

Do you mean networking? I think you mean networking. Couch multiplayer is not as popular as it used to be.

You need to decide if you are going to do any networking at all, and decide early. Having a big scary thing called network in the middle of your game will wreck your software architecture.

What kind of networking are we talking about? Will there be a central server? Will you do P2P? Should the game engine even decide that?

---

You want to isolate any external system. That includes input, network, graphics, sound, etc...

Isolating the input means, that you make an interface with whatever verbs the game needs and an adapter that implements the interface and uses some input device. If you want to support more input devices, you add more adapters.

Furthermore, who says that the input comes from an input device? It could come from a recording of inputs. This is useful for those good old game demos that arcade games did. It also useful to record a game session and replay it later. It is also useful for debugging.

In fact, who says the input comes from the same computer at all? The input could come from another player across the network!

There are two approaches that you may take around the network: send inputs, and send states. That is, you could stream every input a player does and replay them on the other side. Or you could send the state of the game objects and rebuild them on the other side. in fact, I would argue for supporting (if not using) both.

However, over which protocol? TCP? UDP? Websockets? WebRTC? How about using the Discord SDK? You know how this goes... you make an interface with the network operations the game needs, and then you implement the adapter with the underlying protocols you want. If you decide to switch protocols, you can implement another adapter.

And, yes, the same goes for physics. Perhaps you want to use Box2D, or Bullet, or PhysX... whatever, you make an interface and an adapter, you know the drill.

Similarly... OpenGl? How about DirectX or Vulkan or Metal? Well, you make... hmm... This one is trickier, because you have to deal with a shader languages. *Perhaps we can make a custom langu... wait...*

-- xkcd: Standards

I'd say go full GLSL and thus OpenGL. *Screw DirectX and Metal*. And if you decide to switch to Vulkan, you can convert GLSL to SPIR-V with KhronosGroup/glslang.

With that said, you probably should still make an adapter for OpenGL, and expose an interface that understand loading models and scenes instead of buffers and draw calls. You may also want it to compose shader programs.

---

I don't want to tell you here what to do about your game loop, or whatever or not you should use ECS, or stuff like that. You can research and figure what you want.

However, you should have a set of interfaces under you control, which the game can use to work. Keeping the game code free from details about the hardware or the libraries that the framework uses.

To pick what adapter to use should depend on configuration. You are going to need a composition root.

*Oh, do not forget some good infrastructure: error handling, logging, loading and saving configuration, etc.*

Thus, by virtue of software architecture we can distinguish:

* The game
* The interfaces
* The adapters
* The framework
* The composition root
* The IDE or other tools

You can choose to make modules like this, for example:

* The game
* The framework, composition root, interfaces and adapters
* The IDE or other tools

*The company that makes the engine is in control.*

That is not what software architecture would suggest, but it leaves the less work to develop the game module, while tying the game to the engine. *Like the company likes it.* You do not have to do it like that, bundle them however you want.

---

Finally, I want to recommend the video: Write a Game Engine? - WHY and HOW.

---
Tags: c#, opengl, 3d, game-design, software-engineering
---


# Question
Title: Turn-based combat AI with multi turn planning
My current AI system uses the now very common utility AI. I generate a list of possible actions, I then calculate fitness score for each action and generate a list of possible chains of actions (Move \> Attack \> Reload or Use Offensive Ability \> Leap backwards). The sum of those scores are then sorted and I pick the most (or not, depending on how smart I want the particular AI player to be) appropriate chain to execute.

The issue that I've run into though is that I'm having issues with more complex interactions that require multi-turn planning. To give an actual example: one of my characters got two spells that can deal massive damage when used in the right order.

1) A buff ability that increases target's Mind attribute (cast on self)

2) A powerful spell that deals damage based on your Mind (cast on the enemy)

Both of those actions cost a lot of Action Points and so you can't execute them both in one turn. A very obvious combo is to use the buff and then the damage spell, but if both of those actions are available to the AI, then it always chooses to open with the second action. The buff itself, when considered in isolation, produces a very low fitness score.

A very obvious idea is to then to allow the AI to build chains of actions for two or even three turns ahead. However, this greatly increases the performance cost as I'd have to use similar heuristics for other players to get at least somewhat reasonable gamestate for the AI to go off of. I would also have to think of a fail-safe mechanic for when the player does something unexpected, thus ruining this long-term plan.

Another idea that I had is to let the designer define interesting combos and have the AI see if it can execute one, but it feels messy and a bit hard to implement with the current generic system.

How do the other games do it?

# Answer
> 3 votes
When you have a game with a decision tree which grows too much when you plan too far ahead, then the standard solution is alpha-beta pruning: Don't waste time with exploring branches of the tree which are unlikely to provide good results.

Usually you would discard those branches with the lowest fitness ratings on their current iteration depth. But in this particular situation it could be useful to instead break off those branches early which are unlikely to result in useful combos.

You could add a flag to those actions which have the potential to be useful in a combo (buffs, debuffs, etc) and explore those branches which contain such actions to a deeper level than those which do not.

---
Tags: algorithm, ai, turn-based-strategy
---


# Question
Title: Unity's Box Collider isn't preventing an object from falling through the floor
I'm working on a little "Tower of Hanoi" AR game in Unity using Vuforia, where the game is projected onto an image target.
Now I wanted to make the rings "fall" into place, so I added an invisible ground floor plane, with a box collider, and added mesh collider and rigid body to my ring.

Here are the settings:

Now there are quite a few questions about objects falling through the floor around and I tried many of the different suggestions (thickness of box collider, continuous instead of discrete collision detection,...) but none of them solved my issue.

Since this is my second little Unity project, I guess the issue is obvious (maybe my ring is too small (few centimeters) or something, but I'm not sure.

The problem is also, that I can't really see what is happening during runtime, since the camera has to find the image target first, after that the ring (currently testing only the bottom one) is gone and I just see the y-value of it's position changing.

Any help is much appreciated!

# Answer
> 1 votes
Maybe you are making a simple mistake, for collision there is no need to add joints and all that. Just make sure to take these steps:

* add both side collider (3d or 2d as per game type)
* add Rigidbody for physics.
* don't tick `isTrigger` if you want collision.

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


# Question
Title: Script Component not Being detected by Vuforia's Default Trackable Event Handler Script
I have a Script Component named `Start` inside a `GameObject` named `StartSpawn` and I am trying to run a function from `Start` when the target is found but Unity/Visual Studio is not detecting the `Start` script component. I even tried restarting both Unity and Visual Studio to only worsen the problem. When I opened both programs again and inspecting the code, the code I added was deleted and the script `DefaultTrackableEventHandler.cs` was back to its original code. Btw, the function I'm calling to Instantiates a Prefab.

Here's the code inside the `DefaultTrackableEventHandler.cs`:

```
protected virtual void OnTrackingFound()
{
    if (mTrackableBehaviour)
    {
        var rendererComponents = mTrackableBehaviour.GetComponentsInChildren<Renderer>(true);
        var colliderComponents = mTrackableBehaviour.GetComponentsInChildren<Collider>(true);
        var canvasComponents = mTrackableBehaviour.GetComponentsInChildren<Canvas>(true);
        //test
        Start summoner = GetComponentInChildren<Start>();

        // Enable rendering:
        foreach (var component in rendererComponents)
            component.enabled = true;

        // Enable colliders:
        foreach (var component in colliderComponents)
            component.enabled = true;

        // Enable canvas':
        foreach (var component in canvasComponents)
            component.enabled = true;

        //test spawn
        summoner.OnAppear();
    }
}

```

# Answer
> 0 votes
For Vuforia, I am giving few tricks to you for instantiate object:

1. make a script `CustomTrackableEventHandler.cs`
2. add on image target in place of `DefaultTrackableEventHandler`.
3. copy code from `DefaultTrackableEventHandler` to `CustomTrackableEventHandler`.
4. add variable `public Gameobject prefab;`
5. add function in `OnTrackingFound()` and `OnTrackingLost()` as per this:

```
public void InstantiateObject(){
    Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity);
}

public void DestroyObject(){
    Destroy(this.gameobject);
}

```

This is just basic logic; if you want to learn advanced logic, let me know and I will help you.

---
Tags: unity, android, 3d, vuforia
---


# Question
Title: Rotating 2D bone in LateUpdate have jittering issue
I made a skinned 2D character and applied IK to each hand and leg.

In my game, player can aim up and down by moving fire joystick up and down. This is implemented by update "chest" bone's rotation in LateUpdate, because it renders after all animation stuffs.

Here'e the code I'm trying:

```
void Update() {
    // Handle move forward & backward
    ...

    m_FireMovement = new Vector2(m_FireJoystick.Vertical, m_FireJoystick.Horizontal);
    m_DeltaTime = Time.deltaTime;
}

void LateUpdate() {
    float verticalMovement = m_FireMovement.x;
    float horizontalMovement = m_FireMovement.y;

    // Which side facing? Depends on Fire Joystick.
    if (horizontalMovement < 0) {
        transform.rotation = Quaternion.Euler(0, 180, 0);
    }
    else {
        transform.rotation = Quaternion.Euler(0, 0, 0);
    }

    // Rotate chest bone depends on vertical input
    // TODO: Fix jittering issue
    float newRotation = verticalMovement * m_AimAmount * m_DeltaTime;
    m_ChestBone.Rotate(0, 0, newRotation);
}

```

It works, but there is noticeable jittering issue when aim up and down. Here's the video I recorded for demonstration: https://youtu.be/eYCY0NRG\_AA

So I tried with using Coroutine, invoked from "Start" and keep looping and wait until WaitForEndOfFrame, and try rotate chest bone, but that makes it worse.

In 3D project, rotating bone in LateUpdate didn't make any problem. What am I missing?

Using Unity 2019.1.0f2 and 2D Animation Package@2.1.0, 2D IK@1.1.0.

# Answer
> 3 votes
You should not multiply by delta time here:

```
float newRotation = verticalMovement * m_AimAmount * m_DeltaTime;

```

Multiplication by delta time is useful when you're accumulating an incremental movement each frame, so the total movement builds at a consistent rate even if your frames are uneven durations.

But that's not what you're doing here.

Here, every frame the animation update resets the chest bone to its position & orientation in the animation data, erasing whatever you did to it last frame. So the correction you apply in `LateUpdate` isn't an incremental accumulation into a total state that persists from frame to frame. It's your one and only chance to snap that bone to where you want it.

If you multiply your correction by delta time, then on longer-than-normal frames you rotate further from the animated pose, and on short frames you rotate less. So the net result is that you vibrate back and forth in the vicinity of your average frame duration.

So, delete the delta time part here and adjust your aim amount variable to keep the overall rotation in your desired range.

# Answer
> 0 votes
Smooth Quaternion Rotation - Unity Answers

Possible solution might be to rework the code to use `Quaternion.RotateTowards();`

Another thing to try would be a simple scalar multiplier on `m_DeltaTime` or `m_AimAmount`, sometimes multiplying it by a random number like 20.0f or 0.5f will help smooth `newRotation` by having less difference between frames.

If none of that helps, you could try reworking the `m_FireMovement` to also be a delta between frames (how has movement changed from last `Update()` ) or an offset from center / normal rotation

---
Tags: unity, 2d, skeletal-animation, skinning, bones
---


# Question
Title: How to apply linear drag to a velocity vector?
I have built my own movement code for my character as I want to make smooth movement. (This project is just a character and a floor/wall for testing).

The code seems to work fine, but I of course need to apply my own drag somehow. I've tried many ideas for this, and tried to read around a lot. But I can't work out if this code I made is frame dependant or not.

I am getting 120fps in Unreal editor for example (and my monitor is 144hz if that affects it), but what if someone played my game and was on 60fps, or another number.

After many hours I came up with the code below, and I did even go on the calculator and try to test with various numbers, but sadly I'm no expert mathematician, I wasn't sure if the figures I got meant it was good or bad.

Anyway, here is the move method, pretty self-documenting. With the drag part at bottom. Does this drag formula apply consistent drag for the character over any frame rate?

```
void APostie::Move()
{
float DeltaTime = GetWorld()->GetDeltaSeconds();
FHitResult Hit;

CurrentVelocity.X = FMath::Clamp<float>(CurrentVelocity.X + (InputAxisVector.X * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
CurrentVelocity.Y = FMath::Clamp<float>(CurrentVelocity.Y + (InputAxisVector.Y * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
FVector ForwardMovement = GetActorForwardVector() * CurrentVelocity.X;
FVector SidewaysMovement = GetActorRightVector() * CurrentVelocity.Y;
FVector Velocity_Localised = ForwardMovement + SidewaysMovement;

float r = 1;
FVector DeltaMovement = Velocity_Localised * (FMath::Pow(r, DeltaTime) - 1.0f) / FMath::Log2(r);

AddControllerYawInput(LookAxisVector.X * LookSpeed);
GetMovementComponent()->MoveUpdatedComponent(Velocity_Localised, GetActorRotation(), true, &Hit);

// Apply drag
CurrentVelocity *= (1 - WalkDrag) * (1 - DeltaTime);
if (CurrentVelocity.IsNearlyZero())
{
    CurrentVelocity = FVector::ZeroVector;
}
}

```

NOTE: WalkDrag is a uproperty set to 0.01f.

Also, I do of course realise I need to clamp the velocity and to handle hits so velocity is set to zero if I hit walls etc. I'm doing that now, but meanwhile still unsure about this drag formula.

UPDATE: I've tried to take on board DMGregory's help. Here is what I came up with:

```
void APostie::Move()
{
float DeltaTime = GetWorld()->GetDeltaSeconds();
FHitResult Hit;

CurrentVelocity.X = FMath::Clamp<float>(CurrentVelocity.X + (InputAxisVector.X * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
CurrentVelocity.Y = FMath::Clamp<float>(CurrentVelocity.Y + (InputAxisVector.Y * WalkForce), -MaxWalkSpeed, MaxWalkSpeed);
FVector ForwardMovement = GetActorForwardVector() * CurrentVelocity.X;
FVector SidewaysMovement = GetActorRightVector() * CurrentVelocity.Y;
FVector Velocity_Localised = ForwardMovement + SidewaysMovement;

float r = WalkDrag;
FVector DeltaMovement = Velocity_Localised * (FMath::Pow(r, DeltaTime) - 1.0f) / FMath::Log2(r);

AddControllerYawInput(LookAxisVector.X * LookSpeed);
GetMovementComponent()->MoveUpdatedComponent(DeltaMovement, GetActorRotation(), true, &Hit);

// Apply drag
CurrentVelocity *= FMath::Pow(r, DeltaTime);

}

```

# Answer
Well I'd say that every time you calculate your velocity, you should add your drag to it.

Framerate independency is hard to achieve in Unreal, given its reliance on ticking components. So long as you use deltaTime every time you're calculating anything, you should be fine.

```
Force = Mass * Acceleration.

Acceleration = DragForce / ObjectMass

Velocity = InitialVelocity + 1/2(Acceleration * time^2)

FinalVelocity = InitialVelocity + 1/2( (DragForce / ObjectMass) * DT^2 )

```
> 1 votes

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


# Question
Title: Pathfinding With Speed Based Turning Restrictions
I have been working on a path finding project and I’m a bit stuck at the moment. I have an object that can increase or decrease speed, but the faster it moves the larger it’s turn radius is - so a car basically. I’ve implemented A\* with a smoothing algorithm to generate waypoints for the object, however, as you might guess, it doesn’t take into account anything with speed and such. Currently, I’m moving the object at a set speed along it’s forward vector and at each waypoint lerp the direction to the next waypoint.

Is there a method - or a place to start looking - to implement a system to find the best route that’s possible by slowing or taking larger turns? At this point I’d even settle for a way to tell the object exactly how much it needs to slow down for each turn. Thanks for any help!

# Answer
---

## A\* for large search spaces

You do not need to have a graph to run A\*.

*What?*

You only need to be able to query where you can go from a given node. So, when A\* wants the lists of the neighbor nodes, you generate them. You can even lazily generate※ them along with the heuristic values.

Each node will be a position plus an orientation (and probably a speed too, I'm not sure how you handle acceleration). And from there you will generate other nodes corresponding to the state of the car for different changes in speed and orientation.

You, of course, need your heuristic. And whatever heuristic you have for position only would remain admissible for these nodes.

---

※: In general, you want a method that gives you *the next* neighbor. And you call it *to iterate*. That is, you do not generate all the neighbors before iterating over them.

---

**Memory problems**

A\* memory use is exponential. There are two common improvements for A\* to deal with that:

* Iterative Deepening A\*: You use the heuristic of the distance from the start node to the goal to set a limit of how long a path should be. If the cost is greater than this limit, you consider the node closed.

If you did not find a solution, you increase the limit, you move all the closed nodes to open, and explore them again.
* Memory bounded A\*: There are nodes in the open set that are unlikely to lead to a better solution. *So, you are going to get rid of them.*

The idea is that you have a maximum number of items in your open set. If you reach that capacity, you remove the worst. So you never have more than your maximum, and thus your open set does not run out of memory.

---

## Exploring a car driving space

Of course you can explore the whole range of turning angles and speeds.

However, ideally you will generate nodes that reduce the heuristic value first. We are going to approximate that. The idea is that it is better to orient the car correctly first and go fast in stright segments.

You are going to need a function that does this for a time interval:

1. Take a node and a turning angle as input.
2. Figure out what is the higher speed at which the car can turn that much. If there isn't take the minimum speed and the angle what the minimum speed would let you. *You need consider how much the speed can change in the time interval.*
3. Compute a new node that is the result of turning at that angle at that speed.
4. Assume the car goes straight, so set a turning angle to 0
5. Decide an angle step based on the turning angle that would make the car face the goal
6. Feed it to the function, get a node, yield the node to A\*
7. Increase the angle by the step, if the angle has done a complete turn, you are done
8. Repeat from step 2

Please remember that you are feeding nodes to A\*. A\* is still in charge of picking the best path.

For tweaks, consider that making the angle step smaller will result in more nodes. You may, for example, make it a function of nearby obstacle or the distance to the goal. You can do something similar to time steps. That should give the car more maneuverability where needed.

---

## Two level search

If you create a nav-mesh, with large convex areas. The connectivity of the areas is valid, regardless of the speed of the car. You can path find in this coarse nav-mesh, so you can figure out the general path before you worry about car speed and orientation.

Then you can path find with more complex rules from one areas of the nav-mesh to the next. I know that A\* says that you compare the node to the goal. Don't do that, instead you are going to implement the goal as a predicate, which says "it is in the next nav-mesh".

Once you have found a solution that moves the car to the next area of the nav-mesh, you can reconstruct the path, clear memory, and continue the search to the next area of the nav-mesh, which will give you another section to add to the path. You continue like that until you are at the last area where you search for the goal position.

---

## Time budget

Breaking the search algorithm so that it conforms to a time budget is harder, yet possible. Turn the search algorithm into a state machine. To do that, you write it as continuations. Then represent the continuations as data (see "defunctionalization"). *Immutable data structures are good for this.* With that, you can store the current state of the algorithm when the time budget for it is up and extract partial results.

The partial results of the search algorithm up to where it could run in the time budget have some known cost for some nodes, pick among the nodes with known costs the node that would bring the car closer to the goal as per the heuristic, so the car can start driving, even though the search didn't have time to figure out the path to the goal.

In theory you can resume the search the next time budget. Although, I do not think that is very useful for the car, given that backtracking requires to do a U-turn, not simply retracing steps.

If you use the two level search as described above, you can have some confidence that the path is going in the correct general path, and that it will not have to do a U-turn. For the small chance of that happening, you would have to check if the algorithm has gone a different path than the one the car went, and if so, start searching again from the current position of the car.
> 1 votes

# Answer
Add the speed of the vehicle (and the direction) to the search space and let it affect which the possible neighbouring nodes are.

This means that 2 nodes are the same if and only if they are in the same position, have the same direction and are for the same speed.

When generating new nodes you have the range of full left and right possible for the speed, the range left and right when braking (down to 0), and the range left and right when accelerating (up to your speed limit).

This has the downside that the search space is a lot larger, but using the heuristic to prefer larger speeds should avoid needing to explore too much of the walking speed space.
> 0 votes

---
Tags: path-finding
---


title: Instantiating Prefabs at run time

text:
# Question
Title: Instantiating Prefabs at run time
I'm trying to move my project to Addressables and upload assets, prefabs and screens to an archive on the server.
I'm a new in Unity and this a bit challenging for me.
I've prepared all prefabs for addressable usage and now I'm trying load them.

All my prefabs have loads throw `GameObject.Instantiate` For example:

```
    public class PlatformObject : LocationObject
        {
//other properties and methods
            public PlatformObject Clone()
            {
                var clone = ((Runner.PlatformObject)GameObject.Instantiate(this));
                clone.Id = this.Id;
                clone.NextPlatforms = this.NextPlatforms;
                clone.IsStartPlatform = this.IsStartPlatform;
                clone.Level = this.Level;
                clone.Type = this.Type;
                clone.MinimumDistance = this.MinimumDistance;
                clone.AllowDispose = false;
                clone.Size = this.Size;
                return clone;
            }
    }

```

I've tried change this code for usage `Addressables`.

```
public async Task<PlatformObject> Clone()
        {
            var handle = Addressables.LoadAssetAsync<GameObject>(this.name);
            var clone = (await handle.Task).GetComponent<PlatformObject>();
            clone.Id = this.Id;
            clone.NextPlatforms = this.NextPlatforms;
            clone.IsStartPlatform = this.IsStartPlatform;
            clone.Level = this.Level;
            clone.Type = this.Type;
            clone.MinimumDistance = this.MinimumDistance;
            clone.AllowDispose = false;
            clone.Size = this.Size;
            return clone;
        }

```

I've got a cloned object successfully, but object doesn't appears on the scene. Looks like object not initialized properly, bcouz I've got a lot of warnings like that:

> Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject: 'Mid\_Town\_07'). UnityEngine.Transform:set\_parent(Transform)

I've googled and have found a few solution related with parent location. Made changed but it didn't help. I'm still getting those warnings.

# Answer
You will need to also Instantiate the object before setting it's parent transform as it's not yet an instance when you call LoadAssetAsync.

See the docs here: https://docs.unity3d.com/Packages/com.unity.addressables@1.1/manual/AddressableAssetsGettingStarted.html

Notably this line:

```
Addressables.InstantiateAsync("AssetAddress");

```

Or alternatively once you have the GameObject, instantiate it as normal.
> 3 votes

---
Tags: unity, assets, prefabs
---


# Question
Title: How to prevent players from forcing the veto-holder to give up their veto power?
In this game there is a President and the members of the Senate. Most are good, but a few are evil pretending to be good. Each day the majority attempts to figure out who is evil (using clues), takes that player to court (where they may argue in their own defense), and then the entire Senate votes on whether to convict that player (eliminate them from the game) or acquit them.

Only 2 such trials are allowed per day (at night, the evil players murder someone), but only 1 conviction per day.

The President may secretly be good or evil, and differs from the rest only in that he has a veto ability. If someone is taken to court, the President may at any time before the verdict is declared, instantly acquit or convict them.

He may do this only 1 time.

**IMPORTANT EDIT:** *The President must exercise his veto power while voting is in progress, before the decision of the majority has been made public.*

The problem is, the other members of the Senate, unwilling to risk the possibility of an evil President overriding the majority decision to convict an evil player at a crucial point later in the game, have developed a meta where the very first time everyone agrees to convict or acquit someone during the first trial of the game, they vocally demand the President to "waste" his veto power in agreement with the majority vote.

If the President refuses they simply take him to court and convict him, eliminating him from the game.

This effectively reduces the President to a normal player.

How can this sort of meta be prevented?

I've tried giving evil players the ability to temporarily disable the President's veto power, in order to give the President a plausible excuse for not using it immediately. This was an unsatisfactory solution because the evil players did not use it enough for the President's excuse "I was disabled by an evil player" to be convincing. Evil players simply did not care whether the President could veto because it's too early for them to tell whether the President is on their side or not.

# Answer
It seems like you initially had the veto work all the time, but then figured out that this makes the president too powerful, as she can always override the senate. You tried to nerf it to once per game, but as you found out, that's too much of a nerf, because the other players can compel the President to waste it.

You might have to do another redesign of the veto power of the president.

You could do it like the legislative system in the United States does it: The president has a veto she can use as often as she wants, but the Senate can "veto the veto" with a 2/3 majority. That way the presidential veto is still powerful, but not almighty, because the president still needs at least some support for her veto to stay valid.

This of course creates an interesting situation: When 1/3 of the senate are evil, the President is also evil and Team Evil coordinates properly, then they just won the game because the good players no longer have a veto-proof majority to execute players they know to be evil.

This situation could be solved by forbidding the president from using her veto to protect herself. When the good player believe that the game is in this situation, they can execute the president with a simple majority and still have a chance to win.

---

Another option could be to completely redesign the role of the president. For example, you could give the President the sole authority to decide which player is taken to court each round. When the players decide to not convict the player proposed by the president, they then immediately get the option to vote on whether or not to kill off the President instead.
> 5 votes

---
Tags: game-design, balance, social
---


# Question
Title: Unity SkinnedMeshRender: is there a way to cache mesh and restore later?
In unity, I'm writing a script that deforms a mesh associated with a SkinnedMeshRenderer pretty significantly. However, at some point, I'd like to reset it back to particular states. I'd like the ability to both reset to its original position, and an intermediate position.

Right now, I've tried baking the mesh:

```
Mesh originalMesh = new Mesh();
skinnedMeshRenderer.BakeMesh(originalMesh);

```

But when I then try to restore it:

```
skinnedMeshRenderer.sharedMesh = originalMesh;

```

It doesn't seem to behave as I would have expected.

I've also tried:

```
Mesh originalMesh = skinnedMeshRenderer.sharedMesh;
//deform sharedMesh
skinnedMeshRenderer = originalMesh;

```

but this does nothing since it seems to be just storing a reference.

Am I missing something obvious here?

Just to add detail, I want to take a snapshot of all the verticies, weights, blendshapes, etc. And then restore everything back to the snapshot at a later moment in time. I can reset the blendshapes fine, but the mesh seems to be messed up.

# Answer
Based on @DMGregory 's helpful comments, here is my solution:

---

To Cache (called in `OnEnable()`):

```
        void CacheMeshAndSkeleton() {
            if (originalBonePositions == null) {
                originalBonePositions = new Vector3[skinnedMeshRenderer.bones.Length];
                for (int boneIndex = 0; boneIndex < skinnedMeshRenderer.bones.Length; boneIndex++) {
                    originalBonePositions[boneIndex] = skinnedMeshRenderer.bones[boneIndex].position;
                }
            }
            if (originalMesh == null) originalMesh = skinnedMeshRenderer.sharedMesh;
            skinnedMeshRenderer.sharedMesh = Instantiate(originalMesh);
        }

```

Note that the null-check isn't really needed. For me it was, since I'm running the script in edit mode using `[ExecuteInEditMode]`, and edit mode seems to call OnEnable more than once, so I needed to prevent it from overwriting the original mesh with a deformed one.

---

To Reset:

```
        void ResetMeshAndSkeleton() {
            for (int boneIndex = 0; boneIndex < originalBonePositions.Length; boneIndex++) {
                skinnedMeshRenderer.bones[boneIndex].position = originalBonePositions[boneIndex];
            }
            skinnedMeshRenderer.sharedMesh = Instantiate(originalMesh);
            // Note that it seems to me that order might be important here.
            // If you reset the the Mesh first, when you move the bones back,
            // it will apply linearblendskinning to the mesh and deform it to the bone positions.
            // Not sure why this matters, but seemed to in my testing
        }

```

This seems to work great!

UPDATE:

I found an increase in performance by instead caching the mesh's arrays (vertices, etc) and swapping them back to restore.

I used the CopyTo array function. `sourceArray.CopyTo(destinationArray, 0);` where 0 is the index to start copying from.

In my case I was only manipulating the vertices, the tris, normals, etc were never altered, so just copying this one array saved a huge amount of performance vs. instantiation.
> 2 votes

---
Tags: unity, mesh, skinning
---


# Question
Title: Missing UI options in Inspector window when I import FBX files
I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files.

In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well.

This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.

# Answer
> 0 votes
These are NOT solutions to our problem, but work-arounds.

**METHOD A: Using only Unity 2019.3**
After noticing that Avatar Definition its empty/none byt default in 2019.3 I used Create From This Model to have an actual avatar to deform my model:

Then, in order to define loop time/pose and clean up animation clip names, I had to CLONE (ctr+D) all animation clips in the Project window and apply animation clip attributes into the cloned one, like this:

Now you can have your animation clips working in your model.
**METHOD B: Using only Unity 2019.3 + 2019.2**
Import as always your FBX in a Unity 2019.2 project and be sure to go to Animation Tab in the inspector of the FBX, and mark any checkbox that force you to apply changes (in my case I checked Loop Time in Idle animation clip), now the metadata file will be updated with the info needed by 2019.3. Create a custom package and import it to your 2019.3 project, all the meta data and import properties will be there this time like shown in the picture below:

Hope this helps and that Unity guys fix this bug. This doesn't look like a configuration issue but a problem in this new version.

---
Tags: unity
---