# Question
Title: How to update the data in the source code to avoid cheats?
I developed a multiplayer fps game in C++ and many peoples appreciated it, and today someone has created cheats for my game and he is trying to spoil my hard work which I spend developing the game. I am not expert to create an anti cheat system but I know by updating or releasing the new patch can avoid those cheats for a little time and then after some time I will need to update it again.

I want to know the quick and easy way to update all the files. This is a headache to search manually for all classes and strings and values to update them.

Data I want to update to avoid speed hack, aimbot, wall hack and flying hack.

# Answer
> 4 votes
I'm sorry to bring you bad news, but unfortunately it's not really possible to prevent cheating client-sided. Anything which runs on the client is under the control of the client. You can use some commercial anti-cheat tool which spies on the users personal files looking for cheats, but those are expensive, ethically questionable and can not really prevent cheating either. They can make it harder, but anti cheat tools are also software which runs locally and thus can be hacked by a determined user.

But speed hacks and flying hacks are easy to fix server-sided by a simple heuristic which detects when players move in ways they are not supposed to.

Wallhacks can be partially prevented by changing your network protocol to do some visibility calculations on the server and not send position updates about objects to clients which should be unable to see them.

Automation hacks like aimbots are pretty hard to prevent, because a sufficiently advanced aimbot is indistinguishable from a very good player. But you can at elast try to detect naive aimbots by a server-sided heuristic which detects unnatural rotation movements (when the rotation change per tick is low, then suddenly very fast for just a single tick, ends up pointing exactly at an opponent and is then very slow again, then that's very suspicious). After your first couple bans, the cheat programmers will get creative and try to make the movements of their aimbots more natural (which will also make them perform worse). You can make it a lot harder for them to figure out how much they need to nerf their aimbots when you don't kick people immediately but wait a couple days.

---
Tags: c++, anti-cheat
---


# Question
Title: Geometry shader-generated tile mesh isn't any faster than CPU-generated version
For practice, I'm writing a Rogue-like. In order to speed up tile rendering I have a dynamic Mesh/MeshBuilder that collects all the vertices of the visible tiles' quads (4 vertices per tile: position, color, UV; and 6 indicies) CPU-side and emits a single draw call of the large tiled triangle mesh. At 600 FPS/0.0017 ms this is fast enough for my purposes.

I recently decided to practice with the various rendering pipeline stages and thought that this would be a great candidate for the geometry stage and have the GPU generate the tiles for me, passing in only a single vertex/index pair per tile.

There are as many as 2000 tiles visible per frame, yet it was no faster than the CPU version despite passing one quarter the amount of vertices and one sixth the indicies across to the GPU.

It's my understanding that it is a best practice to minimize the amount of data passed between the CPU and GPU, and hand off work to the GPU that it is better suited to do.

**Am I wrong in this understanding?**

**It seems like the geometry shader isn't that useful if offloading work to it doesn't have a benefit?**

**What can be achieved with the geometry shader that other techniques can't do?**

# Answer
This looks like a case of bottlenecks.

When you have a sequence of steps that depend on each other, like...

* uploading data buffer to the GPU
* issuing the draw call
* generating the vertices
* transforming those vertices to the viewport
* rasterizing the resulting triangles
* interpolating values for each fragment
* rendering each fragment
* writing the results to the frame buffer

...then the whole pipeline cannot proceed faster than the most time-consuming operation in the sequences. In chemistry this is called the "rate-determining step," while in programming and graphics we call it a "bottleneck".

Making the operations before or after the bottleneck faster won't substantially speed up the whole, because your time is still dominated by the bottlenecked step. (You can sometimes slightly improve the latency this way, but you don't change the total throughput)

One important bottleneck in graphics is "fill rate". There's a limit to how fast the GPU can write the results of an operation out to the frame buffer. You'll often hit this one if you have very simple shaders that draw over large parts of a high-resolution output target, especially if you draw over them again and again (eg. layering lots of translucent blended sprites)

Another common bottleneck is texture bandwidth. There's a limit to how fast the GPU can read, decode, and interpolate texture samples. You'll often hit this one if you sample a lot of large textures in random patterns that make it hard for the texture cache to re-use recent samples.

For a use case like yours, where building and uploading a few thousand quads really isn't very heavy lifting by modern GPU standards, and you're not doing any fancy calculations in your shader that might slow it down, then either of those two bottlenecks above might end up being the slowest part of your pipeline.

Making the generation/upload step faster won't necessarily give you an observable improvement in framerate, because it's not what was costing most of the time in the first place.

If that's the case, then scaling up your problem size by increasing the number of tiles (while keeping the textures and output resolution the same) will tend to make the cost of that generation/upload higher while keeping the texturing/fill rate costs about the same. Eventually you'll hit a tipping point, where now the generation/upload is the slow part.

At that stage, you may start to see a clearer comparison between your CPU and Geometry Shader methods, without the rendering costs common to both solutions muddying the picture. From your comments, it sounds like that's what happened.
> 1 votes

---
Tags: directx, directx11, hlsl, geometry-shader, dynamic-mesh
---


# Question
Title: Spotlights and Pointlights not working with Unity Render Pipeline?
I'm experimenting with URP, Render Pipelines, and Shaders for the first time recently and have noticed something odd. In the scene I'm building, Point Lights and Spotlights don't work. No matter what I do, they do not affect the environment at all, for static and nonstatic objects. I can't even use a Halo component to visualize them. They exist in the scene but don't do anything and even Lightmaps don't seem to register them.

I suspect that it's because of the render pipeline, but if I go to a blank scene and put a spotlight on an object, it works. I'm just very confused what's happening.

Any idea what might be happening?

# Answer
> 1 votes
As suggested in the comments, clearing Unity's preferences cache made the issue go away.

# Answer
> 0 votes
Not sure if this is the same problem, but I've had a similar issue before on 2019.3.0 (lights work in new scenes but not in original; although I was working with 2D lights) and deleting and replacing the camera on the scene somehow worked.

I think URP makes changes to the camera component, but they don't get updated in your scenes?

---
Tags: unity, lighting
---


# Question
Title: Where to attach global scripts in Unity?
As far as Iknow in Unity, every script must be attached to an object. But what is the case with global scripts? For example in a tetris-like game to which object should I attach the element spawner and mover scripts? Or should a the element handle its movement for itself? Is there any best practice for this problem?

# Answer
To expand on Tetrad's answer, consider a script like this:

```
public class GameSystem : MonoBehavior
{
  public static GameSystem Instance { get; private set; }

  void Awake()
  {
    if (Instance != null) {
      Debug.LogError("There is more than one instance!");
      return;
    }

    Instance = this;
  }

  void Update()
  {
    // global game update logic goes here
  }

  void OnGui()
  {
    // common GUI code goes here
  }

  // etc.
}

```

You can then create an object called "GameSystem" in the root of your scene. The only components it would have would be the built-in transform component (set its position to the origin, its rotation to identity, and its scale to one; not that it matters, but it's good practice). Attached the GameSystem component to that object.

You can now access your global object by simply using GameSystem.Instance.blah(). Its event handler methods are invoked automatically by Unity since it derives from MonoBehavior and exists as a component. You can add fields to it that reference other game objects or components and connect them in the Unity object hierarchy view.

Yes, this is all a little "weird." It can feel a little dirty to have to create an object (that even has a transform) which is always just a global singleton. It's what Unity requires to create global objects that get an Update message and are manipulable with the default Unity property editor, though.
> 17 votes

# Answer
Just create a manager object that you put that script on. Maybe make a static variable for that script that you assign on `Awake` so you have easy global access to it.
> 3 votes

# Answer
This Unity tutorial shows how to create a singleton object.
> 0 votes

---
Tags: unity
---


# Question
Title: Unity Input System: Rebinding composite parts
I have controls for movement defined as composite Binding through Vector 2D.

I have shown in settings any single binding which is not composite. I understood that I must get a composite index for binding, which is correct, I got the right binding like up, down, ...

But whenever I click on button for change something on Move, whole game freezes. And I can't do anything... Is there something I'm missing, when rebending part of composite?

Here is my code and screen, how the control settings looks.

```
public void Start()
{
    Button.onClick.AddListener(() =>
    {
        Key.Text = "Listening";

        _operation = Action.PerformInteractiveRebinding()
            .WithTargetBinding(BindingIndex)
            .Start();

        _operation.OnApplyBinding((op, path) =>
        {
            Action.ApplyBindingOverride(BindingIndex, path);
            Key.Text = Action.bindings[BindingIndex].ToDisplayString();
            _operation.Dispose();
        });
    });
}

```

# Answer
> 2 votes
If you open the package manager, and select the Input System package. You can open the samples dropdown and select the Rebinding UI example. This contains an example for rebinding composite aswell. I would suggest looking at that as it contains a lot more information compared to my answer here.

When I tested your code and compared it to the example, I think your problem originates in the following line:

```
_operation = Action.PerformInteractiveRebinding()
    .WithTargetBinding(BindingIndex)
    .Start();

```

I think it should be like this for it to work properly:

```
_operation = Action.PerformInteractiveRebinding(BindingIndex)
    .Start();

```

Don't ask me why as I actually haven't used the new input system yet. But in the test I did this made a difference...

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


title: Character Controller Rotation in Unity

text:
# Question
Title: Character Controller Rotation in Unity
I am using the following code for moving a capsule:

```
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);

```

I am using the following code for the camera, which is a child of the capsule. (xRotation is intialized to 0.0f, and playerBody is a transform):

```
        float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

```

The character is always moving in the same direction, ignoring the rotation. How can I fix this?

# Answer
> 0 votes
I'm not quite sure what you mean by "ignoring the rotation". However, I'm going to assume this is based off Brackey's FPS movement tutorial, as I have the same code in one of my older projects, and that you are trying to achieve the same thing as the tutorial. In that case, you need to change Vector3 move to

```
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;

```

I'm fairly sure that you can also do this

```
Vector3 move = transform.right * Input.GetAxis("Horizontal") + transform.forward * Input.GetAxis("Vertical");

```

and have the code work

The reason your code is not working is because Vector move will move to the player to a world position, which means it will ignore rotation.

By changing the code to this, the direction of the x and z values will be aligned to the player's x and z axis, meaning that if the player rotates, the axis will rotate as well.

I'm far from an experienced programer, but I hope I explained it well enough.

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


# Question
Title: How can I programmatically change a sprite's pivot without it affecting a game objects current position and rotation?
Because of the complexity of positions, I am using the centre pivot for my game objects sprite. Can I possibly change the pivot without it affecting the game objects current position and rotation? or in other words, can I change the pivot while the sprite remains unchanged visibly? I would preferably like to do this using c# script.

# Answer
> 3 votes
Of course:

`RectTransform::pivot`

> The normalized position in this RectTransform that it rotates around.

Now, if--while changing the pivot--if you don't want it to also move (like what happens in the Unity Editor when you fiddle with the values), you'll have to do some math. Math fortunately Unity has already built in if we don't mind moving between hierarchy transform coordinate systems using `TransformPoint` and `InverseTransformPoint`, rather than working these out for ourselves using a lot of trig (I hate trig and you should too: someone probably already did it).

```
Vector3 GetNewAnchor(RectTransform rt, Vector2 newPivot) {
    Vector3 op = new Vector3(rt.rect.width * newPivot.x - rt.rect.width * rt.pivot.x, rt.rect.height * newPivot.y - rt.rect.height * rt.pivot.y, 0);
    Vector3 pt = rt.TransformPoint(op);
    return rt.parent.InverseTransformPoint(pt);
}

```

What this does is transform a point in local space (the XY position of our new pivot) into world (scene) space and then back down into the local space of the sprite's parent object.

Now you can just do this:

```
RectTransform rt = (RectTransform)sprite.transform;
Vector2 newPiv = new Vector2(0.2f, 0.8f);
Vector3 newAnch = GetNewAnchor(rt, newPiv);
rt.pivot = newPiv;
rt.anchoredPosition = newAnch;

```

Be aware that you need to call `GetNewAnchor` *before* modifying the pivot point.

# Answer
> 2 votes
I made a tool for setting the Sprite pivot points in the editor while maintaining their world positions: https://github.com/thepowerprocess/UnitySpritePivotEditor

This is the part where the sprite texture is edited:

```
SpriteRenderer sr = selectedGameObject.GetComponent<SpriteRenderer>();
string path = AssetDatabase.GetAssetPath(sr.sprite.texture);
TextureImporter ti = (TextureImporter)AssetImporter.GetAtPath(path);
Vector2 newPivot = new Vector2(childMousePos.x / (sr.sprite.texture.width / sr.sprite.pixelsPerUnit), childMousePos.y / (sr.sprite.texture.height / sr.sprite.pixelsPerUnit)) + ti.spritePivot;
ti.spritePivot = newPivot;
TextureImporterSettings texSettings = new TextureImporterSettings();
ti.ReadTextureSettings(texSettings);
texSettings.spriteAlignment = (int)SpriteAlignment.Custom;
ti.SetTextureSettings(texSettings);
ti.SaveAndReimport();

```

# Answer
> 0 votes
I'm not aware of unity specific stuff, but what you can do to change the center of rotation of an object is: translate it to the wished origin, rotate it, translate it back. If T is the translation, T' its inverse ("the translation back") and R the rotation, you can then try something like

```
Transform t = T' * R * T;
myObject.transform(t);

```

(Again, this might need to be modified for unity's syntax and depending on whether their matrices are column or row major, feel free to edit to make this more Unity compliant)

---
Tags: unity
---


# Question
Title: Blender rigid body physics animation into Unity?
I'm stuck trying to get these cube objects to explode into chunks when destroyed in Unity. I've set up a physics sim in Blender of the effect I want, originally planning to replace the unbroken GameObjects with this fragmented one coupled with the explosion animation upon destruction. I guess it's not that simple.

I've tried "Bake to Keyframes" in blender and exporting as an FBX, but Unity imports each individual fragment with its own Animator/Avatar and a crazy amount of animations, which is almost useless. Any better ways to go about this?

# Answer
From this, I can see two solutions. Either you could recreate the effect in Unity, thus negating the problem entirely and leading to potentially cooler results, or you could just fix and export the thing.

**Reanimate in Unity**

Rather than trying to get the object and its animations to export from Blender into a usable format, you could export the model and reanimate it in unity. This would not only involve slightly less hassle, but it might even create a cooler effect, since you could use real-time physics and collisions in-game.

First, export the model, and import it into Unity. You may want to parent the little pieces of the cube to an empty before or after the export so you can keep track of them more easily.

Once the model is in Unity, you could use Unity's built in physics to create the effect in real time. Add mesh colliders and rigidbodies to each piece of the cube, and make a script that launches each piece away from the cube when it needs to explode.

**Just Export It!**

If you really need to have the animation that you made in Blender, then you need to clean up the model some before you can export it. The current problem is that each piece of the cube isn't connected, but is instead its own separate object. This means that Blender has made a separate animator for every piece of the cube.

To fix this, you need to create an empty axis object and parent all of the pieces to this object. Then, bake the animation to keyframes on the axis object. Make sure that you remove any keyframes on the pieces before baking. This should fix the issue, so try exporting the file again.

If it still doesn't work, then you will have to get destructive with your work. You will need to delete the animations off the pieces and recreate them as a single animation, with the empty axis as the animator. Since this completely deletes the animation, you may just want to recreate the effect in Unity if you reach this point.

**Either Works**

I would recommend recreating it in Unity, but it entirely depends on your needs. If this is part of a character's animation, or if you are on a very tight performance budget, then freely moving physics objects may not be the best option. But if you just want to use this as an interesting effect, or even if this is in a cutscene, then Unity's physics may give better results.
> 3 votes

# Answer
What solved the problem for me was: select all the parts then Object-\>Rigid Body-\>Bake to KeyFrames. Export as FBX with Animation option selected and selected objects. The parts will be automatically attached on one parent. Note I am using a FBX exporter add on called Better FBX but should work with the regular FBX exporter
> 2 votes

---
Tags: unity, animation, blender, fbx
---


title: Unity 3D Slow car (wheel colliders)

text:
# Question
Title: Unity 3D Slow car (wheel colliders)
My car is moving very slowly even though I apply high amounts of torque to the wheel colliders. The only thing I found to be helpful was to increase the wheel's friction stiffness, but that really messes up the braking and makes the car shake.

The values I use for setting up the car and torque are realistic (1500 kg car, 20 kg wheels, a realistic torque value accounting for gear ratios etc.), so I don't understand the problem.

# Answer
I think your wheels are slipping. You can check that using rpm attribute from wheel collider component and compare with the rpms of a real life wheel with same specs(radius, current speed of car), you can use https://courses.lumenlearning.com/physics/chapter/6-1-rotation-angle-and-angular-velocity or search by yourself, and use velocity vector of the rigidbody(transform to local and get .z component) to get velocity of car in game. If you have considerable much more rpms or less in unity this means that is slipping, respective skidding, so you lose traction. In this case you have to change forward friction values until the values are similar. Sideways friction is used only for turns, but maybe this have to be change too for smooth movements.

A little difference have to exists, from that difference you have the traction force, this difference is **slip** from curve graphic from the manual. The slip is difference between angular velocity of wheel and linear velocity of car. If slip is too big you will get the asymtote value. So you have to get the corect forces to move the rigidbody with optim slip.

Wheels colliders are very tricky and working with try and error for many of us.
> 1 votes

---
Tags: unity, physics
---


# Question
Title: Why is Camera turning with different speed than Player with same code in different scripts? (with unity)
I want to integrate a running character in my game, so I downloaded an animation via Mixamo. The player is running and if I attach the camera directly to the Player, it's shaking the camera and the game is not playable. Therefor I made a different script for the camera. In there, the camera is always following the player but turns (like the player) via

```
float h = PlayerMovement.horizontalSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, h * Time.deltaTime * 60, 0);

```

(for the camera) and

```
float h = horizontalSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, h * Time.deltaTime * 60, 0);

```

for the player. (horizontalSpeed is a constant) But after a few seconds I'm running in a completely different way then I look. Why is that and how can I solve this?

I tried different animations - nothing worked.

**Update:** If there is no rigidbody and no collider attached to it it works fine. But I need them.

# Answer
> 1 votes
Try updating the player’s rotation through its rigidbody component’s MoveRotation method. Make sure to do this in FixedUpdate.

```
void FixedUpdate() {
  float h = horizontalSpeed * Input.GetAxis("Mouse X");
  rigidbody.MoveRotation(rigidbody.rotation * Quaternion.Euler(0, h * Time.deltaTime * 60, 0));
}

```

The Camera’s rotation would also need to be calculated in FixedUpdate.

# Answer
> 0 votes
You dont need to add a movement script to the camera because if you make camera the child of player then it will follow the player without the script

---
Tags: unity, camera, movement
---


# Question
Title: I try to recreate a plasma gun from halo into my fps game
this is my code:

```
public class WeaponTest : MonoBehaviour
{
    public float weaponHeat;
    public float weaponOverHeat = 100f;
    public bool weaponIsOverHeat;

    // Start is called before the first frame update
    void Start()
    {
        //weaponHeat at the start was 0
        weaponHeat = 0;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1") && !weaponIsOverHeat)
        {
            if (weaponHeat < weaponOverHeat)
            {
                Weapon_Shoot();
                weaponHeat = IsHeating();
            }
        }
    }

    float IsHeating()
    {
        weaponHeat += Random.Range(5f, 10f);
        return weaponHeat;
    }

    void Weapon_Shoot()
    {
        RaycastHit hit;
        if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range))
        {
            // code for damaging the enemy
        }
    }
}

```

the shoot method was function exactly like what is want but I need the cooldown method I already try a few them but it not work exactly like I want. the I idea was went the left mouse was click the weapon heat will increase and when the left mouse was not been click the weapon heat will decrease until it reach 0. I hope you can help me solve this problem

# Answer
> 1 votes
You just need to decrease the heat all the time when you are not firing. Clamping the value to not go below 0.

```
void Update() {
    if (Input.GetButton("Fire1") && (weaponHeat < weaponOverHeat)){
        Weapon_Shoot();
        weaponHeat += Random.Range(5f, 10f);
    } else {
        weaponHeat = Mathf.Clamp(weaponHeat - Random.Range(5f, 10f), 0f, weaponOverHeat);
    }
}

```

But now the fire rate as well as heat build up and cooldown depends on the framerate. Some people will be able to shoot faster (but also overheat sooner). To make it more uniform, you need to include Time.deltaTime.

```
private float fireRate = 0.25f;
private float lastFired = 0f;
private float cooldownRate = 7.5f
void Update()
{
    lastFired += Time.deltaTime;
    if (Input.GetButton("Fire1")) {
        if (weaponHeat < weaponOverHeat && lastFired >= fireRate){
            Weapon_Shoot();
            weaponHeat += Random.Range(5f, 10f);
            lastFired = 0;
        }
    } else {
            //whoever build this thing spent some time on a consistant cooling system
            weaponHeat = Mathf.Clamp(weaponHeat - cooldownRate * Time.deltaTime, 0f, weaponOverHeat);
    }
}

```

Now even if you hold down the trigger, your weapon won't fire faster than the fireRate. And your weapon will only cooldown if you don't hold the trigger.

---
Tags: unity
---


# Question
Title: How to make multiple types of game objects destructible
## Problem

I have a set of various objects on my map that I would like to make destructible. Basically, they are split into 3 parent objects - plants, buildings and moving objects. Each parent contains 100+ children. So, if I shoot an object or objects, it/they should suffer certain amount of damage, and if the damage is critical then get destroyed.

So, I have created a single script called `Damageable` and added it to every child described in the previous paragraph as below:

**Damageable.cs**

```
public class Damageable : MonoBehaviour
{
    private float m_CurrentHealth;
    private bool m_Destroyed;
    ...

    public void TakeDamage(float amount)
    {
        m_CurrentHealth -= amount;

        if (!m_Destroyed && m_CurrentHealth <= 0f)
        {
           HandleDeath();
        }
    }

    ...

}

```

Then, in my **ShellHit** script, I retrieve a list of affected `Damageable` objects and cause them damage via `TakeDamage` method.

**ShellHit.cs**

```
public class ShellHit : MonoBehaviour
{
    ...
    private void OnTriggerEnter(Collider other)
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, m_ExplosionRadius, m_DamageableMask);

        foreach (Collider collider in colliders)
        {
            Rigidbody targetRigidBody = collider.GetComponent<Rigidbody>();

            targetRigidBody = collider.GetComponent<Rigidbody>();
            if (!targetRigidBody)
            {
                continue;
            }

            targetRigidBody.AddExplosionForce(m_ExplosionForce, transform.position, m_ExplosionRadius);

            Damageable damageable = targetRigidBody.GetComponent<Damageable>();

            if (!damageable)
            {
                continue;
            }

            float damage = CalculateDamage(targetRigidBody.position);

            damageable.TakeDamage(damage);

            ...
        }
    }
    ...
}

```

## Question

Is it a common practice in Unity what I'm doing by adding the same script to every game object or is there a more common/efficient way of doing the same? For instance, by adding the script to a parent object and make it handle the damage for its children.

# Answer
There are several ways to accomplish this, I suggest you look into using tags with your colliders. Here is the documentation for the Unity Tag System : https://docs.unity3d.com/2019.3/Documentation/Manual/Tags.html

You can differentiate colliders by tag with something like :

```
 private void OnTriggerEnter(Collider other)
{
   if(other.gameObject.tag == "damagable")
    { //do damage stuff here }
}

```

This way you don't have to do an expensive call to search for the objects rigid body.

You could also look into other ways to improve performance when dealing with a large number of game objects. I suggest researching Unity Addressables and Object Pooling.
> 0 votes

---
Tags: unity
---


title: How to set to fullscreen in GLFW3?

text:
# Question
Title: How to set to fullscreen in GLFW3?
In the version 2.7 everything was pretty simple:

```
glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0, isFullscr ? GLFW_FULLSCREEN : GLFW_WINDOW);

```

But in version 3.x there is no place where i can specify how my my window should be and by default its windowed:

```
glfwCreateWindow(width, height, m_windowName.c_str(), nullptr, nullptr);

```

How can i change my window to fullscreen mode?

# Answer
In 3.x, you specify which monitor you want to use for fullscreen instead of the flag in 2.x.

You can use `glfwGetPrimaryMonitor()` to get a monitor handle and pass it into `glfwCreateWindow()` as follows:

```
glfwCreateWindow(width, height, m_windowName.c_str(), glfwGetPrimaryMonitor(), nullptr);

```

As long as monitor param is not null, it will create full screen window on the monitor specified. This was done to support multiple monitors.

As for various attributes for the window, you need to use window hints by calling `glfwWindowHint` with appropriate parameters and then make the`glfwCreateWindow` call.

Read the docs, its very clear.
> 11 votes

# Answer
```
 int main()
  {
   glfwInit();
   glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
   glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
   glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
   glfwWindowHint(GLFW_SAMPLES,32); // Uhuh?

   glfwWindowHint(GLFW_DECORATED, NULL); // Remove the border and titlebar..

   GLFWmonitor* MyMonitor =  glfwGetPrimaryMonitor(); // The primary monitor.. Later Occulus?..

   const GLFWvidmode* mode = glfwGetVideoMode(MyMonitor);
   SCR_WIDTH = mode->width;
   SCR_HEIGHT = mode->height;

   // GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); // Original..

   // GLFWwindow* window =  glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "My Title", NULL, NULL); // Title now redundant..

   // More elegant?? (the flash still bothers me..)
    GLFWwindow* window =   glfwCreateWindow(glfwGetVideoMode(glfwGetPrimaryMonitor())->width,
                                            glfwGetVideoMode(glfwGetPrimaryMonitor())->height, "My Title",
                                            glfwGetPrimaryMonitor(), nullptr);

```
> 0 votes

# Answer
To have your window be full screen and eat it too -- I mean, not have the white flashing as described in other answers, do the following:

* create the window at a sufficiently low resolution (to avoid the white flash)
* then resize it to your screen's resolution.

> ```
> GLFWmonitor* monitor = glfwGetPrimaryMonitor();
>
> GLFWwindow* window = glfwCreateWindow(low_res_x, low_res_y, "title", monitor, NULL);
>
> glfwSetWindowSize(window, 1920, 1080);
>
> ```
> 0 votes

---
Tags: glfw
---


# Question
Title: Ability system in Unity: Scriptable objects and collections of generic types
I've decided to implement an ability system for my game and set the following requirements:

* Abilities must be `MonoBehavior`s, that-is, components of Player/NPC gameobjects
* Abilities must be able to be added/removed at runtime. Instead of all entites having all abilities on their gameobjects that are disabled/enabled, I'd like to dynamically add/remove abilities using `AddComponent`/`Destroy(component)`

Given these I've implemented the following:

* Settings classes which inherit from a base `AbilitySettings` class which is a `ScriptableObject`. These contain configurable ability settings as well as an enum called `AbilityIdentifier` which identifies the ability (for example a jump ability would have the identifier `AbilityIdentifier.JUMP`)
* `IAbility` non-generic interface containing a few common ability methods (such as `TriggerAbility` and `CanTrigger`)
* `AbstractAbility<T>` class which implements `IAbility` and T is a type that extends `AbilitySettings`. It implements some of the `IAbility` methods and defines others as abstract. Actual abilities extend this class.
* `AbilityManager` is a `MonoBehavior` which contains an array of all possible settings for that entity (added through unity editor) and internally contains a dictionary of `<AbilityIdentifier, IAbility>`. All of the entities abilities are added/removed using the `AbilityManager`

It looks something like this:

```
public class AbilityManager : MonoBehavior
{
    [SerializeField] private AbstractAbilitySettings[] allAbilitiesSettings = { };

    private readonly Dictionary<AbilityIdentifier, IAbility> abilities = new Dictionary<AbilityIdentifier, IAbility>();

    // Add/remove ability methods
}

```

For example, a jump ability pickup gameobject is set somewhere in the world as a trigger. When the player moves over the pick-up object and `OnTriggerEnter` is executed. The script on the pick-up object gets the `AbilityManager` and calls `AddAbility(AbilityIdentifier.JUMP)`

This sounds good but It's far from perfect. First of all, I couldn't figure out an elegant way of creating/removing a component when given the settings class so I've added the creation/destruction code to the settings class itself. That-is I've added the following abstract methods to `AbilitySettings`

```
public abstract IAbility InstantiateAbility(GameObject gameObject);

public abstract void RemoveAbility(GameObject gameObject);

```

which are then implemented in each of the concrete settings classes like this:

```
public override IAbility InstantiateAbility(GameObject gameObject)
{
    JumpAbility ability = gameObject.AddComponent<JumpAbility>();
    ability.Settings = this;
    return ability;
}

public override void RemoveAbility(GameObject gameObject)
{
    JumpAbility ability = gameObject.GetComponent<JumpAbility>();
    Destroy(ability);
}

```

And these methods are called in the `AbilityManager` like this

```
public void AddAbility(AbilityIdentifier identifier)
{
    AbilitySettings abilitySettings = Array.Find(allAbilitiesSettings, s => s.Identifier == identifier);

    abilitySettings.InstantiateAbility(gameObject);
}

```

The implementation of `InstantiateAbility` and `RemoveAbility` is the same for every single ability, the only difference being the ability type. This is a big smell for me. I can't make `AbilitySettings` generic and generify the two methods as these settings are in an array.

My questions are:

* Adding methods such as `InstantiateAbility` and `RemoveAbility` to a scriptable object seems like a code smell to me. Take into account that I'm using the `AbilityIdentifier` to specify to the manager which ability I want to create. I have thought of perhaps creating an `AbilityFactory<T>` but since it's a generic class it can't be a part of an array/list so I'm facing the same problem I did with the settings. Is there a different way I could handle this without having the code in the scriptable object?
* Having the implementation of these two methods `InstantiateAbility` and `RemoveAbility` be the same for every implementation with the only difference being the type is also a big code smell. Is there any way I can generify this but at the same time avoid problems with the inability of having an array or list of those generic classes?

# Answer
> 1 votes
Here's how I often build lists of generics:

```
public abstract class AbilitySettingsBase : ScriptableObject {
    public abstract IAbility InstantiateAbility(GameObject gameObject);
    public abstract void RemoveAbility(GameObject gameObject);
}

public abstract class AbilitySettings<T> : AbilitySettingsBase where T : Ability {
    public override IAbility InstantiateAbility(GameObject gameObject) {
    Assert.IsNotNull(gameObject);
        T ability = gameObject.AddComponent<T>();
        ability.Settings = this;
        return ability;
    }

    public override void RemoveAbility(GameObject gameObject) {
        T ability = gameObject.GetComponent<T>();
        if (ability != null) Destroy(ability);
    }
}

[CreateAssetMenu(menuName="Jump Settings")]
public class JumpSettings : AbilitySettings<JumpAbility> {
}

[CreateAssetMenu(menuName="Fight Settings")]
public class FightSettings : AbilitySettings<FightAbility> {
}

public class AbilityManager : MonoBehaviour
{
    //This will show up in the Inspector and we can assign the appropriate assets
    [SerializeField] private AbilitySettingsBase[] abilitySettings = { };

    //...
}

```

Here we have a *non-generic* base type `AbilitySettingsBase` that defines some abstract functions. We *can* have a serialized list of AbilitySettingsBase because, even though it's abstract, it's not generic. This will expose the list in the Inspector and allow us to select asset files made from ScriptableObject scripts that extend `AbilitySettingsBase`.

Where it can get more complicated is if the `Ability` scripts need to understand the `AbilitySettings` type. If you try to use generics you might end up with a much more convoluted generic scheme, e.g.

```
public abstract class AbilitySettings<T, U> : AbilitySettingsBase where T : Ability<T, U> where U : AbilitySettings<T, U> {
    //code ommitted
}

public abstract class Ability<T, U> where T : Ability<T, U> where U : AbilitySettings<T, U> {
    //code ommitted
}

```

I'm not sure off the top of my head if that would work; I think you'd end up at a catch-22 somewhere in the implementation. Another possibility is to not try to make the generic scheme more complex, and instead do something like this:

```
public class JumpAbility : Ability {
    private JumpAbilitySettings settings;

    override public AbilitySettingsBase Settings {
        get => settings;
        set {
            Assert.IsNotNull(value);
            JumpAbilitySettings settings = value as JumpAbilitySettings;
            Assert.IsNotNull(settings);
            this.settings = settings;
            //apply settings here
        }
    }
}

```

This isn't as type-safe but will save some headaches in generic design.

---

**EDIT:** Part of what makes the above answer complicated is that you've got double-coupling - the Settings is aware of the Ability and the Ability is aware of the Settings. You probably should not make `InstantiateAbility` and `RemoveAbility` functions of the `AbilitySettingsBase`; that way the Settings doesn't need to be generic at all. Instead, you might have a function somewhat like this on your `AbilityManager`:

```
public T AddAbility<T, U>(GameObject go) where T : Ability<U> where U : AbilitySettings {
    Assert.IsNotNull(go);
    T ability = go.AddComponent<T>();
    if (abilitySettingsDictionary.TryGetValue(typeof(U), out var settings)) {
        ability.Settings = settings;
    } else {
        Debug.LogError("Didn't find a settings asset for " + typeof(T));
    }
    return ability;
}

```

---
Tags: unity, architecture, scriptable-object
---


# Question
Title: Crash when Setting Up Minecraft 1.12.2 Mod in IntelliJ
I'm trying to set up a Minecraft modding environment in IntelliJ. (I've settled for 1.12.2 as this version still by far the largest stable platform for Forge modding with the best support.)

Anyway, I've followed the instruction laid out in the Readme, as well as guides and videos online that date from only a few months ago, so the process should be the same to get a mod set up. However, I'm having an issue actually running the basic "mod" that is shipped with the Forge MDK. The full crash log is below:

```
---- Minecraft Crash Report ----

// My bad.

Time: 12/3/20 8:13 PM
Description: Initializing game

java.lang.NoSuchMethodError: java.nio.ByteBuffer.flip()Ljava/nio/ByteBuffer;
    at net.minecraft.client.Minecraft.readImageToBuffer(Minecraft.java:841)
    at net.minecraft.client.Minecraft.setWindowIcon(Minecraft.java:680)
    at net.minecraft.client.Minecraft.init(Minecraft.java:456)
    at net.minecraft.client.Minecraft.run(Minecraft.java:378)
    at net.minecraft.client.main.Main.main(Main.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
    at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraftforge.legacydev.Main.start(Main.java:86)
    at net.minecraftforge.legacydev.MainClient.main(MainClient.java:29)

A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- Head --
Thread: Client thread
Stacktrace:
    at net.minecraft.client.Minecraft.readImageToBuffer(Minecraft.java:841)
    at net.minecraft.client.Minecraft.setWindowIcon(Minecraft.java:680)
    at net.minecraft.client.Minecraft.init(Minecraft.java:456)

-- Initialization --
Details:
Stacktrace:
    at net.minecraft.client.Minecraft.run(Minecraft.java:378)
    at net.minecraft.client.main.Main.main(Main.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
    at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraftforge.legacydev.Main.start(Main.java:86)
    at net.minecraftforge.legacydev.MainClient.main(MainClient.java:29)

-- System Details --
Details:
    Minecraft Version: 1.12.2
    Operating System: Windows 10 (amd64) version 10.0
    Java Version: 1.8.0_271, Oracle Corporation
    Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
    Memory: 358011464 bytes (341 MB) / 785383424 bytes (749 MB) up to 7626293248 bytes (7273 MB)
    JVM Flags: 0 total;
    IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0
    FML:
    Loaded coremods (and transformers):
    Launched Version: ${MC_VERSION}
    LWJGL: 2.9.4
    OpenGL: ~~ERROR~~ RuntimeException: No OpenGL context found in the current thread.
    GL Caps:
    Using VBOs: Yes
    Is Modded: Definitely; Client brand changed to 'fml,forge'
    Type: Client (map_client.txt)
    Resource Packs:
    Current Language: ~~ERROR~~ NullPointerException: null
    Profiler Position: N/A (disabled)
    CPU: <unknown>

```

The only information I can find online is that this error is apparently caused by IntelliJ compiling the mod using Java 1.9. However, this is impossible in my case. The only JDK installed on my machine is version 1.8, which is also what my JAVA\_HOME is set to, as well as the only JDK/RE in my PATH. There is no 1.9 JDK to build with. What's causing this, and how do I make it stop? I've checked and I am 100% sure that all compilation through IntelliJ is set to compile with Java 1.8 *ONLY*. Is there an option I've missed?

**Minecraft Version:** 1.12.2
**Forge Version:** 14.23.5.2854 (latest recommended)
**JDK:** 1.8.0\_271

I do apologize if my question isn't as clear or concise as it could be. I've been struggling to get this working for almost a month now, and it's really draining me mentally and emotionally. I'm happy to provide more information as needed.

# Answer
> 0 votes
I have discovered the issue! It involved deleting the .gradle folder in my User Home, and then re-importing my project (or rather, a new one because I didn't even *have* a project) to rebuild the cached contents of said folder.

I don't know what sort of incorrect stuff was being cached in my User folder, but there was 1.6 GB of it.

# Answer
> 0 votes
I am no expert at this but I'm taking a wild guess. Update your .net run-times. This may not fix anything but I understand the frustration when mods do not work. And will try my best to help those of us who do experience the issues

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


# Question
Title: How do I load Player position as new gameobject?
I want to make game-like time travel, the player has the ability to go to the future by limited time, for that, I want to add some game mechanic like save the player position.

Additional information: ignore the red text. When pressing the button the player will create a new platform and immediately teleport to the original position. After the player teleported, the player will save the new platform as the new teleport position. after 2 seconds or pressing a button. the new platform will disappear and the player will return to the platform position.

I have this \_playerController Script and I already implement the save position, but I don't know how to make it like what I explain.

<pre><code>    public Rigidbody2D theRB;
    public float speedMovement;
    public GameObject prefabGameObject;

    [Space(10)]
    private BoxCollider2D boxCollider2D;
    [SerializeField] private LayerMask GroundMask;
    public float jumpVelocity;

    [Space(10)]
    public float past;
    public float future;

    [Space(10)]
    public float hor;

    // Start is called before the first frame update
    void Start()
    {
        theRB = gameObject.GetComponent<Rigidbody2D>();
        boxCollider2D = transform.GetComponent<BoxCollider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        PlayerPosSaveLoad();
        PlayerMovement();
        PlayerJump();
    }

    public void PlayerMovement()
    {
        hor = Input.GetAxis("Horizontal");
        if (hor > 0 || hor < 0)
        {
            theRB.velocity = new Vector2(hor * speedMovement * Time.deltaTime, theRB.velocity.y);
            if (hor > 0)
            {
                transform.localScale = new Vector2(1f, transform.localScale.y);
                //Animation
                Debug.Log("ToTheright");
            }
            else
            {
                transform.localScale = new Vector2(-1f, transform.localScale.y);
                //Animation
                Debug.Log("ToTheLeft");
            }
        }
    }

    public void PlayerJump()
    {
        //animation
        if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            theRB.velocity = Vector2.up * jumpVelocity;
        }
    }

    public bool isGrounded()
    {
        float extraHeighText = .1f;
        RaycastHit2D raycast2d = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, boxCollider2D.bounds.extents.y + extraHeighText, GroundMask);
        Color raycolor;

        if (raycast2d.collider != null)
        {
            raycolor = Color.green;
        }
        else
        {
            raycolor = Color.red;
        }
        Debug.DrawRay(boxCollider2D.bounds.center, Vector2.down * (boxCollider2D.bounds.extents.y + extraHeighText), raycolor);
        return raycast2d.collider != null;
    }

    [SerializeField]
    private Vector2 saveThisPosition;

    public void PlayerPosSaveLoad()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            saveThisPosition = transform.position;
            SpawnGameObject();
        }
        if (Input.GetKeyDown(KeyCode.Q))
        {
            SwitchWithsavedPosition();
            Destroy(prefabGameObject);
        }
    }

    private void SwitchWithsavedPosition()
    {
        Vector2 temp = transform.position;
        transform.position = saveThisPosition;
        prefabGameObject.transform.position = temp;
    }

    public void SpawnGameObject()
    {
        Instantiate(prefabGameObject, transform.position, transform.rotation);
    }

And this is the Camera Script because connected with the player.

```lang-cs
    public Transform Player;

    // Start is called before the first frame update
    void Start() { }

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector3(Mathf.Clamp(Player.position.x, -7.3f, 7.3f), Mathf.Clamp(Player.position.y, 1f, 2f), transform.position.z);
    }
</code></pre>

# Answer
1. First you need to save the position ONLY when you request it. Currently your code is spam saving the location (twice per FixedUpdate). This needs to be changed. Make a new Method for it, check if a certain key is pressed and only than save the location.
2. Do not save those locations to playerpref. PlayerPrefs are for storing and accessing player preferences between game sessions. All you need to have is a local Vector2 in your controller that saves the position.
3. Since you just want a teleport and not the block option as in the video, you can just display an image at the position from 2). No rigidbody/ boxcollider needed on it.
4. https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html You call in the same condition as under 2) a teleport back method. The example code even shows how to add the 2sec delay. Your teleport code just assigns the saved vector2 as the new position of your player, removes the image from 3) and should as well set the vector2 to null.
5. As a tip, do not capture user input in Fixedupdate. Input.GetKeyDown is only true in the frame it gets captured and not afterwards. That means you might miss the keypress and your code is not working as you would expect it.

If you have are stuck on one of the points, please update your code and I will further explain the step.

A simple save can be as easy as

```
private Vector2 saveThisPosition;
private void PlayerPosSave() {
    saveThisPosition = transform.position;
}

```

Within your playerController, you can access always saveThisPosition and you have the location of the place where you pressed your key. The switch between the object that you spawned and the current Player is just switching their positions.

```
private void SwitchWithSavedPosition() {
    Vector2 temp = transform.position;
    transform.position = saveThisPosition;
    spawnedGameObject.transform.position = temp;
}

```

spawnedGameObject is the reference to the old player that you have to create when you press your saveLocation key.
> 1 votes

# Answer
so this is my full script.

```
    public Rigidbody2D theRB;
    public float speedMovement;
    public GameObject prefabGameObject;
    private GameObject go;

    [Space(10)]
    private BoxCollider2D boxCollider2D;
    [SerializeField] private LayerMask GroundMask;
    public float jumpVelocity;

    [Space(10)]
    public float hor;

    // Start is called before the first frame update
    void Start()
    {
        theRB = gameObject.GetComponent<Rigidbody2D>();
        boxCollider2D = transform.GetComponent<BoxCollider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        PlayerPosSaveLoad();
        PlayerMovement();
        PlayerJump();
    }

    public void PlayerMovement()
    {
        hor = Input.GetAxis("Horizontal");
        if (hor > 0 || hor < 0)
        {
            theRB.velocity = new Vector2(hor * speedMovement * Time.deltaTime, theRB.velocity.y);
            if (hor > 0)
            {
                transform.localScale = new Vector2(1f, transform.localScale.y);
                //Animation
                Debug.Log("ToTheright");
            }
            else
            {
                transform.localScale = new Vector2(-1f, transform.localScale.y);
                //Animation
                Debug.Log("ToTheLeft");
            }
        }
    }

    public void PlayerJump()
    {
        //animation
        if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            theRB.velocity = Vector2.up * jumpVelocity;
        }
    }

    public bool isGrounded()
    {
        float extraHeighText = .1f;
        RaycastHit2D raycast2d = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, boxCollider2D.bounds.extents.y + extraHeighText, GroundMask);
        Color raycolor;

        if (raycast2d.collider != null)
        {
            raycolor = Color.green;
        }
        else
        {
            raycolor = Color.red;
        }
        Debug.DrawRay(boxCollider2D.bounds.center, Vector2.down * (boxCollider2D.bounds.extents.y + extraHeighText), raycolor);
        return raycast2d.collider != null;
    }

    [SerializeField]
    private Vector2 saveThisPosition;

    public void PlayerPosSaveLoad()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            saveThisPosition = transform.position;
            Destroy(go);
            SpawnGameObject();
        }
        if (Input.GetKeyDown(KeyCode.Q))
        {
            SwitchWithsavedPosition();
            Destroy(go);
        }
    }

    private void SwitchWithsavedPosition()
    {
        Vector2 temp = transform.position;
        transform.position = saveThisPosition;
        prefabGameObject.transform.position = temp;
    }

    public void SpawnGameObject()
    {
        go = Instantiate(prefabGameObject, transform.position, transform.rotation) as GameObject;
    }

```
> 0 votes

---
Tags: unity, game-mechanics
---


# Question
Title: How to manually render with a given camera in Unreal Engine 4?
I would like to render with any camera at any given time for a Portal clone project.

There's a `USceneCaptureComponent2D` but it renders the whole scene to a texture.

I don't need to render the entire scene. I would like to setup stencils to avoid unnecessary rendering. I don't think this component supports this.

Additionally, I would like to render directly to the main framebuffer - without render textures, which this component uses.

Is it possible to do something like this in Unreal Engine 4?

# Answer
It depends on what exactly you're trying to render without rendering the whole scene which is useful for things like security cameras.

If you're just trying to do a player preview in an equipment UI then you need to put the SceneCaptureComponent2D on the player itself then in the Scene Capture options, under Primitive Render Mode, choose "Use ShowOnly List" then, in the construction script of the player, get the SceneCaptureComp, get the ShowOnly list and add all unique items to the array with Self as the bottom pin.
> 0 votes

---
Tags: rendering, graphics, unreal-4
---


# Question
Title: Calling functions that needs to be on update()
So I have a function `DialogueRun()` for a Dialogue System that changes the line on the dialogue box whenever you click. Which means it has to be in `Update()`. My test works so far but my next problem is how to make the whole dialogue box only appear whenever I click on a character.

I tried making the characters as buttons and it does make the dialogue box show up whenever clicked, but it won't change the dialogue lines because that function has to be in an update method.

I'm looking at `OnMouseDown()` right now but the result will be probably the same. Any ideas?

```
 public void DialogueRun()
{
    dialogueBox.SetActive(true);
    dialogue.text = textLine[nextLine];

    if (nextLine < textLine.Length - 1)
    {

        if (Input.GetKeyDown(KeyCode.Mouse0))
        {

            nextLine += 1;
        }
    }
    else
    {            //counter++;
        dialogueBox.SetActive(false);
        return;
    }

```

# Answer
> 1 votes
You can do something like this:

```
private bool dialogShowing;

void OnEnable() {
    dialogShowing = false;
}

public void DialogueRun()
{
    if (dialogShowing) return; //we don't want to show the dialog if it's already showing
    dialogueBox.SetActive(true);
    dialogue.text = textLine[nextLine];
    StartCoroutine(AdvanceTextOnClick());
}

//while the coroutine is running, check each frame to see if the user
//has clicked. if so, advance to the next line of dialog, or close the
//dialog if the user has reached the end
private IEnumerator AdvanceTextOnClick() {
    dialogShowing = true;
    while (true) {
        yield return null; //wait until the next frame
        if (Input.GetKeyDown(KeyCode.Mouse0)) {
            if (nextLine < textLine.Length - 1) {
                nextLine ++;
                dialogue.text = textLine[nextLine];
            } else {
                dialogueBox.SetActive(false);
                dialogShowing = false;
                yield break; //exit coroutine
            }
        }
    }
}

```

When "DialogueRun" is called, we show the `dialogueBox` and start a coroutine that listens for user clicks. When the user clicks, the coroutine will advance the dialog to the next line, or close the dialog if the user reaches the end. This coroutine behaves similarly to an `Update()` function but unlike `Update()` it only runs when we need it to run.

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


# Question
Title: Why I see duplicated resolutions values in the dropdown ui after changing resolution?
When I'm running the game then in my graphics settings when I expand the options they are all duplicated and I can scroll down but the scrolling is very slow with the mouse wheel.

And it happens only in the build when building the game and running the exe file. In the editor the items are not duplicated.

This is the script I'm using to get the resolutions values and assign them to the dropdown ui :

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using TMPro;
using System;
using UnityEngine.Events;

public class Settings : MonoBehaviour
{
    public AudioMixer audioMixer;
    public TMP_Dropdown resolutionDropdown;
    public TMP_Dropdown qualityDropdown;
    public Text musicText;
    public Text sfxText;
    public Slider[] audioSliders;
    public Toggle fullScreenToggle;

    private Resolution[] resolutions;

    private void Awake()
    {
        resolutionDropdown.onValueChanged.AddListener(new UnityAction<int>(index =>
        {
            PlayerPrefs.SetInt("resolutionvalue", resolutionDropdown.value);
            PlayerPrefs.Save();

        }));

        qualityDropdown.onValueChanged.AddListener(new UnityAction<int>(index =>
        {
            PlayerPrefs.SetInt("qualityvalue", qualityDropdown.value);
            PlayerPrefs.Save();

        }));

        fullScreenToggle.onValueChanged.AddListener(new UnityAction<bool>(index =>
        {
            PlayerPrefs.SetInt("fullscreen", boolToInt(fullScreenToggle.isOn));
            PlayerPrefs.Save();

        }));
    }

    private void Start()
    {
        qualityDropdown.value = PlayerPrefs.GetInt("qualityvalue");

        resolutions = Screen.resolutions;
        resolutionDropdown.ClearOptions();

        List<string> options = new List<string>();

        int currentResolutionIndex = 0;
        for(int i = 0; i < resolutions.Length; i++)
        {
            string option = resolutions[i].width + " x " + resolutions[i].height;
            options.Add(option);

            if(resolutions[i].width == Screen.currentResolution.width &&
                resolutions[i].height == Screen.currentResolution.height)
            {
                currentResolutionIndex = i;
            }
        }

        resolutionDropdown.AddOptions(options);
        resolutionDropdown.value = PlayerPrefs.GetInt("resolutionvalue", currentResolutionIndex);
        resolutionDropdown.RefreshShownValue();

        float musicvolume = PlayerPrefs.GetFloat("musicvolume");
        float sfxvolume = PlayerPrefs.GetFloat("sfxvolume");

        musicText.text = musicvolume.ToString();
        sfxText.text = sfxvolume.ToString();
        audioSliders[0].value = musicvolume / 100f;
        audioSliders[1].value = sfxvolume / 100f;

        fullScreenToggle.isOn = intToBool(PlayerPrefs.GetInt("fullscreen", 0));

    }

    public void SetResolution(int resolutionIndex)
    {
        Resolution resolution = resolutions[resolutionIndex];
        Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
    }

    public void SetMusicVolume(float volume)
    {
        audioMixer.SetFloat("musicvol", Mathf.Log10(volume) * 20);
        musicText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("musicvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));
    }

    public void SetSfxVolume(float volume)
    {
        audioMixer.SetFloat("sfxvol", Mathf.Log10(volume) * 20);
        sfxText.text = Math.Round(volume * 100, MidpointRounding.AwayFromZero).ToString();

        PlayerPrefs.SetFloat("sfxvolume", (float)Math.Round(volume * 100, MidpointRounding.AwayFromZero));
    }

    public void SetQuality(int qualityIndex)
    {
        QualitySettings.SetQualityLevel(qualityIndex);
    }

    public void SetFullscreen(bool isFullscreen)
    {
        Screen.fullScreen = isFullscreen;
    }

    int boolToInt(bool val)
    {
        if (val)
            return 1;
        else
            return 0;
    }

    bool intToBool(int val)
    {
        if (val != 0)
            return true;
        else
            return false;
    }
}

```

# Answer
> 0 votes
This is the solution. I give a link for the solution because there are two ways to do it and I used the second one.

https://answers.unity.com/questions/1463609/screenresolutions-returning-duplicates.html

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


# Question
Title: What's the difference between UnityEvent and OnTriggerEnter()
I'm new into game development and programming and I have a question that might sound silly or stupid, but I'm having issue understanding the difference between `UnityEvent` and `OnTriggerEnter()`. I would like to understand what I can do with `UnityEvent` that isn't possible with `OnTriggerEnter()`.

# Answer
> 1 votes
What `UnityEvent`s give us is *decoupling*. I'll demonstrate that with an example...

Let's say we have a pressure switch in our game that's supposed to open a door. The pressure switch has a trigger collider and a script maybe a bit like this:

```
public class PressureSwitch : MonoBehaviour {

    public Door doorToOpen;

    int _objectsInContact;

    void OnTriggerEnter(Collider other) {
        _objectsInContact++;
        if (_objectsInContact == 1) Activate();
    }

    void OnTriggerExit(Collider other) {
        _objectsInContact--;
        if (_objectsInContact  == 0) Deactivate();
    }

    void Activate() {
        doorToOpen.Open();
    }

    void Deactivate() {
        doorToOpen.Close();
    }
}

```

So far so good. But then in playtests, sometimes players don't notice the door opening, so we want to add a camera animation to show them. So we modify the `Activate` method:

```
void Activate() {
    cameraAnimation.Play();
    doorToOpen.Open();
}

```

Then in level 2, we have another puzzle, but instead of opening a door, we want to extend a bridge. We don't want to make a new class that just copies all the trigger code, so we just add a bridge variable, and then check which of those variables has been set so we can do the right thing for level 1 or level 2:

```
void Activate() {
    if (bridge != null) bridge.Extend();
    if (cameraAnimation != null) cameraAnimation.Play();
    if (doorToOpen != null) doorToOpen.Open();
}

```

(Plus corresponding changes for the `Deactivate` method)

...okay, this is starting to get cumbersome. You can imagine if we keep scaling this to more levels where pressure switches turn on lights or drain water or turn off force fields or activate conveyor belts... this approach just doesn't scale.

Somehow we want to separate the logic of *what activates the switch* from *what happens as a result*. The switch should be responsible for just its own activation state, and shouldn't need to know anything about what happens downstream.

Enter the `UnityEvent`:

```
public class PressureSwitch : MonoBehaviour {

    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;

    int _objectsInContact;

    void OnTriggerEnter(Collider other) {
        _objectsInContact++;
        if (_objectsInContact == 1 && OnActivate != null) OnActivate.Invoke();
    }

    void OnTriggerExit(Collider other) {
        _objectsInContact--;
        if (_objectsInContact  == 0 && OnDeactivate != null) OnDeactivate.Invoke();
    }
}

```

Now we'll have two fields in the Unity Inspector where we can wire up any number of functions on any number of different objects to respond to this switch getting activated or deactivated.

We can use this to trigger sounds, animations, toggle gameobject active states, pretty much anything you can do with a public function (that takes no arguments or a single argument you can set in the inspector). We can even attach and detach new functions to react to this switch at runtime, depending on the player's actions. And our `PressureSwitch` class doesn't need detailed knowledge about *any* of that to do its work.

We've taken the logic of figuring out whether the switch should turn on or off, and "decoupled it" from the logic of what should happen next.

In the process, we've made this class orders of magnitude more powerful, while also making the code *shorter* and simpler! We don't get that pairing very often, so savour it when it happens.

This is also a big win for level designers on your team, who might not be programmers. Now they can use this `PressureSwitch` in hundreds of different configurations just by setting it up in the Inspector. They don't need to come ask you or another programmer on your team to make a code change every time they need a switch to interact with a new type of object in a puzzle. Or even if you're working solo, now you don't need to recompile your code to make this kind of change.

This is a particularly big win when you're making UI widgets. Take `UnityEngine.UI.Button` \- you'll often use this dozens if not hundreds of times when making the interface for a game. But because the developers set it up to work with a `UnityEvent`, you won't need to edit its code or subclass it every time you want it to do something different (like enter play mode, switch to the next tab, close a dialog, purchase an item). You can just tell each instance what you want it to do as Inspector data, while keeping the code simple and shared.

This is an example of something called The Observer Pattern, in case you'd like to read up more about how this is used (or how it works under the hood).

---
Tags: unity
---


# Question
Title: How can I apply setActive to a UI element after an animation finishes?
I have an object animation which plays on the opening of a scene. When the animation is over I want the UI slider to be setActive - allowing the user to rotate the object. I have both these elements in place and working individually - just can't quite work out how to go about combining them.

Any help or advice about what approach I should take is much appreciated.

The animation was created in Maya.

# Answer
> 1 votes
You can do it by waiting until the animation ends. You can use IEnumarator to do it if your function is not in the Update loop.

```
public Animator anim;
public Slider slider;

public void WaitAnimaitonEnds()
{
    StartCoroutine(WaitTillAnimEnds());
}

IEnumerator WaitTillAnimEnds()
{

    yield return new WaitForSeconds((anim.GetCurrentAnimatorStateInfo(0).length + anim.GetCurrentAnimatorStateInfo(0).normalizedTime));
    // do whatever you want
    slider.SetActive(true);
    // do whatever you want
}

```

If you are looking for the alternative ways to do it, you can check the documentation here.

# Answer
> 1 votes
From Unity Answers:

> I find it easier to just add AnimationEvents to the clip at the start and/or end which, in your case, stop and start the movement by calling those functions. It's much more reliable than using a CoRoutine because an AnimationState might get interrupted and this wouldn't be caught be the CR timer.

From StackOverflow:

> You can use events on animation clips. It's explained in Unity manual: https://docs.unity3d.com/Manual/AnimationEventsOnImportedClips.html
>
> In **Animation Inport Settings** in **Annimations** tab You can find **Event** heading. Position the playback to the end and click **Add Event**. Fill the **Function** field with name of the function to call at the end of animation. Just make sure that Game Object with this animation has a corresponding function.

---

Another approach, from Unity Answers:

> This is super old thread, but as far as i can see, "Add Behaviour" in Animator can solve this problem. That will create the script for your state, which has several methods handy for such requirements.
>
> Check this out: https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
>
> Cheers

---
Tags: unity, c#, animation, gui
---


# Question
Title: How can the player open this door and have its collision physics stay in sync?
I just finished modeling a scene in Blender like this:

Now I'm animating and creating interactions between the player and the objects inside the house. When I reached the doors, I started having doubts.

Originally, I created the doors animations using Blend Shapes to easly control the transition between the open/close states and to allow the door being half opened or closed. (That's because my interaction system allows to interact partially with object, like for example the door system at Amnesia The Dark descent / outlast)

The trouble is, that the collider of the doors doesn't update when the Blendshapes values changes.

How can the player open this door and have its collision physics stay in sync

# Answer
> 0 votes
I'd recommend chopping out your doors and exporting them as separate objects, with the pivot in a sensible place like along the axis of the hinge.

In Unity, give the door a box collider and kinematic RigidBody, along with a script to control its opening and closing according to the player's input. You can make a prefab of this so you only need to do this setup once for each kind of door.

Position each door instance inside its door frame within the scene editor.

---
Tags: unity, animation, blender
---


# Question
Title: How can I create a boundary so the sprites don't go off screen?
I'm attempting to create a boundary around the window to stop the sprites of my game from escaping but it doesn't seem to be work, when they hit the area where its supposed to stop them it instead does nothing and sends it into 0,0 not allowing it too move.

```
    def leavingWindow(Xpos, Ypos):#boundry, keeps sprites in the window
    if Xpos<=0:
        return True
    elif Xpos>=950:
        return True
    if Ypos<=0:
        return True
    elif Ypos>=750:
        return True

def Boundry(Xpos, Ypos):
    if Xpos<=0:
        Xmovement=0
    elif Xpos>=950:
        Xmovement=950
    else:
        Xmovement=+0

    if Ypos<=0:
        ymovement=0
    elif Ypos>=750:
        ymovement=60
    else:
        ymovement=+0

    return Xmovement, ymovement

if len(preys) > 0:
        for wolf in Wolf_group:
            movementx, movementy = Track(wolf.x, preys[0].x, wolf.y, preys[0].y)#how the predators move
            Leaving=leavingWindow(wolf.x,wolf.y)
            if Leaving == True:
                movementx,movementy=Boundry(wolf.x,wolf.y)
            wolf.move(0,1)#movementx, #movementy)

```

Ive attempted changing around the code but it keeps doing this.

full code

```
#simulates interactions of wild life
import math
import random
import pygame,sys
import random
import pdb
from pygame.locals  import *

#classes--------------
class Animal(pygame.sprite.Sprite):#main class
    def __init__(self, image, x, y):
        super().__init__()
        self.x = x
        self.y = y
        self.image = image
        self.rect = self.image.get_rect(center = (x, y))
    def move(self, mx, my):
        self.x += mx
        self.y += my
        self.rect = self.image.get_rect(center = (self.x, self.y))#sets the image to the position

    def is_collided_with(self, sprite):#is the eat function
        return self.rect.colliderect(sprite.rect)

class Predator(Animal):#class for predators
    def __init__(self):
        image = pygame.image.load('Icon.png')
        super().__init__(image, 600, 700)

class Prey(Animal):#prey class
    def __init__(self):
        image = pygame.image.load('Prey.png')
        xPos = 300
        xPos  = 400
        super().__init__(image,xPos ,xPos )
        #self.rect = self.image.get_rect(center = (self.x, self.y))
    def move(self, mx, my):#item that moves the sprite
        self.x += mx
        self.y += my
        self.rect = self.image.get_rect(center = (self.x, self.y))

class Carrot(pygame.sprite.Sprite):#food for prey class
    def __init__(self):
        super().__init__()
        self.x = 100
        self.y = 700
        self.image = pygame.image.load('carrot.png')
        self.rect = self.image.get_rect(center = (self.x, self.y))

# Functions-----------
def Track(AgressorX,DefenderX,AgressorY,DefenderY):#finds comapres X and Y, tells sprite how to move
    if AgressorX > DefenderX:
        XMovement=-1
    elif AgressorX< DefenderX:
        XMovement=1
    else:
        XMovement=0

    if AgressorY > DefenderY:
        YMovement=-1
    elif AgressorY < DefenderY:
        YMovement=1
    else:
        YMovement=0
    return XMovement, YMovement

def leavingWindow(Xpos, Ypos):#boundry, keeps sprites in the window
    if Xpos<=0:
        return True
    elif Xpos>=950:
        return True
    if Ypos<=0:
        return True
    elif Ypos>=750:
        return True

def Boundry(Xpos, Ypos):
    if Xpos<=0:
        Xmovement=0
    elif Xpos>=950:
        Xmovement=950
    else:
        Xmovement=+0

    if Ypos<=0:
        ymovement=0
    elif Ypos>=750:
        ymovement=60
    else:
        ymovement=+0

    return Xmovement, ymovement

pygame.init()#setsup pygame
screen = pygame.display.set_mode((1000,800))#setsup screen
clock = pygame.time.Clock()#tells program how fast to update

timmer = 1#how long program has gone on for
#setsup the classes
predator = Predator()
predator2=Predator()
prey = Prey()
carrot = Carrot()

#setsup the classes as sprites
carrot_group = pygame.sprite.Group()
carrot_group.add(Carrot())

Wolf_group= pygame.sprite.Group()
Wolf_group.add(Predator())

Rabbit_group= pygame.sprite.Group()
Rabbit_group.add(Prey())

all_sprites = pygame.sprite.Group()
all_sprites.add(carrot_group)
all_sprites.add(Wolf_group)
all_sprites.add(Rabbit_group)

#start of program
running=True
while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False

    carrots = carrot_group.sprites()
    preys = Rabbit_group.sprites()
    predators = Wolf_group.sprites()

    if len(preys) > 0:
        for wolf in Wolf_group:
            movementx, movementy = Track(wolf.x, preys[0].x, wolf.y, preys[0].y)#how the predators move
            wolf.move(0,1)#movementx, #movementy)

            Leaving=leavingWindow(wolf.x,wolf.y)#keeps sprites in window
            if Leaving == True:
                movementx,movementy=Boundry(wolf.x,wolf.y)
                wolf.x=movementx
                wolf.y=movementy

    if len(carrots) > 0:
        for rabbit in Rabbit_group:
            movementx, movementy = Track(rabbit.x, carrots[0].x, rabbit.y, carrots[0].y)#how the prey move
            rabbit.move(movementx, movementy)

    screen.fill((0,128,0))#background
    all_sprites.draw(screen)#makes the sprites
    pygame.display.update()#updates screen
    timmer=timmer+1

    for carrot in carrots:#removes the carrots if they contact a rabbit
        for rabbit in Rabbit_group:
            if rabbit.is_collided_with(carrot):
                print('works')
                carrot.kill()

    for wolf in Wolf_group:
        for rabbit in Rabbit_group:
            if rabbit.is_collided_with(wolf):
                print("works 2")
                rabbit.kill()

pygame.quit()
exit()

```

# Answer
> 0 votes
The issue lies in the following function:

```
def Boundry(Xpos, Ypos):
    if Xpos<=0:
        Xmovement=0
    elif Xpos>=950:
        Xmovement=950
    else:
        Xmovement=+0

    if Ypos<=0:
        ymovement=0
    elif Ypos>=750:
        ymovement=60
    else:
        ymovement=+0

    return Xmovement, ymovement

```

In no case you are keeping the values you've passed as parameters, you only overwrite them.

It should read:

```
def Boundry(Xpos, Ypos):
    Xmovement = Xpos
    ymovement = Ypos

    if Xpos<=0:
        Xmovement=0
    elif Xpos>=950:
        Xmovement=950

    if Ypos<=0:
        ymovement=0
    elif Ypos>=750:
        ymovement=60

    return Xmovement, ymovement

```

Or, more concisely, as suggested via the existing answer:

```
def Boundry(Xpos, Ypos):
    Xmovement = min(max(0, Xpos), 950)
    ymovement = min(max(0, Ypos), 750)

    return Xmovement, ymovement

```

---

That being said, your code contains a lot of inconsistencies and magic numbers which could bite you down the road.

I also suggest you use tools such as pylint and black to help improve the readability, the consistency, and the robustness of your code.

# Answer
> 0 votes
You'd better try the min-max method to set the boundaries for you object movement, something like:

```
self.x = min(max(0, self.x), screen_width)
self.y = min(max(0, self.y), screen_height)

```

I hope you can set it to your code.

---
Tags: python, pygame
---


# Question
Title: Should the entity handle his own movement?
I am currently building a simple turn based game with a Room consisting of a 2D array of Tile objects. Those can be WallTile or FloorTile. Tile objects have a north, east, south and west Neighbour. The FloorTiles have a Stack of Entities so I can easily draw the top entity.

Now I am wondering, my Player is an Entity, when the player moves, should the player handle that logic, or the Game that holds my Player?

In the first case it would be something along the lines of:

```
class Player : Entity {
    public Tile CurrentLocation

    public bool CanMoveTo(Direction) {
        // Let's say that direction is East
        return CurrentLocation.EastNeighbour == FloorTile
    }

    // This method does the actual move
    public void MoveTo(Direction)
}

```

In the second case it would be like this:

```
class Game {
    public Player Player;
    public Room Room;

    public void Update() {
        // Lets say we get direction from some input from somewhere
        if Room.TileAt(player.Y, player.X) is FloorTile then MoveThere()
    }
}

```

I am not quite sure what the nicest of the two options is. Initially I am thinking about the first solution. Any help or tips would be appreciated.

# Answer
There are no right or wrong ways to do things. Only ways which work for you or don't work for you.

There are several competing philosophies in mainstream game architecture.

## A: Object-oriented architecture

Every entity should be represented by an object. Those objects should contain all of their own logic, encapsulate their internal state and communicate with other objects through well-defined interfaces. The core game engine just calls the "Update" and "Render" methods of all entities in a loop and then lets the entities do the rest.

When you have objects which share some functionality, you would usually do that through inheritance - by extracting the common functionality into a common base-class. For example, you might want to have a class Player and a class Enemy which both inherit from a class Combatant which contains all the combat code and inherits from Entity which contains the basic code for movement. And Enemy would likely be an abstract class which contains only the logic common to all enemies, with the different enemy types and their unique behaviors implemented in classes inheriting from Enemy.

Basically the way you are supposed to do OOP by the book.

This style is frequently seen in developers who came from application development, because it's the predominant style there. And what works for applications is not necessarily completely wrong for games.

## B: Entity-Component architecture

This style prefers composition over inheritance. An entity isn't one object, it is a collection of objects with each object implementing a different feature of that entity. So you don't have a "Player" class implementing every single thing a player can do. You have a generic Entity with a "Sprite", a "Mover", a "Shooter", a "Hitpoints" and a "PlayerInput" component.

The advantage of this approach is that components are very easy to mix and match to create new kinds of game entities. This is pretty useful for rapid iterations on your game design. It's the favorite approach by some popular game engines. Like Unity, for example.

## C: Entity-Component-System architecture

An entity should be a collection of components just like in the "Entity-Component" architecture. But in this architecture, those components should just be dumb data-holders. Usually in form of structures with only public variables and no methods. All the logic should be in systems. Each system is responsible for managing one type of components, or a set of components. For example, you have a MovementSystem which updates the Position component of every entity with a Movement component.

But this is just an oversimplification. If you want to know more, check out the question "What is pure ECS?". You might also look at other questions under our tag.

The ECS approach is currently very in fashion. The main argument for it is that it allows some very neat performance optimizations (particularly when it comes to memory locality and multithreading) without sacrificing the modularity and iteration speed of the Entity-Component approach. But the disadvantage is that a solid and flexible ECS architecture requires quite a lot of architecture code which runs "behind the scenes" and which can be difficult to implement for beginners.

## Which one should you use?

That's something you need to figure that out on your own. But whichever approach you choose for your game, you would be well-advised to stick to it. Avoid mix-and-matching architecture patterns in your game when feasible.
> 7 votes

# Answer
It basically depends on the amount of data traversing your game network. Any massive multiplayer needs to keep track of who is where doing what always (otherwise massive cheating will ensue). However, receiving and sending packets from the server to every and each client (what is known as an authorative server) is seldom practical for any amount of significative users. So, the philoshopy seems to be how much logic you can get the player to control without affecting other players. In other words, what affects you and only you (except for looting) can be handled by the client. Whereas whatever affects several players must be handled by the server. Or, if not handled, al least authorized before any effect ensue.
> 0 votes

---
Tags: 2d, movement, tiles
---


# Question
Title: Unity Animator not animating player, but following transitions perfectly in Animator Window
I am trying to animate a model in my project, and although I have been successful doing the same in other projects, I am not succeeding in this one.

The model does not seem to animate, although in the Animator window, everything looks fine, transitioning from one state to the other and going back.

I have followed the tutorials to import animations from the site where I downloaded the animation, and each animation is the same as other working animations in other projects:

The animations play as expected in the inspector window.

I have tried modifying the "Apply Root Motion" in my character and it does not work either way. My Player model has these properties:

And I have tried adding a Rigid Body but it didn't work neither. I have spend several hours trying to solve this issue and I am running out of ideas to try. How can I make the animation work as expected?

Cheers!

# Answer
After some more hours trying to figure it out, and testing all the possible combinations, my animations play if I set the "Animation type" inside the "Rig" options of the animation, from "Humanoid" to "Generic".

It is really weird as in another project, with the same assets and configuration, it works well with the "Humanoid" option selected.

Cheers!
> 1 votes

# Answer
Whenever you import a mesh, you can import it as legacy (has their own animations baked into the mesh), or humanoid (not having any animations on their own, but having the requiered bones to pose any compatible animation). Some designers actually provide both in the same mesh. The generic, of course, cannot use humanoid animations because it does not have the required bones to pose them. Thus, what seems to happen here is that your mesh has both...

It is always a good idea to correct the T-pose if needed, especially when humanoid animations look weird.
> 0 votes

---
Tags: unity, animation, animator, animation-controller
---


# Question
Title: error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)
```
public class AbilityOne : MonoBehaviour
{
    public PlayerHealth playerHealth;
    public float healthGain = 2f;

    void OnTriggerStay2D(Collider2D other)
    {
        playerHealth.currentHealth += healthGain * Time.deltaTime;
    }
}

```

Im getting this error and do not know how to fix it. Anyone know the problem?Assets\Scripts\Medic\AbilityOne.cs(12,9): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)

# Answer
`playerHealth.currentHealth` is an `int`. Try this. It converts the `float` value to an `int` explicitly. The `(int)` part is a called a "cast", so this is what the error message is telling you that is missing.

```
public class AbilityOne : MonoBehaviour
{
    public PlayerHealth playerHealth;
    public float healthGain = 2f;

    void OnTriggerStay2D(Collider2D other)
    {
        playerHealth.currentHealth += (int)(healthGain * Time.deltaTime);
    }
}

```

BUT this fixes the error, but I bet it's not the behavior you want. It looks like you'll be adding small fractions of health each frame. That will fail if you try to store those fractions in an `int`. I recommend making `playerHealth.currentHealth` a float. Then the code you have in your question will work fine.
> 0 votes

---
Tags: c#
---


title: How to get an ESRB rating for my game?

text:
# Question
Title: How to get an ESRB rating for my game?
What does it take to get an ESRB rating for my game?

# Answer
The primary point of entry appears to be the ESRB's website. The process appears to be that you need to make a physical letter on corporate letterhead with all sorts of information proving you are a real business. You then need to send them the letter and wait 5 days at which point they will send you a user/password for their website, at which point you can request a rating, which will take time and some amount of money.
> 6 votes

# Answer
For anyone looking at this in 2020, the International Age Rating Coalition (IARC) website gives you the info you need. If you have a digital copy game, and submit your game to a place like the Google Play Store or Nintendo eShop, you will fill out the IARC questionnaire. A game rating will immediately be assigned 100% free of charge for all regions where your content is available. **It does not cost money. I repeat, you do not pay the IARC, ESRB, PEGI, etc, for anything.** The only thing that costs money is development licenses which are issued by the digital storefronts, and not by the IARC, ESRB, PEGI, etc.
> 8 votes

---
Tags: content-rating, esrb
---


# Question
Title: Is it possible to correctly catch up a particle system simulation based on long delta time between many frames?
I have a particle system with a physics simulation integrator based on delta time (elapsed time between frames) which is implemented on the GPU in a compute shader. I also have a frustum culling system implemented on the GPU. The frustum culling gives me the possibility to cull away draw calls and the dispatch calls for the particle simulation. The culling of draw calls works well, I also don't have a problem with culling the particle simulation when the camera is looking away.

My problem happens when I want to catch up the particle system simulation when the camera looks back at the particle system after looking away for a while. What I do is accumulate the time passed while looking away, then I resume the simulation using all that accumulated time. The problem with this approach is that if the simulation is anything but a simple constant velocity change in one direction, the simulation just doesn't look the same as if the simulation was playing one frame delta at a time.

From what I have read this is a common issue with using time elapsed between frames to simulate physics. What I wonder is if there's a different approach that can actually allow me to correctly play back many seconds of simulation (let's say 20 seconds) the same as if it was played one frame delta at a time?

# Answer
Look up how Unity‘s FixedUpdate solves this: it’s a commonly used mechanism you might take inspiration from. FixedUpdate is called a fixed number of times per second; you decide how many by setting the fixedDeltaTime value in settings, which by default is 0.02s. Unity will always run this 50 times per second. Doing so any calculations inside the FixedUpdate should be accurate. This is necessary because whatever real-time system you’re developing, you must account for occasional frame drops and your physic simulations must not depend on time deltas.
It’s not too hard to implement the same mechanism in your own system. You can even do it in a separate thread.
Side note: FixedUpdate, as it runs many times in one frame, can easily become heavy so it’s good to make a minimal use of it.
> 1 votes

---
Tags: physics, 3d, graphics, particles, simulations
---


title: How to combine bilateral blur passes?

text:
# Question
Title: How to combine bilateral blur passes?
I'm changing to bilateral blur for my SSAO implementation, just wondering how people usually combine the two passes - do you just add them together, or average, or something else?

I happen to be using Vulkan but don't think that should affect the answer too much.

# Answer
> 1 votes
You apply one pass with your source image as input to get an intermediate image.

Then you apply the second pass using the intermediate image as input to get your output.

```
   Input Image
       ↓
     1st Pass
       ↓
Intermediate Image
       ↓
     2nd Pass
       ↓
   Output Image

```

---
Tags: c++, vulkan, blur
---


# Question
Title: Water shader in Unity3D not working on some Linux distributions/some Mac OS?
I've got reports from some Linux users that the game's **water isn't rendered on his machine**.

3 example operating systems:

* Ubuntu 20.04 (with kernel 5.4.0-54-generic x86\_64
* Linux 4.15 Linux Mint 19.2 64bit
* Mac OS X 10.13.6

I use this shader: https://roystan.net/articles/toon-water.html

I've made a small change so I can use it in **orthographic projection** as well:

```
            float existingDepthLinear = 0;

            if (unity_OrthoParams.w > 0)
            {
                // orthographic camera
            #if defined(UNITY_REVERSED_Z)
                existingDepthLinear = 1.0f - existingDepth01;
            #endif
                existingDepthLinear = (existingDepthLinear * _ProjectionParams.z) + _ProjectionParams.y;
            }
            else
            {
                // perspective camera
                existingDepthLinear = LinearEyeDepth(existingDepth01);
            }

            // Difference, in Unity units, between the water's surface and the object behind it.
            float depthDifference = existingDepthLinear - i.screenPosition.z;

```

I've got a feeling that

```
            #if defined(UNITY_REVERSED_Z)
                existingDepthLinear = 1.0f - existingDepth01;
            #endif

```

is what causing the issue.

When I remove it, on my PC, which was working well until now, the whole surface will be just foam. So plain white. Just like on their computers.

So maybe UNITY\_REVERSED\_Z is not defined?

What could cause this issue? Feel free to ask for more info, maybe I can provide.

# Answer
There was a bug in the shader's code. The issue was ocurring on the machines where the **Z buffer is reversed**.

In that case the **existingDepth01 should be inverted**, but by mistake... well, **I messed up**... I reverted the wrong variable, and also in the line after that I used a wrong variable in the calculation. :D And I couldn't see these obvious errors...

It was working on most of the machines only through sheer luck.

**Here's the problematic part, fixed:**

```
#if defined(UNITY_REVERSED_Z)
    existingDepth01 = 1.0f - existingDepth01;
#endif

existingDepthLinear = (existingDepth01 * _ProjectionParams.z) + _ProjectionParams.y;

```
> 0 votes

---
Tags: unity, shaders, linux, water
---


# Question
Title: How can I turn a Unity game into an MRAID-compliant playable ad?
I need to create a mini-game, one really simple scene, and export it as a playable that comply with the MRAID requirements.

Basically, I can export a WebGL. The question is which adaptations the code needs to have (if any) in order to become compatible with MRAID.

I saw the Luna tool that claims to solve this issue and export the scene on its own engine, to avoid any future adaptations, but honestly, I don't really understand what they're doing differently, if their engine still converts to JS and HTML5.

It seems really blurry at the moment and I can't find concrete, coherent answers.

All I'm getting from the company that approached my to get it done is "it needs to be MRAID compatible".

Does anyone have any experience and can shed some light on this subject?

Thanks in advance, Omer

# Answer
> 0 votes
You cannot turn a conventional\* Unity game into an MRAID-compliant playable ad by just tweaking some code.

At least, not one with a download size and startup time that you would likely consider acceptable. The standard Unity engine is made for full-fledged apps, with a lot of flexibility and rich feature support that make it too heavyweight for mobile ads.

(\* You *may* be able to accomplish this with Unity's Project Tiny - it's one of the project's goals, but I don't have first-hand experience as to how well it's currently been achieved)

What the Luna tool you've found does is to take your Unity content and export it as something that is *not* a Unity game and not running on the Unity engine, but on their own lighter-weight "Luna Engine" which has different feature support. They're effectively piggybacking off of the Unity editor and the familiar workflows it offers, but then bypassing the normal Unity build process and runtime entirely with their own substitute.

If that's sufficient for your needs, then licensing that tool could be a way to solve your problem. Or if you're building this project from scratch, you may want to look into other MRAID-compatible ad creation tools. You may find some that are leaner, if they don't need to go out of their way to emulate Unity features in not-Unity.

---
Tags: unity, html5, advertisements
---