# Question
Title: Does a Utility AI system run every update/frame to determine scoring?
Am learning about Utility AI. I understand what it can be used for but not how to correctly implement it.

Does the scoring for an NPC need to be checked every frame/update/tick?

Imagine you have an NPC that patrols their area (default state), become alert when a player is in range (50ft), or shoot the player if the player gets close enough (25ft).

Does the scoring for the NPC get constantly checked for the NPC to be responsive?

I plan to have a lot of NPCs on the map at the same time in the same area, so concerns of all of them checking every frame seems that it could be quite heavy in regards to performance.

# Answer
> 2 votes
First of all, avoid premature optimization! Recalculating all the scores each frame might in fact be a "good enough" solution, even with a hundred AI agents in the scene. I would recommend you to implement this first, do a stress-test while running a profiler, and see if it even shows up in the profiler log. When it doesn't, then everything is fine and you avoided a lot of work for no notable benefit.

But when it does turn out to be a performance bottleneck, then there are a couple optimizations you can do:

* Don't recalculate scores when the agent is in a situation where it can't change its behavior anyway. For example, when it's caught in an uninterruptible animation.
* Don't recalculate every frame, but every `n` frames. This might actually result in a more natural AI, because the AI will often react to changes in circumstances with a delay which simulates human reaction time. In this case you should do staggered updates (evaluate a different set of AI actors per frame). This also has the useful side-effect that not all AI actors will react on the exact same frame. So they won't act in a perfectly synchronized manner. Another nice trick is to modify `n` depending on distance to the player. Update those AI agents which are far away from the player less frequently than those which are nearby.
* Cache the scores for each AI agent and only recalculate them when an input variable actually changed.
* See what you can optimize regarding the input variables themselves. Some things which often feed into utility AI but can be real performance hooks are sightline calculations, pathfinding or environmental proximity queries. There is usually a lot of optimization potential in these.

---
Tags: ai
---


title: Help with multiple powerup types

text:
# Question
Title: Help with multiple powerup types
I am trying to have a single class that handles multiple powerups types and using enum for the types of power-ups and switching the powers based on enum however when there are multiple power-ups in the scene then the collision only registers only for the last powerup in the scene and gives all the powers associated with the not collision registered when collides with last powerup in scene,
Here is the powerup class and enum:

```
using UnityEngine;

[System.Serializable]

public class PowerUp
{
    public PowersList ListofPowers;
    public string NameofPowerup;
    public GameObject PowerUpItem;
    [Tooltip("Time")]
    public float powerOfftime;
    public bool isTrigger = true;
    [Tooltip("Modifier")]
    public float powerInfluencer;
}
public enum PowersList
{
    Move, Jump, Shoot,None
}

```

Here is the Script for managing powerup class :

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerManager : MonoBehaviour
{
    public List<PowerUp> power;
    private Collider2D playerCollider;
    private Collider2D objCollider;
    PlayerController player;
    private float Time;
    private float powerupInfluencer;
    int index;
    private void Awake()
    {
    }
    private void Start()
    {
        InintalizeComponents();
    }
    private void Update()
    {
        TriggerPower();
    }
    private void InintalizeComponents()
    {
        player = GetComponent<PlayerController>();
        playerCollider = player.GetComponent<CapsuleCollider2D>();
        foreach (PowerUp u in power)
        {
            u.NameofPowerup = u.ListofPowers.ToString();
            powerupInfluencer = u.powerInfluencer;
            if (u.PowerUpItem.GetComponent<BoxCollider2D>() == null) u.PowerUpItem.AddComponent<BoxCollider2D>();
            objCollider = u.PowerUpItem.GetComponent<BoxCollider2D>();
            u.isTrigger = objCollider.isTrigger;
            Time = u.powerOfftime;
        }
    }
    private void TriggerPower()
    {
        if (!Touching()) return;
        if (Touching())
        {
            StartCoroutine(GivePower());
        }
    }
    private bool Touching()
    {
        foreach (PowerUp p in power)
        {
            if (!objCollider) return false;
            if (playerCollider.IsTouching(objCollider)) return true;
        }
        return false;
    }
    private IEnumerator GivePower()
    {
        StartPower();
        yield return new WaitForSeconds(Time);
        EndPower();
    }
    private void StartPower()
    {
        foreach (PowerUp p in power)
        {
            SwitchPower(p.ListofPowers);
            Destroy(p.PowerUpItem);
            Debug.Log("PowerStarted");
        }
    }
    private void EndPower()
    {
        SwitchPower(PowersList.None);
        Debug.Log("PowerEnded");
    }
    private void SwitchPower(PowersList list)
    {
        foreach (PowerUp p in power)
        {
            switch (list)
            {
                case PowersList.Move:
                    player.moveSpeed = powerupInfluencer;
                    break;
                case PowersList.Jump:
                    player.jumpSpeed = powerupInfluencer;
                    break;
                case PowersList.None:
                    player.jumpSpeed = 8; player.moveSpeed = 6;
                    break;
                case PowersList.Shoot:
                    player.deservedAmmo += Mathf.RoundToInt(powerupInfluencer);
                    break;
                default:
                    player.moveSpeed = 6; player.jumpSpeed = 8;
                    break;
            }
        }
    }
}

```

*Please help I am searching for an answer about the week, Thanks in advance. and please suggest is there a better way to do this.*

# Answer
> 1 votes
In your `StartPower` function you are just looping the list of powerups so when you call `SwitchPower` and `Destroy` it will affect all elements in the list. The reason you are seeing an effect only for last power up is that it is the last one in the list. You should change your `StartPower` function to take a type of powerup as parameter (like `StartPower(PowersList typeOfPowerUp)` ) and drop the `foreach` loop because you don't need it there. So when you call that function, you pass it the right type of powerup.

First, you need some way to know which powerup you are colliding with. There are multiple ways to do this: you could use tags or have some variable that identify the powerup. If you are attaching the powerup script to different game objects that you instantiate and you don't have a lot of powerups, the easiest way would be using tags and checking them on collision.

If you have one game object that changes its data based on some type variable Like your `PowersList` then you can check the set type on collision.

That are some approaches that I suggest: instead of using `for` loop for check all the powerups like you did, you could get the information of the powerup in the `OnTriggerenter` function.

Let's return to your specific problem of getting the last element. As I said, you are getting last element because you don't specify what powerup you want in your `StartPower` function. You are just looping them all and applying the same function on all of them. If you insist on using a `foreach` loop here, you should do something like this:

```
private void StartPower(PowersList typeOfPowerUp)
{
    foreach (PowerUp p in power)
    {
        if(p.ListofPowers == typeOfPowerUp)
        {
          SwitchPower(p.ListofPowers);
          Destroy(p.PowerUpItem);
          Debug.Log("PowerStarted");
        }
    }

```

That should apply the functions on only the chosen powerup.

# Answer
> 1 votes
If I was implementing something like this I would probably use inheritance. I would have a base class Power that contains all the methods you need and abstract/virtual methods for applying the power. Each powerup could then be its own class that overrides the virtual apply power method and the rest of the powerup is managed by your base class.

---
Tags: unity, c#, 2d, game-mechanics, platformer
---


# Question
Title: AI for auction bids in the Monopoly game
I'm currently creating a **Monopoly** game simulator in C++.

I am currently struggling with implementing the auction mechanic for AI players.

How could I implement the bots' participation in auctions? How could I define when the bot should buy and item, or when it shouldn't?

I know for a fact that it should take the color of the property and money into consideration, but could you put me on the right track?

# Answer
To determine an auction bid, you need the AI to be able to estimate the **value it expects to be able to earn** from that property.

First then, we need an estimate for **how many rounds the game is likely to last**. You could get this by playing a large number of games and calculating the average number of rounds they go for. Or for a more dynamic estimate, compute the average rate of money loss for a losing player at each turn. The estimated turns remaining can then be found by taking the current net worth of all players and subtracting this value for each projected future turn until all but one is reduced to zero. If you don't have the data gathering to support this, you could also just take the average rental cost on the board currently and divide the second-highest net worth by this value as a crude estimate.

Next, it needs to compute **how many times an opponent is likely to land on that property in that remaining time**. To a first approximation, players land on 1 space per round out of 40 spaces on the board, so we'd expect roughly `remainingOpponents * remainingRounds / 40.0` opportunities to collect rent from this property in future. Multiply this by the rent and you have a guess at how much income this property will generate.

At any time this property may also be **mortgaged**, so add the mortgage value to the expected gain to get our first estimate of its net worth to the AI. (So even a property with negligible future rent prospects may still be worth picking up if we can buy it at/below its mortgage value).

This estimate can now be used as the **upper limit for the AI's bid**. It should start bidding below that value and above any opponents' bids (you can use your heuristic of choice to choose a starting bid/increment), and stop bidding if the leading bid goes above this threshold. At that point we'd estimate that buying this property would be a net loss by endgame.

We can refine this estimate in various ways:

* If the AI collects **all properties of this colour**, or **improves** this property with houses/hotels in future, the rent may increase.
* If the AI **already owns other properties of this colour**, getting this property could increase the rent they can charge at those properties too, or enable improvements via houses/hotels.
* If the AI is short on cash, it may want to factor in the **opportunity cost** of spending its liquid funds at auction. You could evaluate the expected value of buying any of the available properties the AI is *likely* to land on next turn — if the expected value there is greater, cap your bid at what you can spend while still affording this future purchase.
* You could add in the **expected savings in rent** that you would otherwise pay in the future if the opponent with the current leading bid were to win. This can also include savings from landing on their \*other" properties of the same colour, whose rents may increase if they complete their set with this one, and increase further if they then build houses...
* You can add an "**overspending budget**" per lap, equal to the $200 passing GO bonus plus the AI's average rate of earning/spending on rent in a lap (measured from recent laps, or estimated by current property ownership). The AI can over-bid by this amount per lap (or per round if you divide it by the number of rounds per lap), and still stay in the black — still not have a net drain on its coffers. If you spread this over the lap then you'll tend to have leftover budget as you turn the last corner, so you can bid more aggressively on the high-value properties at the tail end of the board.

If the AI has more cash in hand than it's likely to need to pay rent in the short term, then it can similarly increase this budget.
* You could run this estimator from each opponents' perspective, and if it has high value to the leading bidder, bid up to a factor of their valuation, to **drive up the price** they pay or **deny** them the ability to secure it.
* If the supply of available properties is dwindling or the AI is behind its opponents in terms of properties in hand, you may want to increase this estimation by a "**hunger factor**" to guard against the AI being shut out of the property game while waiting for the optimal purchase to come along.

Each of these refinements can make the AI more strategically savvy and might improve numerical results over a large number of games. But they also increase the **complexity** of the algorithm and might not significantly improve the perceived intelligence of the AI from the players' perspective — overcomplicating this could actually make the AI look *less* intelligent, if it makes a bidding choice for non-obvious reasons that look to the players like a bug. So exercise judgement in deciding just how nuanced this feature needs to be for your goals guiding this project.
> 34 votes

# Answer
DMGregory gave you a lot of ideas on how to value property. However, your starting point should back up a bit:

Design your game engine from the ground up to permit running all-AI games that simply write log information but run **without interaction**. You can pit a group of AIs against each other, set it to play 1000 games and walk away.

As you're looking at the logic, try different values. How much value do we attach to having another property in the group? Take a group of AIs that are identical except they attach different importance to this, make them play a lot of games. Whatever AI wins the most is probably the best setting.

I would also try to figure out a reasonable range for settings and make the AIs pick a somewhat random value in that range so it plays a bit differently in each game. Being able to 100% predict the AI behavior isn't fun.
> 17 votes

# Answer
Something else to consider is that there are situations where a property is much more valuable to a particular player than other players. (e.g. it completes their set). A system would likely involve each AI calculating how much it would be willing to pay for the property. As Monopoly is a perfect information game the same calculation could be run from other players' perspectives to understand how valuable the property is to them. Each player could then have a value for their own 'bidding aggression' (it could be dynamically changed to be higher when winning). The player could then set their own perceived value to:

`max(ActualPerceivedValue, BiddingAggression*max(perceived values from other perspectives))`.

A bidding aggression of 0.75 for example would mean that the player would bid to up to 75% of what it is predicting the player who wants the property the most will pay. This is good as it forces said opponent to pay more than they might otherwise. If each AI had its own personality parameters and ran the other perspectives with these parameters it would mean the estimations of the opponents strategies would not be perfect and lead to interesting interactions. The bidding aggression could also be set to \>1 when strongly winning just to bully weaker players out of being able to buy properties and mount a comeback.
> 3 votes

# Answer
It's a very rough approximation of an AI, but this video on the Nintendo Entertainment System version of Monopoly might shed some insight. Especially if you can read assembly: https://www.youtube.com/watch?v=lHhdPrD0mUY
> 2 votes

---
Tags: ai, strategy, economy, bot
---


title: Why the distance is never less than 1?

text:
# Question
Title: Why the distance is never less than 1?
The distance is 1.07 and changing sometimes at this point the distance is 1.06 or 1.07 more or less this range.

```
float playertargetdistane = Vector3.Distance(player.position, target.position);

            if (playertargetdistane < 1.06f && startSlow && speed == 1f)
            {
                StartCoroutine(ChangeSpeed(1, 0, 3f));

                startSlow = false;
            }

```

This screenshot show when the player is reaching the target a cube.

It seems to me that both colliders are almost if not touching each other and yet the distance is never less than 1. So I tried to check for less than 1.06 but sometimes it's 1.07 more or less at this time.

If the colliders are so close to each other ho come the distance is never less than 1 ?

# Answer
> 2 votes
The Vector3.Distance between two transforms is measured from their centres, not the edges of the colliders. You might have btter luck with Collider.ClosestPointOnBounds

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


# Question
Title: How can I bake 2D sprites in Godot at runtime?
I would like to use the technique described here to create a player sprite with unlimited clothing and equipment options (like in Stardew Valley).

To elaborate: I want to have a sprite sheet for the player sprite's body, some number of sprite sheets for clothing items the player sprite could wear, and some number of sprite sheets for tools the player sprite could carry. Once the (human) player has selected the desired body, clothing, and tool, I want to layer and bake the chosen items into one sprite sheet.

In Godot Engine, how is this kind of baking accomplished at runtime?

# Answer
> 6 votes
So you let the player select a series of sprite sheets. And there is some order in which you overlay them to create the sprite sheet of the player.

---

## Image manipulation at runtime

We can create an `Image`:

```
var image = Image.new()
image.create(256,256,false,Image.FORMAT_RGBA8)

```

*Change `256,256` with the appropriate size.*

There the format is important. You want a format that has an alpha channel, otherwise, you will not be able to draw with transparency.

---

Now we need the image we are going to draw (the first sprite sheet). We can use `load` or `preload` to get it. For example:

```
var icon := preload("res://icon.png")

```

We usually import as textures, but we want an image. So we use `get_data()`:

```
var source := preload("res://icon.png").get_data()

```

Then we can draw it with `blit_rect`:

```
image.blit_rect(source, Rect2(Vector2.ZERO, source.get_size()), Vector2.ZERO)

```

There the `Rect2` is the source area (the area of the image we are drawing that we want to draw) which goes from `Vector2.ZERO` to the size of the image. The other `Vector2.ZERO` is the position where we want to draw it.

Now the idea is that you will do that for all the sprite sheets that you need to draw.

---

**Note**: depending on the format of the image you want to draw, you may have to convert it first:

```
source.convert(Image.FORMAT_RGBA8)

```

Also, usually, the images are imported in a compressed format that cannot be converted directly, and thus you would have to decompress first:

```
source.decompress()
source.convert(Image.FORMAT_RGBA8)

```

If the `blit_rect` line is giving you problems, try that.

---

## Using a Viewport texture

If you found the above approach too limiting. You can add a `Viewport` with a `Camera2D`. Then to get the texture from the `Viewport`, you can use `viewport.get_texture()` (and, of course, you can get an `Image` from it with `.get_data()`).

Thus, you can add to the `Viewport` anything you want to draw. Which means that you can add multiple nodes to compose the image, with their transforms and modulations. Or it could be a single one which uses the methods described in Custom drawing in 2D, or CanvasItem shaders (For example, you may allow the user to do a hue rotation of a sprite sheet, implemented in a shader). Or combinations of those techniques.

---

## Creating sprite frames for animation

Once you are done, you can create an ImageTexture from the `Image`, like this:

```
image_texture = ImageTexture.new()
image_texture.create_from_image(image)

```

Since we are talking of sprite sheet, we can create `AtlasTexture`s:

```
func get_texture_frame(row, column):
    var t = AtlasTexture.new()
    t.atlas = image_texture
    t.region = (
            column * SPRITE_WIDTH,
            row * SPRITE_HEIGHT,
            SPRITE_WIDTH,
            SPRITE_HEIGHT
        )
    return t

```

Then we can add the `AtlasTexture`s to a `SpriteFrames` with `add_frame` to use them in an `AnimatedSprite`.

Creating a `SpriteFrames` in code looks something like this:

```
var frames := SpriteFrames.new()
frames.add_animation("animation_name")
frames.set_animation_speed("animation_name", frames_per_second)
frames.add_frame("animation_name", get_texture_frame(0, 0))
frames.add_frame("animation_name", get_texture_frame(0, 1))
# …

```

---

## Persistent storage

If you want to save an `Image`, you can use `save_png`.

If you want to save the `ImageTexture` or the `AtlasTexture`s or the `SpriteFrames`, you can use `ResourceSaver.save`. I suggest to use path in `user://`, see Data Paths.

To load them again, you can use `load` or `ResourceLoader.load`.

---
Tags: sprites, godot
---


title: How does pathfinding in RTS games work?

text:
# Question
Title: How does pathfinding in RTS games work?
\[crossposted from stackoverflow\]

In a game such as Warcraft 3 or Age of Empires, the ways that an AI opponent can move about the map seem almost limitless. The maps are huge and the position of other players is constantly changing.

How does the AI path-finding in games like these work? Standard graph-search methods (such as DFS, BFS or A\*) seem impossible in such a setup.

# Answer
In most cases, using A\* over a navigation mesh (commonly referred to as a "navmesh") is the pathfinding solution commercial RTSs use. There is a detailed explanation of how navmeshes work, why they are a better solution than waypoint systems, and links to implementation resources, here.

If you're planning on developing special game modes (point/node capture) or units that patrol, take cover, etc., you will probably want to implement a waypoint layer atop your navmesh, to control AI behavior (**not pathfinding**).
> 31 votes

# Answer
Check out the Flowfield algorithm used in Supreme Commander 2. It does a much better job than most RTS pathfinding systems do (skip ahead to 0:50 for a few examples.)
> 19 votes

# Answer
Many older games do use A\*. The original Starcraft used A\*; which led to some problems in dealing with collision. Starcraft 2's handles collision very well, using a swaming/flocking behavior to maintain fluid control of large groups. This gamedev article discusses how this might be being achieve.
> 7 votes

# Answer
I agree upon the other answers her already, but also, try to think of WoW/Warcraft3 as actual 2D worlds. They arent that different from tilebased, its just the tiles.

You could also think of how does a GPS find the best path? there a loads of algortimns for pathfinding through linked maps.

I think some of the first "Quake bots" scripts also might help you, as they were developed to work in "unknown areas" because we could design our own levels from scratch.

All in all, my personal way to deal with such a map, would be to think of it as the A\* pathfinder. But first I would pre-calc every "tile point" and index all these with "nearest neighbour" etc. Then when an object needed to go from A to B then just lookup in B, see to what its connected and keep repeating until you reach the goal.

Depending on the type of game and landscape/scenario, different pre-scan tactics might be usefull too. Some games have very little obstracles and these can be "streight line" movement + some "how do I get around" for objects.

Hope this makes a little sense and perhaps gave you some thoughts to work with.
> 2 votes

# Answer
I agree with other answers that the A\* algorithm (or variants) is used often, but in some old RTS games (eg: Command & Conquer / Warcraft 1) a simpler and faster approach is used.

It works this way : project an imaginary line-of-sight from the unit position to its destination. Most of the time, there is no obstacle between unit and target, and it can stop there since it already found the closest path.

If obstacles are found (eg: trees), the algorithm try to get around it by moving around the edges. To do this, the unit is rotated a certain number of degrees (eg: 45) until it can move again. It check two paths : left and right path (depending unit orientation when obstacle is encountered) and it take the shortest one. While moving around the edges, it try to move back towards the imaginary line-of-sight (which might not be possible because there are still obstacles).

Once unit is back to the imaginary line-of-sight, it resume path finding from there. More obstacles might be encountered and so on. It stops once target is reached.

It can result in a suboptimal path but on the other hand, it's really cheap to compute. In some extreme cases, unit might get lost (no path was found while there is at least one).

(from Warcraft 1 : peasant has to backtrack, resulting in suboptimal path)

Sources :
> 2 votes

# Answer
I'm totally not experienced, but I think that a good solution is based on heuristics, not on a complete checking of the known map. Heuristics I can think of are locally based and experience based. Local controls can be based on local terrain check and obstacles, keeping moving toward the required direction. I think that most maps don't require complex maze-like movements, but are pretty connected. Another heuristic is to use previous known paths (explored by other units or explicitly by the user) to move units to known or near-known positions. But I'm talking about moving on big maps, not really in closed spaces like ZorbaTHut said. In crowded cases the algorithm may be more complex, requiring sorts of "prediction", coordination among units of the same team or just semaphore-like waiting strategies. Also, note that continuous or discrete terrain and unit size calculation are really important when working on this case.

I think heuristic algorithms are good because they usually provide a good solution on big spaces with a reasonable computation time (which does matter, when you're moving many units).

Sorry if this a generic answer: I worked with crowds, but the space was pretty peculiar and I can't explain exactly how the algorithm worked (was agent based, anyway, not globally defined). I hope you can get some useful ideas from my answer.
> 1 votes

# Answer
Map is a grid. Grid is a graph. A\* works on graph, it is a graphs searching algorithm. A\* should search few nodes of graph.

As has been mentioned they can use navigation mesh. But the A\* (or something similar) will be on top of that mesh anyway, because polygons of this mesh are just nodes of a graph; A\* will then search for path from one polygon to another polygon.

Not sure about Warcraft or commercial games, but there is also technique called Collaborative Diffusion and it is very simple; it is usually done on grid. There is also technique called Potential Fields, which is very similar to previous one if not the same.

You might also try:

* whether some of these games have source code available
* whether some of clones of these games have source available
* whether SDK or editors don't hint something
* ask employers of companies making these games, some of them might be willing to share
> 1 votes

# Answer
Most games do use some sort of Search Algorithm or A\* to find paths on a map. The AI is tweaked in some aspects obviously for performance reasons.

You will notice this in Starcraft 2 where Zerglings obviously don't path well at all, it would be a CPU nightmare to do that for Zerglings. They just do there best to get from A to B and don't even attempt to find the best path. They will get as close as possible then bottle neck at the chokes or ramps.
> 0 votes

# Answer
Those older games probably did use grids and standard A\* but maybe with additional optimisations such as jump search A\* or simply tweaking the heuristic. There's also basic techniques that can be applied like staggering path requests across several frames or grouping path requests for groups of units.

More modern rts games like Starcraft2 may use navmesh or flowfields.
> 0 votes

---
Tags: ai, path-finding, game-mechanics, search
---


# Question
Title: Should Game-Ready Assets Be Single Meshes or Multiple Meshes?
Say for example that someone is modeling a sword asset. A sword has many pieces -- the blade, guard, hilt, pommel, etc. -- so should this be modeled as a single mesh (or as multiple meshes which then get boolean'ed, joined, etc. into a single mesh), or should each piece be modeled separately and then get constructed and glued together later in a game engine environment?

# Answer
Some games/engines might be happy with a single mesh, a generic material and a texture, so that they could put it into the atlas with e.g. other weapons.

Some games/engines might need a standalone model with custom material and textures and masks denoting material properties (diffuse, roughness, specular, metallic, reflectance, etc)

Some games/engines might benefit from or need a multi-mesh and multi-LOD model with custom materials and textures and masks denoting material properties (diffuse, roughness, specular, metallic, reflectance, etc) for each separate mesh.

**It all depends on your target game/engine requirements.**

As an approximate guideline - the more highpoly/detailed the model is - the more effort might need to go into structuring and organizing it (masks, materials, textures, layers, meshes, LODs). If anything, you can include several levels of detalization in the pack.
> 1 votes

# Answer
It depends on how you plan to use those meshes.

On your example, if the sword and the hilt and all the other components are meant to be together, and are **never** meant to be separate, then there's pretty much no reason to have them as separate meshes during loading. It just adds complexity, and could potentially make drawing that asset slower (if not optimised right).

Having said that, both ways would work. A mesh would mostly be divided into separate meshes if it needs to be this way, either because it can be separated at some point during the game (a sword that breaks into pieces?) or if parts of a mesh are reused in other areas (some hilts can be found without a blade in the game).
> 1 votes

---
Tags: 3d-meshes
---


# Question
Title: How can I wait for the coroutine to over before starting again using a flag?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GenerateWalls : MonoBehaviour
{
    public GameObject gameObjectToRaise;
    public float duration;
    public Vector3 raiseAmount;
    public bool go = false;
    public Color[] colors = new Color[4];
    public bool randomColors = false;
    public bool waitForScaleOver = false;

    private GameObject objtoraise;
    private GameObject[] walls;

    private void Start()
    {
        Init();

        ColorWalls();

        // The z Axis must be minimum 1 or any value above 0 could be also 0.1f
        // but it's better to keep it minimum as 1 by default.
        if (raiseAmount.z < 1)
        {
            raiseAmount.z = 1f;
        }

        if (go)
        {
            waitForScaleOver = false;

            StartCoroutine(ScaleOverSeconds(objtoraise, new Vector3(raiseAmount.x, raiseAmount.y,
                raiseAmount.z), duration));
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            if (waitForScaleOver)
            {
                if (objtoraise != null)
                {
                    if (raiseAmount.z < 1)
                    {
                        raiseAmount.z = 1f;
                    }

                    Destroy(objtoraise);
                    Init();
                    ColorWalls();

                    StartCoroutine(ScaleOverSeconds(objtoraise, new Vector3(raiseAmount.x, raiseAmount.y,
                        raiseAmount.z), duration));

                    waitForScaleOver = false;
                }
            }
        }
    }

    private void Init()
    {
        objtoraise = Instantiate(gameObjectToRaise);
        objtoraise.name = "Walls";

        walls = GameObject.FindGameObjectsWithTag("Wall");
    }

    public IEnumerator ScaleOverSeconds(GameObject objectToScale, Vector3 scaleTo, float seconds)
    {
        if (objectToScale != null)
        {
            float elapsedTime = 0;
            Vector3 startingScale = objectToScale.transform.localScale;
            while (elapsedTime < seconds)
            {
                if (objectToScale == null)
                {
                    yield return null;
                }
                else
                {
                    objectToScale.transform.localScale = Vector3.Lerp(startingScale, scaleTo, (elapsedTime / seconds));
                    elapsedTime += Time.deltaTime;
                    yield return new WaitForEndOfFrame();
                }
            }

            objectToScale.transform.localScale = scaleTo;

            waitForScaleOver = true;
        }
    }

    private void ColorWalls()
    {
        for (int i = 0; i < walls.Length; i++)
        {
            if (randomColors)
            {
                walls[i].transform.GetChild(0).GetComponent<Renderer>().material.color
                    = GetRandomColour32();
            }
            else
            {
                walls[i].transform.GetChild(0).GetComponent<Renderer>().material.color = colors[i];
            }
        }
    }

    private Color32 GetRandomColour32()
    {
        //using Color32
        return new Color32(
          (byte)UnityEngine.Random.Range(0, 255), //Red
          (byte)UnityEngine.Random.Range(0, 255), //Green
          (byte)UnityEngine.Random.Range(0, 255), //Blue
          255 //Alpha (transparency)
        );
    }
}

```

In the Update I'm using the flag waitForScaleOver and it's working fine I press the R key and than need to wait for the coroutine to finish before the next R pressing will take affect again.

The problem is if I want not to wait for the coroutine to finish so I can press R in the middle and re start the coroutine over and over. It will work if I will not use the flag waitForScaleOver but I want to use the flag because I want to decide if to wait for the coroutine to finish or not when pressing the R key but I can't find the logic with the flag on how to do it.

# Answer
> 0 votes
I'm not sure what are your intention exactly but you can stop the coroutine by saving a reference from the value returned by StartCoroutine then passing that reference to StopCoroutine when WaitForScale is true and the reference to a coroutine is not null

# Answer
> 0 votes
As Gabriele said you want to save a reference to the coroutine so you can stop when you want to finish it early.

```
Coroutine scaleCoroutine; // Add this reference to the class

private void Update()
{
    if (Input.GetKeyDown(KeyCode.R))
    {
        if(!waitForScaleOver)
        {
            StopCoroutine(scaleCoroutine);// End the coroutine early here
        }

        if (objtoraise != null)
        {
            if (raiseAmount.z < 1)
            {
                raiseAmount.z = 1f;
            }

            Destroy(objtoraise);
            Init();
            ColorWalls();

            scaleCoroutine = StartCoroutine(ScaleOverSeconds(objtoraise, new Vector3(raiseAmount.x, raiseAmount.y,
                raiseAmount.z), duration)); // Update the coroutine reference here when starting the coroutine

            waitForScaleOver = false;
        }
    }
}

```

*Hope this helps as you didn't reply to Gabriele or accepted his answer.*

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


# Question
Title: Entity Component System - How to detect what entity to update
everyone. I'm kinda new to game dev, I saw the idea of the ESC system and I'm inlove with it. I wanted to integrate something like that in my game, so I started rewriting my code. . I have a `World`, that has a `Manager` attached to it. This manager takes care of all the `Systems` attached to this world that we will iterate over and use to update our game. Also the manager takes care of the `Entities` of the `World`. Every `System` and every `Entity` can have a `Component` attached to them. In the `System` the component represents the actual `Components` of every `Entity` that it's responsible for updating. On the other hand the `Entity's` `Components` are just condition (or behaviours) of the `Entity`. Like the player can walk, run, jump etc...

Everything seems to be fine I guess. The problem is when I want to perform the actions of updating the actual components. I can't wrap my head around of what to pass to the `System`. How do I know what entity I have to update? I'm using JS by the way. So lets say I have a `eventListener` attached to the `window` object. Whenever a player presses a KEY I want to update his position. I have a `PositionComponent` that is attached to my `Player` entity that has a ID generated by the following line of code

```
createEntity(components) {
    const id = (new Date().getTime()) & 0xffffffff; // Generate random 32 bit integer

    let mappedComponents = [];
    components.forEach((component) => {
        mappedComponents.push({
            [component.name]: component,
        });
    });

    this.entities.set(id, mappedComponents);

    return id;
}

```

Now this bad boy is a `Entity` with a `ID` and has a `Component` attached to it. But I also have like 10 more enemy entities with the same `Component` as the `Player`. How am I supose to determine who is moving? I just don't seem to get this part.

EDIT:

I probably need to clarify that every `Entity` has a unique by it's `ID`. So are the `Components` in it. Since every `Component` tha is attached to a `Entity` is a new instance of that `Component` and saves the data for the `Entity`. For example: This is a `Position` `Component`

```
export default class Position {
    constructor(x, y, rotation) {
        this.name = 'Position';
        this.state = {
            x,
            y,
            rotation,
        }
    }
}

```

This is how I attach `Component` to a new `Entity`

```
let playerEntityId = gameWorldManager.createEntity([
    new Position(20, 30, 0),
    new Renderable('#FFFFFF')
]);

```

# Answer
> 2 votes
> The problem is when I want to perform the actions of updating the actual components.

What you've shown us seems to imply that the Component instances are owned by the Entity instances.

Assuming that System act upon one or more Component(s) of a single Entity, you need to make them aware that a new Entity has been created and has a set of Components they are interested in.

So once you create the Entity, pass it to every system, and let each system keep a reference to the entity (or to the set of components of that entity).

So when you need to update your game loop, you just need to call every System update method; they'll each loop through their set of component and act upon them.

Given this,

> I can't wrap my head around of what to pass to the System.

You pass nothing when you update your System. You only need to bother about updating the list of references your Systems have when you create or remove components.

> How am I supposed to determine who is moving?

Yep, the Entity representing your Player and the Enemies will all have the same components to display and place them around. The difference will be in how you control them.

You'll attach a "PlayerControlled" Component to the Entity that represents your player, this Component will do nothing per se (unless you need it to keep some kind of state), it's just that one of your Systems will act upon Entities that have both a Position component and a PlayerControlled component: the update method of the system will translate the "keyboard events" into "player moves" and update the Position component with it. Yes, the list of that System will contain only one set of components (or Entity).

Similarly, you'll attach a "AiControlled" Component to the Entities that represent the Enemies. The System that will update entities that have both AiControlled and Position will need to figure out what to do with each of those entities.

---

As a final note, it's great to look around at how other folks have done it, but keep in mind that there is no ECS police that will tell you that you're doing it right or wrong. An ECS is a means to an end, not an end in itself; in the paragraphs above, I mention *"Yes, the list of that System will contain only one set of components (or Entity).*". It could make more sense to you to just have keep this as a variable and not in a list.

If this is your first iteration, and "it works" you can go on with it and release your game with it, then improve upon it with the knowledge that you've gained with this project and release your next game with a better version.

---
Tags: javascript, entity-component-system
---


title: Convert Byte[] to GameObject in webgl

text:
# Question
Title: Convert Byte[] to GameObject in webgl
Currently i am using the package to download zip file which contains 3d models in **obj** format. The download has been completed and converted to byte\[\], but I am not finding any way to convert the byte array to gameobject. Some solutions suggested writing the byte in a file but the problem is i am using webgl platform where IO is not allowed. Then how to convert byte to gameobject in webgl

# Answer
The problem is that an exported Unity project does not include the code necessary for importing models in 3rd party file formats like OBJ into the internal asset format of the game engine. That means importing raw .obj files at runtime would require your own implementation for parsing the file format (here is the specification) and turning it into a Mesh object. It's not actually that complicated compared to other 3d file formats out there, but would still be quite a lot of work, depending on how much of the format you need to support.

However, it would be much easier if you packed those 3d models into Asset Bundles using the Unity engine. An asset bundle is a packed archive of already imported and game-ready Unity assets. These assets can be just the models, or even complete prefabs with multiple components including MeshFilters which reference those models.

You can then download those asset bundles at runtime with the method `UnityWebRequestAssetBundle.GetAssetBundle(url)`. You can then extract the assets from that asset bundle via the methods of the `AssetBundle` class or via Addressables.
> 2 votes

# Answer
You might want to consider Asset bundles. The idea is to first create the gameobject in game then export it in a format which unity is able to load at runtime.
> 1 votes

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


# Question
Title: Limit rotation/direction of two axes with seperate values (Vector3)
#### Issue

I'm trying to create a vector pointing in a direction towards a target, and then using that vector rotate a child transform to face the target while limiting the rotation on the X and Y axis, with seperate min/max values per axis.

#### Current Code

```
Vector3 targetVector = Camera.main.transform - transform.parent.position;
Vector3 rotateVector = Vector3.RotateTowards (transform.parent.forward, targetVector, maxRotation * Mathf.Deg2Rad, 0f);

transform.rotation = Quaternion.LookRotation (rotateVector, transform.parent.up);

```

The above code is closest I've come to getting the child transform to face the target while limiting how much it can rotate, what it doesn't allow me to do though is set different rotation limits on each axis.

#### Theory

Can anyone confirm it's possible to use the forward and up vector of the parent transform to create some form of zeroed rotation reference, and then using the direction vector towards the target to create another vector which is clamped to not exceed some value of degrees on either axis - and then finally use that vector to set the rotation of the child object?

For example, not exceeding negative ten or positive forty five degrees on the Y axis, while also not exceeding negative forty five or positive seventy on the X axis away from the parent transform forward vector.

#### Images

In the hopes of better explaining exactly what I'm trying to do I've created a couple of GIF - represented in them are:

* The pink cross is the target transform
* The orange line is the direction to the target transform vector.
* The solid blue line is the forward vector of the child transform.
* The solid green line is the up vector of the child transform.
* The dashed blue line is the forward vector of the parent transform.
* The dashed green line is the up vector of the parent transform.
* The brighter green arc represents the ideal min/max rotation of the target vector.
* The brighter red arc represents the ideal min/max rotation of the target vector.
* The darker green arc represents the current limited rotation of the target vector.
* The darker red arc represents the current limited rotation of the target vector.

#### In-closing

The crux of the issue is I'm dumb as all hell, and vectors, euler angles and quaternions are the work of the devil so any help would be **greatly appreciated**, and thank you to anyone who reads this.

##### Attempted Solution

Using the code as suggested by DMGregory:

```
Vector3 targetDirection = (transform.parent.InverseTransformPoint (targetPosition) - transform.localPosition).normalized;

float yaw = Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
float pitch = Mathf.Asin(targetDirection.y) * Mathf.Rad2Deg;

yaw = Mathf.Clamp(yaw, minYaw, maxYaw);
pitch = Mathf.Clamp(pitch, minPitch, maxPitch};

transform.localRotation = Quaternion.Euler (pitch, yaw, 0);

```

The pitch angle seems to be reversed, I think it is because the default rotation of the Wrist Bone is one hundred and eighty on the Y axis, while the default rotation of the Hand Bone and Right Hand is zero on the same axis.

```
Vector3 targetDirection = initialRotation * (transform.parent.InverseTransformPoint (Camera.main.transform.position) - transform.localPosition).normalized;

float yaw = Mathf.Atan2 (targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
float pitch = Mathf.Asin (targetDirection.y) * Mathf.Rad2Deg;

yaw = Mathf.Clamp (yaw, limitYaw.min, limitYaw.max);
pitch = Mathf.Clamp (pitch, limitPitch.min, limitPitch.max);

transform.localRotation = Quaternion.Euler (pitch, yaw, 0f) * initialRotation;

```

I've "fixed" the issue by multiplying both the targetDirection and Quaternion.Euler by the initial rotation of the child transform: I'm unsure if this is actually a fix, or just seems to work in the limited amount of testing I have done, do you have any ideas on how to solve this correctly?

---

Thank you very much, I've been trying to do this for weeks (even using code very similar to yours) with zero success until now - I really do appreciate the time you've spent helping me.

###### Probable Solution

<sup> Abondon all hope and finally give up - not just on ever getting this working but on life itself. </sup>

# Answer
> Abondon all hope and finally give up - not just on ever getting this working but on life itself

There's no need to get so dramatic. This is a pretty simple application of spherical coordinates.

```
// Transform the target point into our parent's coordinate space,
// and compute the direction toward it.
Vector3 targetDirection = (
    transform.parent.InverseTransformPoint(
       targetPosition
    ) - transform.localPosition
 ).normalized;

// Convert this local direction into spherical coordinates.
float yaw = Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
float pitch = Mathf.Asin(targetDirection.y) * Mathf.Rad2Deg;

// Apply your desired clamping.
yaw = Mathf.Clamp(yaw, minYaw, maxYaw);
pitch = Mathf.Clamp(pitch, minPitch, maxPitch};

// Convert angles into a local orientation quaternion.
transform.localRotation = Quaternion.Euler(pitch, yaw, 0);

```

This is assuming that you want your min/max specified relative to the parent's orientation — where 0 pitch/yaw points along the parent's forward vector. If you want a different reference coordinate system that can be arranged with a small extra effort.
> 1 votes

# Answer
I think your original solution was correct with one mistake:

```
Vector3 targetVector = Camera.main.transform - transform.parent.position;
Vector3 rotateVector = Vector3.RotateTowards(transform.parent.forward, targetVector, maxRotation * Mathf.Deg2Rad, 0f);
// maxRotation should be updated every frame to incorporate the already applied rotation value
transform.rotation = Quaternion.LookRotation(rotateVector, transform.parent.up);

```

I'm guessing this code snippet is called on every `Update()`, in which case the problem is that you're not properly "updating" the `maxRotation` value. The `maxRotation` will clamp the rotation value for the *specific* call of `RotateTowards`, this means that for every `Update()` call, if the rotation would be larger than the `maxRotation` value it is clamped. However the next call will not take into account the *already applied rotation* on your object. You are essentially moving the goal post further and further, what you should do is subtract from the `maxRotation` value, the current rotation of the transform and once rotation reaches its maximum value then `maxRotation` should be 0.

**EDIT:** Giving an example in code (not sure if my Unity script is correct) I'd do:

```
private readonly float maxRotation = 5f;
private float currentMaxRotation = maxRotation;

Update() {
  Vector3 targetVector = Camera.main.transform - transform.parent.position;
  Vector3 rotateVector = Vector3.RotateTowards(transform.parent.forward, targetVector, currentMaxRotation * Mathf.Deg2Rad, 0f);
  float rotatedAmount = Vector3.Angle(transform.parent.forward, rotateVector);
  this.currentMaxRotation -= rotatedAmount; // if we rotated by 2, then in the next Update call we'll have a maximum of 3 now, until we reach 0.
  if(this.currentMaxRotation < 0) this.currentMaxRotation = 0;
  transform.rotation = Quaternion.LookRotation(rotateVector, transform.parent.up);
}

```

This code obviously needs extra parts for resetting the "currentMaxRotation" to be non 0 again but I wanted to demonstrate the gist.
> 0 votes

---
Tags: unity, c#, rotation, angles
---


# Question
Title: Move between two points at a constant speed in LWJGL
I've been making a game engine in lwjgl and I have been trying to get an ai to move from one point to another. I used a lerp method but the speed is dependent on the distance between the two points, where I need the speed to be constant

```
    public static Vector3f moveTo(Vector3f currentPos, Vector3f targetPos, float speed)
    {
        float x = lerp(currentPos.x, targetPos.x, speed);
        float y = lerp(currentPos.y, targetPos.y, speed);
        float z = lerp(currentPos.z, targetPos.z, speed);

        return new Vector3f(x, y, z);
    }

```

I was thinking of dividing by the distance, like this:

```

    public static Vector3f moveTo(Vector3f currentPos, Vector3f targetPos, float speed)
    {
        float dist = distance(currentPos, targetPos);
        float x = lerp(currentPos.x, targetPos.x, speed / dist);
        float y = lerp(currentPos.y, targetPos.y, speed / dist);
        float z = lerp(currentPos.z, targetPos.z, speed / dist);

        return new Vector3f(x, y, z);
    }

```

but the results are... weird, to say the least.

# Answer
Your question is not about lwjgl or implementation. It's about physics and math in fact.

Velocity from definition is `v = s/t`.
You want `v = const` and you know distance `s = distance(target, source)`, hence you have
`t = s/v = distance(targer,source)/velocity` -- answering *"what's the total time it will take for object to move from source to target?"*.

**What does a `moveTo()` function do?**

If it's meant to determine the position on a segment `[A,B]`, then it has to ask *"at what point in time?"* and be called `getPosition` \- not `moveTo`, because it deosn't tell the object to move -- it answers where would it be at given time. This should then have a signature `position(source, target, speed, t)`.
From source and target you derive distance, speed is your constant, and then you determine your `timeTotal=s/v` (how long it takes to travel from A to B). Doing `t/timeTotal = t / (distance(target,source)/velocity)` gives you a fraction in range `[0,1]` that you then use, to lerp from A to B:

```
position(A, B, speed, t) => lerp(A,B, t/(distance(A,B)/speed))

```

This method returns absolute position at given time `t` of the movement, assuming that the object has uniform motion. It's good in scenarios, when you have a "keyframe" for A, B and want to interpolate between them (like in blender for example).

On the other hand when you want to apply motion in one tick of your physics simulation and you know, that **the velocity is constant**, then simply `ds = v*dt` (delta movement is velocity times delta\_time of the physics).

```
moveTo(currentPos, target, speed, dt) => currentPos + normalize(target-currentPos)*speed*dt

```

where `normalize(target-currentPos)*speed` is direction vector scaled by speed, thus velocity vector.

Both methods are useful in different scenarios - first is related to **Tweening**, second is related to physics simulation (but doesn't generalize well in current form).

If you want more accurate movement with varying acceleration (right now your acceleration is constant and 0, cuz speed is constant), then you should check out methods such as Euler integration, Runge-Kutta integration or (prefereably) Verlet integration (because it +-conserves energy). If you want to read about them, check them out in context of games and algorithms, otherwise you will get lost in the mathematical jargon of the Wikipedia
> 2 votes

---
Tags: java, 3d, movement, ai, lwjgl
---


title: Unity UI Image not rendered?

text:
# Question
Title: Unity UI Image not rendered?
In Unity I created a Panel with 3 children (An UI Image (LogoAch), and 2 TextMeshPro components (Name, Progress)).

It looks something like down below:

I saved this as a prefab and I try to instantiate it through code. Problem is for whatever reason the UI Image is not ?rendered? in the instantiated version? I have this short video showcasing the problem:

https://www.youtube.com/watch?v=RTa\_noJy4bE

Does anyone have any hunch of what exactly is the problem?

My code is the following:

```
// instantiate the popup
GameObject achPopup = Instantiate(prefabAchievementsPopup, transform.position, transform.rotation);

// set it as a child of Canvas
achPopup.transform.SetParent(canvas.transform);

// set Pos Z to 0
// set Left, Bottom to 0, 300
// set Right, Top to 0, -300
// set Scale to (1,1,1)
achPopup.GetComponent<RectTransform>().localPosition = new Vector3(1000, 1000, 0);
achPopup.GetComponent<RectTransform>().offsetMin = new Vector2(0, 300); //left, bottom
achPopup.GetComponent<RectTransform>().offsetMax = new Vector2(0, 300); //right, top
achPopup.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);

// set new sprite in Logo, new text in Name, Progress
achPopup.transform.Find("LogoAch").GetComponent<Image>().sprite = circleOfLifeLogo; // [SerializeField] private Sprite circleOfLifeLogo;
achPopup.transform.Find("LogoAch").GetComponent<Image>().color = circleOfLifeLogoColor; // [SerializeField] private Color circleOfLifeLogoColor;
achPopup.transform.Find("Name").GetComponent<TMPro.TextMeshProUGUI>().text = "Circle of life";
achPopup.transform.Find("Progress").GetComponent<TMPro.TextMeshProUGUI>().text = "1/1";

```

# Answer
You're assigning your image a colour with zero alpha (100% transparent).

Compare the working example in your video:

(White bar under colour swatch = 100% alpha)

...with the non-working example:

(Black bar under colour swatch = 0% alpha)

So go to the inspector where you've configured `circleOfLifeLogoColor` and ensure you give it a higher alpha value to get an opaque image.
> 1 votes

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


# Question
Title: Unity Hub on Linux "Not enough space" download error
I just downloaded and installed the official Unity Hub app on my Ubuntu machine. However, when I try to download the latest version of the editor, an error message pops up:

> ⚠ There is not enough space to download and install the selected items

I tried to change the install location of the Hub but without success. How can I download the Unity Editor?

# Answer
In the Linux environment, temporary downloads are first stored in the `/tmp` folder and then moved to the destination directory. Downloads fail to start if the estimated free space for that folder isn't enough, especially when there are system partitions.

User *apollongt* on Reddit explains a convenient solution to the issue in this thread. I'm assuming the installation directory wasn't changed (the standard directory is `~/Unity/Hub/`):

1. Create a folder named `tmp` in your Home directory (Bash command: `mkdir ~/tmp`).
2. Navigate to the folder where the `UnityHub.AppImage` is and open in Terminal (or, Bash: `cd ~/Unity/Hub`).
3. Execute the following command from the Terminal: `TEMP=~/tmp ./UnityHub.AppImage`.

The Unity Hub will open, and you'll be able to download the Editor. This way, you're telling the Hub to use `~/tmp` in Home as a temporary location for downloads rather than `/tmp` (note the missing '`~`', short for the Home directory).
> 0 votes

---
Tags: unity, linux
---


# Question
Title: How to make an EditorGUILayout.TextField accept multi-line input in a custom inspector
In a regular inspector:

```
[TextArea(4, 100)] [SerializeField] private string message;

```

Will expand a text field and let it accept multiple lines, with enter as opposed to needing \n. On the other hand:

```
script.message = EditorGUILayout.TextField(
                      "Message: ",
                      script.message,
                      GUILayout.Height(80));

```

Will also expand the text field, but does not allow for multiple line input. How can I get my custom inspector to behave the same way as the regular one and accept multi-line input?

# Answer
> 4 votes
Ok, so this works as an alternative:

`EditorGUILayout.PropertyField(message, GUILayout.Height(80));`

# Answer
> 1 votes
You can preempt your `EditorGUILayout.TextArea()` with `EditorStyles.textField.wordWrap = true`

That looks like this in my CustomEditor.cs file:

```
if (info != String.Empty)
{
    showConstructorInfo = EditorGUILayout.Foldout(showConstructorInfo, "Constructor Information");
    if (showConstructorInfo)
    {
        EditorStyles.textField.wordWrap = true; // This sets the wordwrap value of the property
        EditorGUILayout.TextArea(info);
    }
}

```

I have a bit more about how I'm doing some custom inspector stuff on my blog here: https://www.labyrintheer.com/2021/10/01/unity-custom-attributes-and-custom-editors/.

I plan to write a bit more about custom inspector and custom scene view stuff as I get this project wrapped up.

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


# Question
Title: Unity adding objects through script to scrollview (SetParent): Objects overlap
I need to add X objects to a scrollview. I do it like this:

```
GameObject statsObject = Instantiate(instance.statsObjectPrefab);
statsObject.transform.SetParent(statsParent.transform);

```

`statsParent` is the content container if the scrollview.

```
Scrollview
---- Viewport
-------- Content // This is statsParent

```

In the pause I see that then objects are added successfully, but they all overlap and no scrollbar is visible.

The content has a content size fitter and a vertical layout group, but I tried now all settings and the result is always the same.

I use Unity 2019.2

# Answer
This should be very straightforward. Here is a simple example of how to accomplish this.

Here is the scene hierarchy, with the Content game object as a child of the Viewport, which in turn is a child of the Scrollbar gameobject. This is default Unity set up for a ScrollView game object.

The only other thing I've added is a Controller game object, to hold our sample scroll view populator script.

The Content game object needs two components: **Vertical Layout Group** and **Content Size Fitter**. I've added a bit of spacing in the Vertical Layout Group to separate the items. **Child Force Expand *Height*** should be unchecked.

Create the item template(s) as children of the Content game object. For the demo, the item template is very simple, just a background image with a text label child:

Here's the scene so far, with the item prefab in place:

When the template is to your satisfaction, save it as prefab and remove it from the scene hierarchy.

Here is an example script that will populate the ScrollView without the items overlapping:

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

public class PopulateScrollView : MonoBehaviour
{
    [SerializeField] private Transform m_ContentContainer;
    [SerializeField] private GameObject m_ItemPrefab;
    [SerializeField] private int m_ItemsToGenerate;

    void Start()
    {
        for(int i = 0; i < m_ItemsToGenerate; i++)
        {
            var item_go = Instantiate(m_ItemPrefab);
            // do something with the instantiated item -- for instance
            item_go.GetComponentInChildren<Text>().text = "Item #" + i;
            item_go.GetComponent<Image>().color = i % 2 == 0 ? Color.yellow : Color.cyan;
            //parent the item to the content container
            item_go.transform.SetParent(m_ContentContainer);
            //reset the item's scale -- this can get munged with UI prefabs
            item_go.transform.localScale = Vector2.one;
        }
    }
}

```

One thing to note about the script -- I always reset the instantiated prefab's local scale after parenting it to a UI object, as sometimes (often, even) the scale gets messed up when taken out of its Canvas context.

Here are the exposed settings for this component, which was added to the Controller game object:

And here is the result when played:
> 6 votes

# Answer
From the Vertical Layout Group docs:

> The Vertical Layout Group component places its child layout elements **on top of each other**. Their heights are determined by their respective minimum, preferred, and flexible heights according to \[...\]

You have to add a LayoutElement component to your prefab and set its values according to your needs.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity 3d when camera is closer the shadows getting clipped weirdly
When in distance the shadows are appearing correctly but when getting near to the shadows it is getting clipped in a weird way. I was not able to fix it. Any help would be appreciated.

# Answer
> 1 votes
I believe the setting you are looking for is in Project Settings \> Quality \> Shadow Distance. This can be configured per quality setting.

More info here: Unity Manual Quality Settings

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


# Question
Title: In Unity, how do I correctly implement the singleton pattern?
I have seen several videos and tutorials for creating singleton objects in Unity, mainly for a `GameManager`, that appear to use different approaches to instantiating and validating a singleton.

Is there a correct, or rather, preferred approach to this?

The two main examples I have encountered are:

**First**

```
public class GameManager
{
    private static GameManager _instance;

    public static GameManager Instance
    {
        get
        {
            if(_instance == null)
            {
                _instance = GameObject.FindObjectOfType<GameManager>();
            }

            return _instance;
        }
    }

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}

```

**Second**

```
public class GameManager
{
    private static GameManager _instance;

    public static GameManager Instance
    {
        get
        {
            if(_instance == null)
            {
                instance = new GameObject("Game Manager");
                instance.AddComponent<GameManager>();
            }

            return _instance;
        }
    }

    void Awake()
    {
        _instance = this;
    }
}

```

The main difference I can see between the two is:

The first approach will attempt to navigate the game object stack to find an instance of the `GameManager` which even though this only happens (or should only happen) once seems like it could be very unoptimised as scenes grow in size during development.

Also, the first approach marks the object to not be deleted when the application changes scene, which ensures that the object is persisted between scenes. The second approach doesn't appear to adhere to this.

The second approach seems odd as in the case where the instance is null in the getter, it will create a new GameObject and assign a GameManger component to it. However, this cannot run without first having this GameManager component already attached to an object in the scene, so this is causing me some confusion.

Are there any other approaches that would be recommended, or a hybrid of the two above? There are plenty of videos and tutorials regarding singletons but they all differ so much it is hard to drawn any comparisons between the two and thus, a conclusion as to which one is the best/preferred approach.

# Answer
> 69 votes
It depends, but usually I use a third method. The problem with the methods that you used is that in the event that the object is included to begin with, it will not remove them from the tree, and they can still be created by instantiating too many calls, which could make things really confusing.

```
public class SomeClass : MonoBehaviour {
    private static SomeClass _instance;

    public static SomeClass Instance { get { return _instance; } }

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        } else {
            _instance = this;
        }
    }
}

```

The problem with both of your implementations is that they do not destroy an object that is created later. It could work, but one could throw a monkey wrench into the works that could result in a very difficult to debug error down the line. Make sure to check in Awake if there is an instance already, and if so, destroying the new instance.

# Answer
> 49 votes
Here's a quick summary:

```
                 Create object if  Removes scene  Global    Keep across
                 not in scene?     duplicates?    access?   Scene loads?

Method 1            No                No            Yes        Yes

Method 2            Yes               No            Yes        No

PearsonArtPhoto     No                Yes           Yes        No
Method 3

```

So if all you care about is global access, all three get you what you need. Use of the Singleton pattern can be a bit ambiguous about whether we want lazy instantiation, enforced uniqueness, or global access so be sure to think carefully about why you're reaching for the singleton, and choose an implementation that gets those features right, rather than using a standard for all three when you only need one.

(eg. if my game will always have a GameManager, maybe I don't care about lazy instantiation - maybe it's only global access with guaranteed existence & uniqueness I care about - in which case a static class gets me exactly those features very concisely, with no scene loading considerations)

...but definitely don't use Method 1 as written. The Find can be skipped more easily with Method2/3's Awake() approach, and if we're keeping the manager across scenes then we very likely want duplicate-killing, in case we ever load between two scenes with a manager already in them.

# Answer
> 38 votes
The best implementation of a generic `Singleton` pattern for Unity I know of is (of course) my own.

It can do *everything*, and it does so *neatly* and *efficiently*:

```
Create object        Removes scene        Global access?               Keep across
if not in scene?     duplicates?                                       Scene loads?

     Yes                  Yes                  Yes                     Yes (optional)

```

Other advantages:

* It's **thread-safe**.
* It avoids bugs related to acquiring (creating) singleton instances when the application is quitting by ensuring that singletons cannot be created after `OnApplicationQuit()`. (And it does so with a single global flag, instead of each singleton type having their own)
* It uses Unity 2017's Mono Update (roughly equivalent to C# 6). (But it can easily be adapted for the ancient version)
* It comes with some **free candy!**

---

And because *sharing is caring*, here it is:

```
public abstract class Singleton<T> : Singleton where T : MonoBehaviour
{
    #region  Fields
    [CanBeNull]
    private static T _instance;

    [NotNull]
    // ReSharper disable once StaticMemberInGenericType
    private static readonly object Lock = new object();

    [SerializeField]
    private bool _persistent = true;
    #endregion

    #region  Properties
    [NotNull]
    public static T Instance
    {
        get
        {
            if (Quitting)
            {
                Debug.LogWarning($"[{nameof(Singleton)}<{typeof(T)}>] Instance will not be returned because the application is quitting.");
                // ReSharper disable once AssignNullToNotNullAttribute
                return null;
            }
            lock (Lock)
            {
                if (_instance != null)
                    return _instance;
                var instances = FindObjectsOfType<T>();
                var count = instances.Length;
                if (count > 0)
                {
                    if (count == 1)
                        return _instance = instances[0];
                    Debug.LogWarning($"[{nameof(Singleton)}<{typeof(T)}>] There should never be more than one {nameof(Singleton)} of type {typeof(T)} in the scene, but {count} were found. The first instance found will be used, and all others will be destroyed.");
                    for (var i = 1; i < instances.Length; i++)
                        Destroy(instances[i]);
                    return _instance = instances[0];
                }

                Debug.Log($"[{nameof(Singleton)}<{typeof(T)}>] An instance is needed in the scene and no existing instances were found, so a new instance will be created.");
                return _instance = new GameObject($"({nameof(Singleton)}){typeof(T)}")
                           .AddComponent<T>();
            }
        }
    }
    #endregion

    #region  Methods
    private void Awake()
    {
        if (_persistent)
            DontDestroyOnLoad(gameObject);
        OnAwake();
    }

    protected virtual void OnAwake() { }
    #endregion
}

public abstract class Singleton : MonoBehaviour
{
    #region  Properties
    public static bool Quitting { get; private set; }
    #endregion

    #region  Methods
    private void OnApplicationQuit()
    {
        Quitting = true;
    }
    #endregion
}
//Free candy!

```

# How to Use It

```
public class YourManager : Singleton<YourManager>
{
}

```

or

```
public class GameManager : Singleton<GameManager>
{
// Your game-specific variables
  protected override void OnAwake()
  {
    // If needed, put your code here e.g. init your vars.
  }
}

```

When you want to get the singleton object from other scripts, you will write:

```
YourManager.Instance.[Your Method or Variable]
GameManager.Instance.[Your Method or Variable]

```

# Answer
> 11 votes
I'd just like to add that it may be useful to call `DontDestroyOnLoad` if you want your singleton to persist across scenes.

```
public class Singleton : MonoBehaviour
{
    private static Singleton _instance;

    public static Singleton Instance
    {
        get { return _instance; }
    }

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
            return;
        }

        _instance = this;
        DontDestroyOnLoad(this.gameObject);
    }
}

```

# Answer
> 5 votes
Another option might be to split the class into two parts: a regular static class for the Singleton component, and a MonoBehaviour that acts as a controller for the singleton instance. This way you have full control over the singleton's construction, and it will persist across scenes. This also lets you add controllers to any object that might need the singleton's data, instead of having to dig through the scene to find a particular component.

```
public class Singleton{
    private Singleton(){
        //Class initialization goes here.
    }

    public void someSingletonMethod(){
        //Some method that acts on the Singleton.
    }

    private static Singleton _instance;
    public static Singleton Instance
    {
        get {
            if (_instance == null)
                _instance = new Singleton();
            return _instance;
        }
    }
}

public class SingletonController: MonoBehaviour{
   //Create a local reference so that the editor can read it.
   public Singleton instance;
   void Awake(){
       instance = Singleton.Instance;
   }
   //You can reference the singleton instance directly, but it might be better to just reflect its methods in the controller.
   public void someMethod(){
       instance.someSingletonMethod();
   }
}

```

# Answer
> 4 votes
Here is my implementation of a singleton abstract class below. Here is how it stacks up against the 4 criteria

```
             Create object   Removes scene   Global    Keep across
           if not in scene?   duplicates?    access?   Scene loads?

             No (but why         Yes           Yes        Yes
             should it?)

```

It has a couple of other advantages compared to some of the other methods here:

* It doesn't use `FindObjectsOfType` which is a performance killer
* It's flexible in that it doesn't need to create a new empty gameobject during the game. You simply add it in the editor (or during the game) to a gameobject of your choosing.
* It's thread safe

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

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    #region  Variables
    protected static bool Quitting { get; private set; }

    private static readonly object Lock = new object();
    private static Dictionary<System.Type, Singleton<T>> _instances;

    public static T Instance
    {
        get
        {
            if (Quitting)
            {
                return null;
            }
            lock (Lock)
            {
                if (_instances == null)
                    _instances = new Dictionary<System.Type, Singleton<T>>();

                if (_instances.ContainsKey(typeof(T)))
                    return (T)_instances[typeof(T)];
                else
                    return null;
            }
        }
    }

    #endregion

    #region  Methods
    private void OnEnable()
    {
        if (!Quitting)
        {
            bool iAmSingleton = false;

            lock (Lock)
            {
                if (_instances == null)
                    _instances = new Dictionary<System.Type, Singleton<T>>();

                if (_instances.ContainsKey(this.GetType()))
                    Destroy(this.gameObject);
                else
                {
                    iAmSingleton = true;

                    _instances.Add(this.GetType(), this);

                    DontDestroyOnLoad(gameObject);
                }
            }

            if(iAmSingleton)
                OnEnableCallback();
        }
    }

    private void OnApplicationQuit()
    {
        Quitting = true;

        OnApplicationQuitCallback();
    }

    protected abstract void OnApplicationQuitCallback();

    protected abstract void OnEnableCallback();
    #endregion
}

```

# Answer
> 2 votes
I will trow my implementation too for future generations .

```
void Awake()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy(gameObject.GetComponent(instance.GetType()));
        DontDestroyOnLoad(gameObject);
    }

```

For me this line `Destroy(gameObject.GetComponent(instance.GetType()));` is very important because once I had left a singleton script on another gameObject in a scene and the whole game object was being deleted. This will only Destroy the component if it already exists.

# Answer
> 1 votes
I wrote a singleton class that makes easy to create singleton objects. Its is a MonoBehaviour script, so you can use the Coroutines. Its based on this Unity Wiki article, and I will add option to create it from Prefab later.

So you don't need to write the Singleton codes. Just download this Singleton.cs Base Class, add it to your project, and create your singleton extending it:

```
public class MySingleton : Singleton<MySingleton> {
  protected MySingleton () {} // Protect the constructor!

  public string globalVar;

  void Awake () {
      Debug.Log("Awoke Singleton Instance: " + gameObject.GetInstanceID());
  }
}

```

Now your MySingleton class is a singleton, and you can call it by Instance:

```
MySingleton.Instance.globalVar = "A";
Debug.Log ("globalVar: " + MySingleton.Instance.globalVar);

```

Here is a complete tutorial: http://www.bivis.com.br/2016/05/04/unity-reusable-singleton-tutorial/

# Answer
> 1 votes
Alright, and here's my Singleton, which has the additional advantage of initializing lazily and detecting infinite initialization loops.

If you want it to not destroy on load you should set this up in your inheriting class. It will use `FindObjectOfType` if necessary, as sometimes you may want to access this from another object's `Awake` method.

```
using UnityEngine;
using System;

namespace Feed {
  public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T> {
    static T s_instance;
    static bool s_isInitializing = false;

    protected abstract void Initialize();

    public static bool TryGetInstance(out T instance) {
      if (s_isInitializing) {
        throw new InvalidOperationException(
          "Singleton initialization dependency cycle detected"
        );
      }
      if (s_instance == null) {
        var found = FindObjectOfType<T>();
        if (found == null) {
          instance = null;
          return false;
        }
        InitializeAndAssign(found);
      }
      instance = s_instance;
      return true;
    }

    public static T Instance {
      get {
        if (TryGetInstance(out var instance)) {
          return instance;
        }
        throw new InvalidOperationException($"Could not find instance of {typeof(T).Name} in scene");
      }
    }

    void Awake() {
      if (s_instance == null) {
        InitializeAndAssign((T) this);
      } else if (s_instance != this) {
        throw new InvalidOperationException(
          $"Tried to create two instances of singleton {typeof(T).Name}"
        );
      }
    }

    protected virtual void OnDestroy() {
      s_instance = null;
    }

    static void InitializeAndAssign(T instance) {
      if (s_instance != null) {
        throw new InvalidOperationException("Singleton already exists");
      }
      s_isInitializing = true;
      instance.Initialize();
      s_isInitializing = false;
      s_instance = instance;
    }
  }
}

```

# Answer
> 0 votes
https://github.com/jpgordon00/UnitySingleton

All you have to do is add 'SceneSingletonListener' to your scene and you can create singletons like so: using UnityEngine;

public class SingletonComp : Singleton { }

// in any class during runtime... SingletonComp = SingletonComp.Instance;

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


# Question
Title: How to find Particle Position at Time with velocity and friction?
I have a Particle `p`.
A particle consists of a start position `p0`,an age `t`, a velocity `v` and a friction `f`

How can I find the position `pt` at an arbitrary `t`?

I currently have the formula

`pt = p0 + (v*t)`, which works fine.

But I don't know how to corporate `f` into it.

`f` is a multiplier, that should reduce velocity per timestep: `v' = v*f`

I tried `p0 + (v*t * (f/t))` but at time 0 it's a division by 0, and when `t` is high, `pt` converges to `p0`

# Answer
Maybe try this:

```
pt = p0 + v*t - 0.5ft^2

```

It's the physical equation for motion with constant deceleration, just make sure to stop it and save the position when v reaches 0:

```
Vfinal = V - f*t

```

So for V final = 0 you wanna stop it at `t = v/f`
> 1 votes

---
Tags: mathematics, particles
---


# Question
Title: Destroy gameobject that is returning a RaycastHit2D?
As the title suggests I would like to destroy the game object that my raycast hits. I have a movement script attached to my player object. A raycast2d is continuously shot downward, and when it collides with an object on the enemy layer it registers the collision and returns its value. What I want to do now is destroy that object, however when I use the destroy game object command, it destroys the gameObject that the script is attached to, as one may expect. How can I destroy this enemy object, which the script is not attached to.

This is the current code that I am using:

```
bool HitEnemy()
{
    Vector2 position = transform.position;
    Vector2 direction = Vector2.down;
    float distance = 2.0f;

    RaycastHit2D hit = Physics2D.Raycast(position, direction, distance, enemyLayer);
    if (hit.collider != null)
    {
        return true;
    }

    return false;

}

```

I will be doing something similar, where my enemy shoots a horizontal ray, which will then kill the player character. How can I reference these 2?

I am relatively new to C# coding, so any help will be greatly appreciated.

# Answer
> 2 votes
Here is a demo that accomplishes what you are asking.

First, the set up -- the scene consists of a player sprite and 3 enemy sprites.

The enemy sprites are assigned to the **Enemy** Layer. Each has a Collider2D component.

The Player sprite is similar, but it also has a custom component attached and of course is not assigned to the Enemy layer.

On to the script. First we declare a couple of handy variables with sensible default values that we can adjust later in the inspector:

```
    [SerializeField] private Vector2 m_RayDirection = Vector2.down;
    [SerializeField] private float m_RayRange = 4;

```

On **Start**, we let `LayerMask` do the bit-twiddling to calculate the correct mask value:

```
 int enemyLayer;
    void Start()
    {
       enemyLayer = LayerMask.GetMask("Enemy");
    }

```

The fun happens in Update. First, we'll move our player from side to side, simply for demo purposes. `Mathf.PingPong()` is a simple way to do this.

```
transform.position = new Vector3(Mathf.PingPong(Time.time, 4f) - 2.0f, 0, 0);

```

Now, we test for a hit using the parameters we've assembled:

```
   RaycastHit2D hit;
   hit = Physics2D.Raycast(transform.position, m_RayDirection, m_RayRange, enemyLayer);
        if (hit)
        {
            Debug.Log("Hit " + hit.collider.name);
            //You could do other stuff here, like instantiate particles or play sounds...

            //Destroy the enemy GO:
            Destroy(hit.collider.gameObject);
        }

```

Here's the entire script:

```
using UnityEngine;

public class Player_X : MonoBehaviour
{

    [SerializeField] private Vector2 m_RayDirection = Vector2.down;
    [SerializeField] private float m_RayRange = 4;

    int enemyLayer;
    void Start()
    {
       enemyLayer = LayerMask.GetMask("Enemy");
    }

    RaycastHit2D hit;
    void Update()
    {
        //Move the Player back and forth across the screen, for demo
        transform.position = new Vector3(Mathf.PingPong(Time.time, 4f) - 2.0f, 0, 0);

        hit = Physics2D.Raycast(transform.position, m_RayDirection, m_RayRange, enemyLayer);
        if (hit)
        {
            //Draw a debug ray to see what's happening
            Debug.DrawRay(transform.position, m_RayDirection * m_RayRange, Color.green,.5f);

            Debug.Log("Hit " + hit.collider.name);
            //You could do other stuff here, like instantiate particles or play sounds...

            //Destroy the enemy GO:
            Destroy(hit.collider.gameObject);
        }
    }
}

```

# Answer
> 2 votes
I think you could try something like this:

```
RaycastHit hit;
if (Physics2D.Raycast(ray, out hit)
{
    Destroy(hit.gameobject);
}

```

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


title: Unity create Animated Tilemap?

text:
# Question
Title: Unity create Animated Tilemap?
Im trying to create an Animated Waterfall Tilemap from a tutorial video.

In his video when the author right clicks he can see a Animated Tile \> under CREATE option.

But In my case its not there !! Please see picture below.

# Answer
> 3 votes
Just download this script AnimatedTile and put it into your project, then you can find AnimatedTile at Create \> Tiles \> Animated Tile.

In case you don't want to click the link, I copy the script for you

```
using System;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace UnityEngine.Tilemaps
{
    /// <summary>
    /// Animated Tiles are tiles which run through and display a list of sprites in sequence.
    /// </summary>
    [Serializable]
    [CreateAssetMenu(fileName = "New Animated Tile", menuName = "Tiles/Animated Tile")]
    public class AnimatedTile : TileBase
    {
        /// <summary>
        /// The List of Sprites set for the Animated Tile.
        /// This will be played in sequence.
        /// </summary>
        public Sprite[] m_AnimatedSprites;
        /// <summary>
        /// The minimum possible speed at which the Animation of the Tile will be played.
        /// A speed value will be randomly chosen between the minimum and maximum speed.
        /// </summary>
        public float m_MinSpeed = 1f;
        /// <summary>
        /// The maximum possible speed at which the Animation of the Tile will be played.
        /// A speed value will be randomly chosen between the minimum and maximum speed.
        /// </summary>
        public float m_MaxSpeed = 1f;
        /// <summary>
        /// The starting time of this Animated Tile.
        /// This allows you to start the Animation from a particular Sprite in the list of Animated Sprites.
        /// </summary>
        public float m_AnimationStartTime;
        /// <summary>
        /// The Collider Shape generated by the Tile.
        /// </summary>
        public Tile.ColliderType m_TileColliderType;

        /// <summary>
        /// Retrieves any tile rendering data from the scripted tile.
        /// </summary>
        /// <param name="position">Position of the Tile on the Tilemap.</param>
        /// <param name="tilemap">The Tilemap the tile is present on.</param>
        /// <param name="tileData">Data to render the tile.</param>
        public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData)
        {
            tileData.transform = Matrix4x4.identity;
            tileData.color = Color.white;
            if (m_AnimatedSprites != null && m_AnimatedSprites.Length > 0)
            {
                tileData.sprite = m_AnimatedSprites[m_AnimatedSprites.Length - 1];
                tileData.colliderType = m_TileColliderType;
            }
        }

        /// <summary>
        /// Retrieves any tile animation data from the scripted tile.
        /// </summary>
        /// <param name="position">Position of the Tile on the Tilemap.</param>
        /// <param name="tilemap">The Tilemap the tile is present on.</param>
        /// <param name="tileAnimationData">Data to run an animation on the tile.</param>
        /// <returns>Whether the call was successful.</returns>
        public override bool GetTileAnimationData(Vector3Int location, ITilemap tileMap, ref TileAnimationData tileAnimationData)
        {
            if (m_AnimatedSprites.Length > 0)
            {
                tileAnimationData.animatedSprites = m_AnimatedSprites;
                tileAnimationData.animationSpeed = Random.Range(m_MinSpeed, m_MaxSpeed);
                tileAnimationData.animationStartTime = m_AnimationStartTime;
                return true;
            }
            return false;
        }
    }

#if UNITY_EDITOR
    [CustomEditor(typeof(AnimatedTile))]
    public class AnimatedTileEditor : Editor
    {
        private AnimatedTile tile { get { return (target as AnimatedTile); } }

        public override void OnInspectorGUI()
        {
            EditorGUI.BeginChangeCheck();
            int count = EditorGUILayout.DelayedIntField("Number of Animated Sprites", tile.m_AnimatedSprites != null ? tile.m_AnimatedSprites.Length : 0);
            if (count < 0)
                count = 0;

            if (tile.m_AnimatedSprites == null || tile.m_AnimatedSprites.Length != count)
            {
                Array.Resize<Sprite>(ref tile.m_AnimatedSprites, count);
            }

            if (count == 0)
                return;

            EditorGUILayout.LabelField("Place sprites shown based on the order of animation.");
            EditorGUILayout.Space();

            for (int i = 0; i < count; i++)
            {
                tile.m_AnimatedSprites[i] = (Sprite) EditorGUILayout.ObjectField("Sprite " + (i+1), tile.m_AnimatedSprites[i], typeof(Sprite), false, null);
            }

            float minSpeed = EditorGUILayout.FloatField("Minimum Speed", tile.m_MinSpeed);
            float maxSpeed = EditorGUILayout.FloatField("Maximum Speed", tile.m_MaxSpeed);
            if (minSpeed < 0.0f)
                minSpeed = 0.0f;

            if (maxSpeed < 0.0f)
                maxSpeed = 0.0f;

            if (maxSpeed < minSpeed)
                maxSpeed = minSpeed;

            tile.m_MinSpeed = minSpeed;
            tile.m_MaxSpeed = maxSpeed;

            tile.m_AnimationStartTime = EditorGUILayout.FloatField("Start Time", tile.m_AnimationStartTime);
            tile.m_TileColliderType=(Tile.ColliderType) EditorGUILayout.EnumPopup("Collider Type", tile.m_TileColliderType);
            if (EditorGUI.EndChangeCheck())
                EditorUtility.SetDirty(tile);
        }
    }
#endif
}

```

# Answer
> 4 votes
If you are talking about the **Random and Animated Tilemap Tiles tutorial** available in the Unity website, then, you simply need to download and import the provided source below the video....

# Answer
> 1 votes
I had the same problem, and found the answer here: http://shadowpeakstudios.com/2018/10/22/unity-tutorial-animated-tiles/

Basically for it to work you have to download the 2d-extras from here: https://github.com/Unity-Technologies/2d-extras

Steps:

1. Download the 2d-extras
2. Extract the zip, then drag the "**2d-extras-master**" folder into your "**Assets**" folder in Unity
3. Create a new tilemap: **Right-Click in Hierarchy \> 2D-Object \> Tilemap**
4. Then right click on your "**Assets**" folder: **Create \> Tiles \> Animated Tile** (will finally show up)

# Answer
> 1 votes
https://github.com/Unity-Technologies/2d-extras/tree/2017

in the video he is using 2d-extras-2017 . so you should use the same version from branches and use second one.

so use the exact version of software with the same extras and you will be fine.

# Answer
> 0 votes
this is an additional answer for those encountering this issue currently (March 2020). The github link has updated quite a bit since the creation of the udemy guide. I solved my issue with this by going to the github link the asker posted. Then on the branch selector (the button on the far left of the clone/download button), change the branch from "master" or whatever it currently is to 2018. You would then have the similar tools that the author of the guide wants you to download.

# Answer
> -1 votes
you will find it under the "Tile" tab in the menu. check your picture , you will find "Tile"

# Answer
> -1 votes
Updated to Unity 2020.3.15
Enable Preview Packages
Import 2D Tilemap Extras
Create a new Animated Tilemap in Project folder: Create/2D/Tiles/Animated Tile

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


# Question
Title: Libgdx changing animation during runtime?
I've made an animation class that creates an animation for a player. However, I'm wondering how I can change the animation depending on where the player is currently moving? Heres my animation class:

```
public class AnimationTest extends ApplicationAdapter{
Batch batch;
private TextureAtlas textureAtlas;
private Animation animation;
private float elapsedTime = 0f;
private Sapien player;

public void create (Batch batch, String string, Sapien player) {
    this.batch = batch;
    this.player = player;
    textureAtlas = new TextureAtlas(Gdx.files.internal(string));
    animation = new Animation(1f/10f, textureAtlas.getRegions());
}

public TextureAtlas getTextureAtlas(){
    return new TextureAtlas(Gdx.files.internal("Player/Angle1/running/running.atlas"));
}

@Override
public void dispose() {
    batch.dispose();
    textureAtlas.dispose();
}

@Override
public void render () {
    elapsedTime += Gdx.graphics.getDeltaTime();
    //Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw((TextureRegion) animation.getKeyFrame(elapsedTime,true),player.getX(),player.getY(),75,75);
    batch.end();
}

```

I currently call create() and render() in another class.

```
public TiledTestTwo (int scale){
    this.scale = scale;
}

@Override
public void create () {
    View.createInstance(this.scale);
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    player = new Player(animationTest.getTextureAtlas(),400,400,2);
    playerController = new PlayerController(player);
    camera = View.getInstance().createCamera(w, h);

    animationTest.create(View.getInstance().getBatch(), "Player/Angle1/idle/angle1IdleSheet.atlas", player);

    rounds = new Rounds(scale,w, h);
}

@Override
public void render () {
    //Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    //animationTest.render();
    camera.update();
    View.getInstance().setView(camera);

    View.getInstance().render();
    animationTest.render();
    movableSubject.notifyUpdate();
    collisionController.checkCollisions(View.getInstance(), player, this.scale);

    ZombieObserver.getInstance().playerLocation((int) player.getX(),(int) player.getY());
    rounds.checkNewRound(player);
}

```

# Answer
> 0 votes
This is often achieved by loading all the relevant `Animation`s in a separate class, and then referring to those animations from your player class based on some condition.

For example:

```
public class PlayerAnimations {
  public Animation<TextureRegion> walkLeft;
  public Animation<TextureRegion> walkRight;

  public PlayerAnimations() {
    walkLeft = new Animation(1f/10f, new TextureAtlas(Gdx.files.internal("player/walk/left.atlas")));
    walkRight = new Animation(1f/10f, new TextureAtlas(Gdx.files.internal("player/walk/right.atlas")));
  }
}

```

Then, in your player's `render` method you can check which direction the player is moving and pick the correct animation for that direction:

```
@Override
public void render () {
  elapsedTime += Gdx.graphics.getDeltaTime();
  Animation<TextureRegion> animation; // This is no longer set in the constructor, but picked here in render depending on the direction.

  if (isMovingLeft())
    animation = playerAnimations.walkLeft;
  else
    animation = playerAnimations.walkRight;
  batch.begin();
  batch.draw((TextureRegion) animation.getKeyFrame(elapsedTime,true),player.getX(),player.getY(),75,75);
  batch.end();
}

```

---
Tags: libgdx, animation
---