# Question
Title: Method call order & instantiated component instances
I want to call things in a specific order. I'm trying to lay the foundation for my online game. Each player will have its own game object ("avatar"), which is instantiated at runtime. Each of these avatars use prefabs and have their own components.

The prefabs contain items and also styles such as gender, facial hair, etc. So my equipment manager will need to check for default style prefabs if the item slot is empty.

Please correct me if I'm going about this the wrong way.

I have 2 issues.

First off, I'll show you the code.

`CreateAvatarSceneManager` is attached to its own game object in the scene:

```
public class CreateAvatarSceneManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // inst avatar with position & scale
        GameObject avatar = Resources.Load<GameObject>("Avatar");
        avatar = Instantiate(avatar, new Vector3(-5.5f, -2.5f, 0), Quaternion.Euler(new Vector3(0, 140, 0)));
        avatar.transform.localScale = new Vector3(4, 4, 4);

        // set gender
        avatar.GetComponent<AvatarStyle>().gender = AvatarGender.Female;

        // render avatar
        avatar.GetComponent<AvatarManager>().Render();
    }
}

```

`AvatarManager` is attached to the avatar prefab that is instantiated via the scene manager above.

```
public class AvatarManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Unrender();
    }

    // undrender all prefabs
    public void Unrender()
    {
        Debug.Log("called unrender");

        foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
        {
            renderer.enabled = false;
        }
    }

    // render default style prefabs
    public void Render()
    {
        Debug.Log("called render");

        AvatarStyle avatarStyle = gameObject.GetComponent<AvatarStyle>();
        EquipmentManager equipmentManager = gameObject.GetComponent<EquipmentManager>();

        Debug.Log(avatarStyle.gender);
        Debug.Log(equipmentManager.defaultPrefabs);

        /*
        foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
        {
            if (equipmentManager.defaultPrefabs[avatarStyle.gender].ContainsValue(renderer.name))
            {
                renderer.enabled = true;
            }
        }
        */
    }
}

```

`AvatarStyle` is also attached to the avatar prefab that is instantiated.

```
public class AvatarStyle : MonoBehaviour
{
    public AvatarGender gender;
}

public enum AvatarGender { Male, Female }

```

`EquipmentManager` is also attached to the avatar prefab that is instantiated.

```
public class EquipmentManager : MonoBehaviour
{
    public Dictionary<AvatarGender, Dictionary<EquipmentSlot, string>> defaultPrefabs;

    // Start is called before the first frame update
    void Start()
    {
        SetDefaultPrefabs();
    }

    // set default prefabs when item not present
    public void SetDefaultPrefabs()
    {
        Debug.Log("set default prefabs");

        defaultPrefabs = new Dictionary<AvatarGender, Dictionary<EquipmentSlot, string>>();

        Dictionary<EquipmentSlot, string> defaultMalePrefabs = new Dictionary<EquipmentSlot, string>
        {
            { EquipmentSlot.Head, "Chr_Head_Male_00" },
            { EquipmentSlot.Torso, "Chr_Torso_Male_00" },
        };
        defaultPrefabs.Add(AvatarGender.Male, defaultMalePrefabs);

        Dictionary<EquipmentSlot, string> defaultFemalePrefabs = new Dictionary<EquipmentSlot, string>
        {
            { EquipmentSlot.Head, "Chr_Head_Female_00" },
            { EquipmentSlot.Torso, "Chr_Torso_Female_00" },
        };
        defaultPrefabs.Add(AvatarGender.Female, defaultFemalePrefabs);
    }
}

public enum EquipmentSlot { Head, Torso }

```

# Issue 1

It seems like my methods aren't being called in the order I want them to. If I look at the console, it is showing me this:

```
called render
Female
Null
called unrender
set default prefabs

```

You can see the `Null` is causing problems with the `AvatarManager` render function. Since its trying to call render BEFORE the default prefabs are even set, it causes an error.

I want the order to actually be more like this:

```
called unrender
set default prefabs
Female
(dictionary of default prefabs)
called render

```

Why are things firing in this order? Should it not be calling `Start()` BEFORE any other function call?

# Issue 2

OK maybe this is actually related to issue 1. Should I actually be using singletons for the managers? If so, how do I use singletons per avatar that is instantiated?

Also, if you look at the way I am doing things, I want to turn this:

```
// from scene manager
avatar.GetComponent<AvatarStyle>().gender = AvatarGender.Female;

// from avatar manager
if (gameObject.GetComponent<AvatarStyle>().gender) DoStuff();

```

Into something like this:

```
// from scene manager
avatar.AvatarStyle.gender = AvatarGender.Female;

// from scene manager
if (gameObject.AvatarStyle.gender) DoStuff();

```

I'm more concerned with issue #1 right now. Thanks for your time and help.

# Answer
> Should it not be calling Start() BEFORE any other function call?

No, that's not the promise the engine makes to you. Consulting the docs:

> Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.

It promises you that it will call `ScriptA.Start()` before it, *the engine*, calls `ScriptA.Update()` or `ScriptA.FixedUpdate()` or `ScriptA.LateUpdate()`. That's all.

If *you* call `ScriptB.Foo()` inside `ScriptA.Start()`, the engine does not promise to jump in and interrupt this call that *you* made to insert a call to `ScriptB.Start()` before continuing to run the code you wrote.

The problem looks to be here in `CreateAvatarSceneManager`:

```
void Start()
{
    // inst avatar with position & scale
    GameObject avatar = Resources.Load<GameObject>("Avatar");
    avatar = Instantiate(avatar, new Vector3(-5.5f, -2.5f, 0), Quaternion.Euler(new Vector3(0, 140, 0)));
    avatar.transform.localScale = new Vector3(4, 4, 4);

    // set gender
    avatar.GetComponent<AvatarStyle>().gender = AvatarGender.Female;

    // render avatar
    avatar.GetComponent<AvatarManager>().Render();
}

```

Here you know that the avatar's components have had a chance to be instantiated, `Awake()`, and had `OnEnable()` called if enabled, as part of the `Instantiate()` function. Their `Start()` methods won't be called until after the currently-executing `Start()` function returns control back to the engine to continue ticking through its queue of objects that need to be started.

So, if you need something to run as part of the "construction" of the object, before it's returned to the script that spawned it, put it in `Awake()`. Or you can create a custom initialization method and call it yourself.

> how do I use singletons per avatar that is instantiated?

This is a contradiction in terms. I recommend reviewing what a singleton is and why we use it / when to avoid it. A singleton by definition is singular - you can have only one singleton of a type active at a time. This is the main restriction of singletons and one reason why we use them with caution, only on things that logically must be singular/centralized (like the current game rules, or asset cache), and not on things that we might someday want two of (like player characters, or any system that each player in multiplayer needs "their" version/view of)

There's nothing wrong with your use of `GetComponent()` here - so don't make problems where you don't have them. If you find you're calling `GetComponent` frequently, you can cache the reference in a member variable. If you find it inelegant, you can return the first component you want directly from `Instantiate()` by making the prefab field the same type as the component you want to access, and exposing subsequent components through that component's members.
> 1 votes

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


title: Unexpected velocity changes in unity

text:
# Question
Title: Unexpected velocity changes in unity
I have a character that moves with a rigidbody.

When I jump, it looks fine, but sometimes, my character boosts up while in the air and shoots out of the map very quickly.

I checked, and when it happens, it says the velocity is at about 210.

Why is this happening and how can iIfix it?

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

public class playerManager : MonoBehaviour
{
    float xMovement;
    float zMovement;
    float xPosition;
    float yPosition;
    float zPosition;
    public float runningSpeed;
    public Animator animator;
    public Camera camera;
    public float cameraHeight;
    public float cameraAngle;
    public bool isOnGround;
    public float jumpForce;
    Rigidbody playerRigidbody;
    public float gravityMultiplier;
    Vector3 vel;
    public float airSpeed;
    public float groundSpeed;
    public bool canJump = true;

    void Start()
    {
        playerRigidbody = GetComponent<Rigidbody>();
        vel = playerRigidbody.velocity;
    }

    void Update()
    {

        xPosition = transform.position.x;
        yPosition = transform.position.y;
        zPosition = transform.position.z;
        PlayerMovements();
        CameraManager();
    }

    public void CameraManager()
    {
        camera.transform.position = new Vector3(xPosition+cameraAngle,cameraHeight,zPosition+cameraAngle);
    }

    public void PlayerMovements()
    {
        //Jump
        if(Input.GetKeyDown(KeyCode.Space) & isOnGround == true & canJump == true)
        {
            runningSpeed = airSpeed;
            canJump = false;
            playerRigidbody.velocity = new Vector3(xMovement,0,zMovement);
            playerRigidbody.angularVelocity = Vector3.zero;
            playerRigidbody.constraints &= ~RigidbodyConstraints.FreezePositionY;
            playerRigidbody.AddForce(transform.up * jumpForce);
            playerRigidbody.drag = 0;

        }

        //Move the Character
        if(isOnGround == true)
        {
            xMovement = Input.GetAxis ("Horizontal");
            zMovement = Input.GetAxis ("Vertical");
            Vector3 distanceToMove = new Vector3(xMovement,0,zMovement);
            playerRigidbody.AddForce(distanceToMove * runningSpeed);
        }

        //Make the player face the direction he's going at
        transform.LookAt(new Vector3(xPosition+xMovement,yPosition,zPosition+zMovement));

        //Trigger Idle or Running Animations
        if(xMovement != 0 | zMovement != 0)
        {
            animator.SetBool("Run", true);
            animator.SetBool("Idle", false);
        }
        if((xMovement < 0.05f & xMovement > -0.05f) & (zMovement < 0.05f & zMovement > -0.05f))
        {
            animator.SetBool("Run", false);
            animator.SetBool("Idle", true);
        }
    }

    public void OnCollisionEnter(Collision collidedOBJ)
    {
        if(collidedOBJ.gameObject.tag=="Finish")
        {
            Debug.Log(playerRigidbody.velocity);
            Debug.Log(runningSpeed);
        }
        if(collidedOBJ.gameObject.name == "Ground")
        {
            playerRigidbody.drag = 49;
            playerRigidbody.constraints &= RigidbodyConstraints.FreezePositionY|RigidbodyConstraints.FreezeRotationX|RigidbodyConstraints.FreezeRotationY|RigidbodyConstraints.FreezeRotationZ;
            isOnGround = true;
            canJump = true;
            runningSpeed = groundSpeed;

        }
    }

    public void OnCollisionExit(Collision exitCollidedOBJ)
    {
        if(exitCollidedOBJ.gameObject.name == "Ground")
        {
            isOnGround = false;

        }
    }

}

```

# Answer
> 0 votes
Interaction with physics should be done inside FixedUpdate(), not Update(). See https://stackoverflow.com/questions/34447682/what-is-the-difference-between-update-fixedupdate-in-unity

If you add force in Update(), the amount of added force will depend on the frame rate. If you have irregular frame rate, you will get unpredictable physics.

---
Tags: unity, physics, rigidbody, jumping
---


title: How to add noise into a texture?

text:
# Question
Title: How to add noise into a texture?
I'm working on a Heat Map generated from Perlin Noise. So far I've got 2 different outputs. Let's go step by step:

The result should be something like this:  This is the Perlin Noise I've got, easy to get, RED means hot and BLUE means cold, it's already generated in a spherical way.

And this is the gradient TEXTURE, it's based on Y axis as you can see.

At the moment they are generated in different functions in Unity, `public Texture2D PerlinHeat()` and `public Texture2D GradientHeat()`. I'd like to multiply them but you can't just simply do something like `Texture2D * Texture2D`, so I´m trying to figure it out and any help would be appreciated.

I'm using LibNoise as reference but as my gradient is not a noise module I can't multiply them. By the way: How to make a noise gradient? That´s the page that approach the best to my issue, as is about the same, I just don´t know how to implement everything that is said there.

Here is the code of the Gradient Texture, is pretty messy but it allows to change dynamically colors and heat ranges over the texture with just a change in the inspector.

```
    public Texture2D GetGradientHeat()
    {
        var texture = new Texture2D(heatMap.Width, heatMap.Height);
        var pixels = new Color[heatMap.Width * heatMap.Height];
        for (var x = 0; x < heatMap.Width; x++)
        {
            for (var y = 0; y < heatMap.Height; y++)
            {
                    if (y <= southPoleCap || y >= northPoleCap)
                    {
                        pixels[x + y * heatMap.Width] = coldest;
                    }
                    else if (y > southPoleCap && y <= southArcticCap || y < northPoleCap && y >= northArcticCap)
                    {
                        pixels[x + y * heatMap.Width] = colder;
                    }
                    else if (y > southArcticCap && y <= southArcticOuter || y < northArcticCap && y >= northArcticOuter)
                    {
                        pixels[x + y * heatMap.Width] = cold;
                    }
                    else if (y > southArcticOuter && y <= southMiddleOuter || y < northArcticOuter && y >= northMiddleOuter)
                    {
                        pixels[x + y * heatMap.Width] = template;
                    }
                    else if (y > southMiddleOuter && y <= southTropic || y < northMiddleOuter && y >= northTropic)
                    {
                        pixels[x + y * heatMap.Width] = hot;
                    }
                    else if (y > southTropic && y <= southMiddleInner || y >= northMiddleInner && y < northTropic)
                    {
                        pixels[x + y * heatMap.Width] = hoter;
                    }
                    else if (y > southMiddleInner && y < northMiddleInner)
                    {
                        pixels[x + y * heatMap.Width] = hotest;
                    }
            }
        }

        texture.SetPixels(pixels);
        texture.wrapMode = TextureWrapMode.Clamp;
        texture.Apply();
        return texture;
    }
```

Any help with this will be appreciated as I've been trying to do it during weeks and I´m not able to find any more documentation or a pseudocode that I can make work.

**EDIT 2** So answer from DM Gregory just works like a charm, awesome. The resulting output is at follows, with that you can alter that noise strength and playing with the offsets, color multipliers, or other noise modules, you get such a nice output, thanks!

# Answer
> 1 votes
First, change the workhorses of your texture generation loops into its own standalone generator functions. These take in a set of parameters - like which pixel you want to generate a result for - and return the generated result according to some rule.

```
Color GetGradientColor(int x, int y) {
    // TODO: You can probably clean this up with Mathf.Abs() or a lookup table.
    if (y <= southPoleCap || y >= northPoleCap)
        return coldest;
    else if (y > southPoleCap && y <= southArcticCap || y < northPoleCap && y >= northArcticCap)
        return colder;
    else if (y > southArcticCap && y <= southArcticOuter || y < northArcticCap && y >= northArcticOuter)
        return cold;
    else if (y > southArcticOuter && y <= southMiddleOuter || y < northArcticOuter && y >= northMiddleOuter)
        return template;
    else if (y > southMiddleOuter && y <= southTropic || y < northMiddleOuter && y >= northTropic)
        return hot;
    else if (y > southTropic && y <= southMiddleInner || y >= northMiddleInner && y < northTropic)
        return hotter;
    else
        return hottest;
}

```

Now you can either invoke the generator directly, to get the same result you had before:

```
public Texture2D GetGradientHeat()
{
    var texture = new Texture2D(heatMap.Width, heatMap.Height);
    var pixels = new Color[heatMap.Width * heatMap.Height];
    for (var x = 0; x < heatMap.Width; x++)
    {
        for (var y = 0; y < heatMap.Height; y++)
        {
             pixels[x + y * heatMap.Width] = GetGradientColor(x, y);
        }
    }
    // ...

```

Or you can compose the results of your generators, to make one texture that's the composition of multiple rules feeding into each other:

```
public Texture2D GetDistortedGradient(float noiseStrength)
{
    var texture = new Texture2D(heatMap.Width, heatMap.Height);
    var pixels = new Color[heatMap.Width * heatMap.Height];
    for (var x = 0; x < heatMap.Width; x++)
    {
        for (var y = 0; y < heatMap.Height; y++)
        {
             float noise = GetNoise(x, y);
             int shift = Mathf.RoundToInt(noise * noiseStrength);
             pixels[x + y * heatMap.Width] = GetGradientColor(x, y + shift);
        }
    }
    // ...

```

---
Tags: unity, textures, perlin-noise, procedural
---


# Question
Title: How do I make a GameObject carry across only 2 specific scenes?
I have a GameObject in my main menu and help scenes that I want to carry across both scenes but be destroyed on all other scenes. I am having multiple issues with it such as it wont destroy on other scenes or when I go back to the previous scene it will generate 2 GameObjects and so on. Here is the script:

```
public class DestroyObject : MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode)
    {
        if ((scene.name == "Help") || (scene.name == "Main Menu"))
        {
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

```

# Answer
> 1 votes
You could have a gameobject in the scene called GAME\_MANAGER. Add to it a script 'Game\_Manager.cs'

have a public method inside of this script:

```
public static Game_Manager instance; //create a singleton instance to access these methods from other scripts.
private GameObject menuObject;  // store reference to the menuobject you want to activate

void Awake(){
// init the singleton instance if it is not already
if (instance == null)
     instance = this;
else
     Destroy(this);

DontDestroyOnLoad(gameObject); // make sure this object isn't destroyed after scene changes

menuObject = GameObject.Find("Name Of The Object"); // this is one way of many to 'find' the object you are wanting.
}

public void ActivateMenuObject(bool makeActive){
     menuObject.SetActive(makeActive);
}

```

You could call this 'ActivateMenuObject' from any script by accessing the singleton instance:

```
Game_Manager.instance.ActiveMenuObject(true);

```

or you could find another way , for example do it within the Game\_Manager itself, or you could add another parameter to the ActiveMenuObject method asking for a GameObject, and then the method would SetActive the specified GameObject to the specified bool without needing to make a reference to the gameobject in the Game\_Manager.

```
    public void SetObjectActiveState(GameObject obj, bool active){
     obj.SetActive(active);
}

```

I do hope that helps. I'm not an expert but I have been tinkering with Unity at noob level for a few years :) Good luck!

---
Tags: unity, gameobject, scene
---


# Question
Title: Round to the nearest multiple of 0.75 in C#
How can I round a number to the nearest multiple of 0.75 in C# / Unity?

The context is that I have a block and I want its position to be rounded at the nearest 0.75 multiple. For example: 0, 0.75, 1.5, 2.25, 3, 3.25, 4.5, 5.25, 6, ... How can I do that?

# Answer
> 9 votes
The recipe is simple:

1. Divide by your desired interval, so now each multiple of the interval maps to an integer.
2. Round to the nearest integer.
3. Multiply by your interval to bring it back to the original scale.

Here's an example:

```
static float RoundTo(float value, float multipleOf) {
    return Mathf.Round(value/multipleOf) * multipleOf;
}

```

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


# Question
Title: How can I snap player-constructed objects in a 3d world together?
I m trying to build minecraft type of game with more complex builds like that of fortnite, so I wanted to start with the best practices i have to follow to create those builds.

the blocks in minecraft are aligned with proper precision to create those humongous buildings and arts needs to have some kind of alignment algorithm that the developers must have followed. similarly, fortnite follows placement of walls and roof with proper precision.In fornite when the player places a stair it takes some area of the space and when you try to place another stair on the same level a little forward it leaves some space and places another stair after some distance of the first floor....like a stair takes a cube space around itself and then places another after another cube space distance.

now the tricky part is when the player places a stair and goes up to place another stair right above the first one to reach height, what transform position does the second floor needs to have to connect itself to the previous builds.

any suggestions or ideas on how have they achieved this would be a great help!Thanks!

# Answer
There are multiple approaches how you can achieve a good placement snapping.

I personally don't know Fortnite enough to be able to tell you what approach they are using.
I would guess it's some kind of snapping points and a clever decission algorithm on which point to take.

Here's a list with some snapping techniques that I know of.
This list is not a complete one, there are countless ways how you can do snapping.

**Grid:**
Using a 3d grid, in which you can place object is basically how Minecraft does it.
In essence you calculate to which cell the cursor points, then you add the object to the cell.
You can then test the properties of neighbor cells to determine the final shape, orientation, etc. of your new object.
*Example game: Minecraft*

* **Local grid:**
Instead of using a world grid like in minecraft, you can also use local grids.
Let's say the player should be able to place something freely on a terrain.
But when the player tries to place something on top of that other something, it should use a grid snapping relative to that first object.
This can be done by creating a new grid everytime something is not placed in a grid.
Now when you try to place an object on another object, you check whether that other object belongs to a grid, and if yes, place it in the grid. If no, create a local grid.
*Example game: Space Engineers*

**Snapping points:**
Snapping points are locations on your meshes where other meshes can snap to.
If two points snap, the object to be placed gets moved, rotated, scaled or modified, such that both points are at the same place and the snapping criteria is fullfilled.
In case of stairs, the stair would have a snapping point at the top and the bottom of the stairs.
To determine whether two objects can snap, there are also multiple approaches, such as nearest point, look direction, something you come up with or even combinations of them.
*Example game: Kerbal Space Program*

* **Snapping point classes:**
As extension of the snapping points, you can also classify a snapping point, such as "Big object", "Ornament", etc and only snap to snapping points that match a filter criteria.
This can be usefull if certain objects are only allowed to snap to certain snapping points.

**Line snapping:**
Instead of points, one could also snap to a line.
Just define lines along your object that allow snapping.
Then snapp to the nearest point on the nearest line.
*Example game: Don't know...*

**Vertex snapping:**
Just use the mesh vertices as snapping points.
This is usually done in CAD, I haven't seen it in games.
> 4 votes

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


# Question
Title: OverlapBox() dimensions are huge but are fine when tested in isolation
To be completely transparent, I more-or-less copied this question from the Unity forums since I did not get a reply.

I'm creating this system where I'm placing level chunks together and I need to collect a list of colliders that have intersected with a particular level chunk. All of this is being done within one frame (A loop is controlling this placement). A chunk is composed of several colliders.

The way I am doing this is with an `OverlapBox`, copying the dimensions of a collider of a particular child `GameObject` (named area). This is done through the following function, being called from a control script. It's meant to check for collisions that are happening within it, and return true when it's intersecting something it shouldn't.

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

public class CollisionCheck : MonoBehaviour
{
    public LayerMask m_LayerMask; //This is set to Everything in the editor

    public Collider[] collidersTouched;

    public bool IsInappropriateTouchingHappening (GameObject allowedChunk)
    {
        BoxCollider area = transform.Find("area").gameObject.GetComponent<BoxCollider>();
        collidersTouched = Physics.OverlapBox(area.bounds.center, area.bounds.size/2, Quaternion.identity, m_LayerMask);

        Debug.Log("OverlapBox picked up this many colliders: " + collidersTouched.Length);

        foreach (Collider col in collidersTouched)
        {
            Debug.Log("the collider in the obtained array: " + col.gameObject.name + col.gameObject.transform.position);
            if (!GameObject.ReferenceEquals( allowedChunk, col.gameObject) && !GameObject.ReferenceEquals( gameObject, col.gameObject))
            {
                return true;
            }
        }
        return false;
    }

    void OnDrawGizmos ()
    {
        BoxCollider area = transform.Find("area").gameObject.GetComponent<BoxCollider>();
        Gizmos.matrix = Matrix4x4.TRS(area.bounds.center, Quaternion.identity, area.bounds.size);
        Gizmos.color = Color.red;
        Gizmos.DrawCube(Vector3.zero, Vector3.one);
    }
}

```

It tells me that it's picked up pretty much every collider in the scene! However, when I perform an isolated test using one of the chunks that the system is using, everything checks out. Here's the code for the script I'm using for said test. It's a modified version of what's in Unity's documentation for`OverlapBox`.

```
using UnityEngine;

public class OverlapBoxExample : MonoBehaviour
{
    bool m_Started;
    public LayerMask m_LayerMask;

    void Start()
    {
        m_Started = true;
    }

    void FixedUpdate()
    {
        MyCollisions();
    }

    void MyCollisions()
    {
        BoxCollider area = transform.Find("area").gameObject.GetComponent<BoxCollider>();
        Collider[] hitColliders = Physics.OverlapBox(area.bounds.center, area.bounds.size/2, Quaternion.identity, m_LayerMask);
        Debug.Log("Number of colliders hit in test: " + hitColliders.Length);
    }

    //Draw the Box Overlap as a gizmo to show where it currently is testing. Click the Gizmos button to see this
    void OnDrawGizmos()
    {
        BoxCollider area = transform.Find("area").gameObject.GetComponent<BoxCollider>();

        Gizmos.matrix = Matrix4x4.TRS(area.bounds.center, Quaternion.identity, area.bounds.size);
        Gizmos.color = Color.yellow;
        Gizmos.DrawCube(Vector3.zero, Vector3.one);
    }
}

```

The gizmo in this second script is showing me the volume of the `OverlapBox` correctly, but in the first script, it's not.

Does anyone have any ideas? I cannot imagine what makes the two boxes different, aside from the `OverlapBoxExample` script performing its `OverlapBox()` inside `FixedUpdate` instead of frame 1 like it does in my implementation. I don't know why that would affect the size, however.

To recap, the whole issue is that the I'm attempting to create in the first script is inexplicably large. Also, Both the test and the implementations' gizmos show the volume/position of the `OverlapBox` I want. Please let me know if more information is needed.

# Answer
Thanks to what DMGregory pointed out, I was able to solve my issue. I had to use `Physics.SyncTransforms` (Unity Docs) before the first time I called `OverlapBox()`.

It turns out that the `OverlapBox` wasn't incredibly large, but that the transforms needed to be updated manually since everything was happening in one frame. As a result, the `OverlapBox` was the right size, but all of the colliders that I had moved that frame hadn't actually been moved yet according to the physics engine. So, I just needed to make this call before using `OverlapBox`:

```
Physics.SyncTransforms()

```
> 2 votes

---
Tags: unity, collision-detection, physics
---


# Question
Title: How can I update my materials to work with LWRP?
I'm using Unity 2019.1.6f1.

When I open a new scene with the LWRP template project, I see errors from all materials in the scene. For example, the Jigsaw appears in my scene but in console window I see a message telling me:

> Jigsaw\_Mat material was not upgraded. There's no upgrader to convert Lightweight Render Pipeline/Lit shader to selected pipeline UnityEditor.Rendering.LWRP.LightweightRenderPipelineMaterialUpgrader:UpgradeProjectMaterials()

All materials show this message, and I don't know what to do to fix these materials. How can I resolve this error?

# Answer
> 3 votes
To upgrade all the materials that can be supported by LWRP, go to:

Edit Menu -\> Render Pipeline -\> Lightweight Render Pipeline -\> Update Project Materials to LightweightRP Materials

Note - only standard shader materials will be brought across. Lit/specialist shaders will not be converted automatically. You will see warnings in the console about those the cannot be imported.

**FBX meshes with embedded materials**

If you have any FBX imported objects, you will need to reimport them. The easiest way to do them is to find your FBX models in the Project window, right click the FBX and choose Reimport.

Don't forget to save once you've done that!

Tested in Unity 2019.2.0f1.

---
Tags: unity, shaders, rendering, materials
---


# Question
Title: When I exit the pause menu of my game the gun fires
When The player exits the pause menu in my game the gun will fire. I figured out that it happens when the player clicks when the game is paused.

Basically i the player goes to the pause menu and exits without clicking the gun will not fire, but if they go to the pause menu and click then exit the gun will fire. Here are my scripts:

```
public class Shooting : MonoBehaviour
{
    Animator anim;
    public float FireRate = 15f;
    private float NextTimeToFire = 0f;
    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1") && GetComponentInParent<PlayerController>().moving == false && Time.time >= NextTimeToFire)
        {
            NextTimeToFire = Time.time + 1f / FireRate;
            Shoot();
        }
    }
}

```

/

```
public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    public GameObject HUDPanel;
    public GameObject PauseMenuPanel;
    public GameObject OptionsPanel;

    private void Start()
    {
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (GameIsPaused)
            {
                Resume();
            }
            else
            {
                Pause();
            }
        }
    }

    void Resume()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        PauseMenuPanel.SetActive(false);
        OptionsPanel.SetActive(false);
        HUDPanel.SetActive(true);
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

    void Pause()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
        PauseMenuPanel.SetActive(true);
        HUDPanel.SetActive(false);
        Time.timeScale = 0f;
        GameIsPaused = true;
    }
}

```

# Answer
> 2 votes
I guess a possible solution is to have a bool that handles if the player is allowed to shoot.

```
public class Shooting : MonoBehaviour
{
    /// ....
    public bool AllowedToShoot = true;

    void Update()
    {
        if (AllowedToShoot == false) return; // if not allowed to shoot, don't run the code bellow
        // your code
    }
}

```

```
public class PauseMenu : MonoBehaviour
{
    // ...

    public Shooting ShooterAgent; // this must not be null in the editor

    void Resume()
    {
        /// ...
        ShooterAgent.AllowedToShoot = true;
    }

    void Pause()
    {
        /// ...
        ShooterAgent.AllowedToShoot = false;

    }
}

```

You can expand it to only call a method instead of accessing and changing the bool directly.

```
public void AllowShooting(bool status)
{
    AllowedToShoot = status;
}

```

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


# Question
Title: Character blocking when walking on cube edges
I have my character walking on a ground made of cube. (scale 1,1,1). There is no space between them. Also, I have a `RigidBody` with 15 drag and I'm moving with `AddForce`.

When I walk, my character sometimes block when trying to pass over the place where the 2 box meet. Like if my player collider was hitting the collider under him. Any fix for that?

# Answer
Edit-\> Project Setting-\> physics-\> Default Contact Offset to 0.0001 made it for me
> 1 votes

---
Tags: unity, collision-detection, physics
---


# Question
Title: How do I make the player gun stop firing when sprinting
I am trying to get the players gun to fire when the player is walking and the stop firing when the player starts to sprint. The gun will work just fine and ire when the player is walking, but it will continue to fire when they start running and they can also start firing when they are running. I have been trying or most o the day and have not been able to figure out how to fix this.

The top script is obviously the script or the gun firing and whatnot and the bottom script is the controller or movement as well as the animation for the gun.

EDIT: Still no luck.

```
public class Shooting : MonoBehaviour
{
    private float NextTimeToFire = 0f;
    public bool AllowedToShoot = true;

[Space(10)]
    [Header("Floats")]
    public float Damage = 10.0f;
    public float Range = 100.0f;
    public float ImpactForce = 60f;
    public float FireRate = 15f;

    [Space(10)]
    [Header("Others")]
    [Space(5)]
    public Camera FPSCamera;
    public ParticleSystem MuzzleFlash;
    public GameObject impactEffect;

void Start()
    {
    }

    void Update()
    {
            if (AllowedToShoot == false) return;
            {
            if (Input.GetButton("Fire1") && Time.time >= NextTimeToFire)
                {
                    NextTimeToFire = Time.time + 1f / FireRate;
                    Shoot();
                   }
            }
    }

    void Shoot()
    {
        MuzzleFlash.Play();

            RaycastHit hit;
            if (Physics.Raycast(FPSCamera.transform.position, FPSCamera.transform.forward, out hit, Range))
        {
            Debug.Log(hit.transform.name);
            Objects enemy = hit.transform.GetComponent<Objects>();
            if (enemy != null)
            {
                enemy.TakeDamage(Damage);
            }

            if (hit.rigidbody != null)
            {
                    hit.rigidbody.AddForce(-hit.normal * ImpactForce);
            }
            GameObject ImpactGo = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
            Destroy(ImpactGo, 2f);
        }
    }
}

```

///

```
public class WeaponMovement : MonoBehaviour
{
    public GameObject CameraAnimations;
    Animator anim;

    private void Awake()
    {
        anim = CameraAnimations.GetComponent<Animator>();
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                anim.SetBool("Sprint", true);
            }
        }

        if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.UpArrow))
        {
            anim.SetBool("Sprint", false);
        }

        if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
        {
            anim.SetBool("Sprint", false);
        }
    }
}

```

# Answer
you can use `GetBool("State Name")` function to check sprint any where. but right Animator design is always the key to freedom on changing you character behaviour. this is my example code:

```
bool sprint= anim.getBool("sprint");
if(sprint) return;
//you shooting logic here

```
> 1 votes

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


title: unity android sdk error

text:
# Question
Title: unity android sdk error
i am using unity 18.x. i downloaded the android sdk itself and the android studio also but they are not working,unity is not detecting the android sdk. if anyone succceed in exporting the apk successfully. kindly,provide the sdk folder here (request) god will bless you if you share the folder here, because i am trying to export it since 5 month. and if i try to update the sdk from unity the unity stucks and do not respond. i waited for few hours to respond but, it does not respond. please provide the sdk folder here. i am begging please and its also not detecting the android sdk in android studio folder instead of suggesting please share the android sdk folder here . please share the folder here so others who is also having the same issue download the sdk from here. i know this is a silly question but its a huge problem for me now **for more informmation: i also have the 19.3f1f version and not installed the microsoft redistributable i used to launch unity from the hub**

# Answer
Ok you need to set SDK API version in Unity platform

Or Run Studio and update all required tools and platform

Or check out the path of SDK download PATH : C:/USERS/USERNAME/APPDATA/SDK default PATH

Open SDK MANAGER Check Install PATH dir....
> 0 votes

---
Tags: unity, android, export
---


# Question
Title: How to handle grid snapping when the object is greater than the grid cell width and height?
I want to be able to move objects on a grid always by what the grid cell size is, and objects bigger than the grid size should not overlap.

The cube in this GIF below is snapping how I want (1 x 1).

If I then change the size of the object, it doesn't snap to the grid quite how I would like. It snaps, but overlaps. I don't want an object to overlap the grid cell.

The snapping code is pretty straight forward and has been posted quite a lot and seems to work fine.

```
pos.x = Mathf.Round(hit.point.x + (hitNormal.x * objScale.x)) * gridSize;
pos.y = Mathf.Round(hit.point.y + (hitNormal.y * objScale.y)) * gridSize;
pos.z = Mathf.Round(hit.point.z + (hitNormal.z * objScale.z)) * gridSize;

```

I was thinking that I need to somehow set a pivot / anchor point, but I wouldn't want that to be one corner of the object, I was thinking somehow I could find the center of the object and work from there so it can snap correctly. Not sure if this is correct, or how to work that out.

Edit: More code added to show how I am moving objects around currently.

Objects are placed in the world by ray casting. I don't use any grid array to know the location of objects on the grid.

For placement testing (i.e object inside another) this is handled already but removed that part of the code. For that I am doing a simple box overlap test which works nicely.

```
float gridSize = 1f;
Vector3 hitNormal = hit.normal.normalized;
Vector3 localObjScale = transform.localScale;

// - "Determine the minimum grid space this shape will use up"
// Objects will always be whole numbers.  i.e 2w x 1h x 1l (like second GIF)
int cellWidth = Mathf.RoundToInt(localObjScale.x);
int cellsHeight = Mathf.RoundToInt(localObjScale.y);
int cellsLength = Mathf.RoundToInt(localObjScale.z);

Vector3 objScale = localObjScale / 2f; // This sets the pivot to the center
Vector3 pos = Vector3.zero;

// Snap
pos.x = Mathf.Round(hit.point.x + (hitNormal.x * objScale.x)) * gridSize;
pos.y = Mathf.Round(hit.point.y + (hitNormal.y * objScale.y)) * gridSize;
pos.z = Mathf.Round(hit.point.z + (hitNormal.z * objScale.z)) * gridSize;

transform.position = pos;

```

# Answer
> 1 votes
Although the existing answer looks pretty good. Considering your existing code, and the fact that you mentioned that you already handled placement testing. I think there is another answer that is much closer to your existing code and requires less changes.

The idea is here is that the 2x1 cube has its pivot on \[1, 0.5, 0.5\] while the 1x1 cube has its pivot at \[0.5, 0.5, 0.5\].

You could fix your problem by altering the pivot so that 2x1 has a pivot of either \[0.5, 0.5, 0.5\] or \[1.5, 0.5, 0.5\]. This is basically @Chillersanim's answer. It is however still difficult to get the object to snap correctly as you want the center (1, 0.5, 0.5) to be as close to your cursor as possible, not \[0.5, 0.5, 0.5\] nor \[1.5, 0.5, 0.5\].

Another way around the problem is to substract the pivot before snapping and then add it back on after snapping. As an example:

This example is only about the x axis for simplicity.

* If the cursor position on a grid cell is 1.3.
* A pivot of 0.5 for a 1x1 cube would snap like this: round(1.3 - 0.5) + 0.5 = 1.5 (So cube boundaries are from 1 to 2)
* a pivot of 1 for a 2x1 cube would snap like this: round(1.3 - 1) + 1 = 1 (so cube boundaries are from 0 to 2)

Which is exactly the result we want to get both cubes aligned on the same grid and still center correctly on the cursor position, to convert that to the code you are using, would end up something like this:

```
    Vector3 hitNormal = hit.normal.normalized;
    Vector3 localObjScale = transform.localScale;

    Vector3 pivot = localObjScale / 2f;

    // The offset that we need to add to place the object in front of the object we are hovering instead of inside the object we are hovering
    Vector3 normalOffset = Vector3.Scale(hitNormal, pivot);

    // Snap to grid
    Vector3Int hoveredCell = Vector3Int.RoundToInt(hit.point - pivot + normalOffset);

    // Add the pivot again after snapping.
    Vector3 pos = hoveredCell + pivot;

    transform.position = pos;

```

Note that this code might shift your entire grid by +0.5 on all axes, but I don't think that should be to big of a problem to fix.

---

## Edit, rotation

As you noticed, the above code doesn't work when you rotate the object. This is because when we calculated our pivot, we ignore the rotation. So we could apply the rotation to the pivot to fix that.

In the below example I do that. There might be a single line builtin method to do this, not sure. If there is I haven't found it yet...

```
Vector3 localObjScale = transform.localRotation * transform.localScale;
localObjScale = new Vector3 // Make sure scale is positive after rotation :)
{
    x = Mathf.Abs(localObjScale.x),
    y = Mathf.Abs(localObjScale.y),
    z = Mathf.Abs(localObjScale.z)
};

```

To use this just replace the original line where you declare localObjScale with this snippet.

# Answer
> 3 votes
The problem is, that you seem to take the center of the shape as pivot.
What you want is to select a pivot, that places the shape inside the grid, so that it overlaps as few cells as possible.

How to obtain such a pivot:

* Place shape in grid by minimum fit: Place it so, that as few cells are used as possible.
* Calculate how many cells are affected.
* Select a cell in the grid space that will be your pivot cell
* Use the center of the pivot cell as placement pivot for your shape.

Diagram for visual explanation.

When you use this pivot to place your shapes, they will not overlap to much anymore.
At the same time, you can use the calculated grid space for the shape, to determine whether a cell is being occupied or not by a shape.

Keep in mind, the visualized grid is only as a to help understanding the concept.
In generall, you just need the width and length of your shape and the size of each cell.
Then you can calculate the amount of affected cells by dividing as shown in the image.
Also if you want to always use the top left cell as pivot cell, you can skip that step as well.

---
Tags: unity, grid
---


# Question
Title: What is the purpose of the directory Packages in my Assets directory?
So far I used EditorWindow script but few minutes ago without and alert I have strange stuff in the Assets in the Editor. I see now a new folder name Packages I can't figure out where it came from but for 100% I didn't import any packages at all.

Second when I put the mouse on it and right click I can't delete it:

This is how the Packages looks like, Very strange thing:

Another strange thing but maybe it's connected to this Packages is that in the Scene view window I have this blue thing like a line or something that if I click on it it will be blue if not clicking on it it's black. Not sure what it is. It's not an object in the Hierarchy. Not sure where it came from.

I tried to restart the Unity over again but nothing same strange stuff.

I'm using unity3d 2018.2.5f1 Personal. And windows 10 home 64bit version 1803.

I see the Packages folder on the Hard disk now but when I make double click to get inside I see only one small file: manifest.json

And I was working and working with json file format to save and load but I can't figure out what is going on in the scene view and in the assets.

# Answer
> 3 votes
This is where the new Package Manager, available in Unity 2018, stores installed packages. You can read up on it here:

https://docs.unity3d.com/Packages/com.unity.package-manager-ui@1.8/manual/index.html

# Answer
> 2 votes
First, there's one mistake made in this situation:

The *Package* folder is not in the *Asset* folder, but in the project's root.

This was a small change done to Unity since the 2018 version to allow the engine editor to be more versatile and autonomous when it comes to third party plugins and packages imported into a project. Prior to 2018, most of the things you find in the Packages were either automatically included by default (even if not used) in every Unity builds, or had to be imported in the Editor folder that was outside of the Asset folder.

In the Packages folder, the engine automatically add some "default" packages such as Unity UI, Analytics Library, Unity Ads, etc. The importance of each folder is based on what you need in your project.

Should you erase all of them? While it's possible to erase 99% of them, I suggest you first take a look at each Packages' names. For example, if you use the Unity Colalborate feature (multiple developers working from different station), you need to keep the "Unity Colalborate" package. If you're not using the Legacy UI, but an actual in-scene canvas for the UI/Interaction/buttons, you got to keep the "Unity UI" package. If you plan on having some Advertisement in your game (like on Mobile) and want a relatively quick & easy setup for fetching the ads, the "com.unity.ads" includes some really versatile tools. If you plan on having in-App purchase, there's a default package for that too.

One of the reason why this change was done to the Engine is also to allow a better flow with Unity's Asset Store. Prior to this change, when you bought a plugin in the Asset Store that was supposed to be located in the Editor folder (so that the in-editor tools could be displayed), you had to manually move files around which was a real Q&A issue as someone making a mistake could ended up breaking a project. With the addition of the "Packages" folder, not only is it possible for the Asset Store to add all the Editor & Assets of a plugin into the project folder, but it's also possible to update all those files without any user interaction (other than starting the update from the Asset Store).

If you want to remove those folders, at least I suggest you first do it through the Package Manager (Window/Package Manager). This menu explains what each package does and has a cool little "Remove" button that ensure each package are properly removed. (In the Packages Manager, the installed packages have a checkmark on the right of their version number. Those without a checkmark are available, but not installed in the current project).

---
Tags: unity
---


# Question
Title: Nonsense change of floor and enemies materials (when restarting scene)
**I have a game where:**

* player (green cube)
* enemies (red cubes)
* floor (blue plane)

**Image before losing (player colliding with enemy):**

**Image after restarting game:**

**GameOver Code (Player.cs):**

```
void Update () {
    if(!gameOver){
        move();
    }else{
        if(Input.GetKey("space")){
            SceneManager.LoadScene("Cena1");
        }
    }
}

```

---

```
void OnCollisionEnter(Collision obj){
    if(obj.gameObject.tag=="Inimigo"){
        canvas.gameObject.SetActive(true);
        gameOver=true;
    }
}

```

The problem happens every time I collide the player with the enemy and press the spacebar to restart the scene.

The same thing happens if I use: `SceneManager.LoadScene("Cena1");`.

---

**EDIT 1 (Added full scripts)**

**script\_Player.cs:**

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

public class script_Player : MonoBehaviour {

    private float speed=0.4f;
    private float x,y,z,iniX,iniY,iniZ;
    private GameObject canvas;
    private bool gameOver=false;
    public Rigidbody rb;
    // Use this for initialization
    void Start () {
        canvas=GameObject.Find("Canvas");
        canvas.gameObject.SetActive(false);
        iniX=transform.position.x;
        iniY=transform.position.y;
        iniZ=transform.position.z;
    }

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

        if(!gameOver){
            move();
        }else{
            if(Input.GetKey("space")){
                SceneManager.LoadScene("Cena1");
            }
        }

        getPositions();

        parede();

    }

    void move(){
        if(Input.GetKey("w")){
            transform.position+=new Vector3(0,0,speed);
        }
        if(Input.GetKey("s") && transform.position.z>-10){
            transform.position+=new Vector3(0,0,-speed);
        }
        if(Input.GetKey("a") && transform.position.x>-4.25){
            transform.position+=new Vector3(-speed,0,0);
        }
        if(Input.GetKey("d") && transform.position.x<4.25){
            transform.position+=new Vector3(speed,0,0);
        }

        if(Input.GetKey("space")){
            //transform.position+=new Vector3(0,0.3f,0);
            rb.AddForce(0,100,0);
        }
    }

    void getPositions(){
        x=transform.position.x;
        y=transform.position.y;
        z=transform.position.z;
    }

    void parede(){
        if(transform.position.x<-4.25){
            transform.position=new Vector3(-4.25f,y,z);
        }
        if(transform.position.x>4.25){
            transform.position=new Vector3(4.25f,y,z);
        }
        if(transform.position.z<-10){
            transform.position=new Vector3(x,y,-10);
        }
    }

    void OnCollisionEnter(Collision obj){
        if(obj.gameObject.tag=="Inimigo"){
            //Destroy(obj.gameObject);
            //SceneManager.LoadScene("Cena1");
            canvas.gameObject.SetActive(true);
            gameOver=true;
        }
    }
}

```

**script\_Inimigo.cs:**

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

public class script_Inimigo : MonoBehaviour {

    private bool left=false,right=false;
    public float speed=0.08f;
    private float x,y,z,y2;
    // Use this for initialization
    void Start () {
        z=transform.position.z;
        left=true;
    }

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

        GameObject player=GameObject.Find("Player");
        y2=player.transform.position.y;

        x=transform.position.x;
        transform.position=new Vector3(x,y2,z);

        if(left){
            transform.position+=new Vector3(-speed,0,0);
            if(transform.position.x<-4.25){
                left=false;
                right=true;
            }
        }else if(right){
            transform.position+=new Vector3(speed,0,0);
            if(transform.position.x>4.25){
                right=false;
                left=true;
            }
        }

        if(z+3<player.transform.position.z){
            Destroy(gameObject);
        }

    }
}

```

# Answer
> 0 votes
Whenever you have a strange change in your scene, remember to verify your lighting settings. In this case, the problem is caused by the "Auto-generate Lighting" setting within the Unity lighting window being checked. If you manually generate the lighting by un-checking this option and hitting "Generate", then the problem should go away.

Note that lighting changing with in the editor when a scene changes is a persistent and common issue.

---
Tags: unity
---


title: Unity UI glitches while loading

text:
# Question
Title: Unity UI glitches while loading
I have the following scene canvas elements:

```
 left panel
     character game object
 right panel
     option panel - vertical layout group, content size fitter
         slider panel - vertical layout group, content size fitter
             input panel - horizontal layout group, content size fitter
                 text
                 slider
             input panel - horizontal layout group, content size fitter
                 text
                 slider
         button

```

After I hit play, the button's Y position is wrong but corrects itself after a brief second. Why is this happening and how do I fix it?

Here is a gif:

# Answer
> 1 votes
I fixed it by only having the content size fitter on "option panel" and removing it from all children.

---
Tags: unity, gui
---


# Question
Title: 3D title Rendering in Maya For babylon Js Game Engine
I created a 3D title in Maya and applied color through Lambertian shading and rendering with mental ray.

The problem is when the title is rendered in the game engine, it is looking very sad. The colors are faded also the lighting is not the same as Maya's rendered output.

Please tell me how can I make the in-game version look more like the result in Maya. I saw lots of 3D games whose titles and objects are very beautiful, bright and colorful with lighting.

# Answer
> 1 votes
It looks like the most notably absent elements in your engine render are shadows and ambient occlusion. I am not familiar with babylon.js but found these doc pages that will hopefully help you get closer to matching the Mental Ray output.

https://doc.babylonjs.com/babylon101/shadows

https://doc.babylonjs.com/how\_to/using\_the\_ssao\_rendering\_pipeline

---
Tags: 3d, rendering, lighting, maya, babylonjs
---


title: OpenGL Bump Map -- Texture artifacts ?

text:
# Question
Title: OpenGL Bump Map -- Texture artifacts ?
I am learning OpenGL (and learning the math behind it) and I'm making a simple OBJ viewer, nothing fancy. I have diffuse, specular and ambient light/texture working fine and now I am implementing the bump mapping. I based my code on what I learned with the OpenGL 4.3 Redbook and "Mathematics for 3D game programming and computer graphics" book.

There is probably something I didn't understand correctly, I just hope you will be able to help me :)

Anyway this is the result I get (from a free asset used just for testing -- the results are fine in blender) :

This is the diffuse texture and the bump map :

Fragment shader code :

```
void main() {
    vec3 normalDirection = normalize(tangenteSpace*(texture2D( bump_tex, f_texcoord ).rgb*2.0 - 1.0));
    //vec3 normalDirection = normalize(mat3(invTransp)*vertNormal);
    vec3 viewDirection = tangenteSpace*normalize(vec3(invView * vec4(0.0, 0.0, 0.0, 1.0) - position));

    float attenuation = 1.0;//none
    vec3 vertToLightSource = vec3(light.position - position*light.position.w);
    float distance = length(vertToLightSource);
    attenuation = mix(1.0,1.0/(light.constantAttenuation +
                    light.linearAttenuation *distance +
                    light.quadraticAttenuation*distance*distance),light.position.w);
    vec3 lightDirection = tangenteSpace*(vertToLightSource/distance);

    //spotlight if spotCutoff <= 90
    float clampedCosine = max(0.0, dot(-lightDirection, normalize(light.spotDirection)));
    float tempMix = mix(attenuation * pow(clampedCosine, light.spotExponent),0.0,clampedCosine < cos(light.spotCutoff * 3.14159 / 180.0));//if outside of spotlight nothing
    attenuation = mix(attenuation,tempMix,light.spotCutoff <= 90.0);

    //should there be any attenuation ?
    attenuation = mix(attenuation,1.0,light.position.w);

    //------------------------------ ambiant light
    vec3 ambientLight = vec3(ambientScene)*vec3(mat.Ka);

    //------------------------------ specular light
    //get the reflection
    vec4 specularMapPixel = texture2D(spec_tex, f_texcoord).rgba;
    vec3 specularColor = specularMapPixel.rgb;
    float shininess = specularMapPixel.a;
    vec3 specularReflection = mix(
    attenuation * vec3(light.specular) * vec3(mat.Ks)* pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)),mat.Ns*shininess) *specularColor.rgb,
          vec3(0.0, 0.0, 0.0),
          dot(normalDirection, lightDirection) < 0.0
          );

    vec3 diffuseReflection = attenuation*
    vec3(light.diffuse)*vec3(mat.Kd)
    *max(0.0,dot(normalDirection,lightDirection));

    vec4 Color = vec4(vec4(specularReflection,1.0) + vec4(ambientLight,1)*texture2D(amb_tex, f_texcoord) + vec4(diffuseReflection,1.0)*texture2D(dif_tex, f_texcoord));

    FragColor = Color;
}

```

Vertex Shader Code :

```
void main()
{
    //comnpute tangent space
    tangenteSpace[0] = mat3(mv)*normalize(tangent.xyz);
    tangenteSpace[2] = mat3(mv)*normalize(vertNormal);
    tangenteSpace[1] = mat3(mv)*normalize(cross(tangenteSpace[0],tangenteSpace[2])*tangent.w);
    tangenteSpace = transpose(tangenteSpace);

    //position in world space
    position = m * vertCoord;
    f_texcoord = vec2(texCoord);

    gl_Position = mvp * vertCoord;
}

```

# Answer
> 2 votes
The reason you are getting artefacts is because you are not using a bump map shader; You are using a *normal map* shader, with a displacement map.

A normal map (often confused with bump map) looks like this:

The colour represents the surface normal, which you then transform from tangent space to view space.

The texture you have shown is a height, or displacement map, which is used to *generate* the normal map.

If you are using GIMP, there is a nice plugin available here, which will convert a height map to a normal map, and once you bind that resulting texture instead, your artefacts should disappear.

---
Tags: opengl, textures, shaders, maps
---


# Question
Title: Special character's with LibGDX's I18NBundle such as "ü" or "ö" are marked as unknown
I am loading my `I18NBundle` like this :

```
    assetManager.load("i18n/language", I18NBundle.class);
    assetManager.finishLoading();
    i18NBundle = assetManager.get("i18n/language", I18NBundle.class);

```

When I `get(String key)` the values of the german localization I get these symbols for the `ü` and `ö` characters. This is what it looks like when I use the debugger to see the mapped values :

In-game, it will display `Huser` instead of `Häuser`.

The french localization works fine with `é` and `è`. So I'm quite confused as why only the german localization fails.

# Answer
To expand on Cedric's answer you should try these steps to make sore that the encoding is correct:

1. Make sure that the properties file uses the correct encoding. It might help to delete and re-create the file in some cases.
2. Make sure that the `I18NBundle` object uses the correct encoding. You do this by supplying the encoding when loading the bundle into the game:

```
// Loading without asset manager
I18NBundle.createBundle(baseFileHandle, encoding);

// ex.
I18NBundle.createBundle(Gdx.files.internal("game_en"), "UTF-8")

// Loading with asset manager.
I18NBundleParameter param = new I18NBundleParameter(locale, encoding);
manager.load(fileName, I18NBundle.class, param);

// ex.
// null means it uses Locale.getDefualt()
I18NBundleParameter param = new I18NBundleParameter(null, "UTF-8");
manager.load("game_en", I18NBundle.class, param);

```

Note that `UTF-8` is the default encoding for the `I18NBundle` and `Locale.getDefault()` is the default locale, so if you're going to use `UTF-8` you don't have to change the encoding and if you're going to use `Locale.getDefault()` you don't have to change the locale.
3. If none of this works **make sure your font supports your characters!** Too often have I made the mistake of using a font that doesn't include special characters just to notice this during the I18N process.
> 2 votes

# Answer
Simply deleting my `language_de.properties` file and pasting the content back in worked. It may have been an encoding issue.
> 0 votes

# Answer
I had the same problem because language.properties file had been created in ANSI encoding and LibGDX uses UTF-8 by default, using notepad ++ I converted the file from ANSI to UFT-8
> 0 votes

---
Tags: libgdx, localization
---


title: C++ OpenGL texture warping

text:
# Question
Title: C++ OpenGL texture warping
I'm currently doing simple 3D drawing in OpenGL but I have hit a roadblock I just can't seem to get around. The problem is happening with trying to load .obj files. I've written my own .obj reader.

I am using SDL2 and GLEW. I use SOIL for loading textures.

When loading in a texture on a model, the texture on "front" and "back" are always correct, like this:

But on the other sides, it's completely warped, like this:

Now I think it has something to do with the texture coordinates, but I have no clue what. I've tried multiple .obj files, even simple cubes. All experience the same weird glitch.

**Model loader**

```
ModelData* ObjFormatLoader::loadModel(std::string t_filename)
{
    std::string fileAdress = "..//Assets//Models//" + t_filename + ".obj";

    Logger::GetInstance()->logAction("loading .obj file " + t_filename);
    if(!std::experimental::filesystem::exists(fileAdress))
    {
        Logger::GetInstance()->logError("No such file exists.", __LINE__, __FILE__);
        return nullptr;
    }

    std::ifstream model(fileAdress);

    std::vector<glm::fvec3> vertices = std::vector<glm::fvec3>();
    std::vector<glm::fvec2> textures = std::vector<glm::fvec2>();
    std::vector<glm::fvec3> normals = std::vector<glm::fvec3>();

    std::vector<GLuint> indices;

    std::vector<GLfloat> verticesArray = std::vector<GLfloat>();
    std::vector<GLfloat> normalsArray = std::vector<GLfloat>();
    std::vector<GLfloat> textureArray = std::vector<GLfloat>();

    std::string line;
    while (getline(model, line))
    {
        std::vector<std::string> currentLine = splitStringDel(line, ' ');
        if (line.find("v ") == 0)
        {
            vertices.push_back(glm::fvec3(atof(currentLine.at(1).c_str()), atof(currentLine.at(2).c_str()), atof(currentLine.at(3).c_str())));
        }
        else if (line.find("vt ") == 0)
        {
            textures.push_back(glm::fvec2(atof(currentLine.at(1).c_str()), atof(currentLine.at(2).c_str())));
        }
        else if (line.find("vn ") == 0)
        {
            normals.push_back(glm::fvec3(atof(currentLine.at(1).c_str()), atof(currentLine.at(2).c_str()), atof(currentLine.at(3).c_str())));
        }
        else if (line.find("f ") == 0)
        {
            textureArray.resize(vertices.size() * 2);
            normalsArray.resize(vertices.size() * 3);
            break;
        }
    }

    model.clear();
    model.seekg(0, std::ios::beg);
    while (getline(model, line))
    {
        if (line.find("f ") == 0)
        {
            std::vector<std::string> currentLine = splitStringDel(line, ' ');
            std::vector<std::string> vertex1 = splitStringDel(currentLine.at(1), '/');
            std::vector<std::string> vertex2 = splitStringDel(currentLine.at(2), '/');
            std::vector<std::string> vertex3 = splitStringDel(currentLine.at(3), '/');

            processVertex(vertex1, indices, textures, normals, textureArray, normalsArray);
            processVertex(vertex2, indices, textures, normals, textureArray, normalsArray);
            processVertex(vertex3, indices, textures, normals, textureArray, normalsArray);
        }
    }

    model.close();

    verticesArray.resize(vertices.size() * 3);

    int vertexPointer = 0;
    for (glm::fvec3 Vertex : vertices)
    {
        verticesArray[vertexPointer++] = Vertex.x;
        verticesArray[vertexPointer++] = Vertex.y;
        verticesArray[vertexPointer++] = Vertex.z;
    }

    return ModelManager::GetInstance()->loadModelToVao(verticesArray, indices, textureArray);
}

void ObjFormatLoader::processVertex(const std::vector<std::string> &t_vertex_data, std::vector<GLuint> &t_indices_data, const std::vector<glm::vec2> &t_texture_data, const std::vector<glm::vec3> &t_normals_data, std::vector<GLfloat> &t_texture_array, std::vector<GLfloat> &t_normals_data_array)
{
    int currentVertex = atoi(t_vertex_data.at(0).c_str()) - 1;
    t_indices_data.push_back(currentVertex);

    glm::vec2 currentTex = t_texture_data.at(atoi(t_vertex_data.at(1).c_str()) - 1);
    t_texture_array[currentVertex * 2] = currentTex.x;
    t_texture_array[currentVertex * 2 + 1] = 1.0f - currentTex.y;

    glm::vec3 currentNormal = t_normals_data.at(atoi(t_vertex_data.at(2).c_str()) - 1);
    t_normals_data_array[currentVertex * 3] = currentNormal.x;
    t_normals_data_array[currentVertex * 3 + 1] = currentNormal.y;
    t_normals_data_array[currentVertex * 3 + 2] = currentNormal.z;
}

std::vector<std::string> ObjFormatLoader::splitStringDel(std::string const& original, char separator)
{
    std::vector<std::string> results;
    std::string::const_iterator start = original.begin();
    std::string::const_iterator end = original.end();
    std::string::const_iterator next = std::find(start, end, separator);
    while (next != end) {
        results.push_back(std::string(start, next));
        start = next + 1;
        next = std::find(start, end, separator);
    }
    results.push_back(std::string(start, next));
    return results;
}

```

**Drawing**

```
void RenderManager::renderEntity(BaseEntity * t_entity, StandardShader* t_shader)
{
    auto model = t_entity->getModel();
    auto modelData = model->getModelData();
    auto textureData = model->getTextureData();

    glBindVertexArray(modelData->getVaoId());
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    auto transformationMatrix = MathHelper::createTransformationMatrix(
        t_entity->getPosition(),
        t_entity->getRotation(),
        t_entity->getScale()
    );
    t_shader->loadTransformationMatrix(transformationMatrix);
    t_shader->loadProjectionMatrix(MathHelper::createProjectionMatrix());
    t_shader->loadViewMatrix(MathHelper::createViewMatrix(WindowManager::GetInstance()->getCamera()));

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureData->getTextureId());
    glDrawElements(GL_TRIANGLES, modelData->getVertexCount(), GL_UNSIGNED_INT, BUFFER_OFFSET(0));
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glBindVertexArray(0);
}

```

**Texture loading**

```
TextureData* ModelManager::loadTexture(std::string t_filename)
{
    GLint texture;
    std::string FileName = "..\\Assets\\Textures\\" + t_filename;
    texture = SOIL_load_OGL_texture
    (
        FileName.c_str(),
        SOIL_LOAD_AUTO,
        SOIL_CREATE_NEW_ID,
        SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS
    );

    m_texture_vector.push_back(texture);
    return new TextureData(texture);
}

```

**Fragment shader**

```
#version 400 core

in vec2 pass_textureCoords;

out vec4 out_Color;

uniform sampler2D tex0;

void main()
{
    out_Color = texture(tex0, pass_textureCoords);
}

```

**Vertex shader**

```
#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 transformationMatrix;
uniform mat4 viewMatrix;

void main()
{
  vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
  gl_Position = projectionMatrix * viewMatrix * worldPosition;
  pass_textureCoords = textureCoords;
}

```

**Cube.obj**

```
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 02.05.2019 21:59:07

#
# object Box002
#

v -2.5000 -2.5000 0.0000
v -2.5000 2.5000 0.0000
v 2.5000 2.5000 0.0000
v 2.5000 -2.5000 0.0000
v -2.5000 -2.5000 5.0000
v 2.5000 -2.5000 5.0000
v 2.5000 2.5000 5.0000
v -2.5000 2.5000 5.0000
# 8 vertices

vn 0.0000 0.0000 -1.0000
vn 0.0000 0.0000 1.0000
vn 0.0000 -1.0000 0.0000
vn 1.0000 0.0000 0.0000
vn 0.0000 1.0000 0.0000
vn -1.0000 0.0000 0.0000
# 6 vertex normals

vt 0.6677 0.3323 0.0000
vt 0.6677 0.0005 0.0000
vt 0.9995 0.0005 0.0000
vt 0.9995 0.3323 0.0000
vt 0.3341 0.0005 0.0000
vt 0.6659 0.0005 0.0000
vt 0.6659 0.3323 0.0000
vt 0.3341 0.3323 0.0000
vt 0.0005 0.6677 0.0000
vt 0.3323 0.6677 0.0000
vt 0.3323 0.9995 0.0000
vt 0.0005 0.9995 0.0000
vt 0.3341 0.3422 0.0000
vt 0.6659 0.3422 0.0000
vt 0.6659 0.6740 0.0000
vt 0.3341 0.6740 0.0000
vt 0.0005 0.3341 0.0000
vt 0.3323 0.3341 0.0000
vt 0.3323 0.6659 0.0000
vt 0.0005 0.6659 0.0000
vt 0.0005 0.0005 0.0000
vt 0.3323 0.0005 0.0000
vt 0.3323 0.3323 0.0000
vt 0.0005 0.3323 0.0000
# 24 texture coords

o Box002
g Box002
s 2
f 1/1/1 2/2/1 3/3/1
f 3/3/1 4/4/1 1/1/1
s 4
f 5/5/2 6/6/2 7/7/2
f 7/7/2 8/8/2 5/5/2
s 8
f 1/9/3 4/10/3 6/11/3
f 6/11/3 5/12/3 1/9/3
s 16
f 4/13/4 3/14/4 7/15/4
f 7/15/4 6/16/4 4/13/4
s 32
f 3/17/5 2/18/5 8/19/5
f 8/19/5 7/20/5 3/17/5
s 64
f 2/21/6 1/22/6 5/23/6
f 5/23/6 8/24/6 2/21/6
# 12 faces

```

If any other code is needed, please let me know.

# Answer
> 3 votes
This looks like it could be an export issue.

Some 3d modelling programs allow multiple uv co-ordinates per vertex. So if this is the case, you can map the three faces adjacent to that vertex with up to 3 different mappings.

When you export to obj, you only get one uv co-ordinate per vertex. This is why some faces look wrong, because they are using a different uv than was intended.

The only solution that I know of is to split the faces before you export. So instead of a cube having 8 vertices, you would have 4 independent vertices per face, 24 in total. This allows completely independent uv mapping per face.

# Answer
> 1 votes
Each face has different texture coordinates for its 4 vertices. However, your OBJ loading code is *picking one* texture coordinate and using that every time the same vertex position is used.

Your cube.obj file has these faces in it (among many others):

```
f 1/1/1 2/2/1 3/3/1
f 1/9/3 4/10/3 6/11/3

```

Let's just look at the first vertex in each face. The first vertex in the first face is position 1, texcoord 1, normal 1. The first vertex in the second face is position 1, texcoord 9, normal 3.

This is your code for adding a vertex to the model:

```
int currentVertex = atoi(t_vertex_data.at(0).c_str()) - 1;
t_indices_data.push_back(currentVertex);

glm::vec2 currentTex = t_texture_data.at(atoi(t_vertex_data.at(1).c_str()) - 1);
t_texture_array[currentVertex * 2] = currentTex.x;
t_texture_array[currentVertex * 2 + 1] = 1.0f - currentTex.y;

glm::vec3 currentNormal = t_normals_data.at(atoi(t_vertex_data.at(2).c_str()) - 1);
t_normals_data_array[currentVertex * 3] = currentNormal.x;
t_normals_data_array[currentVertex * 3 + 1] = currentNormal.y;
t_normals_data_array[currentVertex * 3 + 2] = currentNormal.z;

```

So you see the first vertex (1/1/1) and you add index 0 to the indices list, then you set the texcoord for index 0 to texcoord 0, and you set the normal for index 0 to normal 0.

Then when you see the other vertex (1/9/3): you add index 0 to the indices list, then you set the texcoord for index 0 to texcoord 8, and you set the normal for index 0 to normal 2. So the first vertex will *also* use this texcoord and this normal!

That's why your texture coordinates are messed up - because you're mixing up texture coordinates from different faces. (You also do this with normals, but I'm guessing you aren't using the normals anyway)

---
Tags: opengl, textures, glsl, sdl
---


# Question
Title: How to limit camera pitch (x rotation) between two angles
I use this script rotate the camera on its local X axis:

```
 float v = verticalSpeed * Input.GetAxis("Mouse Y");
 transform.Rotate(-v, 0, 0);

```

Right now this lets the player look up & down without limit, wrapping around a full 360 degrees. How can I limit this so they can look only 90 degrees up or 90 degrees down from the horizon?

# Answer
This is a straightforward application of `Mathf.Clamp(value, min, max)`. Ordinarily I'd recommend caution calculating new orientations from Euler angles, but for camera orientation it's typically safe enough. You might want to pull back slightly from 90, say 80 degrees, so you don't hit nasty behaviour right at the poles.

```
// Correct for deltaTime so your behaviour is framerate independent.
// (You may need to increase your speed as it's now measured in degrees per second, not per frame)
float angularIncrement = verticalSpeed * Input.GetAxis("Mouse Y") * Time.deltaTime;

// Get the current rotation angles.
Vector3 eulerAngles = transform.localEulerAngles;

// Returned angles are in the range 0...360. Map that back to -180...180 for convenience.
if(eulerAngles.x > 180f)
    eulerAngles.x -= 360f;

// Increment the pitch angle, respecting the clamped range.
eulerAngles.x = Mathf.Clamp(eulerAngles.x - angularIncrement, -90f, 90f);

// Orient to match the new angles.
transform.localEulerAngles = eulerAngles;

```
> 0 votes

# Answer
You can use `if` condition such as:

```
float v = verticalSpeed * Input.GetAxis("Mouse Y");
if (v > 100)  then //100 your limit
    {v= 50}
else
    {v=30}

```

or you can use `math.sign` function which gives you +1,0,-1

> if the result for your case v \> 0 it returns +1
>
> if it is zero than 0
>
> if it is negative then it is -1

you can limit your camera by that way.
> 0 votes

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


# Question
Title: Find optimal placement for label/sticker on a simple polygon with holes
I'm working on a real-time archviz renderer and I need to place a label/sticker/decal on walls, which have openings. So one way to think about this is a simple (possibly concave) polygon with holes. So there are two things I need: optimal position, maximum fitting size.

After some research I came to conclusion that I need a solution for maximum inscribed circle in a simple polygon. That will provide both the position and radius.

https://www.sthu.org/blog/14-skeleton-offset-topology/index.html

And couple of other questions, most answered by Stefan Huber, apparently The Authority nowadays regarding this problem. I'm time constrained and looking for plugin solution. So it's either commercial solutions (\*Vroni) or CGAL that can at least help me construct straight skeleton. However my environment is JVM, not C++ (yes, I can go the FFI way using JNA).

Can you think of any other solution that I could use to position/scale the labels?

# Answer
> 0 votes
voronoi diagrams are pretty cool tools.

since you are searching for the largest circles available and you (judging by you posting an article about voronoi diagrams) are able to use a voronoi diagram of your surface. let's consider a few key facts about circles and voronoi diagrams.

a circle has a center equidistant from all its edges. a voronoi diagram contains polyons where in all points are closer to a single center point than to any other.

these aren't quite the same, but they are similar.

let's also consider that little piece of information i was taught back in middle school. the most optimized amount of space you can get out of an area by perimeter length is a circle

while i can't give you a proof for it, i believe we can predict a statistical tendency of larger area polygons in a voronoi diagram to also have a tendency towards larger circular inscriptions.

using this idea you can write a highly optimized algorithm to start searching the voronoi diagram for large circular inscriptions starting from the largest polygons in the diagram. i dare say you could write an algorithm not only good enough for one time calculation, but an algorithm good enough for 60fps realtime calculation every frame. mainly because voronoi is absolutely ripe for parallelization.

A truly mathematical solution may be more desired, but you asked for other solutions and i believe this is a very practical approach.

if you are looking for information on making voronoi diagrams(and finding their polygon's area) fast, and they can be lightning fast, then i suggest this article.

http://rykap.com/graphics/skew/2016/02/25/voronoi-diagrams/

---
Tags: mathematics, geometry, computational-geometry
---


# Question
Title: Why it's not playing all the sentences and each sentence in a line?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class Dialog : MonoBehaviour
{
    public TextMeshProUGUI textDisplay;
    public string[] sentences;
    public float typingSpeed;

    private int index= 0;

    IEnumerator Type()
    {
        foreach(char letter in sentences[index].ToCharArray())
        {
            textDisplay.text += letter;
            yield return new WaitForSeconds(typingSpeed);
        }
    }

    private void Start()
    {
        StartCoroutine(Type());
    }
}

```

I have 2 sentences. For example the first sentence is :

Hello world Hi everyone

And the second sentence is :

My name is Daniel who are you ?

When I play the game it's playing only the first sentence and also breaking it. It's playing it like this :

Hello world Hi everyone

Instead it should play all the sentences like this :

Hello world Hi everyone

Then the next sentence at the same place of the firsto ne :

My name is Daniel who are you ?

# Answer
> 0 votes
Your index variable is being used to index into the sentence array by the first sentence only.

If you want to go through all of the sentences you could wrap your sentences in another loop that indexes through the sentences array when you're finished presenting it. You may also want to wait for some period and clear your textDisplay.text value at the start or end of the outer loop.

# Answer
> 0 votes
you are just lopping the through characters in first sentence as the index never gets updated. just wrap your code with new for or foreach loop. this is just my psudo code for your problem.

```
string[] sentences;
float TypeSpeed;
ienumerator displayText()
{
 for(int i=0; i<sentences.length;i++)
 {
   for(int j=0;j<sentences[i].length;j++)
   {
    displayText+= sentences[i][j];
    yield return new waitForSeconds(speed);
   }
 }
}

```

its just a psudo code. check your errors in code editor

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


title: Why won't my ball bounce? (Unity, 3D)

text:
# Question
Title: Why won't my ball bounce? (Unity, 3D)
I'm trying to do a very simple ball bouncing setup in Unity. I have a sphere with a sphere collider and a plane below it was a rectangular mesh on it, isTrigger set to false for both, and they both have a physics material with bounciness of 1. I have the ball start a couple units above the plane, gravity pulls it down, but instead of bouncing it stops right at the collider for the plane, then (weirdly) slowly falls through the collider. Once it falls through the bottom it starts falling normally again. The collider is already really thick (I've been trying to fix this by changing collider types and making them way bigger than needed). I just have no clue what's going on and feel like I'm missing something obvious.

# Answer
> 1 votes
It would be more helpful if you post screen shot of the physics material setup. But i did a quick demo and it worked for me. Setup your physics material as:

1. Take a sphere and a Cube with Sphere collider and box collider respectively with "isTrigger" set to false for both objects.
2. Then I've created physics material and assigned it to the sphere collider.
3. here is the Physics material setup:

And its done....

I hope it Works for you....

If you have any question please let me know and i try to be as helpful as i can...

Cheers!

# Answer
> 0 votes
You have to set up your ball physics. It depends on 2 parameters:

1. `rigidBody.mass`
2. `physicsMaterial.friction`

Choose the right mass value for better moving results, and make a Physics Material in Assets and set the right friction to it in the inspector and assign it to your collider.

If you need some controlled or deterministic behaviour, you have to disable the rigidBody and write some physics code for it.

---
Tags: unity
---


# Question
Title: Animator from another gameobject keeps disappearing from script on play
I am working on a gun script and it worked fine until earlier today when I made a change to the script and it stopped working. I put it back, but for some reason now the animator object attached to the script keeps disappearing.

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

public class RifleShooting : MonoBehaviour
{
    private float NextTimeToFire = 0f;
    private int CurrentAmmo;
    private bool IsReloading = false;

    [Space(10)]
    [Header("Floats")]
    public float Damage = 10.0f;
    public float Range = 100.0f;
    public float ImpactForce = 60f;
    public float FireRate = 15f;
    public float ReloadTime = 1.0f;

    [Space(10)]
    [Header("Others")]
    [Space(5)]

    [Space(10)]
    [Header("Others")]
    [Space(5)]
    public int MaxAmmo = 10;
    public Camera FPSCamera;
    public Animator GunAnimations;
    public ParticleSystem MuzzleFlash;
    public GameObject impactEffect;
    public bool AllowedToShoot = true;
// Start is called before the first frame update
    void Start()
    {
        GunAnimations = GetComponent<Animator>();
        if (CurrentAmmo == -1)
            CurrentAmmo = MaxAmmo;
    }

    private void OnEnable()
    {
       IsReloading = false;
        GunAnimations.SetBool("Reloading", false);
    }
    // Update is called once per frame
    void Update()
    {
        if (IsReloading)
        return;

        if (CurrentAmmo <= 0)
        {
            StartCoroutine(Reload());
            return;
        }

        if (AllowedToShoot == false) return;
        {
            if (Input.GetButton("Fire1") || Input.GetButtonDown("Fire1") && Time.time >= NextTimeToFire)
            {
                NextTimeToFire = Time.time + 1f / FireRate;
                Shoot();
            }
        }
    }

    IEnumerator Reload()
    {
        IsReloading = true;
        Debug.Log("Reloading...");
        GunAnimations.SetBool("Reloading", true);
        GunAnimations.SetBool("IsShooting", false);
        yield return new WaitForSeconds(ReloadTime - .25f);
        GunAnimations.SetBool("Reloading", false);
        yield return new WaitForSeconds(.25f);
        GunAnimations.SetBool("IsShooting", true);
        CurrentAmmo = MaxAmmo;
        IsReloading = false;
    }

    void Shoot()
    {
        //shooting script here
    }
}

```

Also if it helps here is what I see in the console when I try to fire:

MissingComponentException: There is no 'Animator' attached to the "M4A1" game object, but a script is trying to access it.

# Answer
As is usually the case, this is happening because you told Unity that's what you wanted to happen.

This block says:

```
void Start() {
    GunAnimations = GetComponent<Animator>();

```

"As soon as this script starts, please throw away whatever value I'd put in the `GunAnimations` variable in the inspector. Instead, I want you to use the `Animator` component attached to the object that's running this script, if any"

But the object that's running this script ("M4A1") doesn't *have* an `Animator` component attached. That component is on a different object, one called "Shooting", according to the screenshots you showed us.

So, it looks like you either want to delete this line and stick with the value you gave the variable in the inspector, rather than overriding it at runtime, or else make sure you point your `GetComponent` call at the object that actually has the component you want attached to it.
> 2 votes

---
Tags: unity, c#, shooter, animator, boolean
---


# Question
Title: How can I calculate all the tiles visible to a camera in 2D?
I am creating a basic tile-based 2D game ~mostly from scratch in Java, however all I need is pseudo-code for how this could be achieved. My problem lies in the fact that my world (stored in a `HashMap` so I don't have to have a null object for every position down to 0) maybe millions or even billions of tiles large, so I'm sure it is not efficient to loop through every tile.

A solution I have thought of to solve this issue would be to try to calculate based on the position of the camera in the world and the size of the tiles how many could fit on the screen in the X and Y axes, and also the offset of them to the screen as well, but I have tried (and failed) to implement this, because I am unsure on how to convert this is Maths/Logic.

How may I go about this? Below I have linked an image showing what tiles I intend to show to the screen, where the black square is the centre and tiles that do not cover the screen are not shown.

# Answer
Using a simple truncation as suggested by @Pikalek does only work with positive numbers. Truncating positive numbers is equivalent to the floor-operator but with negative numbers it is equivalent to the ceil- operator. To make it properly work in both cases you need to explicitly use the floor operation.

```
leftCameraBorder = centerX - camera.width / 2
leftCoordinate = Math.floorDiv(leftCameraBorder, tileSizeX)

```

Use the same code with changed variables for the top border.
> 1 votes

# Answer
Converting any coord to a tile is done by dividing by the tile size & discarding the decimal part.

So for instance, the camera focus will be in tile:

```
cameraTileX = (int)(cameraX / tileSizeX);
cameraTileY = (int)(cameraY / tileSizeY);

```

From there, you can calculate the upper leftmost tile (subtract half the screen size to the camera coord) & the lower rightmost tile (add half the screen size to the camera coord).
> 0 votes

---
Tags: java, camera, tiles, logic
---


# Question
Title: Modify the effect of a card being played
I'm trying to recreate a simple card game. Each played card has an action (draw extra cards, peek at draw stack, eliminate an opponent card, etc). Once played, it goes on a stack, and the card effect is executed in order.

Cards added by effects are added at the end of this stack as well, and executed once it is their turn.

Each player also has a different unique influence on exactly one type of cards that changes the effect (enhances it like draw 4 instead of 2 or taking cards instead of trashing them to graveyard).

So far a card has a simple interface with value, type and doAction. While I could on each card do a check if a player influence would take effect, this seems like a hard coded noodle salad and makes it difficult to add new cards or influences. And more than once influence can take effect on the same card (for example, one effect could be steal 2 instead of 1 and the second effect, you can steal only a certain type of card from a second influence instead of free choice)

I'm looking for a way to react on a method call (played card that gets executed) and change it accordingly. I'm investigating using delegates for this purpose.

# Answer
As the comments have indicated, delegates may be your saviour, but let me add a little context and maybe a few extra pointers.

delegates are nice because you can form a subscriber system whereby the player can be subscribed to the card with some functions X that executes the desired actions on the card.

however delegates may not be the perfect solution as your game grows, while functionally similar, code may become more readable in a situation where cards could do anything like... Switching owners, reversing effects, or affecting other cards... if you format this as a list of Func that run on the card before it's effect is executed then you can easily encapsulate further for more functionality.

So i am proposing that you may prefer a solution like

```
class Card{

     public object value;
     public object type;
     public list<action<Card>> ExtraEffects;
     public void Execute(){
          //create a new card that can be modified however you like with the funcs without modifying the base card
          var cloneCard = Clone();
          foreach(var fun in Modifiers)
               cloneCard = fun(cloneCard);
          cloneCard.ExecuteModified();
     }
     public void ExecuteModified(){
          //do your thing here.
     }
     public list<Func<card, card>> Modifiers;
     public void ClearModifiers(){
          //clear all modifiers.
     }
     public Card Clone(){
          //clone code
     }

```

this is really good because it scales easily. if at any point you decide you want to keep the thing that causes an effect referenced then you can just encapsulate func with something else next to it like a reference to thing that caused the effect.

```
struct Effect{
    Func<Card, Card> Modifier;
    object Source;//like the player, field effects, enemy effects, other card's effects
}

class Card{
    public List<Effect> Modifiers;
    ....
}

```

This is as opposed to delegates and events where it becomes difficult to track each subscription as opposed to just running all of them.

for instance you could use this architecture to add functions like

```
public void ClearPlayerModifications(){
    Modifiers = Modifiers.Where(x=>x.Source != Player)
}

```

games where a lot of dynamic effects happen can grow wildly really easily, its worth it in my experience to manage it this way instead.

this is as opposed to growing the class in ways like this

```
public void ClearPlayerModifications(){
    //a likely implementation with events and delegates. really error prone for a system where effects could change every turn.
    Modificatiers.Clear();
    Modifications.AddEverythingThatShouldStillBeThere();
}

```
> 2 votes

# Answer
Delegates can be used to achieve what you're doing but the code here will most likely not 'just work' with what you already have. In addition, I've had to make several assumptions about how things work / what you have described (see **assumptions** at the end).

# Cards

Given your description, I imagine the interface your cards use to look something like this:

```
interface ICard {
    CardType cardType {get;}
    int amount {get;} // Or whichever number type is appropriate
    void DoCardAction();
}

```

You said that player effects could completely change the action of your cards. A delegate property instead of an interface method for the card's action would support this replacement.

```
interface ICard {
    CardType cardType {get;}
    int amount {get;} // Or whichever number type is appropriate
    Action doCardAction {get; set;} // The delegate
}

```

Having a card without any action is probably not what you want. To avoid that, the implementing class would then assign the 'normal' action to this property on initialisation / construction, e.g.:

```
class CardImplementation : ICard {
    // etc...
    void CardAction() {/* etc...*/}
    public CardImplementation() {
        doCardAction = CardAction;
        //etc...
    }
}

```

# Influences

With this new delegate-centred interface, modifying the card's base effect would be replacing it with a delegate to a different method. We can also incorporate another delegate for modifying the 'amount' values so that different players can effect different modifications without the need for subclassing.

```
class PlayerInfluence {
    CardType modifies;
    Func<int, int> modifier; // Or Func<X, X> where X is the data type of your card's 'amount'
    Action replacementAction;

    public bool CanModify(ICard target) {
        return modifies == target.cardType;
    }

    public void ModifyCard(ICard target) {
        // Replace the card's action if a replacement was supplied
        target.doCardAction = replacementAction ?? target.doCardAction;

        // Augment the target's amount property using a function, if supplied
        target.amount = modifier?.Invoke(target.amount) ?? target.amount;
    }
}

```

Delegate properties can hold lambdas, so creating a player with a specific effect is as simple as defining that effect on player creation. The example below creates an influence that will modify Peek cards by doubling the amount, but leaving the action unchanged.

```
PlayerInfluence peekingCardDoublingInfluence = new PlayerInfluence(CardType.Peek, (x) => x * 2, null);

```

# Using a player's influence to modify a card

To bring this together, the routine for resolving an action from the stack would look something like:

```
currentEffect = effectStack.Pop(); // Get the next effect
if(currentPlayer.influence.CanModifyCard(currentEffect)) {
    currentPlayer.influence.Modify(currentEffect); // Modifiy the effect, if possible
}
currentEffect.doCardAction(); // Run the effect

```

---

(some of the) Assumptions I'm making:

* your card type is represented by an enumeration (called `CardType`)
* you have implemented a constructor for `Player` as `Player(CardType, Func<int, int>, Action)`
* The routine which controls stack resolution has access to the current player
* Card effects are cloned on to the stack, rather than pointing to the same instance in the deck, if you want the modifications to be one-time-only
* A card's default action is an instance method bound to `ICard.doCardAction` when the card is constructed / initialised.
* If replacing a card's action, then `ICard.amount` is not relevant to the new action i.e. they are mutually-exclusive modifications
> 2 votes

---
Tags: unity, c#, software-engineering, card-game, effect-modifier
---


# Question
Title: Unity get component throwing NullReferenceException only in standalone build
I'm having a very frustrating issue with `GetComponent()`.

```
private void Show()
{
    var transition = GetComponent<TransitionAnimation>();

    Debug.Log($"Transition: {transition}");
    transition?.FadeIn();
}

```

In the editor, this works just fine. `transition` is not null and `FadeIn()` is called. In the standalone build, `GetComponent()` returns null, throws a `NullReferenceException`, and execution stops before it can even print `transition` to the console.

This is the output from the log file.

```
Uploading Crash Report
NullReferenceException
  at (wrapper managed-to-native) UnityEngine.Component.get_gameObject(UnityEngine.Component)
  at UnityEngine.Component.GetComponentInChildren (System.Type t, System.Boolean includeInactive) [0x00001] in <e314adc5a7494b5f8760be75461a94d4>:0
  at UnityEngine.Component.GetComponentInChildren[T] (System.Boolean includeInactive) [0x00001] in <e314adc5a7494b5f8760be75461a94d4>:0
  at Winglett.RR.UI.Gradient.Show () [0x00001] in /Users/redacted/Documents/repos/radical-relocation/Assets/_Core/Scripts/UI/Gradient.cs:63
  at (wrapper delegate-invoke) <Module>.invoke_void()
  at Winglett.RR.Gameplay.GameState.SetPause () [0x00001] in /Users/redacted/Documents/repos/radical-relocation/Assets/_Core/Scripts/Gameplay/GameState.cs:46
  at Winglett.RR.Gameplay.GameState.SetPause_STATIC () [0x00000] in /Users/redacted/Documents/repos/radical- relocation/Assets/_Core/Scripts/Gameplay/GameState.cs:70
  at Winglett.RR.UI.Wrapper.SetGameStatePause () [0x00000] in /Users/redacted/Documents/repos/radical-relocation/Assets/_Core/Playground/ui/Wrapper.cs:27
  at UnityEngine.Events.InvokableCall.Invoke () [0x00011] in <e314adc5a7494b5f8760be75461a94d4>:0
  at UnityEngine.Events.UnityEvent.Invoke () [0x00023] in <e314adc5a7494b5f8760be75461a94d4>:0
  at Winglett.RR.Utils.ESCButton.Update () [0x00026] in /Users/redacted/Documents/repos/radical-relocation/Assets/_Core/Scripts/Utilities/Other/ESCButton.cs:21

```

I wondered if the issue might be because the gameobject is disabled. So I tried `GetComponentInChildren<TransitionAnimation>(true);` where true is an overload for inactive gameobjects. This didn't change anything.

# Answer
I found the problem.

It was all because of a stupid little workaround I was making. For some context, I was having problems with the new prefab workflow resetting scene references in all my levels. I have a lot of levels and it's a real pain to have to go through each one and manually hook everything up again. So instead, I started using static events.

When the scene loaded it would subscribe and when it unloaded it would unsubscribe from the event. However, the gameobject that this script was on was disabled in the hierarchy so I think `OnDestroy()` mustn't have been called so it never unsubscribed from the event. When `Show()` was called from the event in the new scene, it tried to call it on the gameobject from the previous scene which had since been destroyed and unloaded.

Instead of using `OnDestroy()` to unsubscribe from the events, I now use another event thats called just before a new scene is loaded. Events are now unsubscribed from properly and the weird `NullReferenceException` went away.
> 3 votes

---
Tags: unity, component-based, debugging
---