# Question
Title: 2D Animation based on Time.deltaTime has problems when the game performs long operations
I animate my 2D sprite using the `Update()` method:

```
float timer = 0.0f;
float delayPerFrame = 0.04f;

void Update() {
    timer += Time.deltaTime;
    if (timer >= delayPerFrame) {
        timer = 0;
        // Logic to display the next frame
    }
}

```

As you can see, it is pretty simple: every `0.04` seconds the next frame will be set.

But sometimes, my game needs to do some exhausting processing (like loading large scenes and whatnot), which causes a tiny little lag in the game. When this happens, my sprite begins with a ***wild***, fast animation. Then eventually it resumes at a normal pace.

I imagine this is because the lag caused the `Time.deltaTime` value to skyrocket for a period of time. I am also under the impression that `Update()` is called too often during such period (although that shouldn't matter).

I don't want to use existing animation features of Unity. My game is already built under this particular piece of logic, so I'd like to fix it.

Using `FixedUpdate()` doesn't help. I can also confirm that `Time.deltaTime` does indeed peak at the beginning.

Note that this occurs only after doing an exhaustive operation. If you spawn a sprite of these in the middle of the game, everything will go smoothly. But if you spawn them immediately after doing something like loading a large scene, then they will have some sort of boost at the beginning.

# Answer
If you are rolling your own sprite animations you may need to track elapsed time so that you can control how long each frame is displayed.

A common approach is to use an accumulator e.g.:

```
float animationFramesPerSecond = 15;
float animationFrameDuration = 60f / animationFramesPerSecond;
float animationFrameIndex = 0;

float accumulator = 0;

void Update()
{
    accumulator += Time.time;
    while (accumulator <= animationFrameDuration)
    {
        animationFrameIndex++;
        accumulator -= animationFrameDuration;
    }
}

```

---

An additional consideration might be to identify any heavy weight tasks that are taking too long to execute and splitting them up over a more than one frame. Frequently coroutines can be used for this purpose.
> 1 votes

# Answer
I would recommend not having heavy loads during the game play and only doing them during a loading screen. I usually set the `Time.timeScale = 0f;` during these loading screens and once I'm done loading stuff I resume game play.
> 0 votes

# Answer
In Unity Execution Order of Event Functions

I see that "Internal Animation Update" comes after all Update stuf, but before LateUpdate. As you manage animation on your own, try putting all animation logic (and only animation logic) into LateUpdate.
> -1 votes

# Answer
The `Time.deltaTime` is the amount of time elapsed between two consecutive Updates() calls. When the game tries to load a heavy asset , the update doesn't get called often as the process is stuck doing some task. Hence there is a lag between two Updates. Due to which the `Time.deltaTime` increases , which signifies that the system is lagging and not accelerating.

So it all boils down to how you are using Time.delta time. The problem lies in the logic to display the next frame.
> -1 votes

# Answer
as workaround, if nobody figures out what is the problem, you can , after loading a schene, fade it in until the sprites starts animating the right way.
> -1 votes

---
Tags: unity
---


title: How to calculate item drop rate?

text:
# Question
Title: How to calculate item drop rate?
I am developing an RPG that will be played in the browser, so far the development is going very well. However, I reached a point in the project where I'm "stuck" because I can't find a good solution. My game players will duel against monsters, when defeating a monster needs to drop the items, in this scenario an example would be.

Monster A has a chance to drop the items:

* 5% sword
* Gold (between 2 and 5 gold)
* 35% potion (Hp or Mp)

Currently I put it to generate a random number, for example, rand(0, 100), the problem is that there are millions of failures, the first is that sometimes the player gets the sword 2 times in a row because I'm generating the random number and I'm comparing whether it is greater or less than the defined %.

I would like to know if there is a better way to do this control and how it could be done.

# Answer
Try randomly checking "will this item drop?" for every item. You could store the information for item and drop chance as pairs in a list:

```
drops = [["sword",5],["hp_potion",35],["mp_potion",35]]
loot = []
for i in drops:
    if random_chance(i[1]):
        loot.append(i[2])
give_player_loot()

```

...but this does not account for quantity, and maybe you'd like to prevent one item from dropping if another does. My solution for this would be nesting lists even further, with an item name, chance, and min/max quantity going in list A. List A is put within pool B, within the drops variable, C.

So, this would look something like:

```
# SLOW BUT EASY WAY TO BUILD LOOT TABLE
# You do this when the monster is created, if you are keeping a list of monsters
# that is made at the start of the game, this is also where you'd put this.
# this example loot pool has a 35% chance to drop 1-3 HP potions, OR, failing
# that, a 35% chance to drop 1-2 MP potions.
A = ["hp_potion",35,1,3] # individual item drop chance
A2 = ["mp_potion",35,1,2] # another one, to help describe the concept.
B = [A,A2] # the loot, A and A2 is going into pool B.
C = [B] # B goes into the final drop pool
monster_drops = C
# COMPACT WAY:
monster_drops = [[["hp_potion",35,1,3],["mp_potion",35,1,2]]]

```

Next, we have to iterate between all drops like so:

```
loot = []
for i in monster_drops: # go through all pools
    for j in i: # go through all items
        if random_chance(j[1]):
            loot += [j[0]]*random_range(j[2],j[3]) # add this item to the loot,
                                                   # multiplied by the number of
                                                   # items it should drop.
            break # exit the loop
give_player_loot(loot)

```

Sorry for the poor formatting, it's based on python and I don't really know how to use StackExchange, but I hope this was helpful! (Also, I noticed you are using JS, but hopefully the same concepts apply there!)
> 1 votes

---
Tags: mathematics, game-design, javascript, rpg
---


# Question
Title: In Unity, why won't the speed change when I'm crouching?
```
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    public CharacterController controller;
    public Transform trnsform;

    public float JumpH = 3f;

    //these are the speed variables (which are the variables that are the problem)
    public float Speed = 20f;
    public float AirSpeed = 10;

    // this is to check if the player is on the ground
    public LayerMask Groundmask;
    public Transform groundcheck;
    bool isGrounded;
    public float GroundDistance = 0.4f;

    bool isCrouching = false;

    Vector3 Velocity;
    public float Gravity = -9.81f;

    private void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //this is the movement
        float X = Input.GetAxis("Horizontal");
        float Z = Input.GetAxis("Vertical");
        Vector3 move = transform.right * X + transform.forward * Z;
        Velocity.y += Gravity * Time.deltaTime;
        controller.Move(Velocity * Time.deltaTime);
        controller.Move(move * Speed * Time.deltaTime);

        //this defines what needs to be met for isGrounded to be true
        isGrounded = Physics.CheckSphere(groundcheck.position, GroundDistance, Groundmask);

        //this resets the players downward velocity when they're on the ground
        if(isGrounded == true  && Velocity.y < 0)
        {
            Velocity.y = -2f;
        }

        //this controls jumping
        if(Input.GetButtonDown("Jump") && isGrounded && !isCrouching)
        {
            Velocity.y = Mathf.Sqrt(JumpH * -2f * Gravity);
        }
        else
        {
            if (Input.GetButtonDown("Jump") && isGrounded)
            {
                Velocity.y = Mathf.Sqrt(1.5f * -2f * Gravity);

            }
        }

        //this is the code that isn't working
        if(isCrouching)
        {
            Speed = 10f;
        }
        else
        {
            Speed = 20f;
        }

        //this makes the player crouch
        if(Input.GetKey("left ctrl"))
        {

            trnsform.localScale = new Vector3(1f, 0.5f, 1f);
            isCrouching = true;
        }
        else
        {
            trnsform.localScale = new Vector3(1f, 1f, 1f);
            isCrouching = false;
        }

        //this makes the player move slower while in air
        if (isGrounded == false)
        {
            Speed = AirSpeed;
        }
        else
        {
            Speed = 20;
        }

    }

    //this makes the player bounce when they hit anyting tagged with bounce
    private void OnControllerColliderHit(ControllerColliderHit hit)
    {
        if(hit.collider.tag == "Bounce")
        {
            Velocity.y = Mathf.Sqrt(9f * -2f * Gravity);
        }
    }

}

```

# Answer
> 5 votes
At the end of your Update method, you have this block:

```
    if (isGrounded == false)
    {
        Speed = AirSpeed;
    }
    else
    {
        Speed = 20;
    }

```

That means that after this block, `Speed` will be either `AirSpeed` or `20`. The stuff you are doing further above based on the value of `isCrouching` is irrelevant, because it gets overwritten before the value is used for anything.

So you need to add some logic in the else-branch to decide whether to set the speed to the crouch speed or to the walk speed.

```
    if (isGrounded == false)
    {
        Speed = AirSpeed;
    }
    else
    {
        if (isCrouching) {
            Speed = CrouchSpeed;
        }
        else
        {
            Speed = WalkSpeed;
        }
    }

```

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


# Question
Title: Smooth rotation to target with separate yaw, pitch and roll smooth times
I'm trying to write a camera script in Unity that would smoothly rotate the camera over time towards the desired rotation, with separate input parameters for yaw, pitch and roll smoothing, and I can't figure out how to do it properly. That camera would be meant to follow a vehicle that can move and rotate in 3D space. I've tried many things, most recently the code below:

```
Vector3 targetLookDirection = (lookTarget - cameraPosition).normalized;
Quaternion targetCameraRotation = Quaternion.LookRotation(targetLookDirection, vehicleTransform.up);

Vector3 currentDeviation = (transform.rotation * Quaternion.Inverse(targetRotation)).eulerAngles;
//since deviation * target = current, then deviation = current * inv(target)
Vector3 newDeviation = new Vector3
{
    x = Mathf.SmoothDampAngle(currentDeviation.x, 0f, ref pitchVelocity, pitchSmoothTime),
    y = Mathf.SmoothDampAngle(currentDeviation.y, 0f, ref yawVelocity, yawSmoothTime),
    z = Mathf.SmoothDampAngle(currentDeviation.z, 0f, ref rollVelocity, rollSmoothTime)
};
transform.rotation = targetRotation;
transform.Rotate(newDeviation);

```

where `lookTarget` and `cameraPosition` are Vector3s, and `transform` refers to the camera transform since the script is attached to the camera Game Object. The code is in `LateUpdate()`.

The code looks logical to me, but in reality when I run it with the `Smooth Times` set to around 0.25 the camera just shakes chaotically. The shaking behaviour is also different depending on which way I look in 3D space (with visibly different behaviour when looking towards z+ direction), which is weird to me since the smoothing is only working with relative rotation of the camera from the target rotation, and not their world rotations.

I would very much appreciate it if you could let me know how to fix this script to make it work properly.

# Answer
> 0 votes
I fixed the problem. I changed the last two lines of the code.

Instead of:

```
transform.rotation = targetRotation;
transform.Rotate(newDeviation);

```

I wrote:

```
Quaternion newDeviationQuat = Quaternion.Euler(newDeviation);
transform.rotation = newDeviationQuat * targetRotation;

```

And now it works perfectly. Don't ask me why.

# Answer
> 0 votes
Quaternions are hard. Usually to avoid gimbal lock and to make life easier I would advice to split up the camera arm. So one transform is doing x and z rotation while the other transform, its child, is doing y in local space.

I can recommend the asset DoTween, there is a free version, it makes interpolation quite easy you could just say `transform.DoLookAt` and say how long it should take as an argument. DoTween can also just rotate on one axis.

---
Tags: unity, camera, rotation, quaternion, easing
---


# Question
Title: Multiple AudioSources or one AudioSource with multiple AudioClips?
I have a character with a bunch of different attacks + sound effects in Unity.

One way to architect this is to create a single AudioSource, and then set the AudioSource.clip to a specific sfx each time an attack happens. E.g.:

```
playerAudio.clip = laserSfx;
playerAudio.PlayOneShot();

```

(Where `playerAudio` is an `AudioSource`, and `laserSfx` is an `AudioClip` loaded at runtime)

Another method is to have child game objects with their own AudioSources, so when I do attack A, I can do something like `AttackA.GetComponent<AudioSource>().Play()`

Is there a preferred way of doing this in Unity? Considering performance impacts and such.

# Answer
> 0 votes
The question is more about which sound effects can play at the same time and which should be cut hard.

If they can play at the same time, I would consider a Pool, which makes sure that the audiosources gets disabled when returned to the pool. The pooling therefore guarantees there are never too many audiosources in the scene than needed. The pool could even grow when needed or in fact limit how many can be active at once.

---
Tags: unity, audio
---


# Question
Title: CR LF replacement in Unity Input Fields when copy and pasting
I setup a bit of code to detect line breaks using `\n` char (line feed), from the `TMPro_InputField`:

```
foreach(char c in text)
{
    if (c == '\n')  { splitLines.Add(cur);  cur = ""; }
    else {cur += c;}
}

```

When only characters are pressed directly into the input field, things worked great, but when I pasted in text from notepad, the results are confusing. After a ton of debugging I realize that Windows use CRLF (carriage return + line feed combo), so I simply use `Replace()` to sort things out.

Problems arise when the user copy and paste. If I implement a copy button, then I can replace `"\n"` with `"\r\n"` manually:

```
public void copyFromText()
{
    TextEditor textEditor = new TextEditor();
    textEditor.text = textField.GetComponent<TMP_InputField>().text;
    textEditor.text = textEditor.text.Replace("\n", "\r\n"); //this line here
    textEditor.SelectAll();
    textEditor.Copy();
}

```

Same goes for pasting. But when user press `Ctrl+C` or `Ctrl+V`, things get complicated. I could detect keys pressed, check if input field is highlighted, and replace stuff by hand, etc... but that's too much of a nuisance.

Is there a way to resolve this quicker? Or better, just config Unity to use CR LF with input fields somehow?

# Answer
> 0 votes
Why not use #define directives?(https://docs.unity3d.com/Manual/PlatformDependentCompilation.html)

So when on Windows UNITY\_STANDALONE\_WIN Or on windows editor UNITY\_EDITOR\_WIN Then always replace with CR LF

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


# Question
Title: How can I get/set values within a custom array in unity?
I wanted to create a custom array that contains both strings and integers to represent the name and amount of an item a player has. While this did work in the inspector, I don't know how to access or change values or add new elements in a custom array during gameplay. The website that I used as a guide had 2 functions, but they unfortunately didn't work. How can I edit a custom array during gameplay?

Here is the minimum required code:

```
using System;
using System.Collections.Generic;
using UnityEngine;
public class CustomArrayTest: MonoBehaviour
{
    [SerializeField] private PlayerScrolls[] playerScrolls;
    public void SetValue ()
    {
        //Function to set a value in the array
    }
    public SubClass GetValue ()
    {
        //Function to get a value in the array
    }
}
[System.Serializable]
public class PlayerScrolls
{
    public int scrollAmount;
    public string scrollName;
}

```

Website I based his code off of: https://owlcation.com/stem/Using-Single-and-Multi-Dimensional-Arrays-in-C-and-Unity3D

# Answer
Getting your code to work is the easier part. You would need to change your `getter` and `setter` to match what the tutorial is teaching you. A `setter` needs the parameter to well, set things. Your `getter` returns a totally different class than you would expect, it should be of type `PlayerScrolls`.

```
public void SetValue (PlayerScrolls item, int index) {
    playerScrolls[index] = item;
}

public PlayerScrolls GetValue (int index) {
    return playerScrolls[index];
}

```

But this gives you a new challenge. How do you know the index? While for some kind of games it might work (like you have 4 inventory slots and the player presses the first slot, so you would know index = 0), even adding an item will be a problem. You would need first to find out, where did you store it. Afterwards retrieve it, adjust the item amount and store it back. Your array has no knowledge where it actually stores things. And you might run into index problems if you try to access parts that are not allocated.

Unity offers a tutorial which might interest you about Lists and Dictionaries which might be a good start to check out.

Edit to your comment:

If you would like to add an amount to an already existing item, you could do it like this. I'm reusing the previous getter/ setter.

```
public void AddItemAmount(int amount, int index) {
   PlayerScrolls item = GetValue(index);
   item.scrollAmount += amount;
   SetValue(item, index);
}

```
> 1 votes

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


# Question
Title: confusion with Mathf.MoveTowardsAngle being in the Update method
I've got some code that looks like this:

```
    public void SomeClass: Monobehaviour{

    private smoothAngle = 0.0f;

    void Update(){

        var localDesiredVelocity = transform.InverseTransformVector(navAgent.desiredVelocity);
        var angle = Mathf.Atan2(localDesiredVelocity.x, localDesiredVelocity.z) * Mathf.Rad2Deg;
        smoothAngle = Mathf.MoveTowardsAngle(smoothAngle, angle, 80.0f * Time.deltaTime);
}
    }

```

From what I could gather from the documentation it's sort of a lerping or slerping of the angle value.

My confusion is , why is it in the `update` function. since, `desiredVelocity` is dynamic, it would make the angle dynamic. So, suppose in 2 executions of the `Update` function:

```
1st execution:

var smoothAngle = Mathf.MoveTowardsAngle(0, 80, /other_parameters/);

2nd execution:

var smoothAngle = Mathf.MoveTowards(/someValue/, 82, /other_parameters/);

```

My point is , while `smoothAngle` is s/lerping due to the first execution in the update function, once new values are passed for it during the second execution, would it cancel the first `s/lerping` and follow the latest one, or how would it handle new values for it in consecutive execution of the `Update` function.

# Answer
> 2 votes
It sounds like you're operating under a common misconception about functions like `Mathf.MoveTowards`, `MoveTowardsAngle`, `Lerp`, etc., which is the belief that these are "tweening functions", equivalent to saying:

"Over the next several frames, continue animating this property from value A to value B"

If that were the case, then calling them each frame would indeed be concerning, because last frame's invocation is "still running" and would need to be interrupted/halted to avoid conflict or weird stacking with the new invocation.

But that's not what these functions do.

These are just math functions, like `+`. They take some numbers, calculate some new numbers, and return them. That's all. They have no persistence, they have no memory of the frame before, and they do not continue executing on future frames.

So this line:

```
smoothAngle = Mathf.MoveTowardsAngle(smoothAngle, angle, 80.0f * Time.deltaTime);

```

...will calculate an angle from `smoothAngle` that's one step closer to `angle`, with the size of that step being limited using the current frame time so that it does not exceed a speed of 80 degrees per second. It then returns that angle, and assigns that number to `smoothAngle`. Nothing else happens.

To make this object keep moving next frame, we have to call this function again, to calculate a new angle to advance `smoothAngle` towards.

---
Tags: unity, vector
---


# Question
Title: Is diffuse reflection definition failed when we see both reflection(diffuse,specular) is happening on one single object?
Let us consider the situation where only we moved the camera.

The object and the light source remain in the same place. Thus the angle of the incident light is the same for every point.I have captured one image where 5 arrows marked as specular reflection (from one particular camera position) and rest of the portion could be treated as diffuse:  But when I change the camera position (but object position and light source position remain as it is) the specular portion becomes diffuse and vice versa in the image of that object. But we know that diffuse reflection is independent of camera ( only depends on normal and direction of incident light). My question is how diffuse reflection is failing to show same intensity from all direction?

**I want to share my understandings why this is happening, don't know my postulation is right or not:**

1. When we see diffuse and specular reflection is happening on one single object then the definition of diffuse reflection isn't going to work but when only diffuse reflection is happening on one single object then definition of diffuse reflection has properly worked.
2. When we see diffuse and specular reflection is happening on one single object then diffuse reflection is also dependent of camera like specular reflection.Then when the angle between viewing direction (camera) and reflection is increasing then specular portion gradually converging to diffuse.

# Answer
> 2 votes
First of all,

> the angle of the incident light is the same for every point

The angle between the incident light and the normal is different. Even if the incident light comes form the same direction※, the normal is different for each point of the surface of the object.

※: In reality this would be an approximation admisible for a light source very far away. For computer graphics, we are talking about a directional light source instead of a spot or cone light source.

---

> But when I change the camera position (but object position and light source position remain as it is) the specular portion becomes diffuse and vice versa in the image of that object.

I believe we have gone over the fact that the position of the specular highlights depends on the position of the camera, the object and the light source. Thus, moving the camera is sufficient to move the specular highlights. The last paragraphs of a prior answer are about that.

---

> But we know that diffuse reflection is independent of camera ( only depends on normal and direction of incident light).

Right. What we are trying to model with diffuse reflection is light being scattered in every direction. This is why it is independent of the direction of the camera.

**Every point with incident light has both specular reflections and diffuse reflections**. There are no portions of the object that are getting specular reflection but no diffuse reflection, nor viceversa. There are no portions of the object that are inherently specular or diffuse. In fact, specular reflection and diffuse reflection happen together.

Instead, for a single point on the surface of the object with incident light:

* Specular reflection dominates over the diffuse reflection.
* Diffuse reflection dominates over the specular reflection.
* Or somewhere in the middle. *Because the decay of the specular highlight is not abrut.*

The specular reflection is negligible everywhere except on the specular highlight. I mean, the specular reflection decays away from the specular highlight until it is virtually zero.

In consequence where you see an specular highlight, the specular reflection is much more intense than the diffuse reflection, so we do not perceive the diffuse reflection.

---

I want to point out that "specular highlight" and "specular reflection" are not the same thing. In the prior answer, on first paragraph, I took the care to define "specular highlight":

> The specular highlight (…) is an specular reflection **of the light source**.

*Emphasis added on "of the light source"*.

Other objects aside from the light source also appear in the specular reflection. But only the reflections of the light source are specular highlights.

---

While the way specular reflection decays attempts to model roughness. The diffuse reflection attempts to model scattering.

I quote form Wikipedia's article on Diffuse reflection:

> Diffuse reflection from solids is generally not due to surface roughness. A flat surface is indeed required to give specular reflection, but it does not prevent diffuse reflection.

*A light ray travelling from one medium to another scattering inside the object. This picture is taken from the article THE PBR GUIDE BY ALLEGORITHMIC - PART 1.*

So, some of the light gets refracted and scattered back out the surface. And the distribution of the direction and intensity of that light is close to uniform. So we model it as being the same from every direction.

---

If we consider an object with a mirror finish (i.e an object with very little micro-imperfections, i.e an object with very low roughness, i.e. a very smooth object), the object will act as a mirror. And in a mirror we can see sharp specular reflections of the environment (including objects other than the light source).

I continue quoting from Wikipedia:

> A piece of highly polished white marble remains white; no amount of polishing will turn it into a mirror. Polishing produces some specular reflection, but the remaining light continues to be diffusely reflected.

However, even mirrors have some diffuse reflection. It just happens to be very, very, hard to notice. But we can make it more evident by making repeated reflections, by reflecting a mirror in a mirror.

*Picture taken from the video What Color is a Mirror by VSause.*

We observe that the repeated reflections are less bright, and have a tint. *Usually a green tint, due to the chemistry of the glass.*

*By the way, the the video includes a picture that suggest diffuse reflection happens due to roughness. So, I'll reiterate that we attempt to model scattering as diffuse reflection.*

---

> 1. When we see diffuse and specular reflection is happening on one single object then the definition of diffuse reflection isn't going to work but when only diffuse reflection is happening on one single object then definition of diffuse reflection has properly worked.

The specular reflection, diffuse reflection (and ambient and any other components according to the lighting model) contribute to the final shading of every pixel.

But away from the specular highlight, the contribution of the specular reflection is negligible. Leaving only the contribution of the diffuse reflection (and ambient reflections or any other component according to the lighting model) noticiable.

On the other hand, on the specular highlight, the specular reflection is very intense. As a consequence we do not notice the contributions of the diffuse reflection (and ambient reflection and so on).

That is, the definition of diffuse reflection holds. But it does not account for how its contributions is combined with the others. *For any lighting model, the contributions of specular reflection, diffuse reflection, (and any other component) must be combined to make up the final shading of the pixel. This is usually a weighted sum.*

---

> 2. When we see diffuse and specular reflection is happening on one single object then diffuse reflection is also dependent of camera like specular reflection.Then when the angle between viewing direction (camera) and reflection is increasing then specular portion gradually converging to diffuse.

The final result of combining the reflection is dependent on the camera. Because the specular reflection is dependent on the camera. But the diffuse reflection, considered on its own, isn't dependent on the camera.

---
Tags: lighting, reflection-rendering, shading, global-illumination, specular
---


title: Serialize List of References

text:
# Question
Title: Serialize List of References
I have a list of object references inside a serializable class, like this:

```
[Serializable]
public class Test : MonoBehavior{
    public List<SomeSerializableObject> list;
}

```

When I instatiate a copy (with Instatiate()), the objects inside the list get copied and are no longer references to the original elements in the list. Using `[SerializeReference]` only works for the list itself, but how do I do it for the items inside the list?

# Answer
> 2 votes
#### The Problem

In Unity's Docs :

> * \[Serialize\] Referenced values **cannot** be shared between UnityEngine.Object instances. For example, two MonoBehaviours cannot share an object that is serialized by reference. Use ScriptableObjects instead to share data.

As Instantiate creates a new Unity Object, its data cannot be shared by reference by just decorating the fields with a \[SerializeReference\] Attributes.

#### The Solution

Instead, each member of the list that you want to be copied by reference during instantiation must be **it's own Unity Asset**. This means each member has to be inherit from UnityEngine.Object and be an actual Asset on disk with a .meta file with a GUID. It's these GUIDs which are the links which Unity's serialization system uses to stitch all the references back together at edit or runtime.

You can create an Unity asset via script by going AssetDatabase.CreateAsset(\[...\]) with anything which inherits from UnityEngine.Object. But instead what you probably want to do for convenient sake is inherit from ScriptableObject and then create your assets via the asset menu (which you can open by right clicking in the project window). This way you can create new assets in the editor and don't have to create custom inspectors to edit their values.

Here are the two scripts which get the job done:

```
[CreateAssetMenu(menuName = "Custom/test so", order = 0)]
public class MySO : ScriptableObject
{
    public int Value;
}

```

And:

```
public class Test : MonoBehaviour
{
    public List<MySO> scriptableObjectAssets;
}

```

Opening the asset menue to create the scriptableObject:

The inspector for the the Monobehavior with the members which will be copied by reference during instantiations:

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


# Question
Title: How do you break up or architect Unity scripts?
I have a player script that is turning into a bit of a monster. I don't know too much about Unity so I'm just jamming the whole game logic in there which does not seem right. The player is currently handling input, re-stacking stairs, moving the player object, checking successful moves, updating the score, resetting the world on mistakes... I am about to implement pause behavior and it is also going to be listening for `esc` and pausing the world, resetting the timer so the player has 1 second when they unpause...

I have read through How to architect code as your project scales by Unity. I am just not sure where to apply it. From reading that I think I should have -

* A game state for keeping score and resetting the world.
* A player for getting input and moving the player.
* Something needs to check player move success?
* Maybe a platform manager for juggling the platforms to create the illusion of infinite stairs.
* A presentation layer to draw everything?

What do I attach these to? There are also some concepts I haven't used yet, like prefabs and scriptable objects. If there is a good tutorial or course to understand this architecture, please point it out!

Code is below (with gratuitous comments) if anyone can give advice on how to break it up. I am cloning and Overwatch Workshop mode called Bastion Stairs or Infinite Stairs. It can be seen here.

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

public class Player : MonoBehaviour
{
    enum Direction
    {
        Left,
        Right,
        NoDir
    }

    // upcoming steps (Left / Right)
    List<Direction> ahead;
    // completed steps
    List<Direction> behind;
    // stair objects
    List<GameObject> stairs;

    // player box
    public Rigidbody2D rb;
    // score displays
    public UnityEngine.UI.Text txtScore;
    public UnityEngine.UI.Text txtHighScore;

    // tracker to stop key repeats
    Direction last;
    // player's score
    int score;
    // player's high score
    int highScore;
    // index of the bottom stair
    // bottom stair is moved to top when off screen
    int bottomStair;
    // count of stairs
    int stairCount;
    // how many stairs should be trailing the player
    int trailing;
    // 1 second time out so you don't dawdle
    float staminaTimeout;

    Direction RandDir() {
        return (Direction)Random.Range(0, 2);
    }

    void Start() {
        // instantiate stuff
        ahead = new List<Direction>();
        behind = new List<Direction>();
        stairs = new List<GameObject>();
        last = Direction.NoDir;
        stairCount = 16;
        trailing = 6;
        highScore = 0;

        // fetch platform (stair) objects
        for (int i = 0; i < 16; i++) {
            GameObject stair = GameObject.Find("blank_" + i);
            stairs.Add(stair);
        }

        reset();
        initStairs();
    }

    void stairStack() {
        // moves the bottom stair object above the current top stair
        GameObject bottom = stairs[bottomStair % stairCount];
        Vector2 bpos = bottom.GetComponent<Rigidbody2D>().position;

        int topStair = (bottomStair + (stairCount - 1));
        GameObject top = stairs[topStair % stairCount];
        Vector2 tpos = top.GetComponent<Rigidbody2D>().position;

        bpos.y = tpos.y + 1f;

        // offset left or right depending on top direction
        if (ahead[stairCount-(trailing+1)] == Direction.Left) {
            bpos.x = tpos.x - 0.5f;
        } else {
            bpos.x = tpos.x + 0.5f;
        }

        bottom.GetComponent<Rigidbody2D>().position = bpos;
        bottomStair++;
    }

    // reset game state
    void reset() {
        ahead.Clear();
        behind.Clear();
        score = 0;
        bottomStair = 0;
        staminaTimeout = 0f;

        txtScore.text = "Score: " + score;

        for (int i = 0; i < stairCount; i++) {
            ahead.Add(RandDir());
        }

        // move player to bottom
        Vector2 pos = new Vector2(0f, -4.5f);
        rb.position = pos;
    }

    // sets up stairs at game start
    void initStairs() {
        // first stair position
        float xpos = 0f;
        float ypos = -4f;
        for (int idx = 0; idx < stairCount; idx++) {
            // offset left or right depending on direction
            if (ahead[idx] == Direction.Left) {
                xpos += -0.5f;
            } else {
                xpos += 0.5f;
            }

            // set stair object position
            GameObject stair = stairs[idx];
            Vector2 pos = stair.GetComponent<Rigidbody2D>().position;
            pos.x = xpos;
            pos.y = ypos + idx;
            stair.GetComponent<Rigidbody2D>().position = pos;
        }
    }

    void Update() {
        // get move
        float move = Input.GetAxisRaw("Horizontal");

        // convert move to direction
        Direction inpt = Direction.NoDir;
        if (move < 0) inpt = Direction.Left;
        if (move > 0) inpt = Direction.Right;

        // check stamina timeout
        if (staminaTimeout > 0 && Time.time > staminaTimeout) {
            reset();
            initStairs();
            return;
        }

        // ignore repeats
        if (inpt == last) {
            return;
        }

        last = inpt;

        // ignore no input
        if (inpt == Direction.NoDir) {
            return;
        }

        // set stamina timeout (1s)
        staminaTimeout = Time.time + 1f;

        // get correct direction
        Direction curr = ahead[0];
        // update ahead
        ahead.RemoveAt(0);
        ahead.Add(RandDir());

        Vector2 pos = rb.position;

        // handle going in the correct direction
        if (move < 0 && curr == Direction.Left) {
            // increment score
            score++;
            // track move for no reason in particular
            behind.Insert(0, curr);

            // move player
            GameObject stair = stairs[(behind.Count-1) % stairCount];
            pos.x = stair.GetComponent<Rigidbody2D>().position.x;
            pos.y += 1f;

        } else if (move > 0 && curr == Direction.Right) {
            // same same but right
            // and yea, I can consolidate this with the one above
            score++;
            behind.Insert(0, curr);

            GameObject stair = stairs[(behind.Count-1) % stairCount];
            pos.x = stair.GetComponent<Rigidbody2D>().position.x;
            pos.y += 1f;
        } else {
            // wrong move
            reset();
            initStairs();
            return;
        }

        // update player
        rb.MovePosition(pos);

        // move bottom stair to top
        if (behind.Count > trailing) {
            stairStack();
        }

        // update score display
        txtScore.text = "Score: " + score;
        if (score > highScore) {
            highScore = score;
            txtHighScore.text = "High Score: " + highScore;
        }
    }
}

```

# Answer
## Single responsibility principle

Every script should do exactly one thing. So when you describe the functionality of a script and you use the word "and" in that description, then that's a sign that it should probably be split up.

For example, this script could be documented as "This script spawns the stairs **and** moves the player **and** updates the score display".

Two "and"s means that this should probably be three scripts instead of one.

## Every game object should control itself.

When you have an UI element, then the code to control that UI element should be in a script on that UI element. When you have a player, then that code should be on the player game object.

Now you might encounter the problem: "But the UI element needs to know the players score. It can't access that because it's part of the player script". It can. That's where references to other scripts come in handy.

1. Go to the player script and turn the variable `int score` into `public int score`. Now the score of each player can be accessed by other scripts.
2. Go to the score script and create a variable `public Player player`.
3. When you now go to the Unity editor, the script will have a slot "Player" in its inspector. Drag the player into it. Now you told the score display which player to visualize. Yes, that means that when you want to add a second player with a separate score later, then you just need to create a second score display and assign the other player to it.
4. Now you can refer to the players score in your UI script with `player.score`.

## But sometimes self-controlling game objects are not feasible

Like with the stairs, for example. There are many of them, and it's far easier to control them all together instead of having each stair try to manage itself. So you should create a "StairManager" script which handles the movement of stairs. Common practice is to create a separate game object at the root of the scene just to host such manager scripts.
> 2 votes

# Answer
Posting since this might help someone else. Thanks to @Philipp's helpful answer, this is what I ended up with. This organization feels much cleaner!

StairMaster feels a little weird since it does not use Start or Update, and StaminaBar had a bit of a race condition where Player was calling `Reset()` on it before `Start()` was called, so `localScale` was being assigned `Vector3(0f, 0f, 0f)`.

```
// HighScore.cs

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

public class HighScore : MonoBehaviour
{
    public Player player;
    int highScore = 0;

    void Start() {
        gameObject.GetComponent<UnityEngine.UI.Text>().text = "High Score: 0";
    }

    void Update() {
        if (player.score > highScore) {
            highScore = player.score;
            gameObject.GetComponent<UnityEngine.UI.Text>().text = "High Score: " + player.score;
        }
    }
}

```

```
// Score.cs

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

public class Score : MonoBehaviour
{
    public Player player;
    void Start() {
        gameObject.GetComponent<UnityEngine.UI.Text>().text = "Score: 0";
    }

    void Update() {
        gameObject.GetComponent<UnityEngine.UI.Text>().text = "Score: " + player.score;
    }
}

```

```
// StairMaster.cs

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

public class StairMaster : MonoBehaviour
{

    public enum Direction
    {
        Left,
        Right,
        NoDir
    }

    List<GameObject> stairs = new List<GameObject>();
    List<Direction> ahead = new List<Direction>();
    List<Direction> behind = new List<Direction>();

    int bottomStair = 0;
    int stairCount = 16;
    int trailing = 6;

    public void Reset() {
        if (stairs.Count == 0) {
            for (int i = 0; i < 16; i++) {
                GameObject stair = GameObject.Find("stair_" + i);
                stairs.Add(stair);
            }
        }

        ahead.Clear();
        behind.Clear();
        bottomStair = 0;

        for (int i = 0; i < stairCount; i++) {
            ahead.Add(randDir());
        }

        initStairs();
    }

    public Direction NextDir() {
        return ahead[0];
    }

    public Vector2 NextStairPos() {
        GameObject next = stairs[behind.Count % stairCount];
        return next.GetComponent<Rigidbody2D>().position;
    }

    public void StairStack() {
        Direction curr = NextDir();
        ahead.RemoveAt(0);
        behind.Insert(0, curr);

        ahead.Add(randDir());

        if (behind.Count <= trailing) {
            return;
        }

        GameObject bottom = stairs[bottomStair % stairCount];
        Vector2 bpos = bottom.GetComponent<Rigidbody2D>().position;

        int topStair = (bottomStair + (stairCount - 1));
        GameObject top = stairs[topStair % stairCount];
        Vector2 tpos = top.GetComponent<Rigidbody2D>().position;

        bpos.y = tpos.y + 1f;

        if (ahead[stairCount - (trailing + 1)] == Direction.Left) {
            bpos.x = tpos.x - 0.5f;
        } else {
            bpos.x = tpos.x + 0.5f;
        }

        bottom.GetComponent<Rigidbody2D>().position = bpos;
        bottomStair++;
    }

    void Start() {
        // intentionally blank
    }

    Direction randDir() {
        return (Direction)Random.Range(0, 2);
    }

    void initStairs() {
        float xpos = 0f;
        float ypos = -4f;
        for (int idx = 0; idx < stairCount; idx++) {
            if (ahead[idx] == Direction.Left) {
                xpos += -0.5f;
            } else {
                xpos += 0.5f;
            }

            GameObject stair = stairs[idx];
            Vector2 pos = stair.GetComponent<Rigidbody2D>().position;
            pos.x = xpos;
            pos.y = ypos + idx;
            stair.GetComponent<Rigidbody2D>().position = pos;
        }
    }

    void Update() {
        // intentionally blank

    }
}

```

```
// StaminaBar.cs

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

public class StaminaBar : MonoBehaviour
{
    Vector3 initialScale;
    Vector3 uninitialized = new Vector3();
    float timeoutDelta = 0f;
    float timeSet = 0f;

    void Start() {
        initialScale = gameObject.GetComponent<Transform>().localScale;
    }

    public void Reset() {
        timeoutDelta = 0f;
        timeSet = 0f;
        if (initialScale != uninitialized) {
            gameObject.GetComponent<Transform>().localScale = initialScale;
        }
    }

    public bool TimedOut() {
        if (timeoutDelta == 0f) {
            return false;
        }
        return Time.time > timeout();
    }

    public void SetTimeout(float delta) {
        timeoutDelta = delta;
        timeSet = Time.time;
    }

    float timeout() {
        return timeSet + timeoutDelta;
    }

    void Update() {
        if (timeoutDelta == 0f) {
            gameObject.GetComponent<Transform>().localScale = initialScale;
            return;
        }

        float diff = timeout() - Time.time;
        if (diff < 0f) {
            diff = 0f;
        }

        Vector3 scale = initialScale;
        scale.y = scale.y * diff;
        gameObject.GetComponent<Transform>().localScale = scale;
    }
}

```

// Player.cs

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

public class Player : MonoBehaviour
{
    public Rigidbody2D rb;
    public StairMaster stairMaster;
    public StaminaBar staminaBar;
    public int score;

    StairMaster.Direction last;

    void Start() {
        last = StairMaster.Direction.NoDir;
        reset();
    }

    void reset() {
        stairMaster.Reset();
        staminaBar.Reset();
        score = 0;

        Vector2 pos = new Vector2(0f, -4.5f);
        rb.position = pos;
    }

    void Update() {
        float move = Input.GetAxisRaw("Horizontal");

        StairMaster.Direction inpt = StairMaster.Direction.NoDir;
        if (move < 0) inpt = StairMaster.Direction.Left;
        if (move > 0) inpt = StairMaster.Direction.Right;

        if (staminaBar.TimedOut()) {
            reset();
            return;
        }

        if (inpt == last) {
            return;
        }

        last = inpt;

        if (inpt == StairMaster.Direction.NoDir) {
            return;
        }

        staminaBar.SetTimeout(1f);
        StairMaster.Direction curr = stairMaster.NextDir();

        Vector2 pos = rb.position;

        if (move < 0 && curr == StairMaster.Direction.Left || move > 0 && curr == StairMaster.Direction.Right) {
            score++;
            pos.x = stairMaster.NextStairPos().x;
            pos.y += 1f;
        } else {
            reset();
            return;
        }

        rb.MovePosition(pos);
        stairMaster.StairStack();
    }
}

```

> 0 votes

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


# Question
Title: Drawing rectangle with line's causes join artifact with the graphics api
how can I join lines to draw rectangles, I get this artifact like this, here's my code:

```
   graphics.line(40,20,30,20)
   graphics.line(30,20,30,30)

   graphics.line(30,30,40,30)

```

# Answer
> 2 votes
You are drawing independent and unconnected lines. What you *probably* want is a polyline. You can get a polyline by passing in more than two points to the `line` function. Note the comment for the last argument on the `line` function documentation.

Here I render four lines. Three unconnected lines and a four point poly-line.

*You will notice the artefact renders a bit different from yours. This could be caused by differences between your environment and mine.*

And here is the relevant code to help you understand the difference between both approaches.

```
local graphics = love.graphics

function love.load()
    love.window.setMode(700, 400)
end

function love.draw()
    graphics.scale(10)
    graphics.setLineWidth(2)

    -- unconnected
    graphics.line(30,10, 10,10)
    graphics.line(10,10, 10,30)
    graphics.line(10,30, 30,30)

    -- connected
    graphics.line(60,10, 40,10, 40,30, 60,30)
end

```

*I changed the coordinates for the initial three lines a bit to better frame the examples in the screenshot.*

---
Tags: graphics, lua, love2d
---


# Question
Title: Can't spawn an enemy from a prefab after destroying one of the instantiated prefabs
I'm making a game where the player fights enemies that spawn at the top of the screen and move down. I have several presets of enemy groups that spawn at once.

The first thing that spawns is one enemy, and later, I want to spawn three of the same prefab at once, which works generally, but if the player kills the first enemy that spawns, the next time the game tries to spawn that enemy, I get the following error:

> MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

Here is the code that spawns the enemies.

One instance of the enemy:

```
void OneLarry()
{
    oneLarry = Instantiate(oneLarry, rb.position + Vector2.down * 5.5f, Quaternion.identity);
}

```

Three instances of the enemy:

```
void BusyLarry()
{
    Instantiate(oneLarry, rb.position + Vector2.down * 5.5f, Quaternion.identity);
    Instantiate(oneLarry, rb.position + Vector2.down * 5.5f + Vector2.left * 5f, Quaternion.identity);
    Instantiate(oneLarry, rb.position + Vector2.down * 5.5f + Vector2.right * 5f, Quaternion.identity);
}

```

When the enemy dies, I use:

```
Destroy(gameObject);

```

I'm unsure why this isn't working as from my understanding of prefabs, you should be able to destroy one and simply spawn another right afterwards.

This error only occurs for one type of enemy box. All others work as intended, and will spawn again if the player kills one of them.

They are all built in the same way - An empty object with an enemy prefab inside.

Every enemy runs off the same script, which is set to destroy it on death, and the box that contains those enemies destroys itself once it has no children.

Edit: When showing the error to a friend, they noticed that the prefab itself is getting unassigned from the spawner box's list of prefabs. This doesn't happen to any other prefab.

# Answer
You are destroying the same `oneLarry` hence it is giving Missing reference exceptions.

Just seperate prefab and the one you are instantiating like following

```
[SerializeField] private GameObject oneLarryPrefab;
private GameObject instantiatedOneLarry;

public void SpawnOneLarry() {
    instantiatedOneLarry = Instantiate(oneLarryPrefab, somePosition, someRotation);
}

public void DestroyOneLarry() {
    Destroy(instantiatedOneLarry);
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: How do I use Input.GetButton in the new Input System?
I know this is so easy, but I am new Unity user. How do I use `Input.GetButton` in the new Input System?

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public GameObject projectile;
    public float fireDelta = 0.5F;

    private float nextFire = 0.5F;
    private GameObject newProjectile;
    private float myTime = 0.0F;

    void Update()
    {
        myTime = myTime + Time.deltaTime;

        if (Input.GetButton("Fire1") && myTime > nextFire)
        {
            nextFire = myTime + fireDelta;
            newProjectile
                = Instantiate(projectile, transform.position, transform.rotation) as GameObject;

            // create code here that animates the newProjectile

            nextFire = nextFire - myTime;
            myTime = 0.0F;
        }
    }
}

```

# Answer
Semantic actions defined in the Input Manager panel (like "Fire1") can no longer be used with the new input system. But you can still check the status of specific keyboard keys. The 1:1 equivalent of the old `Input.GetKey(KeyCode.Space)` would be `Keyboard.current[Key.Space].isPressed`. More examples for drop-in replacements for the old input system can be found in the official migration guide.

However, if you *really* want to benefit from **all** the advantages which the new input system offers, including semantic input actions like "Fire1", then you need to rethink the way you handle player input on a fundamental level. The way the new input system is *supposed* to be used is not by checking the state during an Update method. The new architecture is designed for having dedicated handler methods for input events which get called by the input system when the player performs an input action.

First, you define all your inputs in an Input Action asset. These assets serve basically the same role as the old Input Manager panel in the Project Settings, but they are a lot more advanced and flexible. Among other things, they again allow you to define semantic input actions like "Fire1" and map multiple physical inputs to them.

Then you assign handler methods for those actions in your scripts using either the PlayerInput component or the auto-generated C# class.
> 1 votes

# Answer
Using `DefaultInputActions` can be one way to help transition your code. For example, the following could replace your class:

```
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class ExampleClass : MonoBehaviour
{
    public GameObject projectile;

    private float nextFire = 0.5F;
    private GameObject newProjectile;

    private DefaultInputActions defaultInput;

    private void Start()
    {
        defaultInput = new DefaultInputActions();
        defaultInput.Player.Fire.performed += c => StartCoroutine(OnInputFire());
        defaultInput.Player.Fire.canceled += c => StopAllCoroutines(); // ensure a single coroutine is running even if fire is re-performed within nextFire seconds
        defaultInput.Enable();
    }

    private IEnumerator OnInputFire()
    {
        while (defaultInput.Player.Fire.IsPressed())
        {
            newProjectile
                = Instantiate(projectile, transform.position, transform.rotation) as GameObject;

            // create code here that animates the newProjectile

            yield return new WaitForSeconds(nextFire);
        }
    }
}

```
> 0 votes

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


# Question
Title: Why is the Unity pixel color read from RenderTexture bigger than 1?
The pixel color component read from the Unity renderTexture is bigger than 1.0 without HDR environment map.

I'm writing a mini program to test the reflectance of Unity PBS. I use six pure white (1,1,1,1) textures to construct a skybox as a GI source. Then I set a plane with Unity standard shader material and camera. In every frame, I change the material arguments (albedo, metallic, smoothness), and get the pixel color at the center of view.

The light source I use is not bigger than 1.0 (pure white skybox, not a HDR texture). So, why is the pixel color (as reflectance) is bigger than 1? I think it supposed to be less than 1.0. The biggest data I get is near to 5. Actually, if I use the color picker to check the color from screen, the color data is never bigger than 1.0.

Here's my code:

// code in OnPostRender()

Texture2D image = new Texture2D(2, 2, TextureFormat.RGBAFloat, false, true);
// only read the center four pixels
image.ReadPixels(new Rect(renderWidth/2, renderHeight/2, 2, 2), 0, 0);

Color a = new Color();
a = image.GetPixel(0, 0);
b = image.GetPixel(1, 0);
c = image.GetPixel(0, 1);
d = image.GetPixel(1, 1);
// average the four pixels to get the exact center color
return (a.r+b.r+c.r+d.r)/4.0f;
```

# Answer
> 0 votes
With GI, every side of the skybox acts as a separate light source. You have 6 lightsources with a strength of 1 each. One of them is behind the object. So measuring a brightness of up to 5.0 is expected.

Your monitor can't display more brightness than 1, so that's what the value you measure with the color picker tool is clamped at.

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


# Question
Title: Why does assigning an empty delegate to this Unity Event Action on construction make it work? (But it is dead/broken without it?)
I am learning about Actions/Events in Unity and just built a system around them which works. However, it seems I just got lucky and I'm not sure why.

Roughly, my class in a simple illustrative form (skipping the deeper logic and just showing one Action) looks like this:

```
public class ClickableElement: VisualElement {
    public event Action setClickedDownAppearance;

    public ClickableElement() {
        setClickedDownAppearance += delegate { }; //EMPTY DELEGATE LINE NEEDED FOR SCRIPT TO WORK
    }

    private void updateClickState() {
        if (mouseDown) {
            setClickedDownAppearance(); //line that throws the error without the above line present
        }
    }
}

```

Then when I create my element it would be something like:

```
ClickableElement testElement = new ClickableElement();
testElement.setClickedDownAppearance += delegate { testElement.style.backgroundColor = new StyleColor(Color.cyan); };

```

The idea is that I can set the parameters for what it should look like or what functions it should run on clicking when I generate the element.

As I said it works fine just like that.

What I don't understand is if I get rid of the line tagged `EMPTY DELEGATE LINE NEEDED FOR SCRIPT TO WORK` the whole thing breaks. It says `Object reference not set to an instance of an object` when I try to run `setClickedDownAppearance();`.

I actually just got completely lucky in building this because I had some simple debug code added to the blank delegates in the constructor. Without that none of this would have worked. But I'm not sure what the issue is since I barely understand these "event Action" things enough to use them.

If I got rid of the line `setClickedDownAppearance += delegate { };` is there some way I could write `public event Action setClickedDownAppearance;` so that it still "exists" and can function?

Thanks for any clarification.

# Answer
Normally you would subscribe an Action with:

```
action += method;

```

and then when you want to call it:

```
action?.Invoke();

```

so the question mark ensures that it will return and not throw an error if nothing is subscribed.
> 1 votes

---
Tags: unity, events, objects, unity-ui
---


# Question
Title: enabling / disabling components from editor, while avoiding "SendMessage" warning
I am creating an editor tool that requires me to enable / disable components and or gameObjects via script while in edit mode. Currently everything that has to execute in edit mode is called from `OnValidate()`

When calling either `gameObject.SetActive(...)` or `component.enabled(...)` from `OnValidate` I get the following warning:

```
SendMessage cannot be called during Awake, CheckConsistency, or OnValidate (Scrample: OnBecameInvisible)
UnityEngine.StackTraceUtility:ExtractStackTrace ()

```

From what I can tell from googling, in particular this thread, this is expected behaviour.

If that is the case, what would be the best way to enable / disable stuff via script when in edit mode?

Thanks

# Answer
The way I got around this was to set a bool in `OnValidate` that is checked in Update. You will need to add the compiler directive `[ExecuteAlways]` in front of the class declaration. This causes the `Update` method to run in the editor.

```
void OnValidate()
{
    if (bInspectorVar == true)
    {
        //set flags for use in Update
        bUpdateFlag1 = true
    }
}

void Update()
{
    if(bUpdateFlag1==true)
    {
        //do instantiation/destroyimmediate here
    }
}

```
> 2 votes

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


# Question
Title: Dealing with Floating Point precision in a Minecraft-like game
As far as I know, you can walk for 30 million meters in either direction in Minecraft to reach the end of the world.
My question is, how does Minecraft handle loss of precision when dealing with player position (especially in multiplayer)?

And how could I implement it?

# Answer
By nature of floating point precision, Minecraft starts to have issues as close as 33.5 million blocks in any direction, where the lighting engine stops working, and at over 1 billion blocks, where villages stop generating correctly. Problems like these led to Minecraft's developers to make the hard limit of 30 million, though this limit was only finalized in 1.8, with early implemenations existing as far as Infdev version 20100313 This isn't any raw technical limit, just an arbitrary one. The actual technical limit is the signed 32-bit integer in Java (±2,147,483,647). Basically, Minecraft's way of reducing errors caused by floating-point precision loss is just making it impossible to go to areas it affects.
> 4 votes

---
Tags: floating-point
---


# Question
Title: How to associate text with each sprite in a list?
I have made a simple script, where I am changing image sprites by button click. I want to give an explanation for these images, so I am wanting to add text components for each sprite.

How to do that?

Here is what I made:

```
public class TutorialMenu : MonoBehaviour
{
    public List<Sprite> spriteCollection = new List<Sprite>();
    public Image original;
    public GameObject okButton;
    public GameObject startButton;

    private int m_spriteIndex = 0;
    private int m_spriteCount = 0;

    private void Start()
    {
        m_spriteCount = spriteCollection.Count;
        original.sprite = spriteCollection[m_spriteIndex];
    }

    public void NewImage()
    {
        m_spriteIndex++;
        if (m_spriteIndex == m_spriteCount)
        {
            m_spriteIndex = m_spriteCount -1;
            okButton.SetActive(false);
            startButton.SetActive(true);
        }
        original.sprite = spriteCollection[m_spriteIndex];
    }
}

```

# Answer
> 2 votes
Something like this? Here we use a serializable struct to bundle together some text information with each sprite in the collection, and a TextMeshProUGUI component to display that text when the sprite is selected.

```
[System.Serializable]
public struct DescribedSprite {
    public Sprite sprite;
    public string description;
}

public List<DescribedSprite> spriteCollection;
public Image original;
public TextMeshProUGUI description;

public GameObject okButton;
public GameObject startButton;

private int m_spriteIndex = 0;

private void Start() {
    SelectSprite(m_spriteIndex);
}

public void NewImage() {
    if (m_spriteIndex < spriteCollection.Count - 1) {
        SelectSprite(m_spriteIndex + 1);
    } else {
        okButton.SetActive(false);
        startButton.SetActive(true);
    }
}

public void SelectSprite(int index) {
    m_spriteIndex = index;
    original.sprite = spriteCollection[index].sprite;
    description.text = spriteCollection[index].description;
}

```

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


# Question
Title: How do I expose a field of an abstract type to the Inspector?
I have a class hierarchy with an abstract parent class.

I would like to have a field of this type exposed to the inspector but it appears to not display.

This test code:

```
[Serializable]
public abstract class AbstractClass
{
    public string testField;

    public AbstractClass(string testValue)
    {
        testField = testValue;
    }
}

[Serializable]
public class ConcreteClass : AbstractClass
{
    public ConcreteClass(string testValue) : base(testValue)
    {
    }
}

public class MonoBehaviourClass : MonoBehaviour
{
    public AbstractClass abstractClass = new ConcreteClass("abstract");
    public ConcreteClass concreteClass = new ConcreteClass("concrete");
}

```

Produces this result:

As you can see the field for the abstract class is missing.

How can I expose a field of an abstract type to the inspector?

# Answer
> 4 votes
It's possible natively since 2019.3 release via `[SerializeReference]` attribute.
Unity's SerializeReference documentation.

# Answer
> 2 votes
The answer is that you can not, Unity uses reflection to find fields to show and the fields shown are the public fields of serializable classes and private fileds with SerializedField attribute (inherited fileds included) but not from abstract classes.

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


# Question
Title: Basis of Estimate (BOE) for Freelance Game Developers
First off I wanted to apologize if this isn't the right place to post this; I wasn't sure where else to go. I plan to cross-post this question to the Game Maker forums since that's the engine the game will be run off of.

My problem:

I'm looking for the amount of hours it would take and at what rate two mid-level developers would charge to code a game with the following requirements, at about 5 hours in length. Note, the definition of 'mid-level developer' in this context would be someone with 3-5 years of experience. Obviously I know that the answer to this varies widely across the industry, but I'm looking for more of a general average, if possible. The reason I'm trying to find this information is because I'm developing a project proposal and my potential investors want to know what the estimated cost/schedule look like.

About the project:

This project is a 2D action platformer with similar mechanics to the games "Hollow Knight" and "Dead Cells".

We would like to take generic mechanics like those found in Hollow Knight such as dashes, jumps, and other shooting and melee mechanics and combine them with basic follower mechanics (i.e. one sprite follows behind the other without getting stuck, and in the event it does get stuck has a method for getting unstuck), camera perspective changes (from side scrolling to top down and vice versa), static image cut scene triggers, and a light RPG customization system to allow players to focus on melee or shooting customization paths depending on their preferences.

What I've tried:

I've tried scouring the internet for a possible answer to this, but I can't find anything since average salaries and programmers' abilities to code vary widely. The research I've done suggests mid-level developers would charge anywhere from $21-$40/hr but I have no basis for the amount of hours they'd need to put in to finish the project. This has left me without the ability to figure out how much time and funding I need to set aside and/or raise to allow them to complete the project.

If you have any further questions or concerns, please let me know. Thanks!

Thanks!

# Answer
Your mid-level cost estimate is about right, $30 / hr for most mid-level freelancing game devs over the last few years is normal, but it can be up to $40 / hr or even above depending on country etc. The rate also depends on duration of contract, urgency etc.

As for estimating the time it will take, this problem is the age-old one of waterfall approach to software development. This is where you try to plan everything out up front, the number of hours calculated from said planning, and multiplied by the hourly rate(s) per developer (experience level). That is what you are presently trying to do, even if you don't realise it. There are numerous problems with this, and being a poor fit for most of today's complex software projects, it is a terrible fit for game development especially, given the highly creative / iterative nature of this field.

I suggest getting hold of a book like Agile Game Development With Scrum. Use the expertise in the book, along with paying experienced people for an hour or two here or there (gamedev.net forums, Discord gamedev channels, LinkedIn etc.) to advise you in planning various prototyping phases. These experts should provide a safe, third party perspective on durations and costs *without being involved in the project* \- this assures their views are unbiased.

You can then fund these phases individually, limiting the cost each phase will take. For example, 2 weeks app setup and basic combat, 3 weeks physics, 3 weeks combat refinement, 2 weeks character assets, etc. Your timeframes and categories may differ widely from these. Planning of each successive phase will be based on the results of the last phase, hence "Agile" not "Waterfall".

As you can see, this is more about saying "this is what I'm willing to pay for such and such an amount of progress or discovery". Games development is very much discovery driven.

It is a risk as you cannot be certain that you will get results out of any given prototype phase; the best way to avoid that risk is to hire individuals who can provide solid references, portfolios etc.
> 2 votes

---
Tags: game-design, game-maker, platformer, game-maker-studio-2
---


# Question
Title: How to save Unity HDR renderTexture into a .exr file?
\[Purpose\]:
I need to save the Unity camera view into a .exr file.

\[Error\]:

```
Remapping between formats 74 -> 73 is not supported

```

\[What I've tried\]:
I tried the official solution.

First, I set the `renderTexture` format as `RenderTextureFormat.DefaultHDR` to make sure that it stores HDR data.

```
renderTex = new RenderTexture(renderWidth, renderHeight, 16, RenderTextureFormat.DefaultHDR);

```

Then, I tried to save the `renderTexture` data into a .exr file.

```
Texture2D image = new Texture2D(2, 2, TextureFormat.RGB9e5Float, false, true);
image.ReadPixels(new Rect(renderWidth / 2, renderHeight / 2, 2, 2), 0, 0);
image.Apply();

byte[] bytes = image.EncodeToEXR(Texture2D.EXRFlags.CompressZIP);
File.WriteAllBytes(Application.dataPath + "/HDRs/"+tag+"reflectance.exr", bytes);

```

The error may be related to the `RenderTexture` and `Texture2D` format. I tried to change the `Texture2D` format to `TextureFormat.RGBAFloat`. The error changed:

```
Remapping between formats 74 -> 52 is not supported

```

It seems that the Texture2D format cannot store the HDR `RenderTexture` data, and the original data gets truncated. I've tried all the formats tagged "HDR" as listed in the TextureFormat documentation. None of them work, some of them are unsupported... What can I do to save a HDR camera view into a .exr file?

# Answer
There is a solution: have equivalent formats for both, `ARGBFloat` for the RT and `RGBAFloat` for the texture.

Thanks to @AcidArrow from this Unity forum.
> 1 votes

---
Tags: unity, rendertexture, hdr
---


# Question
Title: Why is Unity applying different settings to an object copied from another?
I am trying to create some turrets, I have my Blender model which I import into Unity just fine. This model is a double turret with identical turret models for top and bottom. I have to apply a -90Z rotation to the model to ensure the turret points the correct direction when aiming at the targets. It imports fine and works as expected.

I then literally copy this file, save it with a different file name and remove a turret. So now it is just a single turret model. I then leave the settings as is change nothing. When I import to Unity, it then applies a -90X and 90Z rotation. I have changed nothing except remove a turret leaving the values the same. Why is it doing this?

# Answer
> 1 votes
Whilst waiting for answers, I figured out that my double turret is contained within an empty game object assuming this is automatic as it is two objects where as the single turret was not. Once I put the single turret into an empty game object I was able to correct the rotation issues with the single turret.

---
Tags: unity, blender, import
---


# Question
Title: gmod adjust player health on func_button
Because I spent so long figuring this out, here is a post for it.

I want to make a relative adjustment to the player who presses a button's health.

I have two brushs, tied to two separate "func\_button" entities and would like to, on pressing one button add a relative amount of health to the player who pressed the button, say +/-15 hitpoints; and on pressing the other button, remove 15 health simmialrly.

Futhermore, i would like to modify the player health by a relative amount when they use a physics prop.

things that dont seem to work

* onButtonPushed !activator AddHealth: AddHealth broken for players
* onButtonPushed !activator RemoveHealth: RemoveHealth broken for players
* onPlayerUse !activator SetHealth: activator is broken

# Answer
What worked for me finally

gmod specific, add a new entity, lets say its target name is "healthpot", of class "lua\_run", give it a code edict value like

```
ACTIVATOR:SetHealth(math.Clamp(ACTIVATOR:Health()+15, 0, ACTIVATOR:GetMaxHealth()))

```

for the heal func\_button, OnButtonPressed, healthpod, RunCode

---

this button can be parented to a physics\_prop, and the code calue can be made to subtract rather than add as needed.
> 0 votes

---
Tags: hammer, garrys-mod
---


# Question
Title: Unity Game - Multiple threads to improve AI bulk computation?
I'm making a chess-like game with an AI that implements minimax algorithm with alpha beta pruning. The AI raw computation is effectively infinite, so I'm forced to limit the depth I traverse, thereby limiting the strength of the AI.

I'm extremely sensitive to the engine speed, as it is unacceptable for the player to have to wait even a few seconds for a move. Hence I must keep the depth pretty low.

If I launch multiple threads, will this effectively increase the speed? My concern is that I can't predict how strong the player's computer will be, so I kind of need to assume they have a weak machine (so the game is playable for everyone). That said, even if they have only 1 core on their entire cpu, there won't be much cost to launching a few extra threads (the overhead of launching \<10 extra threads is frankly minimal). And in the case they have a CPU with 2 or 4 threads, they will go that much faster.

Do most computers have multiple cores that will work well for multiple threads (like, at least 2?)? I'm thinking of using either 1, 2, 4 or 8 threads. Seeking general advice.

Also, is the GPU relevant at all? (I tend only to think # of threads should equal # of cores ... )

# Answer
> 1 votes
The current state-of-the-art for multithreading in Unity is the jobs system using the burst compiler. It not only gives you far more performance than regular C# code for most situations (at the cost of being restricted to a subset of the language), it also gives you multithreading managed by the engine itself. So you can just schedule parallel jobs and let the engine manage the distribution of tasks to CPU threads.

The whole system is unfortunately too complex to explain it from start to finish in a single answer, so I would recommend you to read the documentation I linked above and ask a new question when you run into any roadblocks on your way.

> Do most computers have multiple cores that will work well for multiple threads (like, at least 2?)?

The last single core CPUs made by Intel were the cheapest of the cheapest Celeron CPUs from the Sandy Bridge generation (10 years ago). And that was an outlier: The three generations prior had no single core chips at all. AMD CPUs only got relevant again when they started to outdo Intel in regards to core count.

The first iPhone with a multi-core CPU was the iPhone 6 from 2014.

The landscape of Android devices is too vast to evaluate completely, but multi-core CPUs also seem pretty ubiquitous for several years there too.

So yes, you can safely assume multiple CPU cores nowadays.

# Answer
> -1 votes
You could use a ComputeShader to offload the ai logic to your GPU, which is better in running parallel tasks, like AI pathing and the sorts.

Or just teach your AI chess with unity ml-agents, so that fuzzy logic and neural network make the AI more human and choose the best move that "feels right", and you could just edit the thinking time and have different agents learning for different lengths of time.

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


# Question
Title: How to calculate accelation times and vector to orient a pointmass to a new orientation
I'm trying to design a space game where the user has 2 types of input:

* forward and backwards thrust in the current direction
* change orientation

The game is based on actual physics, for the sake of simplicity we can assume everything is presented as a pointmass.

A pointmass has the following attributes (known by the physics engine):

* position (vector3)
* orientation (quaternion)
* linear\_velocity (vector3)
* angular\_velocity (vector3)
* inverse\_mass (float)
* linear\_forces (vector3)
* angular\_forces (vector3)

Given these values, a user clicks a point in space, and commands the spaceship to orient itself in that orientation. As such, we can ignore: position, linear\_velocity, linear\_forces at that point already. Furthermore we can assume that the maximum angular forces have a set maximum (angular\_forces\_max \>= angular\_forces.length()).

My question is now, what is the fastest way to get to the new orientation, given that we also want to have angular velocity set to 0 when we reach this new orientation.

In my thoughts, given these input variables:

* current orientation: quaternion
* wanted orientation: quaternion
* current angular\_velocity: vector3
* wanted angular\_velocity: vector3 (nilvector)
* maximum angular\_acceleration: float

And as output:

* angular\_acceleration, vector3 (this will determine the forces how to get to the new orientation)
* t1 time in seconds how long we will use the positive angular\_acceleration forces (speeding up)
* t2 time in seconds how long we will use the negative angular\_acceleration forces (slowing down)

I'm having trouble grasping this concept as a whole, I believe we will need to at least translate the quaternion to a vector + angle, so we can at least add 2 * pi to the angle so we can also calculate it while approaching it from the other side. This due to the fact you can't do a 2 * pi rotation with a quaternion and maintain the same quaternion.

---

To give an example how this would work in 2D:

```
w = wanted orientation, angle, in radians
v = wanted angular velocity, in rad/s
w0 = current orientation, angle, in radians
v0 = current angular velocity, in rad/s
a_max = max angular acceleration in rad/(s^2)

w = w0 + v0*t + (a_max/2) * t1_short^2 - (a_max/2) * t2_short^2
v = 0 = v0 + a_max * t1_short - a_max * t2_short
// fill in and substitute the formulas
// store t1_short, t2_short

w + 2*pi = w0 + v0*t + (a_max/2) * t1_long^2 - (a_max/2) * t2_long^2
v = 0 = v0 + a_max * t1_long - a_max * t2_long
// fill in and substitute the formulas
// store t1_long, t2_long

if (t1_short + t2_short) <= (t1_long + t2_long) {
  return (t1_short, t2_short);
} else {
  return (t1_long, t2_long);
}

```

This gives a deterministic manner of calculating t1 and t2 (acceleration time and deceleration time) in 2D, the forces vector is just a singular element vector here \[a\_max\] (`a_max = [a_max].length()`).

My question is pretty straightforward, how can we do this in 3D with matrices, vectors, quaternions?

(should this be instead posted to the physics / math department of stack exchange btw?)

# Answer
> 1 votes
Here's a simple way to handle the case where you have no initial angular velocity. You can transform your start and end quaternions into an angle-axis representation of the desired change in rotation:

```
Quaternion deltaQuat = endQuat * Quaternion.Inverse(startQuat);

float deltaAngle = Math.Acos(deltaQuat.w) * 2.0f;

Vector3 axis = Vector3.Normalize(new Vector3(deltaQuat.x, deltaQuat.y, deltaQuat.z));

```

Now you can work in the 2D plane perpendicular to this rotation axis, applying your existing 2D solution to rotate by `deltaAngle` (let `w0 = 0f`, `w = deltaAngle`).

Your resulting angular acceleration will act along the rotation axis: `axis * a_max` for the accelerating portion and `axis * -a_max` for the decelerating portion.

The problem of how to extent this to work with arbitrary initial/final angular velocities that might lie out of the plane of rotation between the start and end orientation is more complicated, so I might need to take another stab at that after I've had my coffee, unless someone else can beat me to it.

---
Tags: physics, mathematics, rotation, quaternion, rigid-body-dynamics
---


# Question
Title: How to create large Sidescrolling Map in Godot?
I would like to create a 2D Sidescrolling map, like one for a platformer, but for a shooter game.

At first I thought I could just draw a big map based on a tilemap and make the player and the enemies move around in it and just create a camera to follow the player, but now I am concerned Godot will try to render everything outside the camera and waste GPU resources. Is that the case? If so, how can I go about hiding the sprites off screen, would something like this work?:

```
if [$Sprite is outside camera]:
    $Sprite.visible = false

```

# Answer
**Godot will not draw 2D objects out of view.**

So, do not worry about GPU resources.

You can confirm this yourself. With the game running, go to the Debugger panel (you can find it on the bottom of Godot editor), and then the Monitor tab. On the left you will see a list of categories. You are looking for 2D. You should see both Items and Draw Calls reflect the objects that are in view. If there is nothing in view, they will fall to zero.

---

While we are at it, you might also be interested in the profiler. On the same Debugger panel, you will find a Profiler tab. If you enable it, it will show how much time different parts of the game take. Including time dedicated audio, physics, and to execute script functions.

If you are having performance problems, check the Profiler. *You know what they say about premature optimization.*

---

As you may have guessed, enemies outside of view still have a cost: **Their scripts are still executing** (and if they are moving their physics is being computed).

You might or might not want to have them executing. For sake of argument, let us say there are some enemies you want to stop when they are away form the player character.

You can enable or **disable callbacks**:

* `_process` with `set_process`
* `_input` with `set_process_input`
* `_physics_process` with `set_physics_process`

These functions take a `bool` parameter. Pass `true` to enable the callbacks (for example when the player character is nearby), and `false` to disable them (when the player character is away).

And how to know if they are near the player character? Put a large detector `Area2D` around the player character. Then you can use the `"body_entered"` signal to enable them and the `"body_exited"` signal to disable them.

*As alternative to a large detector `Area2D`, you can use `get_world_2D().direct_space_state.intersect_shape`. See `Physics2DDirectSpaceState`.*

---

Yes, that means they still have their scripts and their `_init` and `_ready` will run. And they can also respond to signals. So, some animations, timers and similar might still be ticking.

Again, for the sake of argument, let us say you don't want that. What you need is to **only load enemies near the player character**. That can be with `load` or with Background loading.

If we don't have loaded the instances, that also imply there is nothing for our detector `Area2D` to detect per-se. So we need to modify our approach.

You might be interested in `InstancePlaceholder`. You can create them by adding scene instance to the Scene panel, and the select "Load As Placeholder" from their context menu. However `InstancePlaceholder` don't have a transform, so checking distance is not directly an option.

Let us see… We need something with a position. And ideally something for our detector `Area2D` to detect. We can use another `Area2D` as placeholder!

To the placeholder `Area2D` attach an script with a `func` that instances whatever necessary (e.g. perhaps it has `InstancePlaceholder`s as children, and the `func` calls `replace_by_instance` on them) and you want to either have it remove itself (in which case you want to move the children to siblings first) or disable itself (by setting `monitoring` and `monitorable` to false). Then when we get the `"area_entered"` signal call the that `func`.

As you can imagine these placeholder `Area2D` do not have to represent a single enemy. They can be responsible of triggering the load of multiple enemies. For example, a room full of enemies, that would otherwise be wasting resources being there out of view.

*By the way, take advantage of collision layers and masks on both detector `Area2D` and placeholder `Area2D` so you can filter out any other areas you are not interested in. And, by the way, yes, you can do this with `intersect_shape` too.*
> 2 votes

---
Tags: maps, platformer, godot, side-scroller
---


# Question
Title: How to create custom gravity in unreal engine and only affect specific actors?
I am fairly new to unreal engine and I would like to know how to set custom gravity in a specific point or area instead of down. For example I do not want the gravity pull to be down but more to the center of my level (center plane not center point) and that gravity to only affect specific actors. Other actors will be affected by normal gravity or affected by no gravity at all.

How can I do this? (blueprints or c++)

# Answer
> 4 votes
I know they're planning to un-hardcode Gravity \[Source: I'm a moderator on the official Unreal Engine forums, I know things ;)\] but the best way is to either add force in the direction you want or set the player to "Flying" mode and push him about with Launch character / Add force.

This is the only way without altering source code (Until they un-hard code gravity).

Tl;Dr - Fake it for now, A fix will come eventually!

# Answer
> 2 votes
You can not change the direction of the built-in gravity, it always points to the negative z-axis. You can also not change the gravity for single actors, only globally. But why do you need that, you can always just increase the mass of your actor.

You can easily turn off gravity completely for any actor, just look for "gravity" in the blueprint options of that actor.

# Answer
> 1 votes
I've been drifting through forums looking for what others have done for gravity solution as I'm working on centrifugal gravity in my work.

The first to counter global Z gravity to have the effect of a null gravity environment is simply add the game's gravity * delta time to Z movement while inside the zone. Then apply your own acceleration for the gravity you want.

In your situation you want to apply acceleration in the direction of your centre point.

At the moment I'm still trying to figure out how apply of Coriolis effect.

This is basic theory but it is all maths.

Hope it helps.

# Answer
> 1 votes
This topic is old but I think this video may help future visitors. What you are trying to do is possible: it's called dynamic gravity. Check this video https://www.youtube.com/watch?v=kkq5En9sG8Y

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


title: Unity: detect animation's end

text:
# Question
Title: Unity: detect animation's end
I need a way to detect if animation's clip finished playing and then execute a certain code. Here's some script, that I wrote (called in Update):

```
    if (Input.GetButtonDown ("Fire1") && pc_atttacking == false && PlayerStats.staminaCurrent != 0) {
        pc_atttacking = true;
        pc_anim.SetBool("attack", true);
    }

    if (pc_anim.GetCurrentAnimatorStateInfo (0).IsName ("attack")) {
        pc_atttacking = false;
        pc_anim.SetBool("attack", false);
    }

```

But it doesn't work as I want; it executes second code too early - when "attack" animation is at slightly more than half of playing position. I want to execute it when "attack" animation is at last frame.

# Answer
I usually prefer to use Animation Events for this, so that there's not a check hitting every Update when it's rarely actually needed. You could even make a generic alert system and pass in arguments to handle different animations ending or other events.

In this example, AlertObservers is in a component on the animated object.

```
    public void AlertObservers(string message)
    {
        if (message.Equals("AttackAnimationEnded"))
        {
            pc_attacking = false;
            pc_anim.SetBool("attack", false);
            // Do other things based on an attack ending.
        }
    }

```
> 22 votes

# Answer
As I was very often in the position to check for an animation when it starts or ends, I came up with simple generic solution. It will dispatch animation start and animation end events for any `AnimationClip` controlled by the `Animator`.

```
using UnityEngine;
using UnityEngine.Events;

[System.Serializable]
public class UnityAnimationEvent : UnityEvent<string>{};
[RequireComponent(typeof(Animator))]
public class AnimationEventDispatcher : MonoBehaviour
{
    public UnityAnimationEvent OnAnimationStart;
    public UnityAnimationEvent OnAnimationComplete;

    Animator animator;

    void Awake()
    {
        animator = GetComponent<Animator>();
        for(int i=0; i<animator.runtimeAnimatorController.animationClips.Length; i++)
        {
            AnimationClip clip = animator.runtimeAnimatorController.animationClips[i];

            AnimationEvent animationStartEvent = new AnimationEvent();
            animationStartEvent.time = 0;
            animationStartEvent.functionName = "AnimationStartHandler";
            animationStartEvent.stringParameter = clip.name;

            AnimationEvent animationEndEvent = new AnimationEvent();
            animationEndEvent.time = clip.length;
            animationEndEvent.functionName = "AnimationCompleteHandler";
            animationEndEvent.stringParameter = clip.name;

            clip.AddEvent(animationStartEvent);
            clip.AddEvent(animationEndEvent);
        }
    }

    public void AnimationStartHandler(string name)
    {
        Debug.Log($"{name} animation start.");
        OnAnimationStart?.Invoke(name);
    }
    public void AnimationCompleteHandler(string name)
    {
        Debug.Log($"{name} animation complete.");
        OnAnimationComplete?.Invoke(name);
    }
}

```
> 13 votes

# Answer
You can check if the animation is complete by looking at the normalizedTime property of the Animator's AnimatorStateInfo:

```
if(pc_anim.GetCurrentAnimatorStateInfo(0).IsName("attack") &&
   pc_anim.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1.0f)
{
    pc_atttacking = false;
    pc_anim.SetBool("attack", false);
}

```
> 9 votes

# Answer
Well, on the other hand sometimes `Coroutines` would be just like a gift of God for you.

You can use it in more good way.

```
void Update()
{
    if (Input.GetButtonDown ("Fire1") && pc_atttacking == false && PlayerStats.staminaCurrent != 0) {
        pc_atttacking = true;
        pc_anim.SetBool("attack", true);
        StartCoroutine("OnCompleteAttackAnimation");
    }
}

IEnumerator OnCompleteAttackAnimation()
{
    while(pc_anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f)
        yield return null;

    // TODO: Do something when animation did complete
}

```
> 4 votes

# Answer
Use StateMachineBehavior, there's `OnStateExit`

```
override public void OnStateExit (Animator animator,
                                  AnimatorStateInfo stateInfo,
                                  int layerIndex)
{
    if(stateInfo.IsName("attack")) return;
    pc_atttacking = false;
    pc_anim.SetBool("attack", false);
}

```

Create class (a new component) that inherit `StateMachineBehaviour` with above code, add the component to the gameobject that has the animation.
> 4 votes

# Answer
I normally use Animation Event Handlers

```
public Animator animator;
public AnimationClip AttackedAnimationClip;

private void Awake()
{
    AttackedAnimationClip.AddEvent(new AnimationEvent()
    {
        time = AttackedAnimationClip.length,
        functionName = "OnCompletedAttackedAnimation"
    });
}

public void OnAttacked()
{
    // this is initiated first
    animator.SetBool("isAttacked", true);
}

public void OnCompletedAttackedAnimation(string message)
{
    // called on completed animation
    animator.SetBool("isAttacked", false);
}

```
> 1 votes

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


# Question
Title: How can I give the object the shape I want?
I want to fit the net behind the goal but I don't know how to shape the net object? Example in the picture below (how can I give the shape I want to the black drawn place?);

# Answer
I guess that's Unity.

Unity has a tool called **ProBuilder** that allows you to do basic modeling things. This tool has an option called *Probuilderize*, which basically converts meshes into editable models through ProBuilder. I've never used this option so I can't talk much about it, however I know it's there and I know it does that.

This is a simple task, so I don't see why not take advantage of what you have on hand. However, I would recommend solving these types of problems in dedicated software, such as Blender. But that is already out of the scope of this answer.
> 1 votes

---
Tags: unity
---


# Question
Title: Accessing DualShock 4 motion sensor in Windows (ideally Unity)
I'm trying to use a DualShock 4's IMU as a motion controller in Unity, under Windows 7.

So far I've tried:

* **DS4Windows** (1.5.11): reads motion sensor data, but does not expose them to Unity as axes unless I map them to the left & right sticks. This is not enough since I lose use of the sticks, I can only fit 4 of the 6 channels of data, and the values coming through are clipped into a narrow range.
* **Motioninjoy** (0.7.1001): does not appear to detect the DS4 as a controller (latest docs refer only to DS3 and prior)
* **GlovePIE** (0.43): after following instructions for using the DualShock 3 with LibUSB-Win32 (a long shot), SixAxis properties are all blank.

In the past I've used external programs like GlovePIE to capture Wii remote motion sensor data and pass it to Unity via OSC messages, so I'd be open to an approach like this if I can't get Unity to read the controller's sensors directly through its Input system.

Anyone had luck with this?

# Answer
I've found a workable approach. I grabbed the DS4Tool source and copied the bits I needed into my Unity project so I could read the reports from the device directly.

(That's the **NativeMethods** class to interface with Kernel32.dll, the device enumeration from **HidDevices**, and reading the report from the **HidDevice** class. I cut out the rest to keep things as simple as possible - I've just got a thread polling for new data as fast as it can.)

This guide told me where to find the motion sensor data within the 64-byte report. A little empirical testing and it looks like this gets the data into gs and radians/sec:

```
accel = new Vector3(
            System.BitConverter.ToInt16(_inputBuffer, 19),
            System.BitConverter.ToInt16(_inputBuffer, 21),
            System.BitConverter.ToInt16(_inputBuffer, 23)
            )/8192f;

gyro = new Vector3(
            System.BitConverter.ToInt16(_inputBuffer, 13),
            System.BitConverter.ToInt16(_inputBuffer, 15),
            System.BitConverter.ToInt16(_inputBuffer, 17)
            )/1024f;

```

It's a right-handed coordinate system with x+ right, y+ up, and z+ pointing toward the player.

Fetching the data this way doesn't interfere with Unity's InputManager, which will still pick up the buttons & sticks as expected, without needing to download non-standard drivers or run extra software in the background.

---

## Update: Wireless (Bluetooth)

I found two problems extending this to work wirelessly (and two solutions):

1. **DualShock 4s don't like to stay paired to Windows** (prior to Windows 8). This silly procedure seems to work around that on Windows 7.
2. **No motion sensor data when connected via Bluetooth**. I discovered you need to write an Output Report to the device (see HidDevice for the method and DS4Device for the magic numbers) in order to coax it into sending motion data. Once this is done, the input reports you get back will be shifted by 2 bytes.
> 7 votes

# Answer
I've created a solution to this myself. It's called JoyShockLibrary, and reads from DualShock 4, Switch Pro Controller, and Joy-Cons. It's open source, MIT license, and works well, although Bluetooth support for the DS4 was only added recently and is still improving.

It's used in JoyShockMapper, which is an input-mapping tool, and JoyShockOverlay, which isn't public yet, but you can see it in action here (Gfycat) and here (YouTube).

JoyShockLibrary complements XInput nicely -- besides its IMU reports, it looks very similar to XInput -- so you can cover all current gen console controllers easily, with the benefit of gyro and accelerometer input from those that support it.

It's pretty easy to use with Unity, though I should put up a .cs file to make it easier for others.
> 3 votes

# Answer
Those appear to all be tools that wrap DirectInput to XInput. Unity has support for DirectInput and so you should be looking at getting it work without 3rd party tools. The key is if the IMU is mapped to anything in DirectInput and if it is already in a usable state. If not, you might have to write your own DirectInput handler to deal with the raw data.

You can thank the xbox for all these controller woes.
> 0 votes

# Answer
These days, I strongly recommend SDL2 for the job. As of last year it can read motion sensors for DualShock 4, DualSense, Switch Pro Controller, and Switch Joy-Cons and converts them all to the same coordinate space and units. It's cross-platform, open source, MIT license, unifies the layout of a ridiculous number of different gamepads, and while it can do a lot of unrelated things, too, it can be initialised as a controller-only library.

Use these functions to see if the connected controller has supported motion sensors:

```
SDL_GameControllerHasSensor()
SDL_GameControllerSetSensorEnabled()
SDL_GameControllerGetSensorData()

```
> 0 votes

---
Tags: unity, windows, gamepad, motion-control, playstation4
---