# Question
Title: How do you de/serialize a monobehaviour class?
It seems `JsonUtility.FromJson` does not work for MonoBehaviour classes (and I can't get Newtonsoft to parse strings to Vector3s)

Suppose you have a MonoBehaviour class like this (so that the values can be easily specified in inspector in editor)

```

public class PropertyClass:MonoBehaviour{
  public Vector3 location;

  public string name;
}

```

Suppose you have json data downloaded as a string called `text`, that you try to convert to `PropertyClass[]` format via using an JSONHelper around `JSONUtility.FromJson(text);`

How do you have it autopopulate?

If you specify a FromJsonOverwrite solution - how do you have that work with JSONHelper?

using System;
using UnityEngine;
using System.Collections;

public static class JSONHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = UnityEngine.JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return UnityEngine.JsonUtility.ToJson(wrapper);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}
```
</code></pre>

# Answer
> 1 votes
Typically, **you don't**.

`MonoBehaviour` is not (de)serializable by `JsonUtility.FromJson`. Components only make sense when attached to `GameObject`s, so you can't serialize a collection of them then deserialize them into free-floating blobs unlinked from your scene and game object hierarchy.

This behaviour is described in the documentation, so be sure to consult the docs for the methods you're using:

> Internally, this method uses the Unity serializer; therefore the type you are creating must be supported by the serializer. **It must be a plain class/struct marked with the Serializable attribute**. Fields of the object must have types supported by the serializer. Fields that have unsupported types, as well as private fields or fields marked with the NonSerialized attribute, will be ignored.
>
> **Only plain classes and structures are supported**; classes derived from `UnityEngine.Object` (such as **`MonoBehaviour`** or `ScriptableObject`) **are not**.

JsonUtility.FromJsonOverwrite, however, *will* give you the ability to deserialize JSON into the serialized fields of an *existing* MonoBehaviour or ScriptableObject instance. So you can't load *new* scene content or a whole game object hierarchy this way, but you can update the properties of an object or collection of objects that already exists, while keeping their existing relationships to your various objects/scene graph intact.

Another strategy you can use is to give yourself a little serializable class or struct to hold your data, then pack that into a `MonoBehaviour`.

```
[System.Serializable]
public class PropertyClassData {
    public Vector3 location;
    public string name;
}

public class PropertyClass : MonoBehaviour {
    public PropertyClassData data;
}

```

Now you can use JSON, XML, BinaryWriters, etc. to serialize and deserialize collections of `PropertyClassData`, which is just a "Plain Old Data Structure" with no extra methods or entanglements in your scene hierarchy that need to be navigated. That keeps the (de)serialization simple and efficient, and lets you use the `FromJson` method without a pre-existing object to overwrite into. This also removes your dependency on the built-inUnity serializer, so you're free to drop in other solutions if you need different formats than it supports

Once you have those values, you can choose to construct `GameObject`s in your scene or Assets folder with `PropertyClass` components to hold the data items. Or you can read the `data` members from a collection of existing components into a serializable collection.

The trick here is to only ask to serialize the data payload you actually want, not all the complexity that the full `MonoBehaviour` type brings along for the ride.

---
Tags: unity, serialization
---


title: Taking moving colliders into account

text:
# Question
Title: Taking moving colliders into account
I am currently in the process of creating my first game (as a hobbyist) and I have an issue with Unitys Rigidbody.

The objective of the game is to steer a ball in a 2-d-ish environment (3-d rigidbody that is constrained to two dimensions) by moving (e.g. rotating) the platforms the ball touches. Basically this works kind of well, but movent after hitting a platform "feels" a bit off. When the platform rotates, the ball kind of slides off instead of bouncing, supposedly because the movement of the platform is not taken into account when the ball hits it.

I set the types of the mesh colliders of the platforms to convex and non-trigger. The rigidbody calculation is *"continuous dynamic"*. The platform colliders are pill-shaped (basically cylinders with demi-sphere on both ends).

Is there any built in way to take the platforms dynamics into account with the rigidbody or will I have to roll my own physics implementations? (It feels that this would be quite difficult, since I'd have to calculate the speed of the platform at the point of the collision and somehow take this into account!?)

# Answer
> 2 votes
Fortunately, the comment

> How are you moving your platforms at present?

gave me the hint what I was doing wrong: I used the transform component of my platforms for rotation, which was abviously wrong, because

> when you move an object with its Transform component, that's treated as a teleportation by the physics engine. It instantaneously switches to a new position/angle, rather than moving there, so there's no linear or angular velocity behind the motion for it to impart on objects it hits along the way\[.\]

The correct way of doing this, would not be using the transform component of the platform to rotate it, but adding a rigidbody component. This way I was able to add a torque to the rigidbody, which allows Unity to get the physics right and calculate bounces correctly.

In order to prevent the platform drifting away and exposing other unwanted behavior, I constrained the translation of the rigidbody in all 3 dimensions and the rotation in the x- and y-dimension. Furthermore I disabled gravity (which should be unnecessary with the constrained translation, but to be sure ...) and set the rigidbody to *"continuous dynamic"*.

# Answer
> 0 votes
What appears to be happening (correct me if I am wrong) is the loss of energy during a collision. This would be a possible reason why the ball was not being given adequate momentum after the bounce.

I encountered the same issue while creating bouncy bullets for a 2D Metroidvania for Ludum Dare 47.

One quick fix I found was to add a **Physics Material** to the bouncing object and set its **Bounciness attribute to 1** while keeping the Friction at 0. Your game looks like it depends on the torque provided by the rotating platforms to project the ball. In that case, you could try playing around with the bounciness to adjust the difficulty and skill required to master the mechanics. Good luck with your project.

---
Tags: unity, rigid-body-dynamics
---


# Question
Title: How do I calculate the x,y of the rectangle after rotating?
I'm using SDL2. I want to draw a textured rectangle and I'd like it rotated so I'm using SDL\_RenderCopyEx. However SDL2 doesn't give me the option of repeating texture so I need to manually do it myself. The problem is I have no idea how to do the math.

My texture us 20x20, so I make the rects 20x20, I chosen a fixed angle of 45, my rotation point is `10,5` which appears to make the left middle of the rect the point it rotates from. I can see the two rects aren't touching if the second rect is (firstX+15,firstY+15). However if I change one of them to 14 they touch and it looks solid

I don't understand how to find the numbers. I'm finding the angle but doing

```
double angle = atan2(mouseX - x, mouseY - y) * 180 / PI;

```

Making the second rect relative to the first by `+15,+14` only works if it's a 45 deg angle but is complete wrong for other angles.

How do I figure out the x,y the subsequent rect based on the angle?

# Answer
The unit vector along the x+ axis `(x, y) = (1, 0)`, after rotation counter-clockwise by a given `angle`, changes to a new unit vector `( cos(angle), sin(angle) )`

Similarly, the unit vector along the y+ axis `(0, 1)` rotates to `( -sin(angle), cos(angle) )`

Multiplying these values by 20 gives you the displacement between your 20x20 tiles after rotation.

So at 45 degrees you get a shift of about (14.14214, 14.14214) between tiles in the same row, and (-14.14214, 14.14214) between tiles in the same column.

At 30 degrees, it's (17.32051, 10) and (-10, 17.32051), etc.
> 1 votes

---
Tags: sdl2, rotate
---


title: can't instantiate different objects

text:
# Question
Title: can't instantiate different objects
I'm trying to instantiate different prefabs at once. But couldn't figure out how. I tried to use Random.Range method but didn't worked for me. It instantiates only one of the prefabs. I want it to instantiate all of the prefabs.

# Answer
> -1 votes
You haven't explained nearly enough about what you're trying to do, but here are some examples:

```
public List<GameObject> prefabs;

//Instantiate one of each prefab
public void InstantiateAll() {
    foreach (var prefab in prefabs) {
        Instantiate(prefab);
    }
}

//Create the given number of instances from random prefabs
public void InstantiateRandom(int count) {
    for (int i = 0; i < count; i++) {
        int index = UnityEngine.Random.Range(0, prefabs.Count);
        var prefab = prefabs[index];
        Instantiate(prefab);
    }
}

```

---
Tags: unity, gameobject, prefabs
---


# Question
Title: Architecture for scaling a large 2D MMORPG world vs player load
I want to make 2D MMORPG in a post-apocalyptic world.

I would like to make the game world seamless and big, with big battles for the players. Something similar is in Eve Online (in 3D), but I do not like the fact that during major battles time in EVE slows down. All this due to the limitations of the game. I thought, what if we come up with a new architecture to handle large player numbers in one region without slowing down? I had the following idea:

**Server cluster Quadtree**

The whole world is one big quadtree. And each quadrant of the tree is processed by a separate server.

If a big battle is coming, the quadtree subdivides, and the number of servers in the battle region increases automatically.

Can this strategy work at all?

How do you handle conflicts in this world?

I think that everything will be built using ECS (EnTT). Each server should have a connection to the servers nearby tell them information if, for example, I shoot a player while I am in server 1 and they are in server 2.

Perhaps you see some other problems with the implementation of such an architecture?

# Answer
> Can this strategy work at all?

Yes.

---

Thus, I will answer a different but related question: **How can we build up to that strategy?**

I will cover most of what you ask. Except one detail: ECS. Why? it is a detail.

---

**Base architecture**

Go back to the original conception of object oriented programming. The way Alan Key expressed about it. Objects are like little computers, with memory, processing, input and output. These objects exchange messages. *Alan Kay was thinking of cells, due to his background in biology.*

Let us start there. Make every node in your quad tree an object. *An object that would make Alan Kay proud. So no getters and setters, and no query methods. Tell, don't ask.*

We will later make this into a networked solution. To make that transition easier, make the communication between these objects async.

For async the following is the easy route: forbid returning anything from methods. That way, there is no waiting for anything (no need for promise objects or similar). If an object needs to tell another something it will call a method on it send a message. And if there were something to return we use the same mechanism.

Of course, to send a message you need the objects to be aware of each other. You cannot have pointers/references because that does not work across the network. Instead, have a service object that will allow communication.

The communication service object will have methods to send messages between objects. Also methods to callbacks. The communication service object will execute the callbacks when it receives a message. Inject the communication service object on construction. You will also need a way to address objects, so they can say to which other object to send the message.

Each server will run ticks, at some predetermined frequency. That gives the server a time budget. It has to deal with all the messages before the next tick comes. The messages can arrive at any moment, so buffer them. Each tick, the server swaps the buffer and deals with the messages.

---

**The division problem**

Each object will decide when to divide. To divide, the object has to:

* Create the new objects
* Send messages to the new objects to set them to the same state
* Sends messages to the neighbors to notify them about the change
* Die

To create the new objects, the object will need a factory. Which, again, you can inject on construction. *No, don't call new. Using a factory will make it easy to replace this later.*

Sending messages takes time from the time budget. Thus, this time budget is a good measure to know when to divide. Let us say that when the time used to process the messages reaches 50% the time budget, you divide. *You will later test it in practice if that good, tweak the percentage as needed. Or even change the metric. For example, if you know how much time it takes to deal with each entity, you can compute how many entities are too much.*

There might be messages that arrived while the object was sending messages. Deal with any messages left on the buffer by relaying them to the new object. Then the object can die.

---

**The joining problem**

Joining has a different challenge: objects need to agree to join.

I believe it is necessary for nodes to know who are their siblings. So they can notify them when they want to join, and when they no longer want to join. Each object would keep track of whether or not its siblings want to join, and if they all agree they can migrate to a single object that remplaces them.

This adds to the factory the constrain that they must all get the same object, so they actually join, instead of creating four versions of the parent. Given that we will later distribute them over the network, you would want to put that coordination on a central server. *Which would the same that does load balance.*

You may find the situation where one object believe all the siblings agree… Then it goes on to request the parent object… Meanwhile, one of the siblings decides it no longer wants to join.

To avoid that, each of the objects will request the new parent, then notify to the siblings that they requested it. If an object gets notified that the parent was requested, it will migrate to it.

---

**Milestones**

First milestone: the architecture described above, single process, single thread. Make sure it works OK, fix any problems. If the system does not work under this conditions, it will not work later.

Second milestone: single process, each object runs on a thread. See that threading does not introduce bugs, fix any.

Third milestone: single process, each object on a thread, use sockets for communication. Each thread listens to a different port. Make sure that those messages are sending get serialized and deserialized. Also, you need to solve how you are going to address/identify the objects.

Fourth milestone: add a facade process. It serves as a layer between the client and the servers, over the network. It relays input from the client to the corresponding server. Also it queries the server to tell the client what to show. The servers will have to notify the facade when they divide.

Fifth milestone: multi process. Each process runs a single object, they all talk over the network. Do you remember that factory to create objects? It has to spawn processes now. You need to update the facade.

*You might also want to synchronize ticks. NTP comes to mind.*

Sixth milestone: works across many machines. Thus, if you had "localhost" hard-coded, fix that. You got to solve how to start a server process on another machine.

Have a instance manager service running on each machine, listening to a fixed port. The instance manager service returns how many server processes it is running. It is able to spawn new processes on that machine. You could discover these services on the local network with a broadcast. You could do simple load balance by spawning in the machine with less process servers. It also makes it easy to add machines. *I guess the idea of having servers sleep when they have no activity is also useful.*

You will still have the challenge of removing machines. Start with a solution to migrate a server. It works like division, except it only creates one the new object, on a different machine. Migrate all servers on a machine, and then you can shutdown the machine.

---

As you are aware, it takes less to come up with this plan than to actually try it. I don't know what I don't know. We don't expect the unexpected, but unexpected things happens. Thus, I guess you will run into some problems along the way. Make those their own questions when you get there. If you find a better way, consider sharing what you learned so it can help others.
> 3 votes

---
Tags: 2d, networking, mmo, client-server, scalability
---


# Question
Title: Make UI draggable from clicked vertices of UI
I am able to make my UI panel draggable. Here is the script, it will be helpful:

```
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UIElementDragger : EventTrigger
{

    private bool dragging;

    public void Update()
    {
        if (dragging)
        {
            transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        }
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        dragging = true;
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        dragging = false;
    }
}

```

It is working fine but with one issue. Each time I click to drag the panel, my UI panel drag from the center (i have custom panel anchor). Is there any way available to move it with the clicked position of UI? I mean it should be draggable from where i have clicked. Certainly, problem lies in this line

```
transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

```

transform.position need to change to clicked position of object?

https://www.youtube.com/watch?v=gayEHaol4Lc

# Answer
This is pretty trivial:

```
private bool dragging;
public Vector2 dragOffset;// = new Vector2(5,5); // Store the offset of the center/pivot from the clicked position.

public void Update()
{
    if (dragging)
    {
        transform.position = (Vector2)Input.mousePosition
                           + dragOffset; // Add the offset when dragging to get the center point.
    }
}

public override void OnPointerDown(PointerEventData eventData)
{

    dragging = true;

    // Compute the offset from the cursor position to the object's center/pivot.
    dragOffset = (Vector2)transform.position - (Vector2)Input.mousePosition;
}

public override void OnPointerUp(PointerEventData eventData)
{
    dragging = false;
}

```
> 1 votes

# Answer
Here is another version of dragging and keeping click position offset.

This one uses delta value of eventData, so you'll have to also take Canvas scaleFactor into calculation.

Note, this one works with both:

* Screen Space - Overlay Canvas
* Screen Space - Camera Canvas

This solution doesn't work with World Space Canvas (for VR/AR?), for such solution you'll have to use (maybe) local coordinates of Canvas RectTransform and RectTransformUtility.ScreenPointToLocalPointInRectangle to get your Canvas positions.

```
public class DragItem : MonoBehaviour, IDragHandler
{
    Canvas canvas;

    private void Awake()
    {
        canvas = GetComponentInParent<Canvas>();
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.localPosition += (Vector3)eventData.delta / canvas.scaleFactor;
    }
}

```
> 0 votes

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


# Question
Title: Detect Mouse Enter on An oval shape image in unity
I have an image that is attached to a panel and I want to detect On Pointer Enter and exit. The event is working fine but currently, it is working on the full image while I want to detect this event on an inner oval shape. Actual the remaing are of the image is transparent.

# Answer
> 1 votes
Assuming you have the bounding rectangle that wraps the ellipse. There is a transformation from that to a circle. You can create the transformation that maps that rectangle to a square.

You can use it to transform the position of the mouse pointer, and then check the distance to the center and compare with the radius (the same as the radius of the square you mapped to), and that will tell you if the mouse pointer is in the ellipse or not.

---

I have an implementation of an ellipse touch joystick in GDScript. The following is based on that.

We will need a rectangle defined in "global coordinates" (meaning the same coordinates of the mouse pointer). That rectangle is the rectangle that bounds the ellipse.

Let us say that:

* `size` is a vector with the `width` and `height` of the rectangle.
* `position` is a vector with the `left` and `top` of the rectangle.

We define `offset` as `size * 0.5`. And `center` as `position + offset`.

Then we convert from "global coordinates" to "local coordinates" (meaning coordinates with `center = (0,0)`, and `center + offset = (1,1)`, meaning that the rectangle goes from `(-1,-1) to (1,1)`) like this (GDScript):

```
func global_to_local(global_position: Vector2):
    return (global_position - center) / offset;

```

Once we have the "local coordinates", just checking the length of the vector will do.

---

This is my interpretation of `global_to_local` in C#:

```
Vector2 GlobalToLocal(Vector2 globalPosition)
{
    var diff = globalPosition - center;
    return new Vector2(diff.x / offset.x, diff.y / offset.y);
}

```

Check `GlobalToLocal(mousePosition).magnitude <= 1.0f`.

---

I suppose another way to go about it is `GetComponent<Image>().sprite.texture.GetPixel(x,y).a > 0.0f`. Which would be getting the pixel color and checking if it is not fully transparent. I don't know how to about the transformation to get the right coordinates to query the texture. I suppose it is similar to what I describe above, except mapped to the dimensions of the texture.

Mapping `(-1,-1)` to `(0,0)` and `(1,1)` to `(w,h)` is

```
return new Vector2((p.x + 1.0) * 0.5 * w, (p.y + 1.0) * 0.5 * h);

```

Thus, doing the transformation I described earlier (except for the rectangle of the panel instead of the rectangle of the ellipse) and then this transformation should give the coordinates for `GetPixel`.

# Answer
> 1 votes
By far the easiest solution would be setting the Image.alphaHitTestMinimumThreshold to anything other then 0. This is a property, so you can't set it in the inspector. Also note that you need to set the Sprite import settings correctly. In my test I had to set the following but there might be others, so if anyone finds any other that need to be set, please comment on this answer...

1. Read/write Enabled (Unity will throw an error if you don't do this)
2. Mesh type set to full rect (In my test it didn't follow the transparent edge correctly when set to tight)

Example code would be:

```
[RequireComponent(typeof(Image))]
public class Example : MonoBehaviour
{
    private void Start()
    {
        GetComponent<Image>().alphaHitTestMinimumThreshold = 0.5f;
    }
}

```

Where 0.5f is hardcoded in this example, but could ofcourse be set to your needs.

If you need a more sophisticated way of determining which parts are clickable and which parts aren't, you could also implement ICanvasRaycastFilter with your own custom logic.

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


title: Corrupt Save File Problem Csharp Opentk

text:
# Question
Title: Corrupt Save File Problem Csharp Opentk
I am trying to save player's objects but my loaded result is corrupt and placed in weird shapes like 3D arrows. Weirdly enough when terrain is saved, the terrain is fine but objects added later cause the problem. I am using OpenTK for OpenGL.

What I expect:

What I get:

The file seems to contain some repeated parts? Here is a part of the (large) file I end up with:

```
(0; 0; 0),(0; 0; 0),(0; 0; 1),(0; 1; 0),(1; 0; 0),(0; 0; 2),(0; 2; 0),(2; 0; 0),(0; 0; 0)

```

Here is my loading code:

```
void MapLoad(string filelocation)
{
    string[] map_;
    string line = File.ReadAllText(filelocation);//
    map_ = line.Split(new char[] { ',', ';', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

for (int xj = 0; xj < line.Split(',').Length; xj += 3)
        {
            // Here xj is an index of a X coordinate, xj + 1 is an index of a Y coordinate, xj + 2 is an index of a Z coordinate
//copied pasted for suring answer will work
         block_file.Add(new Vector3(Int32.Parse(map_[xj]), Int32.Parse(map_[xj + 1]), Int32.Parse(map_[xj + 2])));
        }

}

```

The `Vector3` is from OpenTK.

Here is my writing code:

```
if(key.KeyCode == Keys.F7)
{
    File.WriteAllText("usermap.txt", String.Join(",",block_file));//new char[] { ',', ';', '(', ')'
}

```

# Answer
Your indexing is broken.

```
for (int xj = 0; xj < line.Split(',').Length - 2; xj++)

```

Inside the loop you are accessing `xj`, `xj + 1` and `xj + 2`. Currently then your next iteration will use `xj + 1`, `xj + 2` and `xj + 3`. You didn't include how you write the save file, but I assume there is a similar issue there as you seem to write vector components into wrong places.

Instead, you want to increment the loop counter with 3 each time, so that instead of reading the same values 3 times, you only read them once and then move onto the next element. So `xj += 3` is what your loop increment should be.

```
for (int xj = 0; xj < map_.Length; xj += 3)
{
    // Here xj is an index of a X coordinate, xj + 1 is an index of a Y coordinate, xj + 2 is an index of a Z coordinate
}

```

Also note that you want to iterate until `map_.Length`, since this is what contains your coordinate values, not `line.Split(",").Length`.
> 0 votes

---
Tags: c#, opengl, maps, opentk
---


# Question
Title: How to fix issues with repeated coroutines for lerping values?
I have created a progress bar system that lerps the value over a duration to provide some life to the progress bars.

I've done this using a coroutine that gets called each time a value (such as life or exp) gets modified.

The problem with this is, if the coroutine gets called in rapid succession, i.e. before the previous instance of the coroutine is finished, the lerped values inside the progress bar get messed up. They get fixed at the next coroutine call, but it kind of bothers me, so if someone can provide some insight into this, or maybe a workaround or an alternative way of accomplishing this, I would very much appreciate it.

The code for the coroutine I'm using is this:

```
private IEnumerator FillLerp(int currExp, int expNeed)
{
    float lerpDuration = 2f;
    float lerpSpeed = 3f;
    float i = 0f;
    float amountToFill = (float)currExp / expNeed;

    while (i < lerpDuration)
    {
        yield return null;
        _experienceBarFill.fillAmount = Mathf.Lerp(_experienceBarFill.fillAmount, amountToFill, Time.deltaTime * lerpSpeed);
        i += Time.deltaTime;
    }
}

```

# Answer
> 1 votes
I often like to tackle this with the following pattern, where I store the coroutine instance while it's in progress, and stop it if I need a new one.

```
Coroutine _fillAnimation;

void AnimateFill(float targetFill, float duration) {
    if(_fillAnimation != null)
        StopCoroutine(_fillAnimation);

    _fillAnimation = StartCoroutine(AnimateFillCoroutine(targetFill, duration);
}

IEnumerator AnimateFillCoroutine(float targetFill, float durationForCompleteFill)
{
    float startFill = _experienceBarFill.fillAmount;

    // We'll scale our lerp speed so the total duration of the animation is
    // proportionate to how much the value has changed.
    float speed = 1.0f / (durationForCompleteFill * Mathf.Abs(targetFill - startFill));

    for(float t = 0; t < 1f; t += speed * Time.deltaTime) {
        // I've replaced your exponential ease-out Lerp with a quadratic version that
        // completes in a finite number of steps, and is easier to correct for deltaTime.
        // (The exponential one never quite reaches its target)
        float progress = 1f - t;
        progress = 1f - progress * progress;
        _experienceBarFill.fillAmount = Mathf.Lerp(startFill, targetFill, progress);
        yield return null;
    }

    // Account for any loose change to ensure we end exactly where we want.
    _experienceBarFill.fillAmount = targetFill;
    // Clear the coroutine so we know we don't need to interrupt it next time.
    _fillAnimation = null;
}

```

# Answer
> 0 votes
Well, there are two main ways you can do this. The first and probably easier way is to not use a coroutine at all and have a central update. Something like.

```
private void Update() {
    if (desiredFillAmount > _experienceBarFill.fillAmount) {
        _experienceBarFill.fillAmount = Mathf.Min(desiredFillAmount, _experienceBarFill.fillAmount + Time.deltaTime * 0.1f);
    } else if (desiredFillAmount < _experienceBarFill.fillAmount) {
        _experienceBarFill.fillAmount = Mathf.Max(desiredFillAmount, _experienceBarFill.fillAmount - Time.deltaTime * 0.1f);
    }
}

```

The other way is that you can instead create your own coroutine runner that instead of playing coroutines all at once plays them sequentially by putting them in a queue.

So instead of `StartCoroutine(FillLerp())` you'd have something like `CoroutineRunner.instance.run(FillLerp())`. It may sound hard, but all you really need to do is something like:

```
public void runCoroutine() {
    if (coroutineQueue.Count > 0) {
        if (!coroutineQueue.Peek().MoveNext()) {
            coroutineQueue.Pop();
        }
    }
}

```

---
Tags: unity, c#, coroutines, lerp
---


# Question
Title: How to Generate Level Map Based on Golden Ratio
I am trying to generate a map based on the Golden Ratio:

> **a**+**b** is to **a** as **a** is to **b**.

I was looking at a JavaScript math library that had a built-in `phi`, but I wasn't sure how to apply it.

I also tried using hard-coded values as can be seen in this example:

```
<!DOCTYPE html>
<html>

  <head>
    <script src="https://unpkg.com/konva@7.1.0/konva.min.js"></script>
    <meta charset="utf-8" />
    <title>Konva Drag and Drop Demo</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #f0f0f0;
      }

    </style>
  </head>

  <body>
    <div id="container"></div>
    <script>
      function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      }

      var multiplier = 10;
      var width = 65;
      var height = 50;
      var color = getRandomColor();
      var x = 0;
      var y = 0;

      var stage = new Konva.Stage({
        container: 'container',
        width: width * multiplier,
        height: height * multiplier,
      });

      var layer = new Konva.Layer();

      function square(s) {
        var box = new Konva.Rect({
          x: x,
          y: y,
          width: s * multiplier,
          height: s * multiplier,
          fill: color,
          strokeWidth: 0,
          draggable: true,
        });

        // add cursor styling
        box.on('mouseover', function() {
          document.body.style.cursor = 'pointer';
        });
        box.on('mouseout', function() {
          document.body.style.cursor = 'default';
        });

        x += s * multiplier;
        color = getRandomColor();

        return box;
      }

      var level_map = [];

      level_map = [1, 2, 3, 5, 8, 13, 21, 34]; // golden ratio

      level_map.forEach(function(size, index) {
        level_map[index] = square(size);
      });

      x = level_map[0].x();
      y = level_map[0].height();

      console.log("x: ", x);
      console.log("y: ", y);

      level_map.forEach(function(square, index) {
        layer.add(square);
      });

      stage.add(layer);

    </script>
  </body>

</html>

```

Which creates the following pattern:

What I am looking for is more like this:

Note: this grid was roughly hand drawn and is not to scale.

# Answer
> 1 votes
Start with an area of dimensions `fib(i)` by `fib(i-1)` units, then...

* Pick a starting "end" of the shape.
* Create a "room" square of size `fib(i-1)`
* Set the new working area to the original area minus the room.
* Decrease `i` and repeat.

You can obviously reverse the process and start from the inside.

---
Tags: mathematics, tilemap, maps, html-canvas
---


# Question
Title: How to discourage micromanagement in strategy games?
When designing a strategy game (or one in a similar genre), how do you avoid having your players focus almost entirely on micromanagement? What should be done and what avoided in gameplay mechanics?

# Answer
From left field:

> **Don't allow the player to give direct orders to his units**

The idea is that you give the player's troops the same AI capabilities as the enemy, and then provide him with a goal setting system and a state toggle system.

The player can set goals/objectives attached to enemy units or map locations, such as:

* Destroy this
* Guard area
* Clear out area

These "objectives" can be more sophisticated, and can be revealed to the player progressively during the game so that she isn't overwhelmed by new options.

Then, allow the player to switch the state of the units:

* Aggressive
* Defensive
* Reserve
* etc...

The unit AI then decides how to act. For example, reserve units might decide to spontaneously reinforce a failing defense objective, or patrol areas that the player marked as "To Guard", without the player having given any orders.

You could also set up a threshold system for units (for example, defensive units could have a low "repair damage" threshold, meaning that they return for repairs when they lightly damaged, whereas attack units would have a high threshold, exiting from a fight only when in a critical state.) Giving the player the option to customise states based on these threshold would give great re-playability and strategic depth. The player could then create new unit states to suite her gameplay.

This would eliminate the following complaints:

> my troops won't kill weak units before targeting stronger ones, they won't target high dps units before lower dps units, they won't concentrate fire to take out individual units

Since those would be customisable thresholds and preferences.

A good analogy to what I am proposing is that in conventional RTSs, the player gives order to units on a battlefield, whereas in this system, she sets the doctrine of combat and the objectives, leaving the immediate tactics to subordinates (AI, in this example). In essence, she is teaching the AI her command style so that she doesn't have to make immediate tactical decisions.
> 21 votes

# Answer
Don't allow it. Give the player a specific role, and that's it. The guy who gives the orders to attack a group of enemies to the north isn't sitting there at the fight telling each guy who to shoot, he's back at base giving more orders to other soldiers.

For a more realistic/immersive experience, and to discourage/prevent micromanagement, allow the player (to choose(?)) a well-defined role, and don't allow actions that aren't part of that role.
> 9 votes

# Answer
I agree with thedaian but would like to expand upon his point. Most micromanagment is done to make up for the AI being inefficient. When I micro its usually because either: my troops won't kill weak units before targeting stronger ones, they won't target high dps units before lower dps units, they won't concentrate fire to take out individual units (kind of goes back to the kill low hp units before high hp), or they block other units from entering the fight.

The last point is my biggest gripe and the source of most of my micromanagment in Starcraft. Darn buggies will make an impenetrable ring around the enemy units that doesn't allow my shorter ranged and slower units though. As a result I'm having to move buggies 10 feet forward to let my infantry though.

There's simply no point in micromanaging if the AI is efficiently utilizing the available units.
> 8 votes

# Answer
> Our life is frittered away by detail . . . simplify, simplify. (Henry David Thoreau)

My answer is similar to those that suggest picking a clear role for the player. What they're really saying is to simplify I think.

The reason micromanagement happens is because there are very many choices to make during play, and in general they only really matter in aggregate, if at all. "Strategy" as a game genre doesn't mean "an almighty pile of things to fiddle with," it means "making decisions with consequences that don't arrive for awhile."

I'll give two very classic examples. Chess and Go are known for very deep strategy but both in both cases it results from very simple rules and very simple mechanical decisions. The state of a chess game can be summarized into, what, thirty-two pairs of very small integers? And your turn is to change the value of *one* of those pairs!

And yet, Chess and Go are both very well-loved by real military strategists, and have been for a very long period of time. Surely that's saying something important to us armchair generals with our gee-whiz digital chessboards.

Another big problem with strategy gamers is that they have no understanding of how large groups of fighting units actually work together. I've heard an aphorism, that "armchair generals talk tactics, real generals talk logistics."

Think it over. Say I can position a particular starfighter in a space 4X game. Starfighters work in squadrons, and breaking them up to has dramatic logistical and organizational consequences. So why does the game let me move around an individual starfighter? That'd be like the President of the United States calling your math teacher to give her suggestions about the day's lesson. I'm the grand admiral of a mighty space fleet, so my units to move about the board should be task forces and battle groups.

There are ways to let players work on organizational choices though. For instance, paper war games use "operational turns" which only come around once every several "tactical turns." I can't recommend paper wargames enough for understanding good strategy game design. James F. Dunnigan has written extensively on this kind of thing; his *Complete Wargames Handbook* is very insightful, provided you're willing to see past the datedness of some of the discussions.
> 7 votes

# Answer
If you want players to just focus on managing resources, economy, etc. you can do what Startopia did. Which is, the player recruits or produces units and then builds structures for them which they'll inhabit automatically. As for combat, player can set up points of interest for the troops to gather at or attack (if it's an enemy unit or building) and assign values to these points so the AI can decide which unit goes where.

If you're making a "hardcore" RTS like Starcraft, then it comes down to "either you learn to manage your economy or you'll get overrun", it's a matter of balancing the difficulty level, you won't stop 20 Hydralisks with 5 Marines no matter how good you are, etc. In multiplayer it's survival of the fittest, either you macro or you lose, so i wouldn't worry about that part.
> 4 votes

# Answer
Instead of click-speed limiting how many orders a player can send, make it an in-game resource. Click too fast and you run our of orders and have to wait to accumulate new ones. Order single units and you can only afford to move a few per minute, but make big group moves and you can keep your entire army moving. There would still be a benefit to micro-manage, but it would be much more expensive in terms of leaving all other units without orders for a long time.

The in-game limit could be some abstract command-point counter (as used in several board wargames) or you could make it more part of the game world, eg by having messengers running/riding/flying to deliver orders. When all messengers are busy the player simply has to wait for one of them to return before being able to send a new order. Depending on theme it could be more or less difficult to make the limit fit in nicely.
> 4 votes

# Answer
Consider dividing the player's focus such that micromanagement is only available at a level of extreme focus. In Starcraft or like games, the interface is the same whether you're building buildings or directing units. However, if there were a context shift between resource management, camp development, large-scale strategic unit deployment, and small-scale tactical unit management, then staying too focused on any one of those areas could be detrimental to the others.

In short, make it so that when a player is engaging in micromanagement techniques, or when those actions are afforded by the UI, other (vital) information isn't visible. This would give your player the opportunity to squeeze the most out of their combat units when they wanted to, but would make such micromanagement untenable over a long period of time.
> 3 votes

# Answer
The common suggestion seems to be to not allow the player to directly control the units at all. However, if you want the player to still have some control over the units, you can take some people's advice of making the AI good enough that micromanagement isn't necessary, or you can try my initial idea, which is to make units that just don't have a lot of micro potential. Some examples of this in StarCraft 2 would be the siege tank, and of course, the colossus.
> 3 votes

# Answer
**Make Unit-Orders have a cost per order - regardless of unit size.**

Let's say you give the player 10 "tokens" of something per turn - then giving orders to an individual unit costs one token, and giving orders to an entire *squad* also costs one token. If they have 10 squads, they can give every squad a group-order - *or* they can give 3-4 single units precise orders, at the cost of some squads getting *zero* orders.

In other words: **let the *player* balance the decision on when to micro-manage**, and when to not. If the AI is good enough for most squads, most of them time, then the player will use that - until a situation calls for finer-grained control than the group AI, then they can give individual units specific orders, at a cost.

This basically turns player Focus, into another resource to be managed.
> 3 votes

# Answer
Give them too many units. If you have a hundred units in a battle, not even a skilled RTS player can micromanage all of them. And secondly, make macromanagement more important. For example, in Warcraft 3 micromanagement was very important because macro was weak- low food cap and that upkeep malarky. This is what you want to avoid doing if you want to keep a focus away from micro.
> 2 votes

# Answer
Use squads, as in Dawn of War or Company of Heroes. Micromanagement will still be required, but the fact that you only need to micromanage 5-10 entities will give the player more time to develop their macro.
> 2 votes

# Answer
Don't make a game in such a way that you need to tell your players to not play it a certain way. The controls you give them are there for them to use, and they will assume they are supposed to be using it. Decide what you mean by 'micro', and ensure that players do not control their game units on that level.
> 2 votes

# Answer
You could give short, but noticeable, and random, time-delays for each order given to a unit before it reacts. You could also add a longer transition time for units to switch from one order to another, making them vulnerable to enemy attacks while they prepare to follow a new order. That would also be a bit more realistic than units reacting in an instant to every click
> 2 votes

# Answer
Making the player's army reasonably self-sufficient will help with this. If the army already does what you want, you don't need to micromanage it. For example, special abilities might be 'auto-casted' by default, preventing the player from spending too much time worrying about triggering each ability usage, and more worried about making sure they have the right mix of units to achieve the goal. Strong AI will also be extremely helpful here.

On the engine level, it would help to have units be able to move AND attack at the same time. This means players have much more trouble playing using micro-heavy harassment and animation-cancelling styles well seen in games like Warcraft III (and by extension, DotA) and Star Craft/Star Craft II.
> 0 votes

# Answer
Make the units disposable. If a player doesn't feel the need to keep his/her units alive than they'll likely not waste time managing them as much when they could be doing other things.

Make them cheap in resources. The cheaper units are the less likely a person will spend time trying to keep them alive if they know they can just reproduce them easily. Similarly, make them quick to build. The faster units are being produced the more time a person has to spend actually producing them as opposed to giving them orders. Especially if they're cheap units, this turns the overall strategy of trying to keep units alive to out producing your opponent.

I also agree with automatizing your units as best as possible. Applying general orders of what to do. For example, if an enemy unit comes into range, should they attack? Hold position, should they use any special abilities they have, etc. This, of course, can get pretty tricky, so it could even just be a simple, hold, defend something, or attack. The only issue with this is how far back does it go aggroing units.

Another problem that arises and causes people to micro is path finding. Design your boards to be more linear and open. You can still have elevation but try to avoid cliffs and things that would prevent units from moving in a straight line whenever they're told. A lot of them time in RTS games when units are given a command to move somewhere that is blocked or up a hill they get confused. Path finding has gotten much better recently but it's still an issue in almost every RTS game I've played. This way people can give orders are know that their units are going directly to where you told them.

I'd also suggest making it easy to give general orders without having to turn your attention towards the units. A rallying system would be a sufficient place to start but it'd need to be expanded upon. Perhaps incorporating the passive commands into it so units that spawn automatically are given an order, such as defend or hold position when they get to where they were told to go.

One last thing I'd suggest is making it easy to give general orders without turning your attention away from whatever it is you're doing in the game. Make it possible to give orders to all the units on the board at once, make it easy to select all the units of a given type on the board very easily, etc. Maybe even tie this in to the structure that's building the units. Instead of giving all the orders by selecting the units, select the buildings that make them to give orders to all the units of that type.
> 0 votes

# Answer
Giving the ai all the micro decisions tasks would be the best way. Think about how guerrila fighters work in cells. A leader gives a general order, send the closest cell to x to do x, and then the cell does the actual planning and execution of the task in the way that best suits it's own members and skillsets. Tell a squad or team of units to assassinate a target, and a group of trooper types with machine guns might storm the building they are in, or they might wait till they are on their drive home, be standing in the road, and fire away, but the AI decides that. A cell composed of say, more subtle types, might approach it another way, and a team that has an explosives expert might just explode his house in the night or something. But all the player has ordered is "make that dude dead." And the team that got the order decides how to approach that very general task.

The player is a commander, a leader of a greater force, that level of planning doesn't happen with him. The general just tells his captains to take hills and so on, then the captains tell the soldiers in their squads more specific orders based on the situation on the ground right? And the commander in *chief* is commanding the generals just to go accomplish a general goal with the forces they command. So...decide where in the hierarchy the player is, and only give them the tools that a person in that position would have. Then say, have a "general" ai give troop movement and general orders, and "captain" ai's managing each squad(take that house, lay mines here defend this location, set these traps, dig a trench and so on), and "individual" ai handling a unit's special abilities (say, deciding to throw a grenade, fight on, flee in terror, go into hiding if his squad is destroyed, to make it back home safe, make a last stand, or whatever)and how to interpret the captains orders. So...layers of Ai that put the player in the position of a SINGLE part of the command chain. So, depending on the command structure your units are in, determines what kinds of ai and how they interact.
> 0 votes

---
Tags: game-design, game-mechanics, strategy, user-experience
---


# Question
Title: Regarding Profile Pictures of Facebook Friends
Background: I am creating a Leaderboard of Facebook friends in unity.

Question: Can we download and save the images of Facebook Friends on the device of the user for the purpose of reuse? I would like to store the images of the FBFriends on the user's device so that there is no need to download the same pictures everytime the game is restarted. Is it legal to do so?

I asked the same question in Facebook Developers forums but I did not get any response. Kindly guide me. How do devs build a leaderboard of Facebook friends normally?

Thankyou.

# Answer
Yes, you can. It is desirous, in fact, to reduce bandwidth usage across the board. However, you may want to refresh them occasionally in case the user changes their profile picture, and I would make sure the cache doesn’t grow to large by deleting images that are not currently on the leaderboard and/or haven’t been used recently.

As for how others do it, well, I keep a very short lived cache which is cleared on every launch.
> 0 votes

---
Tags: unity, facebook, leaderboards
---


# Question
Title: How to keep the ball on zigzag movement?
I recently make a zig-zag movement it works perfectly but after the ball hit the collider or obstacle the ball is changing their direction like just forward, not zig-zag anymore I've tried to update the velocity after collide but it's same, also I have tried to constant the magnitude but that's not what I want

here my script

```
public float magnitude;
    public float forwardSpeed;
    public float horizontalSpeed;

    private Vector2 horizontalAxis;
    private Vector2 negationVector;

    public Rigidbody2D rb2d;
    public m_GameManager _GameManager;

    public bool isOver = false;

    private void Awake()
    {

        horizontalAxis = Vector2.right;
        negationVector = new Vector2(-1f, 0);
    }

    private void Start()
    {
        _GameManager = FindObjectOfType<m_GameManager>();
        UpdateVelocity();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ReverseHorizontalVector();
            UpdateVelocity();
        }
    }

    private void ReverseHorizontalVector()
    {
        horizontalAxis *= negationVector;
    }

    private void UpdateVelocity()
    {
        Vector2 velocity = GetCompositeVelocity();
        rb2d.velocity = velocity;
    }

    private Vector2 GetCompositeVelocity()
    {
        Vector2 forward = Vector2.up * forwardSpeed;
        Vector2 horizontal = horizontalAxis * horizontalSpeed;
        Vector2 composite = (forward + horizontal);

        return Vector2.ClampMagnitude(composite, magnitude);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        UpdateVelocity();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Goal"))
        {
            _GameManager.IncreaseScore();
        }
        if (collision.gameObject.CompareTag("L") || collision.gameObject.CompareTag("R") || collision.gameObject.CompareTag("Death")
            || collision.gameObject.CompareTag("Player"))
        {
            StartCoroutine(_GameManager.waitAfterDeath());
            isOver = true;
        }
    }

```

like I said before the ball zig zag but after colliding the movement change like that.

# Answer
solved by add

```
private void OnCollisionExit2D(Collision2D collision)
{
    UpdateVelocity();
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Hacky Slashy: Streamlining 100% Completion for "Non-Foundational" Challenges?
# Some Exposition/Context if You Care About that Sort of Thing (Safe to Skip)

When it comes to gaming, I'm a completionist. You can tell me to finish all 50 optional levels, conquer a near-impossible superboss, or find all 900 pinecones Korok Seeds scattered throughout the entire open world. **I'll do these things simply because you told me to.**

However, I was recently playing Donkey Kong: Tropical Freeze's Hard Mode, which is reserved for the post-game. And it got me thinking...

Now, in Tropical Freeze, there are two sets of collectibles in every level: the four KONG letters and 5-9 puzzle pieces. The KONG letters are generally left out in plain sight, but are difficult to reach. In other words, they test your platforming prowess. By contrast, the puzzle pieces are generally hidden in places you wouldn't think to look if you were just breezing through the levels. In other words, they test your ability to be observant and thorough.

As a 100% completionist, I had collected all of the puzzle pieces before unlocking Hard Mode. Hard Mode does not require you to relocate puzzle pieces that you've already found in normal mode. However, it does present the challenge of re-collecting the KONG letters, as the risky maneuvers you were pulling off in normal mode to collect them are now even MORE risky in Hard Mode. Double the risk, double the fun, am I right?

Here's the thing, though... with the puzzle pieces out of the way, I could focus exclusively on platforming challenges when I played Hard Mode. And I realized that I like the platforming of Tropical Freeze waaaaaay more than I enjoy hunting for hidden collectibles. **In fact, I truly believe that hunting for puzzle pieces damages my overall enjoyment of the game.** So, just don't collect the puzzle pieces on future playthroughs, right?

**WRONG.** I'm a completionist at heart. Knowing that there are secrets that I'm deliberately leaving behind would be like having an intense itch in some place that I couldn't reach to scratch while locked in a room in which every surface was soft and smooth and unfit for scratching.

But, what if Tropical Freeze had systems to enable my completionism addiction without forcing me to engage with all of the game's systems? For example, what if I could exchange 10 Banana Coins for all of the puzzle pieces in a given level? Or something else?

# Hacky Slashy: A Hypothetical Design (If You Were Skipping, You Should Stop Skipping Now)

Ultimately, the question I'll be asking here is, **"Is it beneficial to streamline the 100% completion process for challenges that deviate from the game's foundational mechanics?"**

Let's consider a hypothetical game to which we can apply this reasoning.

We'll call this hypothetical game "Hacky Slashy." Hacky Slashy is a hack-and-slash in which the main quest is just a series of levels. "Beating the game" simply requires that each level's boss be defeated. However, the following additional tasks must be fulfilled to achieve 100% completion:

1. **Receive a gold ranking for each level.** For each level, you're given a "bronze-silver-gold" ranking based on how well you complete it (i.e. taking minimal damage, aggressive fighting style, etc.).
2. **Locate and rescue the captured NPC**. This is a small escort quest where you have to bring an NPC from point A to point B without allowing them to take damage, lest they die. Assume that bad escort mechanics don't contribute to the tediousness of this quest (e.g. the NPC will keep up with your sprinting speed, can intelligently maneuver around obstacles in the path, will make reasonable attempts to dodge incoming hitboxes, and so on).
3. **Find the hidden Shiny Shard.** There is a Shiny Shard hidden in every level. Finding the Shiny Shard involves solving some sort of puzzle or locating some sort of hidden area, but these challenges are unrelated to combat.

Achieving gold rankings falls entirely in line with the core gameplay of a hack-and-slash, as getting a gold ranking does not require players to deviate from hacking and slashing. I would contend that this is good (but feel free to contradict me on this), because my audience will be buying my game to enjoy hack-and-slash gameplay.

The escort quest **can** fall in line with the core gameplay of a hack-and-slash, but it's also true that the optimal way to complete this side quest would be to defeat all of the enemies in the level, backtrack to the NPC, and then escort them through the empty map. In other words, the player may optimize the hack-and-slash out of this challenge. (This is mostly likely indicative of a different problem than the one posed by 100% completion, but I'll leave it in here in case anyone has any additional insight.)

However, finding Shardy Shards simply does not fall in line with the core gameplay of a hack-and-slash, and thus is at the heart of this question. Again, it is reasonable to assume that gamers who purchased Hacky Slashy did so to enjoy its combat. While there will surely be members of my audience who enjoy both combat and puzzles/exploration, there will also be those who only want to engage in combat-related mechanics. However, it's likely that there will be people in both camps who are 100% completionists. Suddenly, they'll be forced to choose between their two tendencies: Complete all of the game's challenges despite the fact that some of them won't be fun for them, or focus only on the fun challenges while leaving the Completionist's Itch unscratched.

**How can Hacky Slashy include Shardy Shards in a way that avoids alienating the completionists who don't particularly enjoy exploration? Are there any games that solved a similar problem in an insightful way?**

# Answer
I think this depends on the context, both yes and no can be towards a designers choice.

Some may say the road to 100% completion is not meant to be easy (or even fun). And collecting all items, of finishing the game with every perk/class available is part of the challenge. A hard example on gacha games, a softer example on archievements, Pokémon/monster-collection games or roguelikes that allows you to start with a different perk/character to complete the game in an unique way.

Other games have a similair collectables, but still allows you to obtain it in different ways. Like the Super Smash Bros series, which has a challenge board, but grants you a limited amount of hammers to free these challenges, due to it's limitation, you rather want to save those for the challenges you won't be able to beat by yourself, and keep them for the home stretch.

Though in my view, some completionists could strife for keeping all hammers too.
So the choice to go for them all, or ignore and/or bypass them is up to you.
> 1 votes

---
Tags: game-design
---


# Question
Title: Complex mesh (created in Blender) is not overlapping when rendered in Monogame (XNA)
community. Just started playing with Monogame and stuck with a quite simple, but still unanswered issue, at least I couldn't find any answer.

The model rendered in Monogame (XNA) is not overlapping with its own parts:  Originally in Blender, it looks OK:

The same in Windows 3D Viewer:

I believe it depends on the order I'm rendering bones:

```
private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
    {
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo( transforms );
        var fixBlenderRotation = Matrix.CreateRotationZ(MathHelper.ToRadians(90));
        var scale = Matrix.CreateScale(0.1f);
        //for (int i = model.Meshes.Count; i > 0; i--) // -> this looks OK
        for (int i = 1; i <= model.Meshes.Count; i++)  // -> this looks BAD
        {
            ModelMesh mesh = model.Meshes[i - 1];
            foreach (var effect in mesh.Effects)
            {
                if (effect is BasicEffect basicEffect)
                {
                    basicEffect.EnableDefaultLighting();
                    basicEffect.Alpha = 1;
                    basicEffect.View = view;
                    basicEffect.Projection = projection;
                    var boneTransform = transforms[mesh.ParentBone.Index];
                    basicEffect.World = (world  * boneTransform * scale *  Matrix.CreateTranslation(_modelPosition)) * fixBlenderRotation;
                }
            }

            mesh.Draw();
        }
    }

```

Depth buffer is enabled:

```
protected override void Initialize()
    {
        _graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        _world = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up);
        var cameraPosition = new Vector3(_radius, 0, 0);
        _camera = new FpsCamera(this, cameraPosition, Vector3.Zero, Vector3.Up);
        Components.Add(_camera);
        base.Initialize();
    }

```

So, cannot figure out how other tools render my model correctly while monogame is messing things up? The hierarchy of objects in Blender is correct:

# Answer
The fix is really simple, just need to move the following line of code:

```
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

```

from *void Initialize()* method to *void Draw(GameTime gameTime)*:

```
protected override void Draw(GameTime gameTime)
{
      GraphicsDevice.Clear(Color.CornflowerBlue);
      GraphicsDevice.DepthStencilState = DepthStencilState.Default;
      DrawModel(_car, _world, _view, _projection);
      base.Draw(gameTime);
}

```

And that has fixed the issue:

Here I have found this solution.
> 0 votes

---
Tags: xna, monogame, blender, mesh
---


title: Multiplayer Replication Unreal Engine 4

text:
# Question
Title: Multiplayer Replication Unreal Engine 4
I have `variable=count(integer)` in a Character Blueprint.
I want to increment the variable when user presses the 'R' key.
What do I so in the Blueprint that variable remains the synchronized between the server & client?
For example:
In server- 'R' key pressed 3 times so count value should be 3.
In client-'R' key pressed 4 times, so then the value should be 7.

# Answer
> 0 votes
If I'm understanding you correctly, you have a variable and you only want it to increment once when the client presses the R key but what's happening is it is being incremented on both the server and client, doubling up the count.

To get around this, you need to use the Switch Authority node

Make sure the variable is replicated and only allow it to be incremented by the server.

---
Tags: multiplayer, unreal-4, unreal
---


# Question
Title: My pixel art looks weird in the game view in Unity
I am making my first 2D game in Unity and something has been bothering me. If I'm in the scene view, my game looks fine but when I go to the game view the pixels in the sprites aren't rendered correctly and everything looks distorted.

Does anyone know an answer to this?

# Answer
You're not maintaining an integer pixel to texel ratio. See some past answers on this topic. The quickest fix is to use the Pixel Perfect Camera in Unity, if you don't want to calculate the ratios yourself. – DMGregory♦ (see comment)
> 0 votes

---
Tags: unity, textures, rendering, sprites
---


# Question
Title: How to keep AI goalkeeper inside their bounds
I'm making a soccer-themed top-down 2D endless game, but I have a problem with the goalkeeper AI.

My game looks like this:

As you can see, the goalKeeper is moving out of bounds.

I have tried to clamp them with

```
transform.Translate(Mathf.Clamp(target.transform.position.x,-1,1),0,0)

```

...but I think this for clamping the speed, not the area boundaries. What should I do instead?

What I want is to have two kinds of goalkeeper:

* **Active Goalkeeper** (Call them `GKA`)

This goalkeeper should chase the player, but only within the bounds of the goal area.
* **Stationary Goalkeeper** (Call them just `GK`)

This goalkeeper should just stand in the middle of the goal, like in the first animation. But before the player reaches them I want this goal keeper to move forward slightly, to pretend it's defending the goal.

Here is my goalkeeper script:

```
if (gameObject.CompareTag("GK"))
    {
        anim.SetBool("GKRun", false);
        gkballInRange = Physics2D.OverlapCircle(transform.position, gkballRange, playerMask);
        float distancePlayer = Vector2.Distance(target.position, transform.position);

        if (gkballInRange)
        {
            transform.Translate(0, -.3f * Time.deltaTime, 0);
            if (distancePlayer <= gkballRange)
            {
                if (theBall.isOver)
                {
                    anim.SetBool("GkC", true);
                    anim.SetBool("GKRun", false);
                    transform.Translate(0, 0, 0);
                }
                else
                {
                    //Animation
                    anim.SetBool("GKRun", true);
                    transform.Translate(target.transform.position.x * speed * Time.deltaTime, 0, 0);
                }
            }

        }

    }

```

and this one is GKA script:

```
if (gameObject.CompareTag("GKA"))
    {

        //Animation
        gkballInRange = Physics2D.OverlapCircle(transform.position, gkballRange, playerMask);
        float distancePlayer = Vector2.Distance(target.position, transform.position);

        if (gkballInRange)
        {
            transform.Translate((target.position.x * Time.deltaTime), 0, 0);

            if (distancePlayer <= gkballRange)
            {

                if (theBall.isOver)
                {
                    anim.SetBool("GkC", true);
                    anim.SetBool("GKRun", false);
                    transform.Translate(0, 0, 0);
                }
                else
                {
                    anim.SetBool("GKRun", true);
                    transform.Translate(0, -speed * Time.deltaTime, 0);
                }
            }
        }
    }

```

# Answer
After applying the goalkeeper's speed, you should Clamp the resulting position to make sure it's within bounds. Here's an example:

```
transform.Translate(speed,0,0);
transform.localPosition = new Vector3(
    Mathf.Clamp(transform.localPosition.x,-1,1),
    transform.localPosition.y,
    transform.localPosition.z);

```

This assumes only the X axis is to be clamped. It's also been a while since I've worked on Unity, not sure if there is a better way than creating a new `Vector3` every frame, but the result should be correct.
> 0 votes

# Answer
An addition to the answer from TomTsagk.

You are using your current transform.translate as it is. This code is placed after the translate, if the gk is running out of the bounds, you are clipping his position back into the bounds. You achieve this with the Mathf.Clamp.

For the forward running, you treat it the same way as a sideway running.

```
transform.localPosition = new Vector3(
    Mathf.Clamp(transform.localPosition.x, -widthOfGoal/2, widthOfGoal/2),
    Mathf.Clamp(transform.localPosition.y, -maxForwardDistance, 0),
    transform.localPosition.z);

```

This assumes that your goalkeeper is placed at 0, 0, 0 at his localPosition.
> 0 votes

---
Tags: unity, c#, game-mechanics, transformation
---


# Question
Title: How to instantiate a prefab at mouse location in the editor in unity?
I want to instantiate a prefab at the mouse position in the editor. All the answers I found till now are for instatiate a prefab at runtime but i want to **instantiate in the editor**. Currently I am trying to use input.GetMouseButtonDown but that doesn't seem to work ? Also is it fine to use raycasting in the editor itself?

**EDIT**: Alright I found that we need to use eventtype.MouseDown but now the script is not executing? there are no errors in the console window

using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class mapMaker : Editor
{
    public GameObject rock;
    private void OnSceneGUI()
    {
        if (Event.current.type == EventType.MouseDown)
        {
            Ray ray = Camera.current.ScreenPointToRay(Event.current.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 1000.0f))
            {
                Debug.Log(Event.current.mousePosition);
                Vector3 newTilePosition = hit.point;
                Instantiate(rock, newTilePosition, Quaternion.identity);
            }
        }
    }
}

```
</code></pre>

# Answer
> 0 votes
You may have to listen to scene events.

Here is an example which creates an Editor Window which you can open from Window menu (in Unity menu bar). I think you can use pretty much the same code if you want to have similar functionality from a Custom Editor.

How to use: Open this window from Window menu (Raycast in editor test), then click 'Enable Raycasting' in Editor Window and click on some Collider in Scene View to spawn Default Cubes.

```
using UnityEditor;
using UnityEngine;

public class Raycast : EditorWindow
{
    static bool active;

    // Open this from Window menu
    [MenuItem("Window/Raycast in editor test")]
    static void Init()
    {
        var window = (Raycast)EditorWindow.GetWindow(typeof(Raycast));
        window.Show();
    }

    // Listen to scene event
    void OnEnable() => SceneView.duringSceneGui += OnSceneGUI;
    void OnDisable() => SceneView.duringSceneGui -= OnSceneGUI;

    // Receives scene events
    // Use event mouse click for raycasting
    void OnSceneGUI(SceneView view)
    {
        if (!active)
        {
            return;
        }

        if (Event.current.type == EventType.MouseDown)
        {
            Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
            RaycastHit hit;

            // Spawn cube on hit location
            if (Physics.Raycast(ray, out hit))
            {
                Debug.Log("Hit: " + hit.collider.gameObject.name);

                var obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
                obj.transform.position = hit.point;
            }
        }

        Event.current.Use();
    }

    // Creates a editor window with button
    // to toggle raycasting on/off
    void OnGUI()
    {
        if (GUILayout.Button("Enable Raycasting"))
        {
            active = !active;
        }

        GUILayout.Label("Active:" + active);
    }

}

```

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


# Question
Title: How does an FPS like Overwatch have client time run ahead of the server?
In watching the GDC talk about Overwatch netcode, it mentions that the client is always ahead of the server, that the "current tick" on the server is behind that of the client.

From their explanation this makes sense. If the client is ahead of the server, then by the time the client messages arrive at the server, the server will have caught up and can handle them when it wants them.

But how does this get setup to begin with? The client connects to the server, the server starts a game... does the client jump ahead of it's own accord? *(Server says "game is starting, I'm at tick 0", and the client is like "okay, well, based on my ping I'm going to be tick 20 then")*

* If the server is in charge of what's going on in the game, how does the client even know what's going on in that future tick? I would assume constant extrapolation of game events from the last server update would be bad. Having the client in the past to allow it to interpolate between server updates would make a lot more sense to me.
* Or am I wrong in assuming that client and server tick times need to remain in sync, and it is instead more loosely based on server updates and the number of client events that happened since that update was received, rather than the client actually caring about what tick they're on compared to the server?

It's the time/tick synchronization, despite one or the other having to be in the past, that I can't wrap my head around...

# Answer
> 4 votes
> But how does this get setup to begin with? The client connects to the server, the server starts a game... does the client jump ahead of it's own accord? (Server says "game is starting, I'm at tick 0", and the client is like "okay, well, based on my ping I'm going to be tick 20 then")

No. Once the connection is established, the client just starts running, and starts sending messages (input) to the server immediately. But the messages take time to reach the server (network latency). And by the time the first message *arrives* at the server, the client is already 10 ticks ahead (let's say), "predicting" what's happening based on its own state of the game world. The client is not in the future, the client just runs its own simulation in real time; it's the server that's always late (because of the time it takes for them to exchange messages).

> If the server is in charge of what's going on in the game, how does the client even know what's going on in that future tick?

It doesn't. It maintains its own state of the game world, and it tries to predict what is going on based on that. Here "predict" just means "run the game based on my own state and hope that the server will eventually come up with the same answers." For this to work the behavior of the game needs to be made as deterministic as possible (see the talk for details). Again, for the client, this is not a future tick, it's the *current* tick; the client just doesn't have the most up-to-date state of the world. E.g. it may not know yet that someone fired a gun at you a couple of milliseconds ago.

The server computes the same kinds of updates as the input arrives, and then sends the results back. That takes time to arrive as well. To the client, that's now some 20+ ticks ago (roundtrip time). The client maintains the past state (and past inputs), and if the state obtained from the server is different, it will throw away everything after it, and *re-predict* from that point on, all the way up to the current frame.

At least, that's a general/conceptual overview; in the talk you'll see that in practice there are some subtleties that need to be taken into account.

> Having the client in the past to allow it to interpolate between server updates would make a lot more sense to me.

Well, the problem is that the game needs to feel responsive. In this type of game, when a player clicks a button to shoot, or whatever, you can't wait for the input to get to the server, be processed, and then to come back. So it's a compromise - the input feels very responsive, but when an occasional misprediction happens, the client does extrapolate from a past state, and just replaces whatever was on the screen with the new thing. Luckily, this usually isn't very noticeable.

---
Tags: client-server, synchronization, timestep
---


# Question
Title: How can I transfer this code (originally for FPS template) for use in a Third Person Template?
I learned how to create a blueprint for making a character be able to pick up and drop objects:  It did not work, and I believe the reason is because it was originally made to work for the FPS template that Unreal comes with. I decided to use the Third Person template, and I think that's why it's not working. Am I correct? What blueprint coding should I be looking at? What's missing, or what's preventing this from working? Thanks!

# Answer
> 2 votes
I figured out that the problem was that I had put a divide node where I should have put a vector add node.

Once I fixed this, it worked fine!

---
Tags: unreal, first-person-shooter, blueprints, third-person-view
---


# Question
Title: How can I check if component is enabled?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraInformation : MonoBehaviour
{
    public string currentCameraState;

    // Start is called before the first frame update
    void Start()
    {
        var components = new List<Component>();
        foreach (var component in GetComponents<Component>())
        {
            if (component != this)
            {
                var fullName = component.GetType().FullName;
                if (fullName.StartsWith("Cinemachine"))
                {
                    currentCameraState = component.
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnEnable()
    {

    }

    private void OnDisable()
    {

    }
}

```

At this line I want to assign the string the component status if it's enabled true or false.

# Answer
> 3 votes
A `MonoBehaviour` has an `enabled` property you can check. So:

```
currentCameraState = component.enabled ? "Cinemachine is enabled" : "Cinemachine is disabled";

```

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


# Question
Title: Can I get world-space z-near-plane vertices from projection matrix + z-near distance?
I'm trying to port ShaderToy VR shaders to WebXR (the new browser API for AR/VR devices).

ShaderToy VR shaders expect two extra parameters: ray origin (view translation) and ray direction (unit vector from ray origin to each pixel). I could easily calculate this ray direction if I had fovX + fovY + distance to projection plane.

The problem: WebXR does not expose FOVs and instead just provides us with a projection matrix (apparently some devices might need more complex projection matrices with shear, roll, etc.) WebXR also exposes zNear and zFar, but that's all the frustum info available if I'm not mistaken.

Is there any way to obtain the zNear plane corners in world-space with this information?

# Answer
> 2 votes
Thanks @DMGregory for the pointer in the comments.

I'm constructing a fullscreen quad at `(x, y, -1, 1)` in NDC. Notice `z = -1` is the near plane in NDC (left-handed unlike normal coordinate systems in OpenGL-land).

In the vertex shader:

```
attribute vec2 aVertexPosition;

uniform mat4 uInvViewMatrix;
uniform mat4 uInvProjMatrix;

varying vec3 vZNearPos;
varying vec3 vRayOrig;

void main() {
  // Vertices in the near plane in NDC
  gl_Position = vec4(aVertexPosition.xy, -1.0, 1.0);

  // Vertices in the near plane in world-space
  vec4 vZNearPosW = uInvViewMatrix * uInvProjMatrix * gl_Position;
  vZNearPos = vZNearPosW.xyz / vZNearPosW.w;

  // Ray origin in world-space
  // This could be a uniform but I was lazy :P
  vec4 rayOrigW = uInvViewMatrix * vec4(0, 0, 0, 1);
  vRayOrig = rayOrigW.xyz / rayOrigW.w;
}

```

The uniforms in JS:

Then in the fragment shader:

```
varying vec3 vZNearPos;
varying vec3 vRayOrig;

void main() {
  // I'm not sure if this can be safely interpolated per-vertex
  // so I kept in the fragment shader just in case
  vec3 rayDir = normalize(vZNearPos - vRayOrig);

  // Paint your VR here!
}

```

---
Tags: mathematics, virtual-reality, frustum, projection-matrix
---


# Question
Title: what is use of ScriptableSingleton in Unity?
in unity 2020.x Unity just has introduced scriptable Singleton. a class that derives from Generic Class Called `ScriptableSingleton` its like singleton but you only can have single instance of it and seems to be good for ScriptableObjects that need to be Forced to be Single. but there are some differences.

they can be project Specific or Shared. they can get any format and unlike usual scriptableObjects they have no visualization in the inspector. the question is how should i use them and they are appropriate for which approaches? this is the link to the reference:

https://docs.unity3d.com/2020.1/Documentation/ScriptReference/ScriptableSingleton\_1.html

# Answer
According to the docs you link:

> The ScriptableSingleton generic class allows you to create 'Manager' type classes in the Unity Editor. In classes that derive from ScriptableSingleton, serializable data you add survives assembly reloading in the Editor. Also, if the class uses the FilePathAttribute, the serializable data persists between sessions of Unity.

So based on this description, the ScriptableSingleton class is used for storing data that you might need for an editor utility.

Say you've built a custom plugin for the scene editor to do some procedural generation. And let's say it needs to do some heavy-duty pre-computation and caching when your assets/settings change, so that it can run at interactive speeds the rest of the time.

If you store that pre-computed data in a normal ScriptableObject, then you have to tell the utility where to look for it. And it gets confusing if someone makes two copies of the asset - which one should it use?

But if you store the data in static variables, then they're lost when you change your game code and reload the assembly, when you enter/exit play mode, or when you exit and re-launch the editor. So you redundantly do the slow pre-processing work over and over, bogging down the editor workflow.

The ScriptableSingleton appears to be made to solve those problems, giving these editor utilities a place to store persistent, easily-accessed information that won't get wiped out by common events like changing a script file.

If I'm reading it right, it looks like you can even store this data outside the Unity project, to share editor utility settings between multiple projects.
> 3 votes

---
Tags: unity
---


# Question
Title: What the difference between public int and int?
I was trying to understand the difference of int and public int by checking how unity respond to it

```
using UnityEngine;
using UnityEngine.Assertions.Must;
using UnityEngine.SceneManagement;

public class Bird : MonoBehaviour

{
 int CurrentState = 1;
 int PreviousState = 1;

}
Void Update()
{(if CurrentState != PreviousState)
 transform.localScale = new Vector3(transform.localScale.x+1,transform.localScale.y+1,transform.localScale.z+1);
  }

```

Since the equality is false, the scale of object remail unchange and in my next step, I changed "int CurrentState = 1" to "public int CurrentState=0" and "int PreviousState = 1" to "Public int PreviousState = 1" . Isn't that this time, the equality is true as 1 !=0 but the scale of object remained the same. Once I deleted the word "public" on both currentstate and previousstate, the scale increase indefinitely. I thought the word "public" basically meant there no access restriction but why it looks like the "if" statement couldn't retrieve the info correctly?

# Answer
`public` variables are visible to Unity's serializer, so you can assign values to them in the Unity Editor's Inspector.

That means that the value in your field initializer code might be replaced by values saved in the Inspector before your `if` statement runs.

So: when working with public or serialized variables, always check the inspector to see if you left them set to a different value than you meant to.
> 2 votes

# Answer
If you don't declare any access modifier (`public`, `private` or `protected`), the default is `private`, meaning it will not show in your inspector *and* will not be accessible from outside of the class.

Making the property `[SerializeField]` will make it show up in the inspector and you could edit it, but still, because it is `private` (by default) it will not be accessible outside of the class.

Making the property `public` will make it both show up in the inspector *and* other class could access this property from outside the class.

You might want to make your property `public` but make it *not* visible in the inspector, just add the `[HideInInspector]` attribute above the desired property, that way its accessible from outside the class, but not from the inspector.

You can read more about it here and here.
> 3 votes

---
Tags: unity
---


# Question
Title: Looking for the name of the tap handle with four 'spokes'
I am looking for the name of this sort of tap handle. This is a screenshot of it in the game *Monument Valley*. It has four spokes and can be rotated, behaving as one would expect of a similar design on a bathroom tap releasing water.

It was during a game design class, that I am no longer a part of, where the teacher told us that there was a specific name for that sort of tool. But I have forgotten the name and I was wondering if anyone might know.

I tried searching things like "tap handle name", "tap handle four spokes name game design", but couldn’t find the term for it. I was expecting it to not just be limited to game design, since, in that lesson, the teacher also mentioned the book *The Design of Everyday Things* by Don Norman and I was thinking that it might be used as a general term for those types of tap handles. (He mentioned the book for the term "affordances" (which I had heard of before), in the context of the tap handle looking like what it does, and relying on that familiarity of users likely having seen those sorts of tap handles in their everyday lives before). But I also couldn’t find the name when I added the term "affordances" to the search.

# Answer
I'm not aware of a specific term used for this kind of widget in UX/UI design specifically (the way we have names for the hamburger menu or kebab/dango menu)

But searching for "cross handle" turns up lots of physical handles with a similar look, mainly for bathroom and kitchen faucets — though you can also get some more general plumbing handles by prefixing it with "valve":

I think describing it as a cross handle affordance is reasonably descriptive.
> 2 votes

---
Tags: terminology, ui-design
---


# Question
Title: Animate Loading Screen During CPU-Heavy Scene Load
I have a scene with lots of lightweight objects and one that takes anywhere between 10 and 45 seconds to load.

At a high level, the Awake method does...

* Query database
* For each result do some (fairly heavy) calculations
* Populate a list
* Use that list to generate game objects

\[Only the last step of which requires the main thread\]

I have another scene to display a loading screen. It has a UI panel with a shader that shows an animation.

The Loading screen starts a coroutine to switch level...

```
private IEnumerator LoadNewScene() {
    AsyncOperation async = SceneManager.LoadSceneAsync("GalaxyMap", LoadSceneMode.Single);
    while (!async.isDone) {
        yield return null;
    }
}

```

At which point, the animation freezes for 10-45 seconds while the heavy object loads.

In an attempt to make the animation CPU-independent, it's coded as a shader using the built-in `_Time` property.

I assume this is because my heavy object's `Awake()` is running on Unity's main thread and thus is blocking updates to the shader.

If so, I can move a lot of the heavy lifting onto a background thread, but I can't work out how to release the thread back to Unity temporarily.

The Awake() method isn't `async`, and any attempt to create a Task and wait for it will just block the same thread.

Conversely, I could have a completion callback for when the load is done. That would allow me to release the main thread sooner, however, Unity would think my scene had finished loading prematurely and remove the loading screen.

How can I either:

* Release control of the thrad intermittently so Unity can refresh the UI
* Explicitly tell Unity when it should consider a scene "loaded" and ready for display

?

# Answer
> 2 votes
As mentioned in the comments, you can use an ordinary variable to pass around information about when the generation is done. Here's one way to do it:

```
public class GalaxyMap : MonoBehaviour {

    static bool IsGenerationComplete { get; private set; }
    public static void PrepareToGenerate() { IsGenerationComplete = false; }

    public UnityEvent OnGenerationCompleted;

    IEnumerator Start() {
        // Do the bulk of your work on another thread.
        var generatorThread = new Thread(DoBackgroundThreadWork);
        generatorThread.Start();

        // Keep ticking this Start method on the main thread
        // until our threadsafe work is done.
        while (generatorThread.ThreadState != ThreadState.Stopped) {
            yield return null;
        }

        // Now apply any final touch-ups that have to be done on the main thread.
        DoMainThreadWork();

        // Signal to any scripts that were waiting for the load to finish
        // that they can start doing their thing now.
        if (OnGenerationCompleted != null)
            OnGenerationCompleted.Invoke();

        // Signal that we can hide the loading animation.
        IsGenerationComplete = true;
    }

    // Define your worker methods down here...
}

```

Your LoadNewScene function would then look something like this, with two waits: one for loading the scene file itself, and a second wait for the generation.

```
private IEnumerator LoadNewScene() {

    GalaxyMap.PrepareToGenerate();
    AsyncOperation async = SceneManager.LoadSceneAsync("GalaxyMap", LoadSceneMode.Single);

    // Wait while the scene file is loaded.
    while (!async.isDone) {
        yield return null;
    }

    // Continue waiting while the generation is in progress.
    while (!GalaxyMap.IsGenerationComplete) {
        yield return null;
    }

    // Now hide the loading animation and show the generated scene.
}

```

If you had other scripts that were starting to do stuff in their own Awake or Start or Update/etc. that need to happen after generation finishes, you should make them subscribe to the `OnGenerationCompleted` event instead to control when those behaviours kick off.

---
Tags: unity, c#, loading, scene, async
---


# Question
Title: Unity difference between accessing asset prefab from reference VS from Resources.Load?
## Question point

Does putting prefab asset in inspector's reference and access its content inside in runtime VS. Load the same prefab asset from `Resources.Load` API, will both cause entire prefab to load and use same memory footprint?

## Backgroud

In UNET or it's replacement lib, Mirror, you will have to register list of prefab on NetworkManager to spawn on server and clients.

Under the hood, these prefab references will be sent to registration function `ClientScene.RegisterPrefab` which in turn access them as far as `prefab.GetComponentsInChildren<NetworkIdentity>();` (I suspect that this will make entire prefab loaded?)

## VS

I put those prefab in Resource folder, then use API like `Resources.Load / LoadAll` to send them to `ClientScene.RegisterPrefab` (which proved to work too) But many fellow dev warned me about how evil `Resources` API is and using these will load all data into memory, etc.

**Didn't this 2 way ultimately need to access inside of prefab and both need to load entire prefab in?** Is there clear advantage for memory footprint for approach?

---

## Some prior research

In official document about resource management, there is some explanation about how resource will load but it still does not clear up difference between these 2 appraoches.

> 2.7. Resource lifecycle
>
> To reduce loading times and manage an application's memory footprint, it's important to understand the resource lifecycle of UnityEngine.Objects. Objects are loaded into/unloaded from memory at specific and defined times. An Object is loaded automatically when:
>
> * The Instance ID mapped to that Object is dereferenced
> * ...

---

## Foot note/ Some clarification

**Why do you need to use Resources.Load?**

Take UNET example case here in my question, and notice that it needs to know every prefab that will be use in game, that's including monsters, items, bullet. Sure you can drag and drop these to inspector (like in screenshot) but will become tedious and unorganized very fast on magnitude of 50+ prefabs. So instead I organize them to Resources folder like

```
Assets/Resources/EnemyPrefab/Stage1/*.*
Assets/Resources/EnemyPrefab/Stage2/*.*
Assets/Resources/ItemPrefab/*.*

```

To get more organized load pattern. `Resources.LoadAll<GameObject>("EnemyPrefab/Stage1")` will do as it suggest. And skipping tedious inspector drag and drop work, let alone checking what did I missed to drag and drop.

**Can't you just profile it yourself? why asking here?**

I could, but if someone already done this work or has knowledge to confirm such behavior, this could be better, thus this question here. And hey, didn't this is how knowledge is shared and this site is for?

# Answer
> 0 votes
I decided to come back to answer my own question half year later since I started explored more into this asset management thing. Including Unity's new **Addressables** system.

Now for my own main point of question:

Does **referencing prefab in scene** VS **Resources.Load** will use same memory footprint?

### Simple answer for now is YES

According to observation by Reddit **"Today I learned: Prefab references in inspector are loaded into memory even if not instantiated."**

Although reddit thread is very old (2014) I assumed this behavior did not changed and that would support this claim.

* It is become clear that Unity computes all dependencies in scene that you are loading.
* All dependencies are loaded by scene loading process. This strategy prioritize performance when using the object but costs the memory.

So referencing "**tank.prefab**" by drag and drop in scene, or load it later using Resources.Load will result in same memory consumed. Just that Resources.Load will consume memory later, while referencing will consume on scene load.

---

So at the end of the day, the requirement still depends on how your game will need. (mobile game where memory is very restrcited? etc) Or else, ultimately current trend is to move to new **Addressables** system for finer control and better content update anyway.

---
Tags: unity, resource-management, unet
---


# Question
Title: AudioSource.Play() outputs only noise from the sound clip
I'm trying to reproduce a sound clip on the AudioSource of a game object by using the .Play method. What i'm trying to do is a card game of sorts, but with each card being a different section of a song of a genre. I combine different cards with different genres and when i press play, the combination should start playing, but now when the play button is pressed, only noise comes out. The code for the start method looks like this:

```

public class AudioStart : MonoBehaviour
{
    AudioSource thisAudioSource;

    // Start is called before the first frame update
    void Start()
    {
        thisAudioSource = this.GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        if (playButton.playPressed) {
            thisAudioSource.Play();
        }
        else {
            thisAudioSource.Stop();
        }

    }
}

```

The way i'm doing it is by having a button that on click changes a bool to true or false depending if there is sound playing (the truth check on the if statement). The AudioSource outputs to an AudioMixer on a specific group under the master group (which group depends on the slot that the card is dropped in). The AudioStart script is attached to different game objects with a different audio clip each. I've also noticed that when i try to reproduce two cards, only one AudioSource gets played. Any help would be appreciated. Thanks!

# Answer
`PlayOneShot()` will start playing the audio every time the function is called, so calling it in your `Update()` function will cause the clip to start playing every single frame. You get noise because the audio clip is playing playing multiple times simultaneously.

## Solution

```
    void Update()
    {
        if (playButton.playPressed)
        {
            if (!thisAudioSource.isPlaying)
                thisAudioSource.Play();
        }
        else {
            thisAudioSource.Stop();
        }

    }

```
> 0 votes

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


# Question
Title: Can I publish a non-commercial game that uses assets from a 30 years old Konami game on Steam, Google Play and App Store?
Do major platforms like Google Play, App Store, and Steam allow apps to use assets without owner permission in case of 100% non-commercial releases? Do companies like Konami care?

# Answer
> 2 votes
Not legally, no, you cannot use it.

"Abandonware" is not a legal concept, and the original copyright ownership still stands, even if the original product is no longer being sold. Likewise it doesn't matter if you're offering your's for free, you would still be using material that is legally owned by someone else.

Finally, and as always, if you want a qualified legal opinion, then consult a qualified legal professional. The opinions of random anonymous people on the internet will not hold up in court.

---
Tags: assets, legal, copyright
---