title: Artificial limitation in games?

text:
# Question
Title: Artificial limitation in games?
I've made a research and found out that without dedicated graphics games use max 50% of each processor's core. And it seems to be an artificial limitation. For a powerful processor 50% is a very big number compared to a powerful graphics card.

> So if you could buy 1 car engine vs. 10 motorcycle engines that apply twice the power for half the cost and weight, which would you buy?

I dont need your long lectures about the cpu and gpu architectures You cant answer the simple question why I must buy 10 motorcycles when I already have an universal car (processor) fastened with prediction and loaded only at 50% that can turn into 10 motorcycles and a car. And by the way today motorcycles (gpus) costs almost as much as cars (cpus)

> Sure, some people and companies write inefficient code.

There is no problems to make a code which will use 100% of a processor's capacity. So it is rather the artificial limitation than unwilling.

# Answer
> why I must buy 10 motorcycles when I already have an universal car (processor) fastened with prediction and loaded only at 50% that can turn into 10 motorcycles and a car.

Because it can **not** turn into 10 motorcycles. Some tasks run very fast on GPU and others very fast on CPU. Calculating a typical GPU task like a pixel shader on the CPU might be possible in theory, but in practice it will run extremely slow. So the FPS gain from moving GPU tasks to the CPU when CPU load is available would be negligible. We are talking about orders of magnitude like 40.4 FPS vs. 40.5 FPS here.

Explaining the reasons why would require a long lecture about the cpu and gpu architectures which you explicitly rejected to read, so you have to just accept that as a fact.

And what is the cost for you for that tiny, unperceivable FPS gain?

* It would require a lot of programmer work to implement that. I might have made it sound easy above to just move a task from the GPU to the CPU, but in practice it is not. Those programmer-hours could alternatively be used to improve the gameplay or graphics.
* There will be more bugs, because a hybrid GPU/CPU rendering pipeline would make a lot of things a lot more complicated.
* Your CPU will run hot when it permanently runs on 100% load, which decreases its lifespan.
* It would cause your CPU to use more power, which increases your electricity bill.

So it's not worth the cost. Neither for your game experience nor for your wallet.
> 0 votes

---
Tags: graphics, hardware
---


# Question
Title: How to manage a lot of items on conveyors
I am making some sort of factory game (topdown 2D) where I will have machines outputting items on conveyors. I was wondering what was the best approach to manage the items on the conveyors. There are two things that I'm not sure what the best way to achieve them is:

* managing the distance between the items
* moving the items

I think it's best to avoid having a rigid body on every items, as it would probably cause lag on for a mobile game if there are a lot of items. I wanted to avoid having colliders but that may make it too difficult.

I was thinking of having a list on each machine containing the items of all the conveyors connected to it and checking the distance between every item and the one in front of it then moving the items if possible at every update. I'm just not sure if that's the good way of doing things or if there is an obvious solution I haven't thought of (which is most likely the case).

# Answer
> 2 votes
First of all, you should know that Factorio is one of the few game projects where the technical requirements are so unusual that writing a custom engine actually made sense. The core of Factorio is written in C++, and the developers are using a lot of low-level optimization tricks to make that humongous number of entities moving around and doing stuff in a large-scale factory work as well as it does. Their development blog (linking to the beginning) is a really interesting read for every game developer.

That being said, it should be possible to create a similar game experience in Unity, as long as you are willing to make a couple concessions to the size of factories and the number of items moving around them.

But you will still have to do a couple optimizations, because representing every single item as a full-fledged gameObject will create far too much overhead.

The entity-component-system architecture would be great for this use-case, but it is still in beta and we already established in the comments that you don't feel brave enough to face it in its current state. Which I fully understand after doing a couple experiments in it myself.

But we can still apply a couple of its principles in the regular Unity architecture.

## Logical representation

For example, instead of each item being represented with a gameObject with a transform, a rigidbody and a collider, we can represent it with a plain old C# object and have each conveyor belt own a couple of those. And the conveyor belts themselves could also be represented by plain old C# objects owned by a global `BeltSystem` `MonoBehaviour`. This system could store all the belts in a two-dimensional array with tile indices mapping to array indices. That makes it very easy to acquire the belt on a specific tile and then the items currently on that belt.

## Visual representation

But you still need to render all those belts and items.

The belts don't move (although they might be animated) and are arranged in a grid, which means that using a Tilemap is likely the most optimized way of rendering them.

But for the items you are going to need SpriteRenderers, which require GameObjects. But you only need those for those items which are actually on the screen. So it might be possible to decouple the logical representation of items from their visual representation by having an object with a SpriteRenderer following the position of each item currently on a belt which is on-screen.

But `Instantiate`ing and `Destroy`ing objects frequently also causes performance issues due to the garbage and memory fragmentation they cause. A good way to handle this problem could be to use an object pool of objects with SpriteRenderers attached. When a belt or items is on-screen, you request a render-object from the object pool. When the item is destroyed or moves off-screen, you return that render-object back to the pool.

---

I wish you the best of luck with your project. You are going to need it!

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


# Question
Title: how do i destroy a DontDestroyOnLoad Gameobject
I have a **DontDestroyOnLoad** Gameobject and i just can't destroy it I have tried a lot of things.

```
private void Awake()
    {

        if (instance == null)
        {
            instance = this;

        }
        else
        {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
    }
        void Start()
    {
        FindObjectOfType<audiomanager>().Play("rain");

    }

```

I have tried destroying it from another script through

```
Destroy(GameObject.Find("rainmanager"));

```

and

```
Destroy(rainmanager.instance.gameObject);

```

it just doesn't get destroyed, I have no idea why.

# Answer
Ok so it was my fault all along, I have been looking for the solution for hours now, but I made 2 mistakes. Firstly I created a duplicte of the dontdestroyonload object in another scene, so even when the original was getting deleted i thought it wasn't.

```
Destroy(GameObject.Find("rainmanager"));

```

The method above doesn't work maybe because I should be destroying the instance.

```
Destroy(rainmanager.instance.gameObject);

```

this method does work.
> 0 votes

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


# Question
Title: How do I display a variable in a UI Text component?
How can I display a variable (say an integer variable) in Unity's UI text? The variable may be a public variable from another script.

Can anyone please help me do it (step by step)?

# Answer
Below is a script that will show the value `myIntValue`, and only ever changes the value on screen when the value changes. Parts of this script will be integrated into whatever script is modifying your integer value. You'll then have a UI component somewhere else that has a `Text` component on it. In the Unity editor, you'd drag the `Text` component onto this script in the inspector. This will assign the `Text` component to the `textComponent` variable in the below script, which will then get updated when the your value changes.

```
public class DisplayValue : MonoBehaviour {

    public Text textComponent;

    private int myIntValue;
    public int MyIntValue
    {
        get { return myIntValue; }
        set
        {
            if(myIntValue != value)
            {
                //Here we're only updating the text shown on screen when the value is changed
                myIntValue = value;
                UpdateText(myIntValue);
            }
        }
    }

    void Awake () {
        //If text hasn't been assigned, disable ourselves
        if (textComponent == null)
        {
            Debug.Log("You must assign a text component!");
            this.enabled = false;
            return;
        }
        UpdateText(myIntValue);
    }

    void UpdateText (int value) {
        //Update the text shown in the text component by setting the `text` variable
        textComponent.text = "Value is: " + value;
    }
}

```

Further, you can see a simpler version of this in the Unity tutorials on UI Text components
> 1 votes

# Answer
While the other answer explains how you can get your value to a text component, here is a way you can format the string. Instead of using something like

```
textComponent.text = "Value is: " + value;

```

as displayed in the other answer, you can use an interpolated string, using the `$`, like such

```
textComponent.text = $"Value is: {value}";

```

Here is a bigger example:

```
int val;

void Start()
{
   val = findObjectOfType<yourScriptName>().VariableName;
}

string name = "John";
string result = $"{name} is {val} years Old";

```
> 0 votes

---
Tags: unity, c#, ui-design
---


# Question
Title: I need a game over (UI image) to appear after timer reaches 0
So here is my timer script that works fine. I need it to activate the game over (UI image) when the timer reaches 0.

I tried attaching a game over script to the UI image (GOS script)..... no luck

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

public class Timer : MonoBehaviour
{
    public Text gametimer;
    public float timeLeft;
    public GameObject Gameover;
    public Text gameovertext;

    void Update()
    {
        if (timeLeft > 0)
        {
            timeLeft -= Time.deltaTime;
        }
        else
        {
            timeLeft = 0;
        }

        displaytime(timeLeft);
    }

    void displaytime(float timeToDisplay)
    {
        if (timeToDisplay < 0)
        {
            timeToDisplay = 0;
            Debug.Log("Game Ova YOung!!!");
        }

        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        gametimer.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

```

Game over screen script:

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

public class GOS : MonoBehaviour
{
    GameObject GameOverScreen;
    public Timer timer;

    void Start()
    {
        timer = GetComponent<Timer>();
        GameOverScreen.SetActive(false);
    }

    void Update()
    {
        if (timer = null)
        {
            GameOverScreen.SetActive(true);
        }
    }
}

```

# Answer
> 3 votes
> there aren't any specific codes or videos too my knowledge.

If you only look for code or videos that do *exactly* what you want to do, then you are limited to making only what has been made before. You cannot develop new games with this approach. A game developer must be able to abstract: break your problem into steps, find solutions to each step, and synthesize into a solution to your whole problem.

You want to be able to make something happen when a value reaches a certain value. It does not matter whatsoever that this thing is "show a game over screen". The logic to detect the value change and call a function in response is the same. So you can look at *any* example of triggering an action in response to a value and abstract that to something you can use in your synthesis.

One simple way to do this is with a `UnityEvent`:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class Timer : MonoBehaviour
{
    public Text readout;
    public float timeLeft;

    public UnityEvent onTimerCompleted;

    void Update()
    {
        if (timeLeft > 0f) {
            timeLeft -= Time.deltaTime;

            if (timeLeft <= 0f) {
                onTimerCompleted?.Invoke();
                timeLeft = 0f;
            }

            DisplayTime(timeLeft);
        }
    }

    void DisplayTime(float timeToDisplay)
    {
        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        readout.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

```

This gives you a widget in the inspector just like the ones on UI Button components. You can use it to wire up any arbitrary thing (or sequence of things) you want to happen when the time hits zero.

Here I've asked it to take my Game Over Screen object, and call its `GameObject.SetActive()` method with an argument of `true` (checked box). But you could also make it call a public function on your own custom script instead. The beauty of this approach though is that you don't strictly need a second script to do the job.

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


# Question
Title: How to fix shadow not casted to terrain when rendering using default and terrain shader (depth shader included)?
Given that I have the `TerrainShader` class and `DefaultShader` class. Also a FBO (Frame Buffer Object) shadow map

The `TerrainShader` has all the terrain, light, shadow related calculations. While the `DefaultShader` has the generic objects light, shadow related calculations.

I have successfully cast a directional shadow map when I only use `DefaultShader` alone with random cube objects and a plane. Now the problem was when I move or use a terrain instead of `TerrainShader`, the shadow is not cast in the terrain.

Question: Am I using the FBO the correct way or I am doing it wrong.

Solution Idea (Not yet applied)

* Merge terrain and default shader as one and create a flag if object or terrain will be rendered? (Still not sure if this is correct.)

Pseudocode (Current successful implementation)

* Create shadow map fbo
* Create default shader
* Create depth shader
* bind shadow map fbo
* clear depth
* render cubes & plane using depth shader (mvp)
* unbind shadow map fb
* clear color and depth
* render cubes & plane using default shader

Pseudocode (with Terrain shadow not working)

* Create shadow map fbo
* Create default shader
* Create terrain shader
* Create depth shader
* bind shadow map fbo
* clear depth
* render cubes & plane using depth shader (mvp) and exclude terrain
* unbind shadow map fb
* clear color and depth
* render cubes using default shader
* render terrain using terrain shader

# Answer
I turns out that I made a mistake, I have filtered out terrain in the list of entities. So by including the terrain again, the shadow map is now displayed in terrain
> 0 votes

---
Tags: opengl, shaders, shadow-mapping
---


# Question
Title: Find the vector orthogonal to a quaternion?
Apologies if the title doesn't quite make sense, it's been a long time since I did any 3D stuff. I would like to be able to pan my camera up and down with the arrow keys. The camera's rotation is described by a quaternion, and I need to rotate that quaternion around an imaginary axis orthogonal to the way the camera is pointing (if you can imagine the camera mounted on the front of a big + then the axis I need would be the horizontal bars).

I know how many radians I need to rotate by, but I'm struggling to work out how to get the axis I need to rotate around. I've tried to draw what I mean:

The red line is where my camera is actually facing. It (eventually) will be able to tilt left and right as well. The green line is "up" from where the camera is pointing, and the blue line is the axis I want to rotate around for up/down panning. Please try and imagine they're all at right angles.

How do I rotate my quaternion *q* around the blue line by *r* number of radians? Is there something I can do with a matrix here and skip looking for an axis? If it helps I'm using g3n in golang so this is what I have to work with.

# Answer
> 0 votes
With a push in the right direction from DMGregory I managed to get this working after a bit of tweaking with the order of multiplication. I was probably overthinking the issue to begin with, but the code looks like this:

```
// Find our new camera quaternion by multiplying quaternions describing l/r and u/d panning.
camPos := math32.NewVector3(cam.Position().X, cam.Position().Y, cam.Position().Z)
camRot := math32.NewQuaternion(cam.Quaternion().X, cam.Quaternion().Y, cam.Quaternion().Z, cam.Quaternion().W)

upDownRot := math32.NewQuaternion(0, 0, 0, 0).SetFromAxisAngle(math32.NewVector3(1, 0, 0), upDownPanSpeed)
leftRightRot := math32.NewQuaternion(0, 0, 0, 0).SetFromAxisAngle(upVec, leftRightPanSpeed)
camRot = leftRightRot.Multiply(camRot.Multiply(upDownRot))

// Rotate the velocity vector which describes "new" movement to our cam's orientation, then add it to the current position.
newPos := math32.NewVector3(leftRightSpeed, upDownSpeed, forwardBackSpeed).ApplyQuaternion(camRot).Add(camPos)
cam.SetPosition(newPos.X, newPos.Y, newPos.Z)
cam.SetRotationQuat(camRot)

```

This answer was particularly helpful in sorting the multiplication order.

---
Tags: rotation, quaternion
---


# Question
Title: Unexpected white pixels when using terrain painting brush
I have two texture layers in my terrain. When I paint the second layer on the base layer the results around some of the the joining areas will be like:

I can remove it by carefully painting over it but in some cases it just grows further and consumes a lot of time and energy. I'm using `Unity 2018.4.0f1` and have never seen such thing in older versions and 2019. However I have not used terrains very much. Tell me if you need any information in the comments. I have tried the following approaches:

* Disabling Alpha Channel in texture import settings
* Testing both color spaces (Linear and Gamma)
* Using the same texture for both layers (The white line still exists)
* Using custom Diffuse Material

The problem seems to be the generated SplatAlpha texture:
As you can see four layers are generated: Red, Green and Black. But you can see the pixels I marked with blue and I don't know where are they coming from. Why is that and how to solve it?

# Answer
> 0 votes
The problem seemed to be the version `2018.4.0f1`. It's a bug in `SplatAlpha` generation. I've ported the project to `Unity 2020.2.7f1` and now it's working fine. It would have been better if there was a fix for 2018 because I really need to implement the game in that version.

---
Tags: unity, rendering, terrain
---


# Question
Title: Is it better design to store event effects within an Entity itself, or within a system?
I'm developing a 2D roguelike with an Entity Component System (ECS) and I've been struggling with this question a lot the past week. For example, let's say you have various effects that occur when an entity spawns, dies, collides with another entity, etc. Where should these effects be coded? I see two main possibilities:

1. In the entity itself. Example pseudocode:

```
let effectsComponent = new EffectsComponent();

effectsComponent.onHit = [ damage(10), deleteSelf() ];
effectsComponent.onDeath = [ playSound("player-death.mp3") ];

// Effects system
for (let effect of ...

```
2. In a system. Example pseudocode:

```
// Damage system
for (let event of scene.events.query<CollisionEvent>()) {
  if (event.entity1 is bullet and event.entity2 is player) {
    event.entity2.damage(10);
    event.entity1.delete();
  }
}

// Sound system
for (let event of scene.events.query<DeathEvent>()) {
  switch (event.entity.type) {
    case ET.Player: playSound("player-death.mp3"); break;
  }
}

```

I can think of numerous pros and cons for each approach. The first approach can likely cut down on some conditionals because since we are defining it on the entity itself, we already know its "type" already, so the only thing we would have to worry about is the type of the receiving entity. As such, it's likely more terse to code in the first manner.

However, the second approach might be more "proper" within the context of an ECS. That is, you could argue that it is not the responsibility of an entity to describe its behavior. Components should only hold state, and not behavior, and it's a short road to spaghetti when you begin mixing in behavior and state within an entity definition.

In addition, many events may not even have a `receiver` or `target` entity, so regardless in some situations we'll have encode it into the system's functionality regardless. And if that is the case, then why not just be consistent and always make systems handle this sort of thing?

Lastly, philosophically, it kind of feels like systems should be responsible for handling the interaction response of two entities. As an example, with the first approach, should the player entity or the bullet entity encode the behavior response for when they collide with each other? It's unclear. Then again, it also feels like entities should describe their data, and things like sound effects should likely be encoded within an entity component instead of being delineated within a system.

In other words, I'm very unsure of how to handle this. What is considered better design here? Should components be responsible for holding this interaction / event data, or should systems?

# Answer
> 2 votes
All ECS architectures run into the problem of event processing eventually. Event processing does not fit neatly into the ECS philosophy, but few moderately complex games can really do without it. So any solution will necessarily feel not entirely ECS-kosher at first.

Approaches I have seen are:

* Attach events as transient components to the entities they belong to, and remove said components after the event was processed. The feasibility of this solution greatly depends on how costly it is in your architecture to add and remove components. If your architecture does not allow duplicate components on entities, then there is also the drawback that each event can only happen once per update to each entity.
* Add the possibility for systems to have event queues. When an event happens, you put it into the event queue of the system which handles the event. The system then processes its event queue in its update.
* If you are using event queues anyway, you can also do them properly. With one global EventManager system which receives all events. Systems can subscribe to events they are interested in and then the EventManager will put those events into their event queues.

But in any case, you should still follow the ECS philosophy that data belongs into components and code into systems. So what actually happens as part of an event should be handled by a system. Components should not contain variables which map to functions or lambda expressions.

---
Tags: javascript, software-engineering, design-patterns, entity-component-system
---


# Question
Title: Unity Input: Thumbstick works in editor, not in WebGL
I've built a game in Unity 2017.1.1f1 for the web. I have inputs to allow user to play with either the keyboard or a gamepad (in my case, a Gamecube USB). So far as I can tell, all controls work fine EXCEPT for my right (C) thumbstick. When I use the keyboard inputs which are an alternate for the C thumbstick, they work, and the C thumbstick works in the editor. These facts seem to rule out that there's any problem with my input settings or with my code or with my gamepad. Any ideas of what I can do to fix this? I'm not even sure where I would begin troubleshooting.

UPDATE: I built a UI to output a float for all axes. In the editor, I got a response for this thumbstick. On the web, the vertical axis for this thumbstick changed nothing.

# Answer
Well, I was unable to reproduce the problem using Unity 2020.3.11f1 and my own gamepad (Cheap XBox 360 compatible gamepad by Speedlink).

I used the Input Manager to create 7 axis inputs and mapped them to the Joystick axis X, Y, 3, 4, 5, 6 and 7 "from all Joysticks". I then created a script to visualize those 7 axis' on the canvas.

The result behaves the same way for me in both the editor and the WebGL build, the latter both in Firefox and in Edge. I uploaded the result to itch.io so you can check it yourself.

Those axis map to my gamepad as follows:

1. Left Thumbstick Horizontal
2. Left Thumbstick Vertical
3. Triggers
4. Right Thumbstick Horizontal
5. Right Thumbstick Vertical
6. D-Pad Horizontal
7. D-Pad Vertical

Note that not all gamepads will map the same way. This is one of many input device compatibility problems the new Input System available in Unity 2019+ solves. When you don't want to migrate to the new input system, then the best workaround is to let the player configure their input axis\` themselves.

When it does work as well for you as it works for me, then I recommend you to update your project to a more recent version of Unity. I can't tell you *how* recent you have to go, so when you don't want to go all the way to 2020, then you have to find the minimum required version yourself using trial and error.
> 1 votes

---
Tags: unity, input, gamepad
---


# Question
Title: Triggering animation only its position changes?
I am a newbie on coding, wanted to work on a game as practice and started to work on a 2D top view game, and on a barren desert area, I have a *Twigball* for my player to touch and move it because of its dynamic rigidbody.

This *Twigball* has 2 animations which those are **idle** and **movement** animations. Everytime my player touches, *Twigball* moves, changes its position. But what I need is: Everytime this *Twigball* moves by touching or any other ways, I want its *"isMoving"* bool is *"true"* and make it start the **"movement"** animation, everytime it stops, I want to start its **"idle"** animation.

It might be simple thing but I couldn't find how to do it with code. Rigidbody works good with its options (linear drag, angular drag etc...) on inspector. I have a `TwigBallBehaviour` script attached to the TwigBall but its empty. OnColliderEnter would work for Player touches etc. but this *Twigball* will also move itself as behaviour. So I need codes to do all that I think, probably calculating position etc... I have already done all changes in Animator window. But what should I write as code? Any advices?

# Answer
> 1 votes
Well I dealt with the problem, here the solution:

I wrote many codes to `TwigBallsBehaviour` which it was empty before, here the codes I wrote:

```
public class TwigBallsBehaviour : MonoBehaviour
{

    private Animator anim;
    public Rigidbody2D rb;
    private bool isMoving;
    void Start()
    {
        anim = GetComponent<Animator>();
        rb = this.GetComponent<Rigidbody2D>();
        anim.SetBool("isMoving", false);
    }

    void FixedUpdate()
    {
        if(rb.velocity.x == 0)
        {
            anim.SetBool("isMoving", false);
        }
        else
        {
            anim.SetBool("isMoving", true);
        }

    }

}

```

I also added a code group to the Player's Script, used simply collisions. You can see below:

```
private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "TwigBall")
        {
            Debug.Log("Turning");
            if (transform.position.x < collision.gameObject.transform.position.x)
            {
                Debug.Log("From Right");

            }
            else
            {
                collision.gameObject.transform.parent.eulerAngles = new Vector3(0, -180, 0);
                Debug.Log("From Left");
            }

        }
    }

```

After all these, added collider to *TwigBall*, tagged it as "TwigBall". This is how I solved my problem.

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


# Question
Title: How could I put a prefab into a field of a game object using editor API in Unity?
How could I put a prefab into a field of a game object using editor API in Unity?

I have a game object. It has a `GameObject` field. I can drag and drop a prefab from my assets into that field.

Now I want to take the prefab (I have a path to it in my code) and put it into that game object field using editor API. Is it possible somehow?

I need this to automate some of my scene setup.

# Answer
You can just assign the value in code.

`myGameObject = thingToAssign;`

You may want to do this in `OnValidate` or with `ExecuteInEditMode`.
> 1 votes

---
Tags: unity, editors, prefabs, api
---


# Question
Title: Why is transform matrix order is reversed in my Scene graph implementation?
I have researched this a lot and so far all the examples, tutorials etc always use the following order: Scale * Rotate * Translate but for some reason this order must always be backwards in my Scene Graph. I am not sure if this is intended due to transforming local matrix to world matrix or it is an inherent bug in my application.

Here is my simple Scene Graph implementation. I am using Vulkan and GLM math library.

```
void SceneNode::setTransform(glm::mat4 transform) {
  transformLocal = transform;
}

void SceneNode::update() {
  // if root node
  if (parentNode == nullptr) {
    transformWorld = transformLocal;
  } else {
    transformWorld = parent->transformWorld * transformLocal;
  }

  for (auto &node : children) {
    node->update();
  }
}

```

And my shader logic:

```
// initialization code hidden for simplicity

void main() {
  // worldTransform = transform matrix calculated during scene node update
  gl_Position = UniformCameraData.projectionView * ModelPushConstants.worldTransform * vec4(vPosition, 1.0f);

  outColor = vColor;
}

```

As a demo, I have created a super simple scene with spheres:

```
Root
  Sphere Center -> Rotate around its own axis
    Sphere 1 -> Position somewhere near the parent and Rotate around its own axis
    Sphere 2 -> Position somewhere near the parent andRotate around its own axis
    Sphere 2 -> Position somewhere near the parent andRotate around its own axis

```

This scene graph gives me one sphere in the middle that rotates and three spheres that rotate due to being children of this sphere; plus, the spheres themselves rotate around their own axis:

However, the implementation of it is quiet weird to me. The order of transformations is Translate * Rotate * Scale instead of the other way around:

```
child1->setTransform(
          glm::translate(glm::mat4{1.0}, glm::vec3{2.0, 0.0, 0.0}) *
          glm::rotate(glm::mat4{1.0f}, glm::radians(frame * 0.9f),
                      glm::vec3{0.0, 0.0, -1.0}) *
          glm::scale(glm::mat4{1.0}, glm::vec3{0.4, 0.4, 0.4}));

// ...other children transformations

scene->update();

```

When I change the order of transformations, the rotation happens around the central sphere:

```
child1->setTransform(
          glm::rotate(glm::mat4{1.0f}, glm::radians(frame * 0.9f),
                      glm::vec3{0.0, 0.0, -1.0}) *
          glm::translate(glm::mat4{1.0}, glm::vec3{2.0, 0.0, 0.0}) *
          glm::scale(glm::mat4{1.0}, glm::vec3{0.4, 0.4, 0.4}));

// ...other children transformations

scene->update();

```

As you can see, the cyan color sphere rotates around the parent instead of its own center.

I was confused by this so, I added translation to the root node (e.g (2.0, 1.0)) and got the same result. If I rotate the sphere, then translate, it will rotate against (0, 0), then translate to (2.0, 1.0) at the same time, which will mean that it is at (2.0, 1.0) and rotating against (0.0, 0.0). On the other hand, if I translate first, then rotate, it will rotate against (2.0, 1.0) and translate to (2.0, 1.0) at the same time, which will mean that its rotating against the newly translated center.

Logically this makes sense to me because these multiplications are happening at the same time and the result is written to node but I still do not understand why the typically suggested transformation order is Scale * Rotate * Translate. Can someone explain to me what I am missing here that I have to use multiply transformations is in reverse order?

# Answer
> 1 votes
For theoretical understanding you'd have to dig a little deeper in how matrix transformations work in 3D space and how they affect the 3D coordinate basis. The simple answer is the following:

Matrix multiplication is **not commutative**. Changing the order of multiplication changes the result and the assumption that *multiplications are happening at the same time* means they should yield the same result is not correct.

More illustrative answer:

When you want to apply a rotation to your object, the end result you are expecting is for it to change the direction "it is looking at". This works if you use a *rotation transform* such as $$R=\begin{pmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{pmatrix}.$$ This transformation will rotate the object by \\$θ\\$ degrees around the \\$z\\$ axis and this is what's important here. Which \\$z\\$ axis are we talking about exactly? In this specific case we're talking about the axis of the rotated object's coordinate basis i.e. the normal vector \\$\vec{z} = (0,0,1)\\$.

Translating the object also moves it based on its coordinate basis. The same for a combination of those transformations. But why does changing the order change the result? Because matrix multiplication is not commutative as mentioned in the beginning. Changing the order of multiplication changes the result.

Let's assume you are rotating a sphere as in your example.

If you do `Rotate->Translate`:

1. The object is rotated around the \\$\vec{z}\\$ basis vector. The rotation "pivot" of the sphere in this case is its center i.e. the point \\$(0,0,0)\\$ which means it rotates like the earth around its own axis.
2. Translation moves the sphere to a designated position in 3D space. Let's say at \\$(3,2,0)\\$

If you do `Translate->Rotate`:

1. The sphere moves to a designated position in 3D space. Its center point is now \\$(3,2,0)\\$
2. The object is rotated around the \\$\vec{z}=(0,0,1)\\$ **basis vector** of that same coordinate basis. The *pivot* of the rotation remains the same as previously at \\$(0,0,0)\\$ but the sphere center is now at \\$(3,2,0)\\$. It now goes all the way around like the earth rotates around the sun.

It is important to understand that a transformation doesn't change the "pivot" point. Everything is expressed based on the object's *coordinate basis*. If you want to change that you have to actually do a *change of basis* operation. This is what the `localToWorld` matrix operations actually do.

---
Tags: c++, transformation, glm, vulkan
---


# Question
Title: After setting a field using the editor API, the field gets cleared on Play in Unity. How to fix it?
After setting a field using the editor API, the field gets cleared on Play in Unity. How to fix it?

I have a menu item. That menu item sets a field on one of my game objects in scene. After the field was set I can see the correct value in editor and I save the scene. But whenever I Play my game from the editor the field gets reset to a default value forever.

I found a brief explanation of the reasons behind that here. In a nutshell before Play Unity is serializing my whole scene and for some reasons it misses the specific field which was set through the editor API. So, later on Unity loads (i.e. creates a copy of what was serialized) the serialized scene and performs the Play itself.

All that led me to try a trick, which actually worked. First, I change the field through the editor API. After that I change another random field using the editor itself and save a scene. Then I revert the random field value and save my scene once more. Now if I Play I get the field value preserved and I get what I am asking for in this question. But this way of doing things seems like a technical debt to me, so I was hoping that someone might suggest something better.

Also, neither the `[System.Serializable]`, nor the `[SerializeField]` properties on that field did not help.

My guess is that while the editor API is executing I need to tell it to take into account the changed field somehow after it was changed. But I was not able to find out how to do that.

# Answer
> 0 votes
After the @DMGregory♦ comment I come across this documentation.

So, to have the changes made through the editor API serialized correctly I did change this way:

```
Undo.RecordObject(gameObjectInScene, "Set reference for itsField.");
gameObjectInScene.itsField = theFieldValue;
PrefabUtility.RecordPrefabInstancePropertyModifications(gameObjectInScene);

```

And if after changing the field you would like to apply the field change to a prefab just add a fourth line:

```
PrefabUtility.ApplyPrefabInstance(gameObjectInScene, InteractionMode.UserAction);

```

---
Tags: unity, editors, serialization
---


# Question
Title: Why does `gameObject.SetActive()` take so long for a hierarchy?
Why does calling `gameObject.SetActive()`(in the Editor) take quite noticeable time (in my case about 8 secs) if a game object has some significant number of children, while changing the state of the same object using its checkbox in the Inspector panel looks instantaneous?

I always thought that the checkbox

and the `SetActive` method do the same job for the object. Don't they?

Test code:

```
[DisallowMultipleComponent]
public class GameObjectState : MonoBehaviour
{
    public bool active;

    private void OnValidate()
    {
        gameObject.SetActive(active);
    }

    private void Reset()
    {
        active = gameObject.activeSelf;
    }
}

```

# Answer
As DMGregory pointed in the discussion my `GameObjectState` component was causing many warnings of this type:

> *SendMessage cannot be called during Awake, CheckConsistency, or OnValidate*

As a consequence, excessive logging led to the editor freezing when toggling the checkbox.

While the reason for this warning is not completely clear to me, it is obvious that it was caused by calling `gameObject.SetActive` from the `OnValidate` method.

A possible workaround for safely calling `gameObject.SetActive` could be to use a custom editor:

```
[CustomEditor(typeof(GameObjectState))]
public class GameObjectStateEditor : Editor
{
    private GameObjectState _target;
    private bool _wasActive;

    private void OnEnable()
    {
        _target = (GameObjectState)target;
        _wasActive = _target.active;
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (_wasActive == _target.active)
            return;

        _target.gameObject.SetActive(_target.active);
        _wasActive = _target.active;
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Can't figure out math for converting negative indices of my voxels and chunks to positives
In my voxel game, I'm trying to spawn chunks in all directions. But since my world starts at `0,0,0`, some chunks can spawn at negative positions like `-1,0,-1`.

My chunks are `16x16x16` size.

When generating(or not) a block, somewhere in the process, I need to find what block is at position A(`xyz 0-15`) in chunk B(`xyz -max +max`), based on block's world position.

So for example, block at world position(can be xyz`-max +max`) `1, 0, 1` should give me chunk `0, 0, 0` and block's relative position inside chunk is `1, 0, 1`.

block at world position `-1, 0, -1` should give me chunk `-1, 0, -1` and index of block relative to this chunk `15, 0, 15`.

But as you see, there is an inconsistency and loss of symmetry(-1 relative to 0 gives -1 and 1 relative to 0 gives 0) relative to `0, 0, 0`, that I can't figure out how to fix.

Currently I find relative index in chunk from world position using this:

```
    int size = 16;

    int x = -1;
    int y = 0;
    int z = -1;

    int chunkRelativeX = x % size;
    int chunkRelativeY = y % size; //0
    int chunkRelativeZ = z % size;

    if (x < 0)
    {
        chunkRelativeX += size; //15
    }
    if (z < 0)
    {
        chunkRelativeZ += size; //15
    }

```

And I find chunk position itself using:

```
    int chunkPosX = Mathf.FloorToInt((float)x / size); //-1
    int chunkPosY = Mathf.FloorToInt((float)y / size); //0
    int chunkPosZ = Mathf.FloorToInt((float)z / size); //-1

```

Problem is, with positives, its correct, since before 1st chunk comes 0st, but before -1st chunk, doesn't come 0st.

I'm really confused and not sure what to do :D

Thanks in advance.

# Answer
> 2 votes
Problem was, as @htmlcoderexe mentioned, the way % works in c#. But I'll accept solution from @DMGregory, which is the simpler one.

@stephane-hockenhull also explained this thing in more technical detail of bitwise `&` *(Under my question)*, but I'll still write my own answer as a bit simpler interpretation for people like me who get confused easily :)

**Modulo in c# is "symmetrical":** `15%16 = 15` and `-15%16 = -15, 16 % 16 = 0,` -`16 % 16 = 0.`

But in my case(Where chunk 0 is actually a starting point and it goes 0 -\> 15), this "symmetry" is actually what broke my count. Since first negative chunk starts at -1 and last block of that chunk will be -16th. So its `-1 -> -16` rather than `0 -> 15` as at positives.

To find block position relative to chunk(in negatives), I added 16, so `-1 + 16 = 15,` which is seemingly correct so far(-1st block is indeed 16th block(or index of 15, we start at 0) in chunk).

Say, we want to find -15th block, `-15 % 16 = -15, + 16 = 1`, indeed, -15th block is 2nd block in the chunk.

But what block comes next before 2nd? Lets check: `-16 % 16 = 0, + 16 = 16,` and its wrong. -16th block is not 16th block in chunk, but actually its the 1st one. Hence, we need to make an exception here.

So *"correct"* version of my initial implementation would be:

```
if (x < 0)
{
    chunkRelativeX += size; //15
    if(x & size == 0){
      chunkRelativeX = 0;
    }
}
if (z < 0)
{
    chunkRelativeZ += size; //15
    if(x & size == 0){
      chunkRelativeX = 0;
    }
}

```

But instead of doing this as a multi step Ifs, it could be written using bitwise `&`(Which in itself contains that "exception" for `n%16` = 0 cases at negatives, but for numbers that are power of 2 - 1) simply as:

```
if (x < 0)
{
    chunkRelativeX = x & (size - 1);
}
if (z < 0)
{
    chunkRelativeZ = z & (size - 1);
}

```

# Answer
> 3 votes
I think your problem might be partially due to the way the `%` operator works with negative numbers. I have a vague memory of tripping up in the same way - I present you my method of dealing with this. I have created a special `struct` that holds 5 numbers - the local XYZ and the chunk position - I use this in a lot of terrain related stuff. I don't use voxels but terrain is still stored in chunks (128x128 but it really doesn't matter here I believe).

What you're probably specifically interested in is creating such coordinates from an arbitrary XYZ - one of the methods in my struct takes a Vector3 and then applies this `Normalize` method to figure out all the numbers.

```
   //chunk size
   public const int Stride=128;
   //local coordinates
   public float X;
   public float Y;
   public float Z;
   //chunk coordinates
   public int BX;
   public int BY;
   //make sure local coords are within range of 0...127
   public void Normalize()
   {

        this.BX += ((int)Math.Floor(X / (float)Stride));
        this.X = ((this.X % (float)Stride+(float)Stride)% (float)Stride);
        this.BY += ((int)Math.Floor(Z / (float)Stride));
        this.Z = ((this.Z % (float)Stride+ (float)Stride)% (float)Stride);

    }
    //Convert a standard XYZ to local XYZ + chunk coords
    public static implicit operator WorldPosition(Vector3 a)
    {
        WorldPosition result = new WorldPosition();
        //set to XYZ
        result.X = a.X;
        result.Y = a.Y;
        result.Z = a.Z;
        //figure out chunk/local coords
        result.Normalize();
        return result;
    }

```

What it more or less does is that after the first `%` that may turn up negative it adds the chunk size again - which for "proper" modulo does not change the result but fixes it for negatives.

---
Tags: c#, mathematics, algorithm
---


# Question
Title: What is get_bounding_rect() method in Pygame?
I got used to `get_rect()` when detecting collisions in Pygame but I've just discovered that another method called `get_bounding_rect()` exists. So what are its uses ?

What is the difference between get\_rect() and get\_bounding\_rect() methods in Pygame? Which one is better ?

# Answer
As the documentation for `get_bounding_rect` says, `get_bounding_rect` will check the pixels in the surface and discard pixels that have an alpha value equal or less to the passed in value.

> Returns the smallest rectangular region that contains all the pixels in the surface that have an alpha value greater than or equal to the minimum alpha value.

So for an example, if your surface has 10 pixels of transparent padding around in all sides, the bounding rect will not contain that padding, but instead be a sub-rectangle starting from `(10, 10)` and being of size `(width - 20, height - 20)`.

The documentation also mentions that the surface pixels will be locked and unlocked during a `get_bounding_rect` call, which most likely means that it will be quite a lot slower than calling `get_rect`. There's really no direct answer as to which one is better, use the one that suits your needs better. The bounding rectangle will perhaps be more accurate for collisions, but if your surfaces don't contain a lot of empty transparent space, it won't be a big difference.
> 2 votes

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


# Question
Title: text - part of the sprite or dynamically generated
I am trying to reproduce the same stamping tool as the one we found in the video game "Papers, Please".

In my case I want my users to be able to modify the text they are going to stamp. I will use a similar blocky font.

As you probably noticed in this sprite, the top of the letters is clearer in order to give an effect of depth.

How should I proceed to copy the same effect? The only solution that came to mind was to create sprites for each needed letter and then include them dynamically over my sprite but there has to be a more efficient way. I suspect the author directly drew them in the sprite but I'm not sure.

# Answer
A simple approach would be to just render the text twice, first with the ligher color, and then with the main color but offset by a pixel down, so that only the top edges of the characters rendered with the ligher color will stay visible.
> 1 votes

---
Tags: 2d, sprites, fonts
---


# Question
Title: Why are all my brushes black when I test the level I built with Hammer?
In Valve's map-making tool Hammer, I have created several brushes which I use as walls, ceilings, and floors. I've added textures to them, and I have a light entity on the ceiling. all the props and entities in the game are textured and visible.

Unfortunately, when I try to play the map, all the brushes are black. There are no textures or colors besides black on the brushes.

What could be causing this issue? I have tried compiling the map with HDR off, and HDR on, but receive the same effect.

# Answer
> 1 votes
I had the same problem as well. I wanted to create a moving brush, but it turned black in my map. I tried turning some light and shadow options on and off in the brush, but it changed nothing.

I solved it like this: in the field "Minimum light Level", put in a low mumber, such as 1.1. If it's still to dark, increase the number, and if it's to bright lower the number.

There is still just one problem. The hole brush is on 1 Light Level, so the Light Level on the brush is the same everywhere, and doesn't vary like on other textures, the more they are near a light Entity.

**Before:**

**After:**

Doesn't look perfect, but at least it fixes part of the issue. You could cut the brush in to multiple ones, and set the Light Level on each of them. Hope this helps.

---
Tags: hammer
---


title: How do I make a bomb sight accurately?

text:
# Question
Title: How do I make a bomb sight accurately?
On the Bombsight Wikipedia page, I get that equation. I do not understand it very well. How would I go about writing that in C#? The drag doesn't matter in my project. It's not a flight sim. I know that the angle of the camera/sight is a non linear function of the speed and altitude of the aircraft. Any pointers would be greatly appreciated. Was this the correct stack to post this question in, or was the physics stack a better option?

# Answer
> 1 votes
The formulas given for vertical & horizontal drag are:

\\$ d\_v = CAρv\_v\sqrt{v^2\_v+v^2\_h} \\ d\_h = CAρv\_h\sqrt{v^2\_v+v^2\_h} \\$

where:

* \\$v\_v\\$ is the vertical component of the velocity
* \\$v\_h\\$ is the horizontal component of the velocity
* \\$C\\$ is the coefficient of drag
* \\$A\\$ is the cross-sectional area (of the bomb)
* \\$ρ\\$ is the air density

Converting that to code, would give you something like this:

```
double speed = Math.sqrt(velocityVert * velocityVert  + velocityHrzt * velocityHrzt);
double dragVert = dragCoeff * area * airDensity * velocityVert * speed;
double dragHrzt = dragCoeff * area * airDensity * velocityHrzt * speed;

```

If your code base is already using vectors, you can replace the `drag` & `velocity` variables with vectors components.

---
Tags: c#, physics, projectile-physics
---


# Question
Title: Trying to access method from other script; getting "Object reference not set to an instance of an object"
Is this an issue with the syntax or something deeper?

There is a method `Pause();` which I'm trying to access from a different script `MyScript`.

Here is the code (I deleted out the irrelevant code):

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

public class MyScript : MonoBehaviour
{

    CharacterMovement _characterMovement;

    private void LateUpdate()
    {
        _characterMovement.Pause();
    }

}

```

This is giving me an `Object reference not set to an instance of an object` error. Could this be syntax or something deeper? Thanks.

# Answer
> 1 votes
Solution: Make `CharacterMovement _characterMovement;`public:

(like this) `public CharacterMovement _characterMovement;`

And then in the Inspector, drag the object that has CharacterMovement script attached to it.

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


# Question
Title: Why is my UI not working on android but works perfectly on PC?
I tested my game for the first time on mobile and the UI almost doesn't work. I use `if(!EventSystem.current.IsPointerOverGameObject())` to check if I'm clicking on the UI (because if I don't click on the UI it moves my object to where I clicked and I don't want it to move when I click a button) and it works well on pc but on android not only it moves behind the button, but the buttons supposed to make it rotate just don't seem to respond. Sometimes I have to double tap the button to make it work once. Why doesn't it work as well as on pc ? Should it be the exact same thing ?

I didn't include screenshots or code because I have no idea where the problem might be coming from but I can provide these on demand.

# Answer
> 1 votes
There is a completely different subsystem for touch-based UI in Unity, which supercedes the older system you are using. This applies in most APIs, not just Unity, that have traditionally supported UI event-based inputs, and which had to be upgraded in the last decade or so to support touch. HTML5 contains another common example of this sort of supercession.

Put in another way: Since `IsPointerOverGameObject()` refers to a pointer, but your mobile screen has no actual pointer i.e. "mouse arrow", but rather only a list of touches, your approach will not work. You need to address your input from scratch in a manner that works for touch, either by building your own using `Touch` and its associated classes, or by grabbing something from e.g. the Wiki or the Asset Store that does that work for you.

---
Tags: unity, 2d, gui, mobile
---


# Question
Title: Is there a way to add animation for just one part of body?
I have 3D character. I added "walk" animation to it and as you know this animation effects all part of body. But I don't want animation effect upper body. Because I want character hands to stay the way I want(I made character upperbody look silly when it walks.).

I tried to change character upper body in animation tab manually but I couldn't. Its really hard to change all joints manually.

So, Is there a way to add animation for just one part of body ?

# Answer
The solution is adding an avatar mask. When you create an avatar mask, you can choose which part of body you want to animate.

To create an avatar mask :

**Create -\> Avatar Mask**

You can enable/disable body parts that you want to animate by this mask. Then you should add this avatar mask to your animation layer. To do this :

There are layers tab in animator window. You should click gear icon in layer tab. And then pick which mask you want to apply.

This video explains it well.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: How to implement complex serializable property with internal GameObject field
I'm trying to create a complex serialized object with property drawer with assignable GameObject field. I want to make something like Binding. So that you could declare a field in an X Monobehaviour with return type of e.g. float. Then in Inspector assign source object, script and path to that binding. Then in X use that binding to get value from another object. This would help decouple code.

I'm facing a problem. I either can't create UnityEngine.Object properly, or when I wrongly tried deriving binding class from ScriptableObject, it wasn't deserializing anything. Or I'll need to create GameObject field in my PropertyDrawer (I don't really like this idea, I've seen ObjectField code).

So, I can't use EditorGUILayout.ObjectField because it needs SerializedProperty of GameObject Source on binding, but I have SerializedProperty of Binding on X. I need either derive binding object from UnityEngine.Object to be able to find property on it and deal with problem of creating that binding or go hardcore recreating EditorGUILayout.ObjectField functionality without need of SerializedProperty in input.

Here is an ExampleProject with code I've thrown together. There is a problem with GUILayout, I wasn't able to use Horizontal grouping, it was throwing errors, when in my main project, exact same code was doing fine. Odin shouldn't mess with these things, I think... Anyway. I'd be incredibly happy if someone would help me with this. I'll be looking into UIElements to make this UI, so maybe I'll be fine with making an ObjectField on a poco and serialize it... And I won't need to do anything with UnityEngine.Object.

Edit: UIElements also need SerializedObject of my binding class or I need to implement IBinding interface. I wasn't able to find anything on how this is done. The only thing I've found was this topic. I dind't get anything from it. Only that it is possible and it isn't documented.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Utility;

[CustomPropertyDrawer(typeof(RelativePropertySelector<>))]
public class RelativePropertySelectorDrawer<T> : PropertyDrawer {
    bool initialized;
    private RelativePropertySelector<T> relPropSelector;
    List<int> selectIndexes = new List<int>() { 0 };
    private Component[] sourcesScripts;

    //Commented for non UnityEngine.Object
    //SerializedObject serializedObject;
    //SerializedProperty sourceProp;

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        //Sadly, this is not drawing that field
        base.OnGUI(position, property, label);
        if (!initialized) Init(property);

        GUILayout.BeginHorizontal();
        //Commented since it is non UnityEngine.Object version. There is no other way to draw this without RelativePropertySelector being UnityEngine.Object
        //EditorGUILayout.ObjectField(property, typeof(GameObject), new GUIContent());

        EditorGUI.BeginChangeCheck();
        try {
            string[] options = sourcesScripts.Select(c => c.GetType().Name).ToArray();
            var newInd = EditorGUILayout.Popup(selectIndexes[0], options);
            if (newInd != selectIndexes[0]) {
                var selectedComponent = sourcesScripts[newInd];
                if (relPropSelector.Component != (object)selectedComponent) {
                    selectIndexes = new List<int>() { newInd, 0 };
                    relPropSelector.SetStep(selectedComponent);
                }
                selectIndexes[0] = newInd;
            }

            for (int i = 0; i < selectIndexes.Count - 1; i++) {
                options = new string[] { "" }.Union(relPropSelector.GetInfos(i).Select(mi => mi.Name)).ToArray();
                newInd = EditorGUILayout.Popup(selectIndexes[i + 1], options);
                if (newInd != selectIndexes[i + 1]) {
                    selectIndexes[i + 1] = newInd;
                    var info = relPropSelector.GetInfos(i).FirstOrDefault(mi => mi.Name == options[newInd]);
                    relPropSelector.SetStep(info, i);
                }
            }
        } catch (Exception) { }

        EditorGUI.EndChangeCheck();
        GUILayout.EndHorizontal();
    }

    private void Init(SerializedProperty property) {
        relPropSelector = property.GetValue<RelativePropertySelector<T>>();

        if (relPropSelector == null) {
            var t = GetTypeOfCustomPropertyDrawer();
            relPropSelector = (RelativePropertySelector<T>)Activator.CreateInstance(t);
            //non UnityEngine.Object
            var zzz = property.serializedObject.targetObject;
            var m = zzz.GetType().GetMembers().FirstOrDefault(mi => mi.Name == property.propertyPath);
            if (m is FieldInfo field)
                field.SetValue(zzz, relPropSelector);
            else if (m is PropertyInfo prop)
                prop.SetValue(zzz, relPropSelector);
            //UnityEngine.Object
            //property.objectReferenceValue = relPropSelector;
            //property.serializedObject.ApplyModifiedProperties();
        }
        relPropSelector.Initialize();
        if (relPropSelector.Source != null) {
            sourcesScripts = relPropSelector.Source.GetComponents<Component>();
            selectIndexes = new List<int>() { ArrayUtility.IndexOf(sourcesScripts, relPropSelector.Component) };
        } else {
            sourcesScripts = new Component[0];
            selectIndexes = new List<int>() { 0 };
        }
        for (int i = 0; i < relPropSelector.PathLength; i++) {
            selectIndexes.Add(ArrayUtility.IndexOf(relPropSelector.GetInfos(i), relPropSelector.GetInfo(i)) + 1);
        }

        //serializedObject = new SerializedObject(relPropSelector);
        //sourceProp = serializedObject.FindProperty("Source");

        initialized = true;
    }

    private Type GetTypeOfCustomPropertyDrawer() {
        var xxxx = GetType().GetCustomAttribute<CustomPropertyDrawer>();
        return (Type)xxxx.GetType().GetField("m_Type", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(xxxx);
    }

    private static MemberInfo[] GetMemberInfos(object obj) =>
        obj.GetType().GetFields().Select(f => (MemberInfo)f)
        .Union(obj.GetType().GetProperties().Select(p => (MemberInfo)p))
        .ToArray();
}

[CustomPropertyDrawer(typeof(RelativePropertySelectorGameObject))]
public class RelativePropertySelectorGameObjectDrawer : RelativePropertySelectorDrawer<GameObject> {
}

[CustomPropertyDrawer(typeof(RelativePropertySelectorString))]
public class RelativePropertySelectorStringDrawer : RelativePropertySelectorDrawer<string> {
}

[CustomPropertyDrawer(typeof(RelativePropertySelectorInt))]
public class RelativePropertySelectorIntDrawer : RelativePropertySelectorDrawer<int> {
}

[CustomPropertyDrawer(typeof(RelativePropertySelectorFloat))]
public class RelativePropertySelectorFloatDrawer : RelativePropertySelectorDrawer<float> {
}

[Serializable]
public class RelativePropertySelector<T> {

    //public static implicit operator RelativePropertySelector<T>(GameObject go) => new RelativePropertySelector<T>() { Source = go };
    public static implicit operator T(RelativePropertySelector<T> s) => s.Ready ? s.GetValue() : default;

    public GameObject Source;
    [HideInInspector]
    public Component Component;
    [HideInInspector]
    public string Path = "";
    List<MemberInfo> MIBreadCrumbs = new List<MemberInfo>();
    List<MemberInfo[]> AllInfos;

    public bool Initialized { get; private set; }
    public bool Ready { get; private set; }

    public void Initialize() {
        if (Source == null || Component == null) {
            Path = "";
            MIBreadCrumbs = new List<MemberInfo>();
            return;
        }
        object obj = Component;
        MIBreadCrumbs = new List<MemberInfo>();
        AllInfos = new List<MemberInfo[]>() { GetMemberInfos(Component) };
        if (!string.IsNullOrEmpty(Path))
            foreach (var step in Path.Split('.')) {
                var infos = GetMemberInfos(obj);
                AllInfos.Add(infos);
                var curInfo = infos.FirstOrDefault(i => i.Name == step);
                MIBreadCrumbs.Add(curInfo);
                if (curInfo is FieldInfo field)
                    obj = field.GetValue(obj);
                else if (curInfo is PropertyInfo property)
                    obj = property.GetValue(obj);
                else
                    break;
            }
        UpdatePath();
        Initialized = true;
    }

    private void UpdatePath() =>
        Path = string.Join(".", MIBreadCrumbs.Select(i => i.Name));

    public int PathLength {
        get =>
MIBreadCrumbs.Count;
    }

    private static MemberInfo[] GetMemberInfos(object obj) =>
        obj != default ? obj.GetType().GetFields().Select(f => (MemberInfo)f)
        .Union(obj.GetType().GetProperties().Select(p => (MemberInfo)p))
        .ToArray() : new MemberInfo[0];
    private static MemberInfo[] GetMemberInfos(Type t) =>
        t.GetFields().Select(f => (MemberInfo)f)
        .Union(t.GetProperties().Select(p => (MemberInfo)p))
        .ToArray();

    public MemberInfo GetInfo(int step) =>
        step < 0 || step >= MIBreadCrumbs.Count ? default : MIBreadCrumbs[step];

    public Type GetStepType(int step) {
        var info = GetInfo(step);
        if (info is FieldInfo field)
            return field.FieldType;
        else if (info is PropertyInfo prop)
            return prop.PropertyType;
        else
            return default;
    }

    public T GetValue() {
        if (!Initialized) Initialize();
        return (T)GetStep(MIBreadCrumbs.Count - 1);
    }

    internal object GetStep(int step) {
        if (!Initialized) Initialize();
        if (step >= MIBreadCrumbs.Count || step < -1) return null;
        if (step == -1) return Component;
        else if (MIBreadCrumbs[step] is FieldInfo field)
            return field.GetValue(GetStep(step - 1));
        else if (MIBreadCrumbs[step] is PropertyInfo property)
            return property.GetValue(GetStep(step - 1));
        return null;
    }

    internal void SetStep(MemberInfo info, int step) {
        if (step < 0 || step > MIBreadCrumbs.Count) return;
        if (step < MIBreadCrumbs.Count - 1) {
            MIBreadCrumbs = MIBreadCrumbs.Take(step).Union(new MemberInfo[] { info }).ToList();
            AllInfos = AllInfos.Take(step + 1).ToList();
            AllInfos.Add(GetMemberInfos(info.DeclaringType));
        } else if (step == MIBreadCrumbs.Count - 1) {
            MIBreadCrumbs[step] = info;
        } else {
            MIBreadCrumbs.Add(info);
            AllInfos.Add(GetMemberInfos(info.GetType()));
        }
        if (step == PathLength - 1 && GetStepType(step) == typeof(T))
            Ready = true;
        else
            Ready = false;
        UpdatePath();
    }
    internal void SetStep(Component comp) {
        Component = comp;
        AllInfos = new List<MemberInfo[]>() { GetMemberInfos(comp) };
        MIBreadCrumbs = new List<MemberInfo>();
        Path = "";
    }

    internal MemberInfo[] GetInfos(int step) {
        return AllInfos[step];
    }
}

[Serializable]
public class RelativePropertySelectorGameObject : RelativePropertySelector<GameObject> { }

[Serializable]
public class RelativePropertySelectorString : RelativePropertySelector<string> { }

[Serializable]
public class RelativePropertySelectorInt : RelativePropertySelector<int> { }

[Serializable]
public class RelativePropertySelectorFloat : RelativePropertySelector<float> { }

```

# Answer
> 0 votes
I won't post the code here, it's just too long. It is mostly the same, except I've moved data I wanted to serialize into a separate script, which I've hid so nobody will be able to see it in add component menu since it is only works in tandem with RelativePropertySelector. And split it in files like it should be editor things in \Editor. MonoBeahviour into it's own, but it is nested in an empty class, so that Unity would hide it.

Asset bundle

It is not finished. There is a bug that prevents you to select anything past first property. So that if you'll want to get something deeper, you'll need to enter Path manually separated by "." e.g. on that RelativePropertySelectorScript Path:"SpawnPoint.transform.position.x" to get SpawnPoint x value.

---
Tags: unity, serialization
---


# Question
Title: Why do my 3d models have a strange after-image effect?
On my Unity project I have a strange behavior for my 3D model which I bought on the Unity asset store.

If I move the player, there appears a wired shine / glow… seems that the character does not move completely, but drags…

Here a screenshot to show you the behavior:

Here is a video where you can see that the animations are not clean: https://youtu.be/3H3r6HcgSaQ

Here you can see the configuration of my camera and PostProcessingVolume:

By the way: I’m using the Built In Rendering Pipeline. This appears not only on this 3d model. I can see this behavior for also other 3d models in my scene.

What could be the issue here? I have no idea…

Thanks in advance for your feedback and assistance!

# Answer
> 5 votes
**tl;dr:** The problem is the combination of Temporal Anti-Aliasing with grass.

---

As DMGregory mentioned in a comment, these ghosting artifacts are caused by the Temporal Anti-Aliasing post-processing effect.

This effect is supposed to smooth animations by interpolating between the current and the previous frames. Unfortunately there are various corner-cases where this can manifest as this undesirable ghosting effect. According to this Reddit thread, this effect can occur especially when there are objects in the background which use shaders with displacement mapping. The grass from the Unity terrain system, for example. Which you also appear to be using in this scene. The reason is that TAA applies motion vectors to individual texture pixels to track their position changes, and displacement mapping can interfere with this.

And looking at this particular frame of your demo video, the grass indeed seems to be the culprit. Notice how the ghosted image disappears as soon as the grass in the background is replaced by the rock wall:

Note that Unity is not the only game engine having problems with TAA. A cursory online search finds several people having similar problems in engines like Unreal, Amazon Lumberyard and also some complaints from players playing games based on inhouse engines. There are solutions, but many of them require very convoluted and situation-specific hacks to get around them. And these usually require rather a lot of in-depth knowledge of shader programming. TAA is just a very fiddly and unreliable technology.

So unless you really *really* want TAA, I would recommend to just use a different anti-aliasing method like SMAA or FXAA. If you insist on TAA, try to disable the grass. If you also insist on having grass in the game (which I would understand in a savanna scenario like this), try to find a grass implementation which does not use displacement mapping in its shader.

---
Tags: unity, 3d, animation
---


# Question
Title: Should state and behavior be combined for Buffs? Cannot decide between data-driven and OOP approach
I'm writing a 2D roguelike that uses an Entity Component System and I'm having trouble deciding between the traditional OOP approach versus a data-driven approach to implementing buffs and debuffs. For the purposes of this question, I've created two examples (Option A and Option B) to demonstrate the differences.

Option A is the data-driven approach where the data and functionality / behavior for the buffs are separated and we maintain a mapping from buff name to corresponding execute function to link them up.

Meanwhile, Option B just uses the standard OOP approach where buff state and behavior is combined into a single subclass.

**Option A:**

```
// Buffs Data File:
let buffs = {
  regeneration: {
    name: "Regeneration",
    description: "Provides some amount of passive regen",
    applyRate: 1000
  },
  snare: {
    name: "Snare",
    description: "Slows the entity by some amount",
    duration: 3000,
    textureName: "items",
    textureFrame = { x: 64, y: 384, w: 32, h: 32 }
  },
  fleeing: {
    name: "Fleeing",
    description: "This unit is running for its life",
    duration: 1000,
    applyRate: 1000
  }
};

// Buffs System
function executeFleeing(scene: Scene, receiver: Entity) {
  let physics = receiver.get(CT.Physics);
  if (!physics) { return; }

  physics.maxSpeed.buffed *= .5;
}

function executeSnare(scene: Scene, receiver: Entity) {
  let physics = receiver.get(CT.Physics);
  if (!physics) { return; }

  physics.maxSpeed.buffed *= 10;
}

function executeRegeneration(scene: Scene, entity: Entity) {
  let health = entity.get(CT.Health);
  if (!health) { return; }

  health.add(5);
}

let mapping = {
  Fleeing: executeFleeing,
  Snare: executeSnare,
  Regeneration: executeRegeneration
};

execute() {
  for (let entity of this.scene.query(CT.Buffs)) {
    let buffs = entity.get(CT.Buffs);

    for (let b of buffs.list) {
      let buffName = b[0];
      let buff = b[1];

      if (!buff.isActive()) { buffs.list.delete(buffName); continue; }

      if (!buff.elapsed()) { continue; }

      buffs.get(buffName).lastTick = performance.now();

      mapping[buffName](this.scene, entity);
    }
  }
}

```

**Option B:**

```
// Date files
class RegenerationBuff extends Buff {
  constructor() {
    super();

    this.name = "Regeneration";
    this.description = "Provides some amount of passive regen";

    this.applyRate = 1000;
  }

  execute(scene: Scene, entity: Entity) {
    let health = entity.get(CT.Health);
    if (!health) { return; }

    health.add(5);
  }
}

class SnareBuff extends Buff {
  constructor() {
    super();

    this.name = "Snare";
    this.description = "Slows the entity by some amount";

    this.duration = 3000;

    this.textureName = "items";
    this.textureFrame = new Frame(64, 384, 32, 32);
  }

  execute(scene: Scene, receiver: Entity) {
    let physics = receiver.get(CT.Physics);
    if (!physics) { return; }

    physics.maxSpeed.buffed *= 10;
  }
}

class RegenerationBuff extends Buff {
  constructor() {
    super();

    this.name = "Regeneration";
    this.description = "Provides some amount of passive regen";

    this.applyRate = 1000;
  }

  execute(scene: Scene, entity: Entity) {
    let health = entity.get(CT.Health);
    if (!health) { return; }

    health.add(5);
  }
}

// Buffs System
execute() {
  for (let entity of this.scene.query(CT.Buffs)) {
    let buffs = entity.get(CT.Buffs);

    for (let b of buffs.list) {
      let buffName = b[0];
      let buff = b[1];

      if (!buff.isActive()) { buffs.list.delete(buffName); continue; }

      if (!buff.elapsed()) { continue; }

      buff.lastTick = performance.now();

      buff.execute(this.scene, entity);
    }
  }
}

```

Option A seems to generally be the recommended paradigm of operation within an ECS (separate state and behavior), but I'm not sure if that would apply to non-components as well. In addition, Option A seems like it could be more performant since entities would only need to maintain a list of buff names rather than instantiate a new buff object every time we want to add one to an entity. This is because the data for the buffs already exists in the data-driven approach, so each entity doesn't need to duplicate the information.

However, Option B has the advantage in that it is conceptually simpler, and finding and editing a buff should be quicker, as all of the relevant information (data and behavior) is in a single place, in a single file. In addition, we don't have to maintain an object mapping that maps from buff name to buff execute function, as it is all contained within the object.

Which option is preferable? Which one would you choose?

# Answer
**Option 1: TL;DR, just use classes, and only classes**

If you don't care a whit about performance, go with the class-based version and forget the rest forever after, because it is far and away the easiest thing to model mentally and to code. There is little reason not use only classes at beginning of your project and *until such time* as performance becomes a problem in terms of simply developing the project further. At that time you will spend a week or two refactoring everything to suit a more performant approach to ECS.

Pros: you're able to quickly modify local members the moment you modify the methods that use them, and vice versa - this of course depends on language, IDE, etc. used, vs. with option 2, where you spend more time doing management between changed structs and their reliant functions.

Cons: This is incidental, and not necessarily the case in *your* code, but one reason classes don't play nicely with ECS is that ECS avoids inheritance entirely, focusing on composition for what it achieves. To use inheritance here is counter-intuitive because of its limitations in terms of permutation count.

**Option 2: Harder to conceptualise, but performant**

Let's clarify first that your initial approach is much closer to what is often referred to as pure ECS. It is the most C-like / Assembly-like way of laying out data.

There has been a lot of flak on this site in the past for that approach, for reasons I'm still not entirely clear on - perhaps others see it as premature optimisation, but there were entire generations of programmers before us who saw things very differently.

Cons:

* have to pass the `this` parameter (or multiple additional parameters if you separate `this` into its component members) which requires more management to keep your struct and your functions that use that struct, in sync.

Pros:

* easier to plan out what the smallest possible data model *should* look like, keeping functionality and secondary / temporary variables completely separate.
* close to the metal and allows for the strongest possible optimisations.

Elaborating on this last point: OOP was intended as an organisational tool. Such programming-time and compile-time concerns should never have negatively affected run-time performance, yet they did. These runtime costs include:

1. Vtables (at least when actually using inheritance) requiring additional `JMP`s
2. Small headers at the beginning of class instances creating admittedly minor data overhead
3. Every class instance that references another class instance has to `JMP` to that location, which, if not in cache already, will require a callout to main memory.

Re this last point, let's go into more detail. Consider memory layout if we have a tree of objects (class instances) in OOP, bearing in mind that this is how most applications are structured:

```
    A
   / \
  B   B
 / \ / \
C   CC  C

```

The layout (at best!) will be as follows :

```
A x1 @ location W

B x2 @ location X

C x2 @ location Y

C x2 @ location Z

```

...Although it is *much more* likely, e.g. in the case you do not put B's and C's into arrays, that each individual object can be allocated in a different memory location, all over main memory (OK, in practice there may be mitigating factors such as a the allocator used, but sometimes you don't have control over that). This non-contiguity matters for objects such as vertices, particles, entities and components of which there can be (tens of) thousands. That's a lot of jumping around in memory if you implement all of these as classes!

Now consider this memory layout (array of `Vertex` structs, note repetition is as per vertex count):

```
[ (x|y|z|normal|colour)(x|y|z|normal|colour)(x|y|z|normal|colour) ... ]

```

Or this layout (struct of arrays of `Vertex` members, again as per vertex count):

```
[ xxxyyyzzznnnccc ]

```

Here we have compacted the data into one large contiguous run in main memory, for optimal cache performance. With classes alone, allocation cannot work like this.

**Option 3: Use classes where you can afford to**

I think it is fair to say that the original designers of OOP, coming from a C background themselves, did not foresee a time when programmers would become so naive as to use classes for absolutely everything. They knew the value of simpler data layouts and would have advocated for them.

A hybrid or balanced approach is what most of us use to get the best of both worlds.

* Use classes at the top levels of your application structure.
* Use compact array-of-struct or struct-of-array only where objects number in the hundreds or thousands.

**Personal experience**

After about a year or two of practice, I did not find it particularly taxing to consider things in terms of option 2, above, and for anyone serious about developing games, simulations, graphics engines or scientific tools, I would recommend teaching yourself option 2. Otherwise, rather keep things simple and focus on your game design and logic.
> 2 votes

---
Tags: javascript, architecture, performance, entity-component-system, effect-modifier
---


# Question
Title: Cursor is locked and hidden, and can't click UI
I have a player with a third person character controller component. I have a problem with the cursor lock: it hides the cursor so I cannot click UI buttons.

```
protected virtual void CharacterInit()
{
    cc = GetComponent<vThirdPersonController>();
    if (cc != null)
         cc.Init();

    tpCamera = FindObjectOfType<vThirdPersonCamera>();
    if (tpCamera) tpCamera.SetMainTarget(this.transform);

    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;
}

```

# Answer
i think you mean mouse cursor. that only locks you cursor not hiding it. to hide you only need:

```
Cursor.visible=false;

```

remember best approach to use mouse cursor is to hide it in the game and set a sign in game ui and always give mouse position to it.

if you want to disable and enable mouse controll you can simply define a boolean variable.

```
bool UseCursor;
void Update(){
if(!useCursor) return;
// use mouse login here
}

```
> 1 votes

# Answer
To be able to see the mouse cursor:

```
Cursor.visible = true;

```

To be able to click UI and unlock the mouse cursor:

```
Cursor.lockState = CursorLockMode.None;

```

Make sure to call these *after* you call the function in your post, otherwise they won't work.
> 1 votes

---
Tags: unity, c#, gui, third-person-view
---


title: FMOD can't enable metering

text:
# Question
Title: FMOD can't enable metering
I’m trying to enable metering, but I keep getting this error. Here’s my code.

```
    protected void Start() => StartCoroutine(EnableMeteringRoutine());
    private IEnumerator EnableMeteringRoutine()
    {
        yield return new WaitUntil(() => FMODUnity.RuntimeManager.IsInitialized);
        FMOD.Studio.Bus bus = FMODUnity.RuntimeManager.GetBus("bus:/Voice");
        FMOD.RESULT result = bus.lockChannelGroup(); // Forces bus to be created
        if (result != FMOD.RESULT.OK)
        {
            Debug.LogError($"Failed to create bus to enable metering {result}");
            yield break;
        }
        FMOD.ChannelGroup channelGroup;
        result = bus.getChannelGroup(out channelGroup);
        if (result != FMOD.RESULT.OK)
        {
            Debug.LogError($"Failed to fetch channel group to enable metering for voice {result}");
            bus.unlockChannelGroup();
            yield break;
        }
        FMOD.DSP dsp;
        if (channelGroup.getDSP(0, out dsp) != FMOD.RESULT.OK)
        {
            Debug.LogError($"Failed to fetch dsp to enable metering for voice {result}");
            bus.unlockChannelGroup();
            yield break;
        }
        dsp.setMeteringEnabled(false, true);
        bus.unlockChannelGroup();
    }

```

This code results in an error when I try to fetch the channel group: ERR\_STUDIO\_NOT\_LOADED

I thought locking the channel group was supposed to force creation. How do I know when it's safe to enable metering for a channel. Also, is this setting persistent or do I need to do it every time a sound is played?

I've been able to make this work by waiting a random number of frames after fetching to bus and locking the channel group, but it's non-deterministic.

I can't find the answer in documentation and the FMOD forum is as unresponsive as ever.

# Answer
From the documentation:

> The channel group may not be available immediately after calling this function. When Studio has been initialized in asynchronous mode, the channel group will not be created until the command has been executed in the async thread. When Studio has been initialized with FMOD\_STUDIO\_INIT\_SYNCHRONOUS\_UPDATE, the channel group will be created in the next Studio::System::update call.
>
> You can call Studio::System::flushCommands to ensure the channel group has been created. Alternatively you can keep trying to obtain the channel group via Studio:: Bus::getChannelGroup until it is ready.
> 0 votes

---
Tags: unity, fmod
---


# Question
Title: I keep get this error with str.Split: Assets\Scripts\store.cs(15,26): error CS1503: Argument 1: cannot convert from 'string' to 'char'
I keep getting this error:

Assets\Scripts\store.cs(15,26): error CS1503: Argument 1: cannot convert from 'string' to 'char'

When I try this:

```
public static string[] toArray(string str) {
        return str.Split(" , ");
}

```

I know other questions have answered this but they haven't worked. :( Why is this happening and how can I fix it?

Thank you.

# Answer
> 1 votes
The method require a `char` not `string`

```
public static string[] toArray(string str) {
        return str.Split(',');
}

```

Try use code editor recommended by Unity like Visual Studio. It show error right away and how to fix them.

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


# Question
Title: How resource-intensive is the java.awt.Graphics2D object at different screen resolutions?
I'm currently making a 2D RPG in pure Java (yes, I know other frameworks/engines exist xD).

I just created a resizing algorithm and I've noticed that different resolutions result in different FPS counts.

Before I get into the details, I have implemented a few optimization methods.

* All tiles are batched together into a single image as they are loaded into memory
* All images are loaded into memory so no disk loading is happening while the game is rendering.
* The game renders everything in a (screenWidth by screenHeight) chunk, otherwise the object is not rendered. This is to prevent unnecessary rendering.
* The game updates at a constant 60 times per second, while the FPS varies with no upper cap.

Now that that's all out of the way, here's the problem.

When the game is at its native resolution (640x360), I get about 840 FPS. When the game is maximized to full screen(1920x1017), I get about 100 FPS.

I tried to debug this by taking out all parts of the render method individually (eg. tilemap, map objects, player, etc). and nothing seemed to make a significant impact. Eventually, I narrowed it down by stripping my render method AND my update method, leaving me with just `graphics.fillRect(0, 0, WIDTH, HEIGHT)` where width and height are the screen dimensions.

* With a screen resolution of 640x360, I get about 2700FPS.
* With a screen resolution of 1920x1017, I get about 290FPS.

Therefore, by process of elimination, I have figured out that the bulk of the problem is not due to my render method or my update method, and that it must be caused by the graphics object needing to simply render more pixels.

Could someone let me know if there is any way to eliminate these differences in the FPS with different resolutions (keeping in mind the optimizations I have already put in place) or if the differences are inevitable due to the nature of the java.awt.Graphics2D object?

---

Edit: I ran my application through JProfiler (which I'm completely new to, so please bear with me for any difficulties).

Here is a screenshot of the JProfiler looking at CPU views -\> Hotspots when my game resolution is 640x360.

and here is one when my game resolution is 1920x1017.

As you can see, `java.awt.Graphics2D.drawImage`, `java.awt.image.BufferStrategy.show` and `java.awt.Graphics2D.fillRect` take the most space. This is what I suspected, as I knew the image rendering would take some time. However, I noticed an interesting trend that occurred in both screen resolutions:

* `java.awt.Graphics2D.fillRect` takes approximately twice the amount of average time per invocation than `java.awt.Graphics2D.drawImage`.

I know that it is the average call time, so of course some images will not always be the same size as the screen, but it still made me curious if that had something to do with it.

As Pikalek said, a higher resolution has more data to push, but is there something else that might be causing these differences in FPS? Poor optimization in some spots perhaps?

---

One more edit, sorry...

I ran the program after removing `graphics.fillRect(0, 0, WIDTH, HEIGHT)`, and the FPS differences did not make much of a difference. Here are the results with everything rendered.

* Resolution of 640x360: Approximately 960FPS
* Resolution of 1920x1017: Approximately 115FPS

# Answer
> 2 votes
1920 * 1017 is just a shade under 2 million. 640 * 360 is about 230000. There's nothing to debug here : you're drawing ~10 times as many pixels so you should expect a roughly commensurate performance drop.

> If the player wants to play at that maximum resolution, should you implement some form of an upper FPS cap for all resolutions so they don’t have to think its some sort of code-based issue when they see the 10x increase/decrease in performance? Would this fix have any negative implications?

Most games typically upper-bound rendering speed to either a commonly-used fixed value, such as 60fps, or to the monitor's refresh rate. Any of your players running on battery power will also thank you for doing this.

---
Tags: java, rendering, optimization, frame-rate, resolution
---


# Question
Title: How to upload a certificate in Unity for an SSL connection
I am developing a videogame in Unity for mobile devices (Android / IOs) that connects to a server through a TCP connection by socket under TLS1.2. For this reason, my client needs to have the server's certificate (cert.pfx) to establish the connection correctly, and this is where my doubts appear.

How do I load the certificate on the client? I have 2 options in mind but I don't know if any of these are safe and correct:

> A) Include the certificate in the resources directory in the compilation of the client application.

> B) Include the certificate in the Streaming Assets directory.

> C) Download the certificate from a URL in the first execution of the application and store it locally in the application directory for future use.

The truth is that I don't know if any of these options is the right way to go. If anyone has more information about it and can help me I would greatly appreciate it.

Thanks :)

# Answer
> 1 votes
I see no reason why you would download the certificate at runtime. You would have to download it over an unencrypted connection, so it could potentially be modified (unlikely but not impossible). And it just makes things a lot more complicated for no good reason.

On the other hand, there is no reason why you would not include the certificate with your game installer. A server certificate only needs to include the public key of the server, not the private key (if you give the client the private key of your server, you are doing something very wrong). So the game installer storing an unencrypted server certificate on the users device should not be a problem. The integrity of the certificate is likely already guaranteed by your distribution channel.

Yes, the certificate could get modified by a malware on the device. But when there is a software on the users device which manipulates the game files, then it can screw with the client in any way it wants anyway. So that's a far bigger problem. Also, app packages are better protected from modification than files in the application directory, so having the certificate in the apk/ipa makes it in fact *more* secure from access by 3rd party apps.

So just include the server certificate with the game client.

*How exactly* you bundle the certificate file with your game - referenced Text Asset, Resources folder, asset pack, Addressable or whatever, is a personal preference.

---
Tags: unity, android, client-server, security, socket
---


title: Scene graph with camera

text:
# Question
Title: Scene graph with camera
I need help with a little problem in my project, in which I have a scene graph with the intented camera like this:

* MovementNode
    + Camera Node
    + Mesh Object

My problem is that I have the propagation of the world\_space\_matrix from the parent to the child done like this:

```
void BaseNode::update_matrix_if_needed() {
        if (_updated_position) {
            BaseNodeInstance* parent = instance.get_parent();

            global_space_matrix = glm::mat4(1.0f); // construct identity matrix

            //scale, rotate, move

                global_space_matrix = glm::scale(global_space_matrix, scl);

                rotation_matrix = glm::rotate(rot.x, glm::vec3(1, 0, 0));
                rotation_matrix *= glm::rotate(rot.y, glm::vec3(0, 1, 0));
                rotation_matrix *= glm::rotate(rot.z, glm::vec3(0, 0, 1));
                global_space_matrix =  rotation_matrix * global_space_matrix;

                global_space_matrix = glm::translate(local_space_matrix, pos);

            if (parent  != nullptr) {
                global_space_matrix = parent->get_data()->global_space_matrix * global_space_matrix;
            }
        }

        _updated_position = false;
    }

```

Then, in the Camera Node, I submit the view matrix like this:

```
void CameraNode::uniform_view_matrix(GLuint location) {
    glUniformMatrix4fv(location, 1, 0, glm::value_ptr(camera_matrix));
}

```

where `camera_matrix` is computed as:

```
void CameraNode::update(float delta) {
    //add_pos(glm::vec3(0, 0, -1) * delta);

    if (_updated_position) {
        BaseNode::update(delta);
        camera_matrix = global_space_matrix;
    }
}

```

However, when I move the camera in my application, the objects are moving in completely different directions than my camera (although they stick together how they should).

I think the problem is in how I interpret the view\_matrix from the cameras local space. What can be my problem?

# Answer
The problem was how I updated my Camera.

I used `global_space_matrix` as my view\_matrix but then I tried to use `glm::inverse(global_space_matrix)` and it is working as intended!

Still I don't completely understand why.
> 0 votes

---
Tags: opengl, rendering, matrix, view
---


# Question
Title: `System.Xml.XmlDocument.Load(Path)` doesn't work on Android
I'm making a little game on Android with Unity. And I use XML file to store different languages using `System.Xml`. The language selection is done when I first start the game. When I run the game in Unity everything works fine - I select the language and the game goes on, but if I run it from Android nothing happens when I select the language. I connected my phone to the computer and looked at the game logs in cmd windows via `adb.exe logcat`, and found this:

```
06-19 20:11:59.724 24342 24382 I Unity   : jar:file:///data/app/com.eSnailStudio.CountTheNumber.Game-f0RdxK_Zfj2jXL2nqoA01A==/base.apk!/assets/Localization/Languages.xml
06-19 20:11:59.724 24342 24382 I Unity   : (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
06-19 20:11:59.724 24342 24382 I Unity   :
06-19 20:11:59.749   604   604 I ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
06-19 20:11:59.751   604   604 I ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
06-19 20:12:00.002  1857  1857 D KeyguardUpdateMonitor: handleTimeUpdate
06-19 20:12:00.021 24342 24382 E Unity   : NotSupportedException: The URI prefix is not recognized.
06-19 20:12:00.021 24342 24382 E Unity   :   at System.Net.WebRequest.Create (System.Uri requestUri, System.Boolean useUriBase) [0x000ae] in <6b80e2850f1c48e6a227f0818ca6b227>:0
06-19 20:12:00.021 24342 24382 E Unity   :   at System.Net.WebRequest.Create (System.Uri requestUri) [0x00014] in <6b80e2850f1c48e6a227f0818ca6b227>:0
06-19 20:12:00.021 24342 24382 E Unity   :   at System.Xml.XmlDownloadManager.GetNonFileStream (System.Uri uri, System.Net.ICredentials credentials, System.Net.IWebProxy proxy, System.Net.Cache.RequestCachePolicy cachePolicy) [0x00000] in <b307146a71634627bcac16b7fdded4d2>:0
06-19 20:12:00.021 24342 24382 E Unity   :   at System.Xml.XmlDownloadManager.GetStream (System.Uri uri, System.Net.ICredentials credentials, System.Net.IWebProxy proxy, System.Net.Cache.RequestCachePolicy cachePolicy) [0x00022] in <b307146a71634627bcac16b7fdded4d2>:0
06-19 20:12:00.021 24342 24382 E Unity   :   at System.Xml.XmlUrlResolver.GetEntity (System.Uri absoluteUri, System.String role, System.Type ofObjectToReturn) [0x00032] in <b307146a71634627bcac16b7fdded4d2>:0
06-19 20:12:00.021 24342 24382 E Unity   :   at System.Xml.XmlTextReaderImpl.OpenUrlDelegate (System.Object xmlResolver) [0x0000c] in <b

```

The first line is the path to the android languages xml file, which I output through `Debug.Log()`. Through `Debug.Log()` I also realized that the code stops on line `xml.Load(Path);` in method below in the `LanguageSystem` script:

```
public static void SetLanguage(string language)
{
    var xml = new XmlDocument();
    xml.Load(Path); // Here the code stops on Android

    Strings = new Hashtable();
    var element = xml.DocumentElement[language];
    if (element != null)
    {
        var elemEnum = element.GetEnumerator();
        while (elemEnum.MoveNext())
        {
            var xmlItem = (XmlElement)elemEnum.Current;
            Strings.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
        }
    }
    else
    {
        Debug.LogError("The specified language does not exist: " + language);
    }
}

```

I also opened the .APK file of the game through the archiver. Attached a photo below + photo of game game logs.

What is my mistake and how do I fix it?

# Answer
Thanks to DMGregory. `TextAsset` is a great solution.

If anyone is interested, here is what the `SetLanguage` method looks like now:

```
public static void SetLanguage(string language)
{
    var xml = new XmlDocument();
    xml.LoadXml(InFile.text);

    Strings = new Hashtable();
    var element = xml.DocumentElement[language];
    if (element != null)
    {
        var elemEnum = element.GetEnumerator();
        while (elemEnum.MoveNext())
        {
            var xmlItem = (XmlElement)elemEnum.Current;
            Strings.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
        }
    }
    else
    {
        Debug.LogError("The specified language does not exist: " + language);
    }
}

```

The way I get `InFile`:

```
InFile = Resources.Load<TextAsset>("Localization/Languages");

```

Unity documentation: https://docs.unity3d.com/ScriptReference/Resources.Load.html
> 1 votes

---
Tags: unity, android, xml
---


# Question
Title: What happens if first we scale a rotation matrix and then multiply it with an object?
This question has been bothering me lately. I know the correct order to scale, rotate and transform a matrix but the question I have is very different. What if we first scale our rotation matrix by some value and then multiply it with our object? What will be its affect on our object?

# Answer
##### Effect

The effect will be to rotate then scale, or scale then rotate your object, depending on what order you perform the multiplications.

###### Explanation

Matrices (at least in less than 3 dimensions) carry super strong geometric intuitions. You can literally just think of them as holding transformations of space: be it translating, scaling, rotating, skewing or any combination of these. Multiplying two or more matrices, has the geometric equivalence of applying these transformations one after another. So if you multiple a **rotation matrix** * **scaling matrix**, you can think of it as scaling, **then** rotating space (or whatever vectors you put through this resulting matrix).

##### As to the name of the resulting matrix...

The definition of a rotation matrix is that it doesn't scale space nor reorder it's basis vectors \[i,j,k\]. More practically: rotation matrices don't change the magnitude of vectors or rearrange their \[x,y,z\] components.

This all means that if you scale a rotation matrix, then by definition it's no longer a "rotation" matrix --\> now it's a matrix that rotates and scales.
> 1 votes

---
Tags: opengl, mathematics, rotation, transformation
---