# Question
Title: How do developers balance games despite massive skillgaps from their players?
My question regards properly balancing games with a high skill ceiling; one unattainable by the developer himself.

For example, Halo is a game with a low skill-ceiling. Master Chief has limited mobility in-game, can only equip 2 guns, and the guns are all pretty standard. Most situations have only a couple of ways to play out, and escape from sticky situations primarily depends on the player's loadout and aim. Fancy high-skill tricks aren't available to players in Halo. Players primarily improve in Halo by improving their situational awareness and aim; skills common to all FPS games. This is not hard for me to imagine balancing.

Rocket League OTOH is a game with a very high skill ceiling, and a rather unique concept / feel. Moreover, Rocket League is the type of game I can see myself developing, but not being very good at myself. The concept is simple, but the number of ways to succeed in a given scenario is hugely dependent on a player's skill and imagination.

This kind of high skill ceiling does not only apply to games of technical skill like Rocket League. For example I consider WoW, DotA, Star Craft, Magic the Gathering, Settlers of Catan, and Minecraft to be games with high skill ceilings as well.

How do low-skill developers approach creating and balancing features within their games which satisfies players vastly more imaginative and technically skilled than themselves?

# Answer
Much of high-level playtesting is done by the users in games like Rocket League and League of Legends.

The developers do the best they can to come up with playbalanced stuff, then the best of the players put that to the test. Then after gathering data, the developers make adjustments.

In the case of LoL, they test changes on their "PBE", which is a seperate set of servers where real players who opt in can try out the new features before they go live. Riot then makes adjustments before rolling out the feature to the playerbase as a whole.
> 3 votes

# Answer
My current project emphasizes a high skill ceiling and tactical complexity. It contains some FPS elements that are (intentionally) difficult to master, and while I consider myself a decent FPS player, some high level strategies are beyond my ability to execute reliably. We've found a few ways to test competitive gameplay anyway:

# AI can make a good practice partner

The most valuable tool in understanding and finetuning our game was to play with and against AI opponents with near-perfect aim and timing. Not only did it allow us to test strategies that we weren't skilled enough to execute, trying your best to beat an "infallible" opponent can lead to all sorts of insights and creative strategies.

Of course, the viability of "super-skilled" AI depends heavily on the type of game you're making, but for the purposes of balance testing, it doesn't need to be perfect, all-encompassing or fair. Don't be afraid to leave some "holes" in their abilities or have them cheat if you know what the outcome of a good move should look like.

# Condense your tests

Sometimes you can only get a good feel for a mechanic if you experience it. For example, landing a complicated combo in a fighting game via the intended means plays rather differently from triggering it with a single button press, so cheating won't give you the required data. What you *can* do, however, is get yourself as close to the situation as possible.

If you know what aspect you want to test, set up that specific scenario and a trigger to reset game state quickly and painlessly, then play through that until you grok the play, even if you can't replicate it reliably. In the fighting game example, place your character right next to an opponent, set your combo bar to full and have at it. It doesn't matter if you mess up the combo 90% of the time, nailing it just a few times is a useful experience.

# Go crazy once in a while

A good way to get a better feel for your game is to tweak the core mechanics in silly ways now and then. Set the global damage multiplier to 1000%, or to 10%. Adjust the game speed, gravity, amount of resources, unit costs, weapon ranges, whatever will break the game in interesting ways. Try to exploit the changes and see which niche strategies might work in the "proper" game as well, and how to counter them.

# Good mechanics are somewhat self-balancing

A core aspect of good game balance is setting up mechanics that counteract any one element or strategy that turns out a smidge too powerful. Whether it's by providing viable counter-picks for any option (LoL), items that alter the core game rules (MtG) or just a general system of soft counters (Starcraft), aim for a system that seeks equilibrium. It might not come to rest exactly where you predicted, but it should stabilize *somewhere*.

# Follow similar games

Few developers have the luxury of a sufficiantly large and dedicated audience to really push the limits of competitive play. If you happen to work on Starcraft or League of Legends - congratulations, but why are you reading this? If you don't, consider picking a successful game or two that's similar to your project in some regard and following the meta, professional matches and analyses for a while. You'll pick up a lot of genre theory that might help you avoid common pitfalls or serve as a tool to examine your own project in a new light.
> 2 votes

# Answer
One very common way for developers to obtain information about balance is by interacting directly with the high-level players who have that level of skill that the developers do not. Conversations with individual players who are known to be very high skill can provide very valuable information. More "general-purpose" testing of new content is often done through some kind of beta environment, but it really depends on the type of your game whether or not information collected from it will be of significant use to you.

In League of Legends, the balance designers at Riot have relationships with a large number of high-level (professional) players that they consult with both for the current state of the game as well as potential changes that they could make to the game. The PBE is used less for balance testing and more for finding bugs with new content, as there are very few high level players consistently playing there, meaning games of entirely high level players (necessary for gaining proper knowledge for balance) are extremely rare.

For World of Warcraft, when a new raid is coming out, they have a few previews of it on their beta realm. The highest level guilds who want to be as competitive as possible in the world first race will participate in these previews and data on their performance is collected and analyzed to balance the raid further. Because these are groups of entirely high level players trying as hard as they can, the data gathered is pretty accurate for what can be expected from high level players in that raid in the future.

As far as actual balancing strategy goes, something important to remember is that *it isn't the end of the world to have things be more optimal than others as long as it's a challenge to figure out and it changes every once in a while*. Balance, contrary to what it might seem from the name, isn't about making everything in the game of equal power level. If the result of every decision is equal regardless of what decisions the player makes, player choice doesn't matter anymore and it sucks a lot of the fun out of the experience.

In many games (Path of Exile with its extreme complexity comes to mind), one of the things that players enjoy the most is theorycrafting new builds/heros/classes/tactics/playstyles in hopes of finding something optimal. Usually, once it is known what the best (or best few) approaches are and the metagame is more or less locked in, it's appropriate to rebalance things every once in a while to prevent things from getting too stale and giving those theorycrafters a chance to find the next "OP" thing.
> 1 votes

# Answer
One possibility is building in **cheat codes** to simulate higher skill levels whether possible. A developer can also **ask other people** (like friends) who have higher skill to try out the game and see if they find any imbalances. It also helps to **look at similar games** and research any balance issues they might have had or even still have currently. **Game forums** are often a decent source of such information, especially if you're willing to wade through pages upon pages of flamewars.
> 0 votes

---
Tags: balance
---


# Question
Title: Input.GetKeyDown need to press button more than once to work
So in Unity3D I'm checking for `Input.GetKeyDown(KeyCode.E)` for stuff like pickups and opening doors. Sometimes it doesn't work the first time I press it and I must press the key `E` like 2-4 times, and then it works. What could be the possible reason for this to occur?

As a further note, `Input.GetKeyDown()` is being called from `OnTriggerStay()`

# Answer
> 2 votes
Unity chose to reset the flag that services `Input.GetKeyDown` every frame as is noted in their docs.

> You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.

So trying to use it from `OnTriggerStay()` will most likely not work as there's a good chance that `Update()` will occur before `OnTriggerStay()` is called and reset the keys state (it also depends on when and how they handle user input from how the operating system reports it). There's even more complexity (physics timesteps are different from `Update()` timesteps, and `OnTriggerStay()` isn't called every frame) so you're basically relying on a race condition to check `E` which is not reliable.

Fixing this isn't so easy as mentioned by @Gnemlock (originally I had a simple flag set using `GetKeyDown`).

There are a couple ways to fix this though. @Gnemlock mentions `Input.GetKey` which returns true as long as you're holding the key down.

```
private bool isEPressed = false;

void Update()
{
    isEPressed = Input.GetKey(KeyCode.E);
}

```

You can also just use an OR expression which you need to clear yourself later

```
private bool isEPressed = false;

void Update()
{
    isEPressed = isEPressed || Input.GetKeyDown(KeyCode.E);
}
void WasEPressed()
{
    //You might want to do a timestamp check here too
    //for like 250ms or something small so that it
    //doesn't stay active forever
    bool ret = isEPressed;
    isEPressed = false;
    return ret;
}

```

If you want to go really modular, you might use a C# event that the trigger subscribes to in `OnTriggerEnter()` (and unsubscribes to when leaves) but that might be too complex for your needs.

# Answer
> 0 votes
`GetKeyDown()` tells us if the user pressed the key down during the *last* `Update()` function. This allows us to react during the frame where the button has been pressed, without reacting in the same way for each consecutive frame where the key *is still being* pressed.

This makes things a bit more tricky, trying to perform the same check in an `OnTriggerStay()` method. `Update()` runs as many times as your hardware can handle, per second. It is entirely possible for *two or more* `Update()` cycles to run in between pressing the button, and triggering `OnTriggerStay()`. Remember, collision is physics based, and only checks with `FixedUpdate()`, which typically runs far less infrequently than `Update()`.

In the end, we could and up with an `OnKeyDown()` that *initially* flips to `true`, but flips back to `false` before we actually get to check it. For this reason, *caching* this value (as suggested in an alternate answer) runs into this same problem.

Having experienced this, before, your best bet is to use `OnKey()`. `OnKey()` checks if the key is down, regardless. If the key is down, it will ***always*** return `true`. In situations where this would lead to issues resulting from always checking the key, you can then start to think about caching a local variable to keep record of whether they key *has just been pressed*, for the purposes of your `OnTriggerStay()` method, or if the key *is still being pressed* from a previous `OnTriggerStay()`.

# Answer
> 0 votes
I went searching for exactly this, and with Coburns suggestion I made the following that will more accurately track when something changes to use for `KeyDown` and `KeyUp` events.

It does need to be run at least once per frame to track accurately as is its only shortcoming as it uses `UnityEngine.Time.frameCount` as for its timekeeping.

using UnityEngine;

public class ChangeObserver
{
    private int _lastStart = -2;
    private int _lastEnd = -1;

    private bool Last => _lastStart > _lastEnd;

    protected bool HasChange(bool current)
    {
        if(current == Last)
            return _lastStart == Time.frameCount
                || _lastEnd == Time.frameCount;

        if(current)
            _lastStart = Time.frameCount;
        else
            _lastEnd = Time.frameCount;

        return true;
    }
}

public class InputChangeObserver : ChangeObserver
{
    public KeyCode KeyCode { get; private set; }

    public bool KeyChange => HasChange(Input.GetKey(KeyCode));

    public bool Key => Input.GetKey(KeyCode);
    public bool KeyDown => KeyChange && Input.GetKey(KeyCode);
    public bool KeyUp => KeyChange && !Input.GetKey(KeyCode);

    public InputChangeObserver(KeyCode keyCode)
    {
        KeyCode = keyCode;
    }
}
```

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


title: change color to rgb in c# unity

text:
# Question
Title: change color to rgb in c# unity
So I am trying to change my color of my sprite to a rgb color. Now I can just change it to a color like red, black or blue...

```
 m_spriteRenderer.color = Color.blue;

```

Thanks,

# Answer
> 1 votes
You can pass the color you want to the constructor of the Color object.

Here is a copy of the documentation's example:

```
using UnityEngine;

public class Example : MonoBehaviour
{
    void Start()
    {
        Color newColor = new Color(0.3f, 0.4f, 0.6f);
    }
}

```

You can also use it like that:

```
Color newColor = new Color(0.3f, 0.4f, 0.6f);
m_spriteRenderer.color = newColor;

```

You can see an example of how it can be used in the documentation of the SpriteRenderer.color function.

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


title: Public MonoBehavior string fields empty

text:
# Question
Title: Public MonoBehavior string fields empty
This is bizarre enough that it *has* to be me being an idiot.

I have a `MonoBehaviour` with some public fields and public methods:

```
public class MyComponentA : MonoBehaviour
{
    public string Message = "Foobar";
    public int Integer = 42;

    public string GetMessage() => "This is a message.";
    public int GetInteger() => 42;
}

```

I've added it to a prefab called `Circle_A`.

`Circle_B` has a `MonoBehavior` that will instantiate an instance of `Circle_A`, get the component and log out the values returned from the fields and the methods:

```
public class CircleB : MonoBehaviour
{
    [SerializeField] private GameObject _circleAPrefab;

    private void Start()
    {
        var circleAInstance = Instantiate(_circleAPrefab, new Vector2(10, 10), Quaternion.Euler(Vector3.zero),transform);
        var myComponentA = circleAInstance.GetComponent<MyComponentA>();
        var message = myComponentA.Message;
        LogIt(message);
        LogIt(myComponentA.GetMessage());
        LogIt(message);
        Log(myComponentA.Integer);
        Log(myComponentA.GetInteger());
    }

    private static void LogIt(string message)
    {
        switch (message)
        {
            case null:
                Log("NULL");
                return;
            case "":
                Log("EMPTY");
                return;
            default:
                Log($"'{message}'");
                return;
        }
    }
}

```

The integer field and both the methods return as expected, the number `42` and the message`This is a message`. The message field however is always an empty string.

What's happening?

# Answer
I checked your code, it's working. Select the prefab with a double click - it is possible that you have emptied the value of Message for the prefab in the Inspector of Circle\_A.
> 0 votes

---
Tags: unity, c#, .net, monobehaviour
---


title: How to change TPS camera angle in Unity

text:
# Question
Title: How to change TPS camera angle in Unity
I'm very new to Unity and this may simply be a failure of google-fu but I hope someone here can help me out.

I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts.

I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code.

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

public class CameraFollowPlayer : MonoBehaviour
{
    GameObject target;

    // Start is called before the first frame update
    void Start()
    {
        target = transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform.position);
    }
}

```

The problem with this is the angle this leaves the camera pointing at in-game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the `LookAt` instruction to result in a shallower X-axis rotation of the camera?

# Answer
> 1 votes
It's a bit hard to give you a specific solution without seeing a screenshot or diagram of the current vs desired behavior, but looking at your script I can suggest two general approaches to extend your camera behavior:

1) Offsetting the targeted point (changing the LookAt target, as you mentioned)

2) Offsetting the camera position or rotation

I've added these two approaches to your script:

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

public class CameraFollowPlayer : MonoBehaviour
{
    GameObject target;
    //Offset variables
    Vector3  targetOffset;
    Vector3  rotationOffset;

    // Start is called before the first frame update
    void Start()
    {
        target = transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        // adding position offset to target
        transform.LookAt(target.transform.position + targetOffset);

        //adding rotation offset to transform
        transform.rotation += rotationOffset;
    }
}

```

By tweaking these variables you should be able to control the camera position and angle, so hopefully you can compose your desired view.

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


# Question
Title: Using points to unlock next scene in Unity
Below is my code and I'm a beginning game designer trying to make my first game for art school teehee! :)

I'm not sure how to unlock the next level with a scene I've already made called `Rust_Room`

Any ideas? :o I also attached the error codes I'm getting!

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

public class Example
{
    HUD hud;
    int points;

    const int ScorePrefix = "Score:";
    int score;

    public void LoadLevel()
    {
        if ("Score==45")
        // load the nextlevel
        SceneManager.LoadScene(SceneManager.GetSceneByName(Rust_Room)().buildIndex + 1);

    }
}

```

# Answer
There are very clear issues with your script as in the error mentioned:

> "Cannot implicitly convert type string to bool"

And this error has been generated by the "if" statement as it needed bool not a string, to fix it just remove the double quotes like this:

> if (Score == 45)

also the same error has been casued by:

> const int ScorePrefix = "Score:";

so you can remove this variable as it not used in this script or you can assign an int value to it. int is basically a number with no decimal point for example 1,2,10,489 etc. **To read more about C# data types please visit here.** **or Here.**

> const int ScorePrefix = 10; //or any value which is int.\*

**Error # 2:**

> "The name 'Rust\_Room' does not exist in the current context"

this is generated by this:

> SceneManager.LoadScene(SceneManager.GetSceneByName(**Rust\_Room**)().buildIndex \+ 1);

as you can see you are passing **'Rust\_Room'** is a **'type'** while it needs name of the scene which is **string**.

So jut do it like this and it resolve the issue:

> SceneManager.LoadScene(SceneManager.GetSceneByName("Rust\_Room")().buildIndex \+ 1);

So the final script will be:

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

public class Example
{
    HUD hud;
    int points;

    const int ScorePrefix = 10; //or any value which is int.
    int score;

    public void LoadLevel()
    {
        if (Score == 45)
        {
             // load the nextlevel
             SceneManager.LoadScene(SceneManager.GetSceneByName("Rust_Room")().buildIndex + 1);
        }

    }
}

```

By the way i will handle this situation using build index instead of name here is how i will do it:

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

public class Example
{
    HUD hud;
    int points;

    const int ScorePrefix = 10; //or any value which is int.
    int score;

    public void LoadLevel()
    {
        if (Score==45)
        {
            int currentScene = SceneManager.GetActiveScene().buildIndex + 1;
            SceneManager.LoadScene(currentScene);
        }
    }
}

```

In this code i first get current scene index and then increment by 1 to get next scene index and finally loading scene with incremented index.

I hope this will help...
> 1 votes

---
Tags: unity
---


# Question
Title: How to create a over world map with multiple sub maps
my game's idea is to use a open world map consisting of say 4096x4096 size, and multiple grids of 64x64 size. When I click on any grid, the map zooms in to show that grid(either creating in from scratch or loading off a JSON) because saving all the grids could not be memory efficient. Is there any algorithm to do like this?

# Answer
> 1 votes
You don't really need any specific algorithm to accomplish this. One way you can achieve that is this:

* Make an array that holds your tiles, most likely a 2D array will do.
* For each tile, make a `json` file, that describes what that tile looks like. Name the `json` files in a sequence, so the first tile would be `tile_0.json` the next one `tile_1.json` etc etc.
* When the user clicks on a tile, depending on which tile it was, open the right `json` file, and load everything that it needs.

Depending on what language / platform / tools you are using, this might look different in actual code.

---
Tags: game-mechanics, maps, minimap
---


# Question
Title: To split or not to split large 3D objects?
I have a fairly simple question for which I'm seeking guidance:

**Should large 3D objects be splitted into smaller ones?**

By wide, I mean an object that would be as wide as a game level is, below is some mountain, the first picture shows it as a single mesh, the second picture shows it as multiple meshes.

Facts I've considered (might be wrong):

* a large object simplifies the scene hierarchy with less objects in total, but at the same time it might be rendered more often than necessary since it will be considered as visible
* a large object made out of smaller objects makes the scene hierarchy more bloated, but at the same time on a performance aspect is better since only visible parts of it by the camera will be rendered, the rest being culled

Note, these objects aren't complex by today standards, that mountain is less than 1K triangles and a complete level is likely to be less than 30K triangles.

Ideally, I would like to have the least amount of objects in the scene hierarchy to keep it simple, but at the same time I am wondering whether or not over simplifying the level might put extra problems on the table I haven't thought about.

# Answer
This question is actually anything but simple :)

There are several advantages to splitting a large object, but they are situational:

* Each of those objects can have an own LOD group. If you set up these LOD groups with differently detailed versions, then nearby parts can be rendered in a much higher detail than those which are further away. This allows for a much higher graphic fidelity without compromising on the size of your scenes. But note that you might encounter issues with visible seams between adjacent parts of the object while they are rendered with different detail levels.
* Each of those objects can be separately culled through occlusion culling or frustum culling. When the whole object is one mesh, then the engine has to render either everything of it or nothing of it.
* A large and complex object often requires a mesh collider. Mesh colliders are performance-heavy, especially when they have a large number of polygons and don't have a convex shape. Breaking the object down into multiple colliders allows the collision detection algorithm to rule out many potential mesh collisions by the bounding boxes of the involved objects. It might also allow you to make at least some of its parts use convex collision meshes. Note: You don't necessarily need to use the same strategy for the collision mesh(es) as you use for the rendering mesh(es). When you have one parent object with a rigidbody and multiple children as sub-objects, then you can put the rendering mesh on the parent and the collision meshes on the children. You can also do it the other way around.

But if these situations do not apply to your case (the whole object is usually on the screen at once, all of it is seen from roughly the same distance and there aren't many potential collisions with it), then it is usually better for performance to keep the whole logical object in one physical object. In fact many projects go the opposite way. They go out of their way to unify many small and simple static objects into one large and complex object at runtime in order to improve performance (this is called "mesh welding" and there is a handy utility method for it).

Now you might be more confused than before. Sorry about that. But if you aren't sure what you are supposed to do now, remember the old saying in software development: **Premature optimization is the root of all evil** (Donald Knuth). Do not waste time and energy on optimizing things in your game when you don't yet know if you even need that performance. Create things the way which is most comfortable for your development process. If you later down the road encounter performance problems, analyze them. And if you find tangible proof that this mountain ridge is indeed the culprit, then you can still consider how to make it more efficient.

I am looking forward to playing your game.
> 3 votes

---
Tags: unity, 3d, optimization, 3d-meshes
---


# Question
Title: Passing by pointer-reference in blueprints with C++ definitions
MyFunction( Class \*& foo )

Inside a derivative BP of the above C++ class:

`foo` shows up as an output rather than an input.

Why?

# Answer
Non-`const` references in C++ functions exposed to Blueprint are always treated as outputs by the parser in UnrealHeaderTool.

You can see this in the (very involved) logic of `FHeaderParser::GetVarType` in `Engine/Source/Programs/UnrealHeaderTool/Private/HeaderParser.cpp`. This is called by `ParseParameterList` during parsing a functions parameter list.

If you want `foo` to be an input, add `const` (this is what functions like `RandomFloatFromRangeInStream` do to facilitate passing the heavyweight stream parameter as an input).

You cannot make it simultaneously an input and an output parameter.
> 2 votes

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


title: Hide "No custom tool available" window

text:
# Question
Title: Hide "No custom tool available" window
I have this annoying window in the bottom right of the scene view. From the manual, it seems like I opened it by clicking on the wrench & scribe button next to the movement buttons.

How do I make it do away now?

Restarting doesn't make a difference, neither does creating a brand new project.

The documentation say this appears it I've clicked on the tools icon and there aren't any custom tools (which I'm sure I have done). Surely is should vanish after a while though.

# Answer
> 3 votes
There are **two** buttons with the crossed tools. Clicking the smaller button at the right side of the Scene View (near the *Gizmos* button) hides the window:

---
Tags: unity
---


# Question
Title: Overriding the sprites in a Animation clip
Right now we are in the process of adding seasonal content to our game. I would like to know of a way to override animation clips. Specifically I want to change the sprites being show at each key-frame. Looking from the text of a animation clip I found the following :

```
 m_PPtrCurves:
  - curve:
    - time: 0
      value: {fileID: 21300000, guid: 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type: 3}
    - time: 0.6
      value: {fileID: 21300000, guid: ae9111d826eb24442b21523b30b748bd, type: 3}
    - time: 0.6666667
      value: {fileID: 21300000, guid: 88840e4f59c4a6040922d9b6eed3dec3, type: 3}
    - time: 1.2333333
      value: {fileID: 21300000, guid: 88840e4f59c4a6040922d9b6eed3dec3, type: 3}
    - time: 2.0001667
      value: {fileID: 21300000, guid: ae9111d826eb24442b21523b30b748bd, type: 3}
    - time: 2.05
      value: {fileID: 21300000, guid: 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type: 3}
    - time: 3.1166666
      value: {fileID: 21300000, guid: 502fc97a961e4424ea008c0e546c83ef, type: 3}
    - time: 3.45
      value: {fileID: 21300000, guid: 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type: 3}
    attribute: m_Sprite

```

This corresponds to the key frames and amount of sprites in the animation clip but I have no idea from where to get the data for the new sprites. I'm guessing the guid is a hashed path to the png files. can someone explain where to find this data so I can write myself a neat little parser to do the job?

# Answer
> 0 votes
https://forum.unity.com/threads/animationclip-problems.218106/#post-1669347

This helped me a little.

You can get serialized Properties and use the `FindPropertyRelative` function to find the data that you want to modify. Like `m_PPtrCurves` and in there `attribute` and `curve`.

`InsertArrayElementAtIndex` combined with `ApplyModifiedProperties` can make new array elements

---
Tags: unity, animation
---


title: How to repeat scene in Unity 3D?

text:
# Question
Title: How to repeat scene in Unity 3D?
When my game ends I want it to automatically restart from the beginning so that the whole scene repeats itself. How do I do that in Unity 3D?

Please refer this link for clarification.

# Answer
To restart your current scene, you need current scene index or name. And once you have the current scene index or name then just reload it. Here the example that how i done it:

```
public void RestartCurrentScene()
 {
     int currentScene = SceneManager.GetActiveScene().buildIndex;
     SceneManager.LoadScene(currentScene);
 }

```

Add this to the very top section of the script. As it is required by "SceneManager".

> using UnityEngine.SceneManagement;

I hope this will help...
> 3 votes

# Answer
you can use this code:

```
    UnityEngine.SceneManagement.SceneManager.LoadScene( UnityEngine.SceneManagement.SceneManager.GetActiveScene().name);

```
> -2 votes

---
Tags: unity, game-loop
---


title: How to use TensorFlow in Unity

text:
# Question
Title: How to use TensorFlow in Unity
I am trying to implement a deep reinforcement learning IA with TensorFlow for a checker game in Unity. How can I do this?

I've searched for it on Google and found a lot of videos and tutorials on how to use machine learning agents with Unity, and other people who explain how to import a TensorFlow trained neural network in Unity, but I didn't see anything related to using directly TensorFlow in Unity to create (and train) neural networks.

If someone knows another package to create CNNs with C#, I am interested.

# Answer
every application works with data. both unity and tensorflow work with data.

tensorflow is just a machine learning library that basically is made for python language. you dont need to find a wrapper to let you work with tensorflow but i think there is some.

assume you need neural network as supervised learning system to teach you agent to move to right direction.

you can simply generate some data in unity that can be used in tensorflow and python and you can generate or convert data to some thing that can be read by unity.

one good example: you want to teach the car to drive automatically that is teached by player.

direction of car and angles with road is the input and buttons that player pushes are output. you can save this in unity a table like excel mysql or...

you feed the neural network with this data and get weights of learned neural network. now you can generate you NN algorithm that drives the car.
> 1 votes

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


# Question
Title: Pixel-perfect 3D sprite-picking on cylidrical-billboarded sprites?
**Background Info**

I have an OpenGL app where a player (just an AABB with an eye-height, look and move vectors), can walk along a 3D grid made of a square cells, essentially like a player walking along a Minecraft level. The cells can also have differing heights, which qualifies it as a 3D level, rather than 2D.

On each cell, there is potential to be a static sprite, which is centered on that cell. The sprite is rendered as a "cylindrical billboard" so that it's always facing the camera, but the base/bottom of the sprite is always rooted in the ground. Like this https://www.youtube.com/watch?v=2-queKkSVnw

(The point I'm making is that these cylindrical billboarded sprites render a bit differently than standard sprites which would be coplanar to the view plane on the vertical axis, as well)

Here's a simple representation, where the green stick is the player, and the pink squares are the billboarded sprites which are centered on their cells.

(Note: normally, the camera view would be from the player's eyes, and thus all the pink sprites should be aligned with the player's view plane)

I also have an "arm reach" vector which is a line segment that extends outward from the crosshair a certain distance, in other words a line segment. This line segment is slightly less than the width of one cell. So, worst case scenario, then, is that this line segment is intersecting with three cells at once, like this:

**Question**

My question is how should I detect that the user's arm reach ray/segment is intersecting with a vertically billboarded sprite, knowing that the sprites may have transparent pixels?

I know that the first step would be to find which cells the ray/segment is overlapping, as shown in the previous pic as the green-highlighted cells. The next step (in my case) shall be a 3D distance check from the player to the sprite location. If too far, can't click it, no matter how you rotate the camera view (and distort the sprite). After that, I'm unsure. I assume I need to somehow first check if the ray is intersecting the billboarded sprite's "rectangle" (the pink rectangle) (I say rectangle in quotes because it will be a distorted rectangle in first person view, due to perspective angle), and then pixel-pick on the sprite and look for the transparent color, but I'm not sure how to do either of those steps.

Daggerfall somehow accomplished this. Interacting with a billboarded sprite (i.e. a treasure pile) requires you to actually click on a non-transparent pixel of that sprite, or the click doesn't count.

Any sources on related techniques would be greatly appreciated. Thank you for your time!

# Answer
I would recommend trying it Bálint's way first, because it is much easier to implement, but here is a CPU only solution. The reason you may want to go with this solution is if the extra rendering pass and CPU/GPU communication is giving you performance problems.

You know the position/orientation of the Billboard and Ray, so you can do a series of Ray/Geometry intersection to determine the position on the sprite.

1. Intersect the Ray with the AABB of the Billboard to quickly determine which sprites have a possibility of intersection.
2. Intersect the Ray with the Triangles that make up the chosen billboards to determine the location of intersection.
3. Compare the intersection location to the edges of the billboard using vector projection to determine where it intersects the billboard in pixel space.
4. Check the value of the pixel to determine if it is a hit or miss (no alpha or alpha)

If you need to improve performance, then you can divide the world into chunks, and check the AABB of the Chunk before proceeding with step #1.
> 0 votes

# Answer
When you need to do pixel perfect mouse picking with non geometric objects (e.g. sprites) it's usually better to simply let the GPU handle the pixel part.

Render your pickable objects into a framebuffer with a solid, distinct color based on an index (there are 2^24 different indexes you can have, you probably won't run out of them), then simply sample the color at the position of the crosshair.

A simple way to convert a 24 bit number to a 3 x 8 bit color is:

```
r = index >> 16 & 255
g = index >> 8 & 255
b = index & 255

```

Then to convert back you simply do

```
index = r << 16 | g << 8 | b

```
> 0 votes

---
Tags: sprites, picking, billboarding, per-pixel
---


title: How to raycast from a UI element

text:
# Question
Title: How to raycast from a UI element
How do I raycast from a UI object? I have tried

```
Ray ray;
Camera cam;
Transform obj; //UI object

ray = cam.ViewportPointToRay(obj.position);

```

AND

```
ray = new Ray(obj.position, obj.forward);

```

Neither of these seem to work.

# Answer
> 0 votes
I've figured it out:

```
ray = cam.ScreenPointToRay(obj.position);

```

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


title: Unity Unique Persistant GameObject ID

text:
# Question
Title: Unity Unique Persistant GameObject ID
I was wondering if GetInstanceID() is persistant at each run?

I intend to save/load gameobjects data by their ID....I needed a persistant ID

# Answer
https://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html

im not sure what you mean at each run? i think you mean when you press play button or run the game. unity assigns a unique id to object when its instantiates. whatever its in editor mode or play mode. so when you delete the object and instantiate another instance of that object type, unity assigns new id to it.

if you want to give unique ids on play mode you can do it in the code. there are algorithms that generate unique strings for you
> 1 votes

---
Tags: unity
---


# Question
Title: Avoid spawning Reverese words in word search game
I was trying to modify a project that I found on Github, but the problem of that game is the words of the game is spawning in reversely as the snapshot below.

there were two classes that has been used in the script and I couldn't find the issue. Can someone help me to solve the problem?

**WordSearch Script**

```
public class WordSearch : MonoBehaviour {
    // you may customize these variables in the Unity Inspector however you want
    public bool useWordpool; // 'should we use the wordpool?'
    public TextAsset wordpool; // if true, wordpool will be utilized
    public string[] words; // overwritten if wordpool = true
    public int maxWordCount; // max number of words used
    public int maxWordLetters; // max length of word used
    public bool allowReverse = false; // if true, words can be selected in reverse order.
    public int gridX, gridY; // grid dimensions
    public float sensitivity; // sensitivity of tiles when clicked
    public float spacing; // spacing between tiles
    public GameObject tile, background, current;
    public Color defaultTint, mouseoverTint, identifiedTint;
    public bool ready = false, correct = false;
    public string selectedString = "";
    public List<GameObject> selected = new List<GameObject>();

    private List<GameObject> tiles = new List<GameObject>();
    private GameObject temporary, backgroundObject;
    private int identified = 0;
    private float time;
    private string[,] matrix;
    private Dictionary<string, bool> word = new Dictionary<string, bool>();
    private Dictionary<string, bool> insertedWords = new Dictionary<string, bool>();
    private string[] letters = new string[26]
    {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    private Ray ray;
    private RaycastHit hit;
    private int mark = 0;

    private static WordSearch instance;

    public static WordSearch Instance {get {return instance;}}

    void Awake() {
        instance = this;
    }

    void Start() {
        List<string> findLength = new List<string>();
        int count = 0;

        if (useWordpool) {
            words = wordpool.text.Split(';');
        } else {
            maxWordCount = words.Length;
        }

        if (maxWordCount <= 0) {
            maxWordCount = 1;
        }

        Mix(words);
        Mathf.Clamp(maxWordLetters, 0, gridY < gridX ? gridX : gridY);

        while (findLength.Count < maxWordCount + 1) {
            if (words[count].Length <= maxWordLetters) {
                findLength.Add(words[count]);
            }
            count++;
        }

        for (int i = 0; i < maxWordCount; i++) {
            if (!word.ContainsKey(findLength[i].ToUpper()) && !word.ContainsKey(findLength[i])) {
                    word.Add(findLength[i], false);
            }
        }

        Mathf.Clamp01(sensitivity);
        matrix = new string[gridX, gridY];
        InstantiateBG();

        for (int i = 0; i < gridX; i++) {
            for (int j = 0; j < gridY; j++) {
                temporary = Instantiate(tile, new Vector3(i * 1 * tile.transform.localScale.x * spacing, 10, j * 1 * tile.transform.localScale.z * spacing), Quaternion.identity) as GameObject;
                temporary.name = "tile-" + i.ToString() + "-" + j.ToString();
                temporary.transform.eulerAngles = new Vector3(180, 0, 0);
                temporary.transform.parent = backgroundObject.transform;
                BoxCollider boxCollider = temporary.GetComponent<BoxCollider>() as BoxCollider;
                boxCollider.size = new Vector3(sensitivity, 1, sensitivity);
                temporary.GetComponent<Letters>().letter.text = "";
                temporary.GetComponent<Letters>().gridX = i;
                temporary.GetComponent<Letters>().gridY = j;
                tiles.Add(tile);
                matrix[i, j] = "";
            }
        }
        CenterBG();
        InsertWords();
        FillRemaining();
        time = Time.time;
    }
    private void CenterBG() {
        backgroundObject.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width / 2, (Screen.height / 2) + 50, 200));
    }

    private void InstantiateBG() {
        if (gridX % 2 != 0 && gridY % 2 == 0) {
            backgroundObject = Instantiate (background, new Vector3 ((tile.transform.localScale.x * spacing)
            * (gridX / 2), 1, (tile.transform.localScale.z * spacing)
            * (gridY / 2) - (tile.transform.localScale.z * spacing)), Quaternion.identity) as GameObject;
        } else if (gridX % 2 == 0 && gridY % 2 != 0) {
            backgroundObject = Instantiate (background, new Vector3 ((tile.transform.localScale.x * spacing) * (gridX / 2)
            - (tile.transform.localScale.x * spacing), 1, (tile.transform.localScale.z * spacing) * (gridY / 2)), Quaternion.identity) as GameObject;
        } else {
            backgroundObject = Instantiate(background, new Vector3 ((tile.transform.localScale.x * spacing) * (gridX / 2) -
                (tile.transform.localScale.x * spacing), 1, (tile.transform.localScale.z * spacing) * (gridY / 2) - (tile.transform.localScale.z * spacing)), Quaternion.identity) as GameObject;
        }
        backgroundObject.transform.eulerAngles = new Vector3(180, 0, 0);
        backgroundObject.transform.localScale = new Vector3(((tile.transform.localScale.x * spacing) * gridX), 1, ((tile.transform.localScale.x * spacing) * gridY));
   }

    void Update() {
        if (Input.GetMouseButton (0)) {
            ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit)) {
                current = hit.transform.gameObject;
            }
            ready = true;
        }
        if (Input.GetMouseButtonUp (0)) {
            ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit)) {
                current = hit.transform.gameObject;
            }
            Verify();
        }
    }

    private void Verify() {
        if (!correct) {
            foreach (KeyValuePair<string, bool> p in insertedWords) {
                if (selectedString.ToLower() == p.Key.Trim().ToLower()) {
                    foreach (GameObject g in selected) {
                        g.GetComponent<Letters>().identified = true;
                    }
                    correct = true;
                }

                if (allowReverse)
                {
                    if (Reverse(selectedString.ToLower()) == p.Key.Trim().ToLower())
                    {
                        foreach (GameObject g in selected)
                        {
                            g.GetComponent<Letters>().identified = true;
                        }
                        correct = true;
                    }
                }
            }
        }

        if (correct) {
            insertedWords.Remove(selectedString);
            insertedWords.Remove(Reverse(selectedString));

            if (word.ContainsKey (selectedString)) {
                insertedWords.Add (selectedString, true);
            }
            else if (word.ContainsKey(Reverse(selectedString)))
            {
                insertedWords.Add(Reverse(selectedString), true);
            }
            identified++;
        }
        ready = false;
        selected.Clear();
        selectedString = "";
        correct = false;
    }

    private void InsertWords() {
        System.Random rn = new System.Random();
        foreach (KeyValuePair<string, bool> p in word) {
            string s = p.Key.Trim();
            bool placed = false;
            while (placed == false) {
                int row = rn.Next(gridX);
                int column = rn.Next(gridY);
                int directionX = 0;
                int directionY = 0;
                while (directionX == 0 && directionY == 0) {
                    directionX = rn.Next(3) - 1;
                    directionY = rn.Next(3) - 1;
                }
                placed = InsertWord(s.ToLower(), row, column, directionX, directionY);
                mark++;
                if (mark > 100) {
                    break;
                }
            }
        }
    }

    private bool InsertWord(string word, int row, int column, int directionX, int directionY) {
        if (directionX > 0) {
            if (row + word.Length >= gridX) {
                return false;
            }
        }
        if (directionX < 0) {
            if (row - word.Length < 0) {
                return false;
            }
        }
        if (directionY > 0) {
            if (column + word.Length >= gridY) {
                return false;
            }
        }
        if (directionY < 0) {
            if (column - word.Length < 0) {
                return false;
            }
        }

        if (((0 * directionY) + column) == gridY - 1) {
            return false;
        }

        for (int i = 0; i < word.Length; i++) {
            if (!string.IsNullOrEmpty (matrix [(i * directionX) + row, (i * directionY) + column])) {
                return false;
            }
        }

        insertedWords.Add(word, false);
        char[] w = word.ToCharArray();
        for (int i = 0; i < w.Length; i++) {
            matrix[(i * directionX) + row, (i * directionY) + column] = w[i].ToString();
            GameObject.Find("tile-" + ((i * directionX) + row).ToString() + "-" + ((i * directionY) + column).ToString()).GetComponent<Letters>().letter.text = w[i].ToString();
        }
        return true;
    }

    private void FillRemaining() {
        for (int i = 0; i < gridX; i++) {
            for (int j = 0; j < gridY; j++) {
                if (matrix[i, j] == "") {
                    matrix[i, j] = letters[UnityEngine.Random.Range(0, letters.Length)];
                    GameObject.Find("tile-" + i.ToString() + "-" + j.ToString()).GetComponent<Letters>().letter.text = matrix[i, j];
                }
            }
        }
    }

    private void Mix(string[] words) {
        for (int t = 0; t < words.Length; t++) {
            string tmp = words[t];
            int r = UnityEngine.Random.Range(t, words.Length);
            words[t] = words[r];
            words[r] = tmp;
        }
    }

    private string TimeElapsed() {
        TimeSpan t = TimeSpan.FromSeconds(Mathf.RoundToInt(Time.time - time));
        return String.Format("{0:D2}:{1:D2}", t.Minutes, t.Seconds);
    }

    private string Reverse(string word)
    {
        string reversed = "";
        char[] letters = word.ToCharArray();
        for (int i = letters.Length - 1; i >= 0; i--)
        {
            reversed += letters[i];
        }
        return reversed;
    }

    void OnGUI() {
        GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();
            GUILayout.Label("   Timer: ");
            GUILayout.Label(TimeElapsed());
            GUILayout.EndHorizontal();

        foreach (KeyValuePair<string, bool> p in insertedWords) {
            GUILayout.BeginHorizontal();
            GUILayout.Label("   " + p.Key);
            if (p.Value) {
                GUILayout.Label("*");
            }
            GUILayout.EndHorizontal();
        }
        GUILayout.EndVertical();
    }
}

```

**Letters Script**

```
using UnityEngine;
using System.Collections;

public class Letters : MonoBehaviour {

    public bool utilized = false;
    public bool identified = false;
    public TextMesh letter;
    public int gridX, gridY;

    void Start() {
        GetComponent<Renderer>().materials[0].color = WordSearch.Instance.defaultTint;
    }

    void Update() {
        if (WordSearch.Instance.ready) {
            if (!utilized && WordSearch.Instance.current == gameObject) {
                WordSearch.Instance.selected.Add(this.gameObject);
                GetComponent<Renderer>().materials[0].color = WordSearch.Instance.mouseoverTint;
                WordSearch.Instance.selectedString += letter.text;
                utilized = true;
            }
        }

        if (identified) {
            if (GetComponent<Renderer>().materials[0].color != WordSearch.Instance.identifiedTint) {
                GetComponent<Renderer>().materials[0].color = WordSearch.Instance.identifiedTint;
            }
            return;
        }

        if (Input.GetMouseButtonUp(0)) {
            utilized = false;
            if (GetComponent<Renderer>().materials[0].color != WordSearch.Instance.defaultTint) {
                GetComponent<Renderer>().materials[0].color = WordSearch.Instance.defaultTint;
            }
        }
    }
}

```

# Answer
I found the answer for the question. what i have done is under the Insert method, I changed directionX,directionY

```
while (directionX == 0 && directionY == 0) {
                directionX = rn.Next(3) - 1;
                directionY = rn.Next(3) - 1;
            }

```

to this

```
while (directionX == 0 && directionY == 0) {
                directionX = Mathf.Abs(rn.Next(3) - 1);
                directionY = Mathf.Abs(rn.Next(3) - 1);
            }

```

Which those **directionX,directionY** variables may return minus values when inserting words to the grid. Thanks.
> 0 votes

---
Tags: unity, word-games
---


# Question
Title: What is the best way to remove a list reference after the object has been deleted at edit time?
Inside a MonoBehaviour `MyComponentA` I have a list of `MyComponentB` (also a MonoBehaviour) like so:

```
List<MyComponentB> myList;

```

This list gets populated mostly through editor scripts at edit time. Now say that someone who is editing the scene comes along and deletes a game object that has `MyComponentB` attached, and also happens to be referenced by the list above.

How can `MyComponentA` fix the list to remove null references after such a deletion? I basically want to make this automatic so that when designers delete these objects, they dont have to go hunt down which `MyComponentA` referenced them and fix the list.

My naive approach was to have a circular reference from `MyComponentB` to `MyComponentA` (so that it knows which list it belongs in), and then unregister it properly when `OnDestroy` gets called. This however doesn't work at edit time unfortunately since `OnDestroy` is not called.

Thanks for your help!

# Answer
> 3 votes
Although there are probably multiple ways to do this, the one you already mentioned is probably the simplest one to implement with the least amount of edge cases in which it doesn't work... That being said, if someone has a better approach, I'm interested aswell.

By adding \[ExecuteInEditMode\] you can get your original idea to work. Note that this means that all other Unity methods will be called outside of playmode aswell (like Start, Update, OnGUI, etc.).

First the class which contains the List:

```
public class Example2 : MonoBehaviour
{
    public List<GameObject> listOfGo = new List<GameObject>(); // This works well with Undo
    public List<Example> listOfExample = new List<Example>(); // This works, but not with Undo :( therefore I advise storing the GameObject instead as done in the list above
}

```

Then the other class that removes itself from the list:

```
[ExecuteInEditMode]
public class Example : MonoBehaviour
{
    [SerializeField] private Example2 _parent;

#if UNITY_EDITOR
    private void OnDestroy()
    {
        if (!Application.IsPlaying(this))
        {
            // Register Undo, so that when you ctrl-z the delete operation, it is re-added to the list
            UnityEditor.Undo.RecordObject(_parent, "Remove from parent");

            // Remove from list
            _parent.listOfGo.Remove(gameObject);
            _parent.listOfExample.Remove(this);
        }
    }
#endif
}

```

Note that i above example, the ListOfExample is only added to show that it doesn't work with Undo, you don't actually need to use 2 lists ;)

You might be able to do this using Undo.postprocessModifications instead but I haven't tried this, I also think that even if you'd get it to work using that callback, it is probably not very robust as Unity might change stuff behind the scenes that you would rely on with that approach...

---
Tags: unity
---


# Question
Title: Can I put real monuments like white house, statue of liberty in my open world game?
I'm currently working on open world game. But I am confused about one thing that, is it ok if I put real monuments and sculptures like white house, statue of liberty etc. in my game? Please help if anyone knows and confident about his/her answer. Thanks in advance!

# Answer
> 0 votes
It looks like there might be some restrictions on certain monuments, but not the ones that you asked about at least.

According to this, which granted is about photography and not games specifically, some famous monuments have restrictions on using them for commercial purposes, but from what I know of copyright laws, this could also translate to using them in games for commercial purposes. Although, as I said above, the monuments that you mentioned are not included in these restrictions, so you should be safe to use them.

---
Tags: 3d, copyright, objects, 3d-modeling
---


# Question
Title: Copyright laws on famous buildings and monuments in games?
I am working on a commercial card game based on the middle east. We would like to have famous buildings and monuments in the game, such as the Burj Al-Arab in Dubai.

Are there laws that would prevent us from using pictures or drawings of famous buildings in commercial games?

# Answer
I'm not expert at copyright law, but according to this article relating to U.S. copyright laws, it seems to be permissible to commercially use depictions of famous buildings. One copyright law mentioned in this article states:

> The copyright in an architectural work that has been constructed **does not include the right to prevent the making, distributing, or public display of pictures, paintings, photographs, or other pictorial representations of the work**, if the building in which the work is embodied is located in or ordinarily visible from a public place.

However, that article only specifically mentions famous buildings in the U.S. as examples. I can only assume that famous buildings from other countries are also acceptable for U.S. citizens to create depictions of.

Unfortunately, after doing a bit of Google searching on the topic of Middle East copyright laws for buildings, the only relevant articles I found were discussing how copyright buildings couldn't be copied in actual construction.

To add to the complexity, the age of famous buildings also affects how much copyright protection they have. One of the articles I found stated this in regards to Middle East building copyrights:

> **Building copyright is not indefinite, but is only of limited duration. For instances, the pyramids, the Taj Mahal and even the Eiffel Tower are now out of copyright.** This means that these iconic buildings can be freely reproduced in new developments and amusement parks such as Dubailand, and other projects which feature replicas or scaled models of these ancient monuments. **Buildings such as the Burj Al Arab, Emirates Towers or Burj Dubai are all buildings that have been built recently and therefore remain within the laws of copyright, and will continue to enjoy copyright protection for a number of years.**

Thus, to answer your question, there may or may not be non-U.S. laws protecting some famous buildings from being depicted in drawings and pictures without permission. However, even if these laws exist, they might not be applicable if you don't live in the countries with these laws.
> 4 votes

# Answer
Note: my answer is assumes US legal jurisdiction. And as usual, this is not legal advice - when in doubt, ask a lawyer.

The short answer is: it's complicated.
As cited from Wikimedia Foundation’s preliminary perspective on matter (emphasis is mine):

> ### Copyright Status of Memorials and Monuments
>
> Federal law **removes** copyright protection from works of the U.S. government, **but** the U.S. government may not have actually designed and created any given memorial or monument. **Works merely commissioned by the government may still enjoy copyright protection**, as one U.S. Court of Appeals has ruled that if the government contracts with a third party to create a work, and the work, as commissioned, is not related to official duties of any government employee, the work will enjoy copyright protection.
>
> ### Freedom of Panorama as it Relates to Memorials and Monuments
>
> U.S. law provides for a concept known as Freedom of Panorama, which **gives people the right to take and distribute pictures of architectural works** visible from public places. **However**, the law defines architectural works as “the design of a building as embodied in any tangible medium of expression, including a building, architectural plans, or drawings.” Federal regulations further specify that the term ‘building’ “means humanly habitable structures that are intended to be both permanent and stationary, such as houses and office buildings, and other permanent and stationary structures designed for human occupancy, including but not limited to churches, museums, gazebos, and garden pavilions.” **These definitions seem to exclude sculptures and other three dimensional graphical works** from architectural works, and in fact the Copyright Act puts three-dimensional works of fine, graphic, and applied art in a separate category of protected works: pictorial, graphic, and sculptural works.

Additionally, there's the matter of source material. In a 2010 the United States Postal Service referenced a Las Vegas-based replica of the real Statue of Liberty instead of the actual statue. The copyright holder of the replica sued in 2013 for ~$3.5M and was upheld in the court's decision.

In summary: check your sources, don't use sources you're unwilling to cite & seek legal council.
> 2 votes

---
Tags: copyright
---


title: Unity Items not being removed from list

text:
# Question
Title: Unity Items not being removed from list
So I finally perfected my RTS multiple movement. The situation is that the game objects are added into a list in a script bound to the camera called `UnitController` they are added from a unit client script `MultiselectClient`, this client accesses the UnitController class and adds itself the gameObject into the list. Each time I do the drag select I want it to clear the list first before adding any more. But for some reason, it doesn't work?

This is in my `UnitController` (below):

```
void MultiSelect(RaycastHit hit)
{
    Debug.Log(SelectedUnits);
    if (SelectedUnits.Count > 0)
    {
        Debug.Log("Moving group to: " + hit.point);
        foreach(GameObject gameObject in SelectedUnits)
        {
            gameObject.GetComponent<NavMeshAgent>().SetDestination(hit.point);
        }
    }
}

```

This is in my client (below):

```
public bool Selected = false;
void Update()
{
    if (Input.GetMouseButton(0))
    {
        Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
        camPos.y = Screen.height - camPos.y;

        //if inside the cameras drag selection area then mark player as selected
        Selected = UnitController.selection.Contains(camPos);

        Debug.Log("Selected");
        if(selected){
           addTo();
        }
    }

}

void addTo()
{

    UnitController.SelectedUnits.Remove(gameObject); //I have also tried .clear() which also hasnt worked.

    if (!UnitController.SelectedUnits.Contains(gameObject))
    {
        UnitController.SelectedUnits.Add(gameObject);
        Debug.Log("Added to list: " + UnitController.SelectedUnits);
    }
    else
    {
        Debug.Log("Im already in that list.");
    }
}

```

# Answer
> 0 votes
# Your problem is this if-statement:

```
    if(selected){
       addTo();
    }

```

If the unit isn't selected, nothing happens. It doesn't matter that you do `remove` or `clear` inside `addTo` because `addTo` isn't being called unless this object is being selected.

```
    if(selected){
       addTo();
    }
    else{
       UnitController.SelectedUnits.Remove(gameObject);
    }

```

---
Tags: unity, rts, storage
---


# Question
Title: Why can't I use the operator '>=' with Vector3s?
I am trying to get a rectangle to move between two positions which I refer to as `_positionA` and `_positionB`. Both are of type `Vector3`. The rectangle moves just fine. However, when it reaches `_positionB` it does not move in the opposite direction, like it should.

I went back into the code to take a look. I came to the conclusion that as the object moved, the `if` statements in the code missed the frame in which the rects position was equal to `_positionB`. I decided to modify the code to reverse direction if the rects position is *greater than or equal to* `_positionB`. My code is not too long, so I will display it below:

```
using UnityEngine;
using System.Collections;

public class Rectangle : MonoBehaviour
{
    private Vector3 _positionA = new Vector3(-0.97f, -4.28f); //Start position
    private Vector3 _positionB = new Vector3(11.87f, -4.28f); //End position
    private Transform _rect_tfm;
    private bool _atPosA = false, _atPosB = false;

    public Vector2 speed = new Vector2(1f, 0f);

    private void Start()
    {
        _rect_tfm = gameObject.GetComponent<Transform>();
        _rect_tfm.position = _positionA;
        _atPosA = true;
    }

    private void Update()
    {
        /*NOTE: Infinite loops can cause Unity to crash*/
        Move();
    }

    private void Move()
    {
        if (_atPosA)
        {
            _rect_tfm.Translate(speed * Time.deltaTime);

            if (_rect_tfm.position == _positionB)
            {
                _atPosA = false;
                _atPosB = true;
            }
        }

        if (_atPosB)
        {
            _rect_tfm.Translate(-speed * Time.deltaTime);

            if (_rect_tfm.position == _positionA)
            {
                _atPosA = true;
                _atPosB = false;
            }
        }
    }
}

```

When I changed it, however, it warned me of the following error message:

> Operator \>= cannot be applied to operands of type Vector3 and Vector3.

This confuses me for two reasons; first, both values are of the same data type. Second, using the comparison operator(`==`) on the two values works without error. Why can't I use the operator `>=` with `Vector3`s?

# Answer
To simplify the answer, `Vector3` is a custom `struct` provided by the `UnityEngine` namespace. When we create custom `class` or `struct` types, we must *also* define its operators. As such, there is no default logic for the `>=` operator. As pointed out by *Evgeny Vasilyev*, `_rect_tfm.position == _positionB` makes sense, as we can directly check the `Vector3.x`, `Vector3.y` and `Vector3.z` values. `_rect_tfm.position >= _positionB` does not make as much sense, due to the fact that a `Vector3` is represented by three separate values.

We could overload the `Vector3` class to contain the suitable operators *in theory*, but that seems rather complicated. Instead, it would be easier to simply *extend* the `Vector3` class with a suitable *method*. That being said, it seems that your intending to use this logic for movement. As such, you might find it much easier to use the `Vector3.Lerp` method; if so, read further below.

### Adding extension methods to `Vector3`

As previously mentioned, applying `<=` or `>=` to a `Vector3` is often illogical. For movement, you probably want to read further for the `Vector3.Lerp` method. That said, you might want to apply the `<=` `=>` arithmetic for other reasons, so I will give you an easy alternate.

Instead of applying the logic of `Vector3 <= Vector3` or `Vector3 >= Vector3`, I propose extending the `Vector3` class to include methods for `isGreaterOrEqual(Vector3 other)` and `isLesserOrEqual(Vector3)`. We can add extension methods to a `struct` or `class` by declaring them in a `static` class that does not inherit. We also include the target `class` or `struct` as the first parameter, using the `this` keyword. Note that in my example, I assume that you mean to ensure that all three main values (`x`, `y` and `z`) are *all* greater or equal, or lesser or equal, respectively. You can provide your own logic, here, as you require.

```
public static class ExtendingVector3
{
    public static bool IsGreaterOrEqual(this Vector3 local, Vector3 other)
    {
        if(local.x >= other.x && local.y >= other.y && local.z >= other.z)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static bool IsLesserOrEqual(this Vector3 local, Vector3 other)
    {
        if(local.x <= other.x && local.y <= other.y && local.z <= other.z)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

```

When we attempt to call these methods from the `Vector3` class, `local` will represent the `Vector3` instance we are calling the method from. You will note that the methods are `static`; extension methods *must* be `static`, but you still have to call them from an instance. Given the above extension methods, you can now apply them directly to your `Vector3` types.

```
Vector3 left;
Vector3 right;

// Is left >= right?
bool isGreaterOrEqual = left.IsGreaterOrEqual(right);

// Is left <= right?
bool isLesserOrEqual = left.IsLesserOrEqual(right);

```

### Moving `Vector3` with `Vector3.Lerp`

Calling the `Vector3.Lerp` method allows us to determine the exact position between two `Vector3` values at a given time. An added benefit of this method is that *the `Vector3` will not overshoot its target*. `Vector3.Lerp` takes three parameters; the start position, the end position, and the current position represented as a value between 0 and 1. It outputs the resulting position as a `Vector3`, which we can directly set as the current position.

Solving your problem, I propose using `Vector3.Lerp` to move to a `targetPosition`. After calling the `Move` method in each `Update`, we can check if we have reached said target; `Lerp.Vector3` will *not* overshoot, so `transform.position == targetPosition` becomes reliable. We can now check the position, and change the `targetPosition` to `leftPosition` or `rightPosition` to reverse the movement, accordingly.

```
public Vector3 leftPosition, rightPosition;
public float speed;
public Vector3 targetPosition;

private void Awake()
{
    targetPosition = rightPosition;
}

private void Update()
{
    Move();

    if(transform.position == targetPosition)
    {
        // We have arrived at our intended position. Move towards the other position.
        if(targetPosition == rightPosition)
        {
            // We were moving to the right; time to move to the left.
            targetPosition = leftPosition;
        }
        else
        {
            // We were moving to the left; time to move to the right.
            targetPosition = rightPosition;
        }
    }
}

private void Move()
{
    // First, we need to find out the total distance we intend to move.
    float distance = Vector3.Distance(transform.position, targetPosition);

    // Next, we need to find out how far we intend to move.
    float movement = speed * Time.deltaTime;

    // We find the increment by simply dividing movement by distance.
    // This will give us a decimal value. If the decimal is greater than
    // 1, we are moving more than the remaining distance. Lerp
    // caps this number at 1, which in turn, returns the end position.
    float increment = movement / distance;

    // Lerp gives us the absolute position, so we pass it straight into our transform.
    transform.position = Vector3.Lerp(transform.position, targetPosition, increment);
}

```

You can see this demonstrated in the following animation. I translate the blue cube with `Vector3.LerpUnclamped`, which gives us a similar result to simple unchecked translation. I translate the red cube using `Vector3.Lerp`. Left unchecked, the blue cube moves off into oblivion; while the red cube stops exactly where I intend it to. You can read more about this type of movement in the Stack Overflow documentation.
> 16 votes

# Answer
Defining `>=` for a `Vector3` type makes no sense. What determines if one vector is greater than another? Their magnitude or their individual x, y, z components?

A vector is a magnitude & a direction. So what determines what direction is greater?

If you need to compare the magnitudes you can use `sqrMagnitude`.

In this case `Vector3` overrides `==` to simply compare the different components to see if they are the same. (within a threshold)

This is the same reason multiplying two vectors using `*` is not possible. There is simply no mathematical way of doing it. Some people use `*` for dot product, but that is an unclear API design.
> 27 votes

# Answer
This is an old question but to put in to less technical terms, a Vector3 is a "container" for 3 float values - x,y,z.

You can compare individual values, such as comparing the x values of two Vector3s, because they are just numbers.

However, an entire Vector3 cannot be compared to another Vector3 because there isn't a single value that can be used to compare the two.
> 3 votes

# Answer
Just adding onto what *Gnemlock* posted, regarding adding extension methods to the Vector3 class. There's an issue in Unity (and I'm sure other game engines) when using certain comparison operators (`==`,`<=` and `>=`) between two float values, due to how floating point calculation is handled. `Mathf.Approximately` should be used instead, thus the following extension methods can be added for checking if two vectors are \>= or \<= to each other:

```
using UnityEngine;

public static class ExtendingVector3
{
    public static bool IsGreaterOrEqual(this Vector3 local, Vector3 other)
    {
        bool xCond = local.x > other.x || Mathf.Approximately(local.x, other.x);
        bool yCond = local.y > other.y || Mathf.Approximately(local.y, other.y);
        bool zCond = local.z > other.z || Mathf.Approximately(local.z, other.z);

        if(xCond && yCond && zCond)
            return true;

        return false;
    }

    public static bool IsLesserOrEqual(this Vector3 local, Vector3 other)
    {
        bool xCond = local.x < other.x || Mathf.Approximately(local.x, other.x);
        bool yCond = local.y < other.y || Mathf.Approximately(local.y, other.y);
        bool zCond = local.z < other.z || Mathf.Approximately(local.z, other.z);

        if(xCond && yCond && zCond)
            return true;

        return false;
    }
}

```
> 0 votes

# Answer
I'd like to propose a different way of interpreting this question. A code pattern like this:

```
if(myPosition >= patrolEnd || myPosition <= patrolStart)
    TurnAround();

```

is basically trying to use the `>=` / `<=` operators as **"has the left side *reached or passed* the right side?"** tests.

Using `>=` / `<=` to mean "reached or passed" makes sense in a one-dimensional sense, if my position is just a float:

```
if(myX >= rightEnd || myX <= leftEnd)
    TurnAround();

```

But in 3D space we don't have any one line to measure along, to decide which side is "high/far" and which side is "low/near." For example, we could be trying to patrol between the points

```
patrolStart = (-10,  0,  5)
patrolEnd   = ( 10,  0, -5)

```

So now we expect `patrolStart <= myPosition <= patrolEnd` on the X axis, but `patrolEnd <= myPosition <= patrolStart` on the Z axis. Our "reached or passed" operator is different from one axis to another, so there's no longer a clear mapping between our concept of passing a threshold and a simple inequality check.

But, there's a way we can pick out just one line in 3D space, and make our `>=` / `<=` behave like the single float case along this line we chose:

```
// Here we select the directed line from our start point to our end point.
Vector3 axis = patrolEnd - patrolStart;

// We can make a single number representing the "low" end of our range
// by taking the dot product of this axis with our start point.
float low = Vector3.Dot(axis, patrolStart);

// And the "high" end by dotting this axis with the end point.
float high = Vector3.Dot(axis, patrolEnd);

// And our progress between is the dot product of the axis with our position.
float progress = Vector3.Dot(axis, myPosition);

// Now we can use our turn-around logic just like we were in the 1D case:
if(progress >= high || progress <= low)
    TurnAround();

```

As a bonus, if you normalize the axis vector before using it, then all the dot products represent distances, so you can measure exactly how far you are from either end, along the axis of travel.
> 0 votes

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


# Question
Title: ScriptableObjects lose references/stored objects upon build/restarting the Unity Editor?
I'm working on implementing **room prefabs** for my **2D procedural map generation** algorithm.

Basically I made a tool which **parses a scene's**

* monsters, items, etc into an ObjectContainer **prefab**,
* and into a **ScriptableObject** containing the tilemap's TileDatas, EntryTiles, and the ObjectContainerPrefab.

It works well, but my problem occurs when I **try to build the game**, or just **restart the editor**.

**The TileData array will be empty.**

*And thus for example the EntryTiles' TileData reference will be null.*

**Here 's how I use them:**

```
[MenuItem("Custom Tools/Parse room prefab from scene")]
private static void ParseRoomPrefabFromScene()
{
    var tilemap = GameObject.Find("Tilemap").GetComponent<Tilemap>();
    RoomPrefab roomPrefab = ScriptableObject.CreateInstance<RoomPrefab>();
    ParseTilemap(roomPrefab, tilemap);
    ParseObjects(roomPrefab, tilemap);
    ParseEntryTiles(roomPrefab, tilemap);
    AssetDatabase.CreateAsset(roomPrefab, "xyz.asset");
    AssetDatabase.SaveAssets();
}

// How I setup my scriptable object, i.e. in ParseTilemap:
var tileDatas = new List<TileData>();
...
    var tileData = new TileData(coordinates, unityTile, isWall);
    tileDatas.Add(tileData);
...
roomPrefab.tileDatas = tileDatas.ToArray();

```

---

**Here are the classes:**

```
public class RoomPrefab : ScriptableObject
{
    public TileData[] tileDatas;
    public EntryTile[] entryTiles;
    public ObjectContainerPrefab ObjectContainerPrefab;
}

[Serializable]
public class TileData
{
    public TileBase UnityTile
    {
        get;
        private set;
    }

    public Vector2Int Coordinates
    {
        get;
        set;
    }

    public bool IsWall
    {
        get;
        private set;
    }

    public TileData(Vector2Int coordinates, TileBase unityTile, bool isWall)
    {
        Coordinates = coordinates;
        UnityTile = unityTile;
        IsWall = isWall;
    }
...

[Serializable]
public class EntryTile
{
    public TileData TileData
    {
        get;
        private set;
    }

    public Vector2Int LeaveDirection
    {
        get;
        private set;
    }

    public EntryTile(TileData tileData, Vector2Int leaveDirection)
    {
        TileData = tileData;
        LeaveDirection = leaveDirection;
    }
...

[Serializable]
public class ObjectContainerPrefab
{
    public Vector2Int Coordinates
    {
        get;
        private set;
    }

    public float Rotation
    {
        get;
        private set;
    }

    public GameObject Prefab
    {
        get;
        private set;
    }

    public ObjectContainerPrefab(Vector2Int coordinates, float rotation, GameObject prefab)
    {
        Coordinates = coordinates;
        Rotation = rotation;
        Prefab = prefab;
    }
}

```

**UPDATE:** here is a freshly parsed scriptable object. In the Editor everything is fine, while in its file its tileDatas array is already empty. Why?

```
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_GameObject: {fileID: 0}
  m_Enabled: 1
  m_EditorHideFlags: 0
  m_Script: {fileID: 11500000, guid: 30263215ad3a45a479bb2dd6409fb0a9, type: 3}
  m_Name: TestRoom
  m_EditorClassIdentifier:
  tileDatas: []
  entryTiles:
  - DebugCube: {fileID: 0}
  - DebugCube: {fileID: 0}

```

# Answer
It was due to having **auto properties** on **serialized classes**:

```
public TileData TileData
{
    get;
    private set;
}

```

Using **properties with `[SerializeField]` private fields** fixes it:

```
[SerializeField]
private TileData tileData;
public TileData TileData
{
    get { return tileData; }
    private set { tileData = value; }
}

```

Or if you are lazy, just use **`[field: SerializeField]`**:

```
[field: SerializeField] public TileData TileData {get; private set;}

```

**UPDATE:**

* It was still losing references,
* solve it by calling `EditorUtility.SetDirty()` before `AssetDatabase.SaveAssets()`
> 4 votes

# Answer
As I hinted at in the comments, it looks like you're missing a call to `Undo.RecordObject()` just before you start populating fields like the tile map data on your `ScriptableObject`

This gives the editor a heads-up: "I'm about to make changes to this object, so note what it looked like beforehand"

After the current editor frame, Unity looks through all the objects that were tagged this way, and does a binary diff against their cached state from when you called `RecordObject`. Where the state is the same, it discards it as a no-op. Where it differs, it creates an entry in the Edit→Undo history to be able to undo the change, and marks the new, modified state of the object as in need of saving.

Then the next time you save your assets (manually or via script), these marked objects are the ones that get saved to disc.

Unity doesn't try to do a diff on every bit of data in your whole project to figure out what's changed (that would make saving way too slow in big projects), so it's up to you to tell the editor which objects you're modifying through scripts so it can add them to its shortlist for the next save.
> 0 votes

# Answer
Faced similar problem when working with ScriptableObjects when build or re-open the project. Actually this issue is not in your side. Issue belongs to here

> \[MenuItem("Custom Tools/Parse room prefab from scene")\]

It's seems funny but whenever you worked with ScriptableObjects and create any Menu item where ScriptableObjects is there, you have to remove any space in Menu/SubMenu name. You can change the names like this

> \[MenuItem("CustomTools/ParseRoomPrefabFromScene")\]

instead of previous one. Hit a try. I solved my problem with this silly solution.

> N.B: If you try this in your existing project, You have to delete those scripts where ScriptableObjects referenced and ScriptableObjects. Then re-open your project so that temp file and solutions being reset. After that you create those scripts and make sure the Menu Item names without space. Hope your problem will be solved.
> -1 votes

---
Tags: unity, serialization
---


# Question
Title: In Godot, how to make a Kinematic body affectable by rigid bodies?
**Background Info**

I'm currently following the FPS tutorial from the official site. By the end of Part 1, there is a Player object implemented as a `KinematicBody` and controlled by player input, and a few cubic blocks scattered around, implemented as `RigidBodies`. The `KinematicBody` is moved with the `move_and_slide` function that takes `static colliders` into account, so the player is able to stand on the floor and bump into walls.

However, the player can't bump into or stand on the cubes. If you attempt to jump onto a cube, it will slide from under you. If you try to push a cube into a wall, it will glitch around a little, then slide away, without even slowing you down. The cubes have no power to stop the `KinematicBody` from moving through them.

**Question**

How can I change the behaviour to make it possible for a `KinematicBody` to stand on a `RigidBody`?

# Answer
`move_and_slide` has a parameter called `infinite_inertia` which defaults to `true`:

> If infinite\_inertia is true, body will be able to push RigidBody nodes, but it won’t also detect any collisions with them. If false, it will interact with RigidBody nodes like with StaticBody.

Try passing `false` instead, like so:

```
vel = move_and_slide(vel,Vector3(0,1,0), 0.05, 4, deg2rad(MAX_SLOPE_ANGLE), false)

```

Now the boxes will slow you down as you push against them, and you should be able to jump on top of them.
> 1 votes

---
Tags: physics, rigidbody, godot
---


# Question
Title: How to use a sprite mask or shader to mask a text?
I'd like to know what I need to learn to apply a shader to achieve masking on the text.

Here is my text object in-game, I'm using a sprite mask to mask the game objects on the card, they're all in their own sorting layer, the order number is 11.

Here is my text in the inspector

However, everything on the card is being masked except the text.

If someone could tell me what I need to learn to solve this problem that'd be great, can this problem be solved using a shader?

# Answer
> 4 votes
If your cards are sprite you should use TextMesh because Text Component made for UI Elements.

# Sprite Solution

**Create a world space Canvas and child it to card sprite.**

**Use Sprite Mask**

**Select Visible Inside Mask**

**Change the Stencil buffer to cut the text**

**Enjoy!**

---

**UI Solution**

your game is a card game so you should use UI Elements Instead.

you can mask your Items in UI by Mask Component.

**Create a canvas**

**Add Mask**

**Child them into mask**

also, you can use SoftMaskForUGUI to have a better result

---
Tags: unity, shaders, masking
---


# Question
Title: Way to Get Collision Box Width Gamemaker
I was coding the wall collision system for my game, and I wanted to do it using intersect boundaries instead of checking every step if they are off the screen. When the player crosses the boundary they get moved back to half of the sprite, but because the intersect boundary uses the collision box, it appears to jitter when you walk into the wall. Is there a way to get the width and height of the collision box so I can move them half of that away from the wall?

# Answer
You can get an instance's bounding box edges position by using the read-only `bbox_*` variables: they are expressed in world coordinates and can be used for your collision resolution purpose.
> 0 votes

---
Tags: game-maker, collision-resolution
---


# Question
Title: can i show logs in unity with different colors or different icon signs?
I'm working on a project that has a lot of **logging** messages that pass very fast.

I can use **error logs** or **warning logs** but is there any way to log something with different colors so it is easier to find?

Right now, I just use something like this:

```
Debug.LogError("show missing gold popup accepted");

```

# Answer
Your very first step to answer this question should be to check the Unity documentation, where you'd find a helpful code example that does exactly this:

`Debug.Log("<color=red>Error: </color>AssetBundle not found");`

Or if you were looking at the Debug.LogError documentation instead, you'd see:

> When the message is a string, rich text markup can be used to add emphasis. See the manual page about rich text for details of the different markup tags available.

And following that link, you'd find the exact syntax for setting a colour:

> **color**
>
> Sets the color of the text according to the parameter value. The color can be specified in the traditional HTML format. #rrggbbaa …where the letters correspond to pairs of hexadecimal digits denoting the red, green, blue and alpha (transparency) values for the color. For example, cyan at full opacity would be specified by color=#00ffffff…
>
> You can specify hexadecimal values in uppercase or lowercase; #FF0000 is equivalent to #ff0000.
>
> We are `<color=#ff0000ff>colorfully</color> amused`
>
> Another option is to use the name of the color. This is easier to understand but naturally, the range of colors is limited and full opacity is always assumed.
>
> `<color=cyan>some text</color>`
>
> The available color names are given in the table below.

So please do get in the habit of reading the documentation first.

This is not the first time I've observed a post of yours that could be answered or improved with a quick check of the documentation or time spent testing in-game. Please take your time and use the full resources available to you, and you'll tend to reach the correct solutions faster than by rushing to post here.
> 6 votes

# Answer
I made a class to debugging easy in Unity:

# Example

```
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        Debug.Log("Hello Green" % Colorize.Green);
        Debug.Log("Hello Bold Green" % Colorize.Green % FontFormat.Bold);

        Debug.Log("Hello Orange" % Colorize.Orange);
        Debug.Log("Hello Italic Orange" % Colorize.Orange % FontFormat.Italic);

        Debug.Log(
            "Failure " % Colorize.Orange % FontFormat.Bold +
            "doesn't mean the " +
            "game is over " % Colorize.Red % FontFormat.Bold +
            "It means try again with " +
            "experience!" % Colorize.Green % FontFormat.Bold
        );
    }
}

```

---

# Font Color

```
using System;
using UnityEngine;

public class Colorize{

    // Color Example

    public static Colorize Red = new Colorize(Color.red);
    public static Colorize Yellow = new Colorize(Color.yellow);
    public static Colorize Green = new Colorize(Color.green);
    public static Colorize Blue = new Colorize(Color.blue);
    public static Colorize Cyan = new Colorize(Color.cyan);
    public static Colorize Magenta = new Colorize(Color.magenta);

    // Hex Example

    public static Colorize Orange = new Colorize("#FFA500");
    public static Colorize Olive  = new Colorize("#808000");
    public static Colorize Purple  = new Colorize("#800080");
    public static Colorize DarkRed  = new Colorize("#8B0000");
    public static Colorize DarkGreen  = new Colorize("#006400");
    public static Colorize DarkOrange  = new Colorize("#FF8C00");
    public static Colorize Gold  = new Colorize("#FFD700");

    private readonly string _prefix;

    private const string Suffix = "</color>";

    // Convert Color to HtmlString
    private Colorize(Color color){
        _prefix = $"<color=#{ColorUtility.ToHtmlStringRGB(color)}>";
    }
    // Use Hex Color
    private Colorize(string hexColor)
    {
        _prefix = $"<color={hexColor}>";
    }

    public static string operator %(string text, Colorize color){
        return color._prefix + text + Suffix;
    }

}

```

---

# Font Format

```
using System;
using UnityEngine;

public class FontFormat{
    private string _prefix;

    private string _suffix;

    public static FontFormat Bold = new FontFormat("b");
    public static FontFormat Italic = new FontFormat("i");
    private FontFormat(string format)
    {
        _prefix = $"<{format}>";
        _suffix = $"</{format}>";
    }

    public static string operator %(string text, FontFormat textFormat)
    {
        return textFormat._prefix + text + textFormat._suffix;
    }
}

```

---

# Update

I made a language to debugging easy in unity.

you can use my tool Kamali Debug.

```
    private void Start()
    {
    DebugX.Log(@"I:orange:b; love:red:b; Unity:yellow:b;
    ColorfullllllllllllllllText:rainbow:b;");

    DebugX.Log("sniper:orange:b; bug:green:b;");

    }

```

### Variables

```
using UnityEngine;
using KamaliDebug;
public class Example : MonoBehaviour
{
    public int score;
    public int health;
    private void Start()
    {
        DebugX.Log($"Score = {score}:yellow:b;");
        DebugX.Log($"Health = {health}:green:b;");
    }
}

```

### Syntax

```
(Text or Emoji):Color:TextStyle;

```

### Font Color

```
DebugX.Log("Hello world:green;");

```

### Font Style

* b = Bold
* i = Italic

DebugX.Log("Hello:b; World:i;");

### Emoji

```
DebugX.Log("love:red:b; love:red:b; love:red:b;");

```

### Complex

```
DebugX.Log("Hello:yellow:b; world:red:b;");

```
> 5 votes

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


# Question
Title: How to seamlessly handle multiple procedural 2D levels in Unity3D?
I have a **dungeon generating algorithm**, but I would like to generate X levels, which are all connected somehow.

I have a **few approaches**, but **all of them has problems and questions**, and I wonder how i.e. Diablo II handles them so **seamlessly**.

**1. Approach: Upon leaving a level, generate the next one on the fly.**

* This would be the easiest, but would result in a relatively long loading screen everytime the player enters a new level.
* So generating the levels should be at the beginning of a new game, thus the next level will just have to be loaded, which is much faster. In theory not even a loading screen is necessary.

**2. Approach: Generate every level at the beginning of a new game and store them.**

* Okay, now levels just have to be loaded, which could be done under half a second. No loading screen is necessary, maybe just a fade out-fade in.
* How do I store them?
    + Make custom files (i.e. scriptable objects) for them, or is there a simpler way?

**3. Approach: Generate and load every level at the beginning.**

* Zero loading time, because everything is already generated and loaded into the tilemap.
* But how do I guarantee that levels don't collide, and the player can't see level Y from level X if there are lots of levels?
* And wouldn't it affect the performance? Because everything is loaded all the time. Yes, renderers, rigidbodies, scripts, etc can be turned off, improving the performance a lot... but still... this seems wrong.

**What is the best way to solve this problem?**

# Answer
From generative code, if you have less than 100 levels, you can save the levels as unity assets / prefabs and load them instantly using a bit of scene management, level code and choose the 100 best that you prefer.

If you have an animation of a level transition, which rewards the player, it can give you a few moments for him to chill out while you do the generative maths.

Whatever time you have to run the generator, using *yield wait* can skip frames every i%10 loops or *yield* when deltatime \> 1/30fps.

Generally, unless you have lots of processor overhead, it's best to generate when you plan the game, else during animations, else to give the player some tasks like lockpicking while the next level loads.
> 1 votes

---
Tags: unity, procedural-generation, tilemap, maps, levels
---


title: MonoGame game running slowly

text:
# Question
Title: MonoGame game running slowly
Through development I've been running my 2D game (Monogame 3.6) on my windows laptop, which has some crummy integrated graphics card and an i5. Now I try my game on my gaming PC, which has a GTX 970 and also an i5 (a slightly better one), and the game runs slow as hell.

I'm at a complete and total loss here. Here's what I've tried to speed up the game, and it's still hovering around maybe 15 FPS:

* Reducing the game from 3 or 4 spritebatch blocks to a single one
* Removing ALL shader uniform changes, so that it only sets up the shader uniforms once and never changes them
* Commenting out 100% of particle rendering code.
* Removing my extra render target that I used for post process fx.

After all of this, making it about as simple as a Hello World renderer, and it's still dog slow. I'm dumbfounded. Codetrack profiler says 80% of my cpu time is inside of a function called `DoDraw` which seems to be XNA framework code. So I'm sure it's not the update logic, or sheer number of things rendering, etc. The time anything is taking pales in comparison to `DoDraw`. The stack looks like this:

* `Tick`
* `DoDraw`
* `Present`
* `PlatformPresent`

But I don't really understand what it's doing and why it's taking so long. Any tips, knowledge of rendering quirks, profiling tips, etc, anything appreciated.

# Answer
> 2 votes
I've deduced that this is an issue with the way I'm telling MonoGame to use vsync. turning it off and setting `FixedTimetep = false` fixes the issue. I am going to get vysnc back on, it's just going to take a bit more tooling.

---
Tags: xna, monogame
---


# Question
Title: Pausing animation and resuming on same frame
How do you stop an animation and then resume on the same frame where you paused? I tried:

```
if (paused) {
    anim.speed = 0;
} else {
    anim.speed = 1;
}

```

Sure, it pauses and plays but it doesn't resume on the frame it paused. It starts over the animation. I also tried playing around the Speed field in Animator (instead of via code) while the animation is playing and its the same way. When the animation is playing and I change the value of Speed, the animation doesn't slow down, it gets reset.

# Answer
I found out my problem. I tried creating from scratch and removing any extra and the anim.speed is actually working. I found out that I had extra state transitions happening in my original project that's why the animation was resetting.
> 1 votes

---
Tags: unity
---


title: Standard Unlit shader doesn't work?

text:
# Question
Title: Standard Unlit shader doesn't work?
I created a project to download and try out free Unity assets. I then transfer the assets I actually want to use to my actual project which uses the LWRP render pipline.

I tried to get some particle system. I copied all settings and then I found that the shader "Standard Unlit" is not working in my project. I tried to use the LWRP shaders but they didn't give me the same results. How to solve this?

# Answer
> 1 votes
The LWRP shader in your project uses "Color Mode: Additive" while the standard shader in the LWRP project uses "Color Mode: Multiply". The result is that those areas where a lot of particles with a very low intensity accumulate create a halo in your shader.

---
Tags: unity, shaders
---


# Question
Title: How can I create a patch of ocean that blends seamlessly into the horizon?
The tagline pretty much says it, but here's a picture to show the problem:

The darker gradient of blue on the horizon comes from the Godot WorldEnvironment, while the lighter shade results from a half-transparent plane that will later be animated with waves. How can I make the ocean plane blend into the horizon?

# Answer
> 1 votes
I have found a possible answer. The Spatial Material property "Distance Fade" appears to produce the kind of effect I had in mind:

After doubling the size of my ocean plane from 1000 to 2000, here's what the result looks like:

---
Tags: godot
---


# Question
Title: Should a beta version of an engine be used to start a new project?
Is it advisable to use a beta version of unity(2019.3b) to make an actual complete project? What are the disadvantages?

# Answer
> 3 votes
The downside of using a Beta version is that it might contain bugs that are never fixed in that version, or features implemented in a preliminary way that end up being implemented differently or scrapped altogether in a future stable version.

If that happens, you might find your project is dependent on a version of the engine that is not stable, or lacks the full feature set you want, but you can't easily upgrade it to the fixed/complete version because the API changed between the Beta and the stable release. This leaves you with a lot of refactoring to do, or a complete port over to the stable version.

So, it's generally considered better practice to use the main line releases, or even a Long-Term Support version, when starting a new project. That way you have confidence that the version you're using has been thoroughly tested, that bug fixes will continue to be available for it, and if you need to do an incremental upgrade later in your project, major refactoring should be more rare.

Beta versions are useful to get a preview of new features, to evaluate them and offer feedback to the devs, or to begin updating tools/middleware you've made so it's ready to share with developers using the new features in the next stable version when it releases.

---
Tags: unity
---