# Question
Title: Tetris block kinematic rigidbodies pass through one another with Transform.Translate
I am trying to build a Tetris 3D game in Unity but I am stuck at getting the different blocks to interact (to detect each other, to sit one on top of the other rather than going through each other). I have set the ground with a box collider and the spwaned blocks come in with rigidbodies and trigger colliders.

This works for them to nicely settle on the ground but when I try to sit a block on top of another block they both have kinematic rigidbodies and the collision detection doesn't work and they end up overlapping. The problem is if I remove the rigidbody of the already settled block then it will go through the ground.

Any idea how to get 2 spawned objects to detect each other?

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

public class moveBlock : MonoBehaviour
{
    public static float speed = 2;
    public GameObject[] blocks;
    public static List<GameObject> blocksSpawned = new List<GameObject>();
    public static List<Rigidbody> blocksRBSpawned = new List<Rigidbody>();
    public static bool triggerPlatform = true;
    Rigidbody rb;

    void Update()
    {
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        Vector3 direction = input.normalized;
        Vector3 velocity = direction * speed;
        Vector3 moveAmount = velocity * Time.deltaTime;

        if (triggerPlatform)
        {
            blocksSpawned.Add((GameObject)Instantiate(blocks[Random.Range(0, 7)], new Vector3(0, 6, 0), Quaternion.Euler(Vector3.right)));
            rb = blocksSpawned[blocksSpawned.Count - 1].GetComponent<Rigidbody>();
            blocksRBSpawned.Add(rb);
            triggerPlatform = false;
        }
        /*if (!triggerPlatform)
        {
            Destroy(blocksRBSpawned[blocksRBSpawned.Count - 1]);
        }*/
        if (blocksSpawned[blocksSpawned.Count - 1] != null)
        {
            blocksSpawned[blocksSpawned.Count - 1].transform.Translate(Vector3.down * Time.deltaTime*speed, Space.World);
            blocksSpawned[blocksSpawned.Count - 1].transform.Translate(moveAmount);
        }
    }
}

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

public class trigger : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        moveBlock.triggerPlatform = true;
    }
}

```

# Answer
From your screenshot I see that you are using kinematic Rigidbodies. Kinematic Rigidbodies don't behave like Rigidbodies in most ways.

* They ignore forces, as I assume you've already noticed since you implemented your own gravity manually.
* They aren't moved or otherwise physically affected by collisions with non-kinematic Rigidbodies
* As DMGregory noted, they won't fire `OnCollisionEnter` if they intersect with another kinematic Rigidbody. **As far as the physics engine is concerned, two kinematic Rigidbodies cannot collide with one another.**

There are only a few highly specific scenarios where it really makes sense to use kinematic Rigidbodies.

If you want your objects to fall and collide using the normal physics engine, uncheck "Is Kinematic".

If you want to keep using your own gravity code, you'll need to also uncheck "Use gravity". If you go that route, you should move the objects in `FixedUpdate()` instead of `Update()` since the former is in step with the physics engine and is a safer place to move physics objects. As DMGregory noted, `Rigidbody.MovePosition()` is a safer function to use for manually moving physics objects. Also, if you keep using your own gravity code, you should disable the `MoveBlock` component once it lands; otherwise it's going to waste CPU cycles trying to move downward for every fixed update for the rest of the game.

If you use standard (non-kinematic) Rigidbodies and want to ensure that the physics engine is only allowed to move the objects directly downward (preventing any lateral motion), check the boxes under "Freeze Position" for "X" and "Z". This will ensure that the physics engine only moves the Rigidbody along the vertical (y) axis. I believe you're still free to manually move it along the X and Z axes from your code.

Alternatively you could throw out the physics engine, remove the Rigidbody components, and write your own code for determining when the blocks have landed; however, I'd expect that to be more involved than using the physics engine correctly.
> 1 votes

---
Tags: unity, rigidbody, collider, spawning
---


# Question
Title: Unity: How to connect to server with status in dialog
I am trying to build in unity a basic logon screen. Now I'm building on something if the connection will have delay or so... There will be a dialog, where the progress of connection to server will be written... Like Attempt 1/3, Attempt 2/3...

I have Dialog class, which is building a Dialog window from prefab:

```
    public class Dialog
    {
        private const string TitleComponent = "Title";
        private const string ContentComponent = "Content";

        private readonly IPrefabFactory _dialogFactory = new DialogFactory(false);
        private readonly GameObject _dialog;

        public event ClickHandler Click;

        public string Title
        {
            set => GetTextComponent(TitleComponent).text = value;
        }

        public string Content
        {
            set => GetTextComponent(ContentComponent).text = value;
        }

        public Vector3 Position
        {
            set
            {
                _dialog.transform.position = value;
                _dialog.transform.localPosition = value;
            }
            get => _dialog.transform.position;
        }

        public bool Active
        {
            set => _dialog.SetActive(value);
            get => _dialog.activeSelf;
        }

        public Dialog(string name)
        {
            _dialog = _dialogFactory.Create();
            _dialog.name = name;
            _dialog.GetComponent<DialogBehaviour>().Dialog = this;
            SetToCanvas();
        }

        public void OnClick()
        {
            Click?.Invoke();
        }

        private void SetToCanvas()
        {
            var uiCanvas = Object.FindObjectOfType<Canvas>();
            _dialog.transform.SetParent(uiCanvas.transform, false);
            Position = new Vector3(0, 0, 0);
        }

        private TextMeshProUGUI GetTextComponent(string name)
        {
            foreach (Transform child in _dialog.transform)
            {
                if (child.name == name)
                {
                    return child.gameObject.GetComponent<TextMeshProUGUI>();
                }
            }

            throw new Exception($"Component with name `{name}` was not found.");
        }
    }

```

And I have some server "Manager", where the connection process is running.

```
        private void Connect()
        {
            Dialog.Active = true;
            var attempts = 1;
            do
            {
                Dialog.Content = $"Connecting to server... ({attempts++}/{MaxAttempts})";
                try
                {
                    if (Client.CurrentState == ComponentState.Ready)
                    {
                        Client.Connect();
                    }
                    else
                    {
                        Client.Reconnect();
                    }
                }
                catch (ConnectionException)
                {
                    attempts++;
                }
            } while (!Client.IsConnected && attempts <= MaxAttempts);

            if (!Client.IsConnected)
            {
                Dialog.Content = "Connection with server could not be established.";
                throw new ConnectionException("");
            }

            Dialog.Active = false;
        }

        private void CheckConnection()
        {
            if (Client.CurrentState == ComponentState.Ready)
            {
                Connect();
            }
            else
            {
                if (Client.CheckConnection()) return;
                Connect();
            }
        }

        protected Message SendAndReceive(Message message)
        {
            CheckConnection();
            Message response = null;

            try
            {
                response = Client.Send(message);
            }
            catch (MessageSendException)
            {
                Dialog.Active = true;
                var attempts = 2;
                do
                {
                    Dialog.Content = $"Sending message... ({attempts}/{MaxAttempts})";
                    try
                    {
                        response = Client.TryReceive();
                    }
                    catch (MessageSendException)
                    {
                        attempts++;
                    }
                } while (response == null && attempts <= MaxAttempts);
            }

            if (response == null)
            {
                Dialog.Content = "Server did not send any response. Probably connection is lost.";
                throw new MessageSendException("");
            }

            Dialog.Active = false;

            return response;
        }

```

I want to provide some output to screen about whats hapening in that dialog class. But, where is the problem. Everything is so much fast, that the dialog can't even render on the start and during all attempts to connect to server, the main thread is just stucked to the time, when the connection ends.

I was finding something about how to make this happen like in another thread or so... Or find coroutines, but I have no idea how to make this work...

It should work like this:

* Render dialog.
* Write that the connection attempt is running.
* During another attempts update the status.
* If successful dismiss dialog.

After all this happen, something similar should happen with the sending. How to make this working without stucking the main thread and make all steps run smoothly one after another?

# Answer
> 1 votes
You didn't post any of the code which actually sends the login attempt to the server, as all of that is abstracted away in an object "Client". And there are quite a lot of ways to do networking in Unity. But most network APIs don't block the current thread until there is an answer. They usually send a message and then return immediately. The actual response is then processed by a handler function when it finally arrives.

You are already using that pattern for the click events for your button. Your networking API likely uses a similar pattern for asynchronous operations.

So the usual pattern you would use is:

1. Send a request using an asynchronous networking API which returns immediately. Such APIs will usually require a callback function which is to be called when there is a response, and often a second one to be called in case of an error.
2. Keep running updates and keep rendering the dialog (which Unity does automatically for you). Perhaps showing some animated indicator that there is a pending connection attempt.
3. When a response from the server arrives, or the network API reports an error, it executes a callback function.
4. That callback function notifies the Dialog of the result of the network operation
5. During the next `Update()` of the Dialog, it notices that there is a notification from the network API and changes the UI accordingly

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


title: My bullets won't bounce in Unity?

text:
# Question
Title: My bullets won't bounce in Unity?
I wanted bullets to bounce when they hit walls. However when colliding with a wall, they just jitter about on them. I didn't want to create a new physics material as I want to keep the ball moving at a constant speed and to have them destroy themselves after they have bounced once. Thus, I wrote everything in Code.

The constraints for the bullet rigidbody's freezing position is the Y axis while the freezing rotation is X, Y, and Z axis.

I also wondered if the initial position the instantiated bullet also had something to do with the speed the bullet travels:

```
GameObject bulletObject = Instantiate(bulletPrefab);
bulletObject.transform.position = transform.position + (transform.forward * -1);

```

Here's the minimum reproducible code:

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

public class bulletMovement : MonoBehaviour
{
    private Rigidbody bulletRB;
    private Vector3 lastVelocity, initialVelocity;
    public float bulletSpeed = 10f;
    private int bounceCount;
    // Start is called before the first frame update
    private void Start()
    {
        bulletRB = GetComponent<Rigidbody>();
        bounceCount = 0;
        bulletRB.AddForce((transform.forward* -1) * bulletSpeed);
    }

    void Update()
    {
        lastVelocity = bulletRB.velocity;
    }

    // Update is called once per frame

    private void OnCollisionEnter(Collision col)
    {
        if (col.collider.tag == "Walls")
        {
            bounceCount += 1;
            if (bounceCount < 2)
            {
                Bounce(col.contacts[0].normal);
            }
            else
            {
                Destroy(gameObject);
            }
        }
    }

    private void Bounce(Vector3 normal)
    {
        var speed = lastVelocity.magnitude;
        var direction = Vector3.Reflect(lastVelocity.normalized, normal);

        Debug.Log("Out Direction: " + direction);
        bulletRB.velocity = direction * Mathf.Max(speed, bulletSpeed);
    }
}

```

lastVelocity = bulletRB.velocity; is required to be in Update or else the bullet won't move at all.

# Answer
> 1 votes
You are moving your bullets by changing their `transform.position` in `Update()`. That way you are overriding the Unity physics engine. That means you can no longer expect it to do its job properly

If you want bullets to behave like ballistic projectiles with realistic physics, then you need to let the physics engine do its job instead of doing it yourself.

That means setting the initial velocity (or even better, set a velocity with `rigidbody.AddForce(transform.forward * shootingForce, ForceMode.Impulse)`). If your shooting force is large enough and your rigidbody settings like mass and friction are correct, then the projectile should move on its own without you having to do anything in `Update or FixedUpdate` and will behave physically correct on collisions (bounce off and transfer an impulse on the other rigidbody).

---
Tags: unity, physics, projectile-physics
---


# Question
Title: What is the process for porting my game SFML from Windows to Mac
I've recently finished version one of a simple arcade game I've been making in SFML. I've already spent months on the physics engine and game, and I'm wondering how much time it will take to port it to Mac. I've been developing it using Visual Studio on Windows10. As far as I can see, this is the only way to do it;

1. Open Visual Studio on my Mac laptop, download all my windows code
2. try to compile it, fail, fix all the various stuff that wont work, try to compile again.

I can't seem to find any tutorials indicating a better process, or how long I should expect it to take. It can't be trivial, or else there wouldn't be so many triple-A games that don't run on Mac. I would greatly appreciate any tips on the process or time estimates. Thanks

# Answer
> 1 votes
Someone on the SFML forums helped me. It looks like I do just have to download the project on a Mac machine and attempt to compile it until it builds. If I were attempting to release it for Linux, I could have used a crosscompiler in visual studio.

---
Tags: sfml, windows, macos, porting
---


# Question
Title: LibGDX changing actors parents is resulting in unwanted (x,y) translation
I have a Rolodex of task item actors I want to drag to an agenda tablet. My drag and drop functionality is non-native, but came from modifying a book's implementation. The problem seems to be when I change the parent of a task item, 'a', to the agenda's parent, 'other':

```
other.getParent().addActor(a);

```

When I do so the actor's coordinates shift. I want the actor to remain in the same spot I dropped it down. It worked as desired previously, possibly because the Rolodex's parent and the agenda's parent shared the same, whole-screen dimensions. I've since moved away from layout to positioning actors and their groups on the screen with setBounds(). Tracking the (x,y) coordinates of my dragged item I'm getting negative values for x while it remains visible on screen, making me think actor.getX() and actor.getY() return values relative to the parent carousel container class I made, and not the screen/stage nor the agenda's container.

I found a set of methods off of Actor that looked promising, localToXXXX(Vector2), and experimented with a variety of them before settling on the following I think should work:

```
            Vector2 snapShot = a.localToActorCoordinates(other.getParent(), new Vector2( a.getX(), a.getY()) );
            other.getParent().addActor(a);
            a.setBounds(snapShot.x, snapShot.y, a.getWidth(), a.getHeight());

```

...but it doesn't. Converting it to stage or screen coordinates with the other method options shifts it even farther away from desired. What am I misunderstanding? How can I change an actor's parent without the x,y shifting?

# Answer
> 1 votes
Adding the dragged actor's parent coordinate values to the actor's values did the trick:

```
Vector2 snapShot = new Vector2(a.getParent().getX() + a.getX(), a.getParent().getY() + a.getY()) ;
other.getParent().addActor(a);

        a.setBounds(snapShot.x, snapShot.y, a.getWidth(), a.getHeight());

```

---
Tags: libgdx, coordinates, scene2d
---


title: Unity: Sprite stretch issue

text:
# Question
Title: Unity: Sprite stretch issue
I have a simple png square 8px x 8px. In Unity I've left the pixels per unit at 100 and added the image to the scene to create a prefab of the item. I then add four items to the screen like so:

```
    var block = Resources.Load("Prefabs/Block", typeof(GameObject));

    Instantiate(block, new Vector3(1f, 0f), Quaternion.identity);
    Instantiate(block, new Vector3(0f, 1f), Quaternion.identity);
    Instantiate(block, new Vector3(2f, 0f), Quaternion.identity);
    Instantiate(block, new Vector3(0f, 2f), Quaternion.identity);

```

The results (as shown in the image below) seem to stretch the image dependant on where the prefab is placed. Is this normal behaviour? Is there a way round this or something I'm missing?

# Answer
You haven't given a lot of information here. What components are attached to the block prefab (`SpriteRenderer`? `Image`?)? My best guess is that you're looking at imprecise pixel alignment, which can happen when the edges of objects in Unity space are not precisely aligned with pixels on the screen.

If these objects are Images displayed in a canvas, you can try enabling "Pixel perfect" on the canvas. If they are SpriteRenderers, things get a bit more complicated. You might try the official "Pixel Perfect" package, if your entire game requires pixel precision.
> 1 votes

---
Tags: unity, sprites, prefabs
---


# Question
Title: How to add post process volume script in unity 2019?
i have old unity 2018 project and imported standard character asset. The 3d player has this script : **post process volume** and **post process layer**. In 2018 i can add this component but not in 2019 . This component is not available in 2019. What is the replacement for this ? or how to achieve the same result for 2019 ?

# Answer
> 1 votes
Install the Post-Processing package from the Unity Package Manager.

---
Tags: unity
---


# Question
Title: Player is not looking at correct direction
My Enemy/Bot is facing the wrong direction as shown in the attached screenshot 1. Basically what I want is that Enemy/Bot gun should directly face the player, not enemy/Bot himself.

> Note: White line in the image is representing Aim direction which is correct.

Here is my Code:

```
Vector3 targetPosition = kbcrd.playerToEngage.thirdPersonPlayerModel.shootTarget.position;
targetPosition .y = 0;

Vector3 botPosition = pb.thirdPersonPlayerModel.gunDirection.position;
botPosition.y = 0;

Quaternion targetRotation = Quaternion.LookRotation(targetPosition - botPosition);

//pb is Bot which is holding transform and other scripts.
pb.transform.rotation = Quaternion.RotateTowards(pb.transform.rotation, targetRotation, kbcrd.lookingInputSmooth);

```

What I Get from the above code is this: (Screenshot # 1)

---

What I want is this: (Screenshot # 2)

Guns And player Orientation:

Full function if needed:

```
public override void WriteToPlayerInput(Kit_PlayerBehaviour pb)
{
    CampaignModeControlRuntimeData kbcrd = pb.botControlsRuntimeData as CampaignModeControlRuntimeData;
    CampaignModeEnemyAI botCampaignModeAI = pb.gameObject.GetComponent<CampaignModeEnemyAI>();

    if (botCampaignModeAI.enemyInRange)
    {
        if (kbcrd.enemyPlayersAwareOff.Contains(botCampaignModeAI.detectedEnemies) == false)
        {
            kbcrd.enemyPlayersAwareOff.Add(botCampaignModeAI.detectedEnemies);
        }

        kbcrd.playerToEngage = botCampaignModeAI.detectedEnemies;
        //CheckForEnemies(pb, kbcrd);
    }
    else
    {
        kbcrd.playerToEngage = null;
    }

    UpdateAimPosition(pb, kbcrd);
    FiringDecision(pb, kbcrd, botCampaignModeAI.enemyInSight);
 }

```

Any help is appreciated. I know its simple problem but I struggling now. :(

# Answer
> 0 votes
Thanks to @derhugo for answering this on Stack overflow Link to Answar

So the problem was basically the offset distance between the gun and the bot. So the Code mentioned in the question was just rotating Bot toward the player while not including the offset between the gun and bot. Here is the final code:

```
var targetPosition = kbcrd.playerToEngage.thirdPersonPlayerModel.shootTarget.position;
targetPosition.y = 0f;

var botPosition = pb.thirdPersonPlayerModel.gunDirection.position;
botPosition.y = 0f;

var gunForward = gunDirection.forward;
gunForward.y = 0f;

var botForward = pb.transform.forward;
botForward.y = 0f;

// Get the offset between the bot's and the gun's forward vectors
var gunBotOffset = Vector3.SignedAngle(gunForward, botForward, Vector3.up);
// Get a rotation to rotate back from the gun to the player direction
var gunToBotRotation = Quaternion.AngleAxis(gunBotOffset, Vector3.up);

// Add the back rotation to the target rotation
var targetRotation = Quaternion.LookRotation(targetPosition - botPosition) * gunToBotRotation;

pb.transform.rotation = Quaternion.RotateTowards(pb.transform.rotation, targetRotation, kbcrd.lookingInputSmooth);

```

**Note:** Mentioned code is the copy of the "@derhugo" code from stack overflow.

# Answer
> 1 votes
Check this link. In your case, it would be, I think:

```
Vector3 targetPosition = kbcrd.playerToEngage.thirdPersonPlayerModel.shootTarget.position;
targetPosition .y = 0;

Vector3 botPosition = pb.thirdPersonPlayerModel.gunDirection.position;
botPosition.y = 0;

Vector3 targetDirection = targetPosition - botPosition;

float singleStep = speed * Time.deltaTime;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetPosition, singleStep, 0.0f);

pb.transform.rotation = Quaternion.LookRotation(newDirection);

```

I hope it works, I didn't try it :)

EDIT 1: This assume that you put this code in the update function

---
Tags: unity, rotation, quaternion, bot
---


# Question
Title: Set up Android SDK path to make Android remote work on Ubuntu
I used Unity 2019.4 on Ubuntu 20.04. I installed Android SDK and all other components through Unity Hub. But unfortunately, I can't use Unity remote. It's written : Set up Android SDK path to make Android remote work. I need help. Thanks

# Answer
It might be related to Unity issue found since 2019.3. See this issue on Unity issue tracker. It shows how to resolve issues regarding OpenJDK, Android SDK and NDK.

### Solutions, provided in the link

In case the link becomes inaccessible, here's a qoute from the link.

> 1. The executables in OpenJDK (Editor/Data/PlaybackEngines/AndroidPlayer/OpenJDK) don't have the right permissions for execution (possibly due to wrong compression/uncompression of JDK archive) - "chmod +x OpenJDK" fixes the JDK location.
> 2. Android SDK (Editor/Data/PlaybackEngines/AndroidPlayer/SDK) is missing the tools directory in it. Copying the tools dir from somewhere else fixes SDK.
> 3. Android NDK is unpacked to the wrong directory (Editor/Data/PlaybackEngines/AndroidPlayer/NDK/android-ndk-r19 instead of Editor/Data/PlaybackEngines/AndroidPlayer/NDK, compared to other platforms) - moving the contents to the correct directory fixes NDK.
> 2 votes

# Answer
I was having the same issues on Windows, with the latest Unity 2019.4 installed from Unity Hub 2.3.2. Just figured out how to get remote working. My solution was to install and run Android Studio(unlike for Unity 2018, having to just download SDK) to configure the SDK. After installing and finishing the setup wizard, there is a "Configure" button on the bottom of the Welcome screen, click to navigate to "SDK Manager". The SDK Manager should open up to the "SDK Platforms" tab in the "Android SDK" option under "System Settings" on the left hand side. Here, you should make sure the Android version you will be running the remote on is checked. Then, in the tab next to the platforms one labeled "SDK Tools" make sure "Google USB Driver" is also checked. Apply the changes with the button at the bottom and wait for the changes to be downloaded and installed. Now, in SDK Manager still, you can copy the location of the newly optimized SDK into your Unity project preferences. Before I tested the remote, I made sure on my phone USB debugging was enabled and that when connecting my phone to the computer: the USB Option on my it was set to "Charging Only" (I had changed it to Media Sync some time ago and forgot), this allowed my phone to recognize my computer's RSA fingerprint when connecting with a cable. After that, I played a test scene, and got it working like before. Sorry if what I typed was too long, but would like to know how it turns out for you.
> 2 votes

---
Tags: unity, android
---


# Question
Title: Initial setting of camera and ppu to match playing table
My goal is to implement another board game as close as possible as I would play it on a table - to not much think about how to arrange elements. The used space on table is in the dimensions of around 1x2m and most of my assets are scans of game cards with a touch of Photoshop (for personal use only). My question is regarding the camera, pixel on import of asset and converting to units. There are no physics in the game involved and it is 2D. For now it will be tailored to my own mobile but I would like to know if one way is preferred if I wanted to later change resolution or is just better best practice. From my understanding it would result both in the same outcomes but there might be some hidden trouble or side effects.

* Should I (convert for myself to get a feel for dimensions) take 1 unit as 10cm -\> scene of 10x20 units would represent my table or rather have a 1x2 unit scene (since most take one unit as one meter)
* Assuming my scanned card has something like 2000x1000 pixel (and is 10x5cm big on a real table), does it make more sense to have it imported as 2000/20000 under pixel per unit or downscale the image first before importing it with a lesser value? I don't really care currently about build/ asset size.

# Answer
Your choice of units within these ranges doesn't matter that much. The math all works out the same.

Usually units only start to be a problem if you're working exceptionally small (eg. 1 unit = 1 pixel) or exceptionally large (eg. 1 unit = 1 km).

Between metres and centimetres, there's not really enough of a magnitude gulf to be a problem, as long as you're close to the origin. So just use what you find comfortable.

Regarding the image size, it sounds like you already understand the trade-off you're making: import time and build size.

If you never plan to show the cards more than about 1000 pixels tall on a screen (filling the screen vertically at 1080p), the extra resolution doesn't really do anything for you, but if you're OK with larger build sizes / VRAM needs or longer import/build processes as the engine resamples the files down to your working sizes — or longer load times as the running game pulls in the whole texture and mip chain — then you can absolutely go either way.

I almost closed this question as opinion-based for these reasons, but hopefully sharing it as a answer makes it clearer why this is just a judgement call you'll need to make based on your own goals and preferred working style.
> 1 votes

---
Tags: unity
---


# Question
Title: Smoothly switch between 2 pairs of oscillating colors
I have a simple script that changes the emission color based on a bool.

* The first color is its idle color, which transitions between orange and light purple using a lerp weighted with a sine wave.
* The second color is its "isinDanger" state, and this lerps between orange and red.

Is there any way to make the transition between both of these color variants smooth? When the bool is set to true the colors switch instantly with no transition. I've tried numerous things to try to get them to be smooth but ultimately it just breaks the lerping.

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

public class GemGlowOrange : MonoBehaviour
{
    public Material Mat;

    Color Red;
    Color lightpurple;
    Color orange;

    public bool isInDanger = false;

    Color CurrentColor;
    float startTime;

    public float speed = 1.0f;

    void Start() {
        startTime = Time.time; // time since game started

        orange =  new Color(1.320755f, 0.5346785f,0.2928088f,1f); // making my colours RGBA

        Red = new Color(0.858f, 0f,0f,1f);

        lightpurple = new Color(1.320755f,0.2973427f,0.8263685f,1f);

        var Mat = GetComponent<Renderer>().sharedMaterial;
        // making a reference to the material so we can enable the emission keyword if you do not want this to affect every object using this
        //material then use "Getcomponent<Renderer>().material" the same goes with setting the color as you can see further down.

        Mat.EnableKeyword("_EMISSION"); // this is making sure this shader has the emission keyword enabled.
    }

    void Update() {

        float frac = (Mathf.Sin(Time.time - startTime) * speed);

        CurrentColor = Mat.GetColor("_EmissiveColor");

        if (!isInDanger) {
            Mat.SetColor("_EmissiveColor", Color.Lerp(lightpurple, orange, frac));
            // getting the same material over and over again each frame and updating its
            // emission colour
        } else if (isInDanger) {
            Mat.SetColor("_EmissiveColor", Color.Lerp(Red, orange, frac)); // if it is in danger then it will alternate between red and orange.
        }
    }
}

```

# Answer
> 1 votes
"I've tried numerous things"

Well, since you didn't tell us what "numerous things" you tried, we can't tell if you already tried just lerping your input colours, then lerping the result:

```
float dangerLevel;

void Update() {
    float transitionDuration = 0.5f;

    // Gradually transition between 0 (no danger) and 1 (danger)
    // over the specified transition duration in seconds.
    dangerLevel = Mathf.MoveTowards(
                     dangerLevel,
                     isInDanger ? 0f : 1f,
                     Time.deltaTime/transitionDuration);

    // Sine wave.
    float frac = Mathf.Sin(Time.time - startTime) * speed;

    // Our colour at the low trough of the sine wave is determined by our danger level.
    var lowColor = Color.Lerp(lightpurple, red, dangerLevel);

    // Our colour at the high peak of the sine wave is always orange.
    // (Though you could lerp a highColor variable for this purpose too).
    Mat.SetColor("_EmissiveColor", Color.Lerp(lowColor, orange, frac));
}

```

But that should cover what you need.

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


# Question
Title: Button not clickable if it's under a Content Size Fitter + Horizontal Layout Group in Unity?
I'd like to make a **Tooltip System**/**Tutorial System**.

I'm using the **Content Size Fitter** and **Horizontal Layout Group** components to have a dynamic text bubble..

Also I'd like to attach a **button** to it,

* so when the tooltip appears, the game pauses,
* and then when the player clicks the button, it closes the tutorial text, resuming the flow of the game.

But for some reason the click doesn't reach the component. **Not even the animation happen**, like something is blocking my button from being clicked.

**Hierarchy:**

**uiTutorialText**

* Has a CanvasGroup to fade the whole structure.

+ Interactable = true, BlocksRaycast = false

**TutorialText**

* Has an Image (background)

+ RaycastTarget = false
* Has a Content Size Fitter and a Horizontal Layout Group

And **Text** and **Button** are just simple plain Text and Button objects, and the Button's Interactable is true.

I also tried **making the Button a child of Text**, and then **translating it sideways**, so the button doesn't share screen space with the tooltip. But it's **not clickable** this way as well.

As soon as I move the Button **out of the hierarchy**, like directly under the canvas, it works.

# Answer
> 2 votes
> Has a CanvasGroup to fade the whole structure. Interactable = true, BlocksRaycast = false

Try checking "blocks raycast". CanvasGroup applies to the parent and all of its children. Unchecking "blocks raycast" is telling Unity "this object and all of its children should ignore the mouse".

---
Tags: unity
---


# Question
Title: Unity augmented reality app doesn't work on android
I am pretty new to unity and augmented reality applications. I use unity 2019.4.4f1 and my project is very simple as you can see in the screenshot below:

I am using Wikitude plugin for image tracking and the image i am using as the marker is the Jack of Clubs card as you can see in the assets. The project works fine when i press play and use my laptop's webcam , but when i build the project for android (unity 2019 automatically uses Gradle to build the project) and install the .apk file in my android phone, all i see on my phone screen when i open the application is:

As you can see the phone camera doesn't work and it gets stuck in this screen. How should i fix it? Does it have to do something with Gradle? I haven't tried using unity version 2018 to build it using the "Internal" build option. Anyways that's just my own thought and i might be wrong, but the final question remains which is how this problem can be fixed?

By the way i don't build the .apk file directly from the unity engine. I use the export option in unity to get a gradle project folder then i use that in Android Studio to build the final .apk file. The reason that i don't use unity to build .apk is that it gives errors and doesn't work for me so this is the solution i found for it.

**Update**: I debugged the application and it seems that the application needs camera permission to work, this is my debugging log:

```
07-22 17:47:16.908: E/Unity(32483): On Camera Error
07-22 17:47:16.908: E/Unity(32483):         Error Code: 1000
07-22 17:47:16.908: E/Unity(32483):         Error Domain: com.wikitude.camera.android
07-22 17:47:16.908: E/Unity(32483):         Error Message: Permission denied. Make sure to have camera permissions before trying to access the camera.
07-22 17:47:16.908: E/Unity(32483):
07-22 17:47:16.908: E/Unity(32483): (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)

```

I'm pretty sure that it didn't ask for camera permission, how should i allow the permission if it's not asking?

# Answer
Here's the documentation for requesting permissions. This is something you could have easily found with a web search.

I believe what you want in your code is this:

```
#if PLATFORM_ANDROID
    if (!Permission.HasUserAuthorizedPermission(Permission.Camera))
    {
        Permission.RequestUserPermission(Permission.Camera);
    }
#endif

```
> 0 votes

---
Tags: unity, android, augmented-reality
---


# Question
Title: Player freezes mid air when not also moving with WASD
Current issue: Player freezes mid air unless you are also using WASD to move around. Also, if you are not moving and you press space it wont jump until you start to move. Here is my script:

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

public class ThirdPersonPlayerController : MonoBehaviour
{
    public CharacterController controller;
    public Transform camera;
    public Transform groundCheck;

    Vector3 direction;
    Vector3 velocity;

    public float moveSpeed = 10f;
    public float turnSmoothTime = 0.1f;
    private float turnSmoothVelocity;
    public float gravity = -39.24f;
    public float groundDistance = 0.4f;
    public float jumpHeight = 3f;

    public LayerMask groundMask;
    private bool isGrounded;

    // Update is called once per frame
    // Unity is currently working on a new input system***
    private void Update()
    {
        IsPlayerGrounded();

        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        direction = new Vector3(horizontal, 0f, vertical).normalized; // direction player is moving

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            Jump();
        }
    }

    private void FixedUpdate()
    {
        MoveAndRotate();
    }

    private void MoveAndRotate()
    {
        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camera.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);
            //  Testing out gravity and this function as one

            Gravity();

            // end test
            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;

            controller.Move(moveDirection.normalized * moveSpeed * Time.fixedDeltaTime + velocity * Time.fixedDeltaTime);
        }
    }

    // Implemented proper gravity from /_\ y = 1/2g * t^2
    private void Gravity()
    {
        velocity.y += gravity * Time.fixedDeltaTime;

        /*controller.Move(velocity * Time.fixedDeltaTime);*/
    }

    // Check if player is grounded and reset velocity
    private void IsPlayerGrounded()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }
    }

    private void Jump()
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }
}

```

Any help would be much appreciated. I cannot seem to find any logical reason as to why this is happening!

# Answer
Expanding on DMGregory's comments:

In this line of code, `direction` could be (0, 0, 0) if the player has not made any input.

```
direction = new Vector3(horizontal, 0f, vertical).normalized;

```

Your MoveAndRotate code looks like this:

```
private void MoveAndRotate()
{
    if (direction.magnitude >= 0.1f)
    {
        [...]
        Gravity();
        [...]
        controller.Move(moveDirection.normalized * moveSpeed * Time.fixedDeltaTime + velocity * Time.fixedDeltaTime);
    }
}

```

Notice that `Gravity()` and `controller.Move()` will only get called if `direction` has a length greater than 0.1, but `direction` can have a length of 0 if the player has not made any input, so `Gravity()` and `controller.Move()` will not be called if the player has not made any input.
> 1 votes

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


# Question
Title: Wheel rotation for a raycast car in Unity?
I've been learning unity and 3d modelling over the last couple of months and I'm trying to set up a basic car game using raycasts, as the wheel colliders in unity aren't great.

Right now I'm trying to get the wheel mesh (wheelTransform in the code) to rotate with as the car moves.

I have the following line to get the speed of the car at the point where the raycast hits the ground in the local space of the car, in the direction that the car is facing.

`wheelForwardVelocity = transform.InverseTransformDirection(carRigidbody.GetPointVelocity(hit.point)).z;`

Then I have the following line to calculate how much the wheel must rotate each frame depending on wheelForwardVelocity. I am not implementing wheel slip at this point so I can just have the wheel rotate based on the car speed.

`wheelRotationAngleAddition = (wheelForwardVelocity * 360 * Time.deltaTime) / (Mathf.PI * 2 * wheelRadius);`

Finally I have the following 3 lines to add change the wheels rotation:

```
Vector3 rotation = wheelTransform.localRotation.eulerAngles;
rotation.x += wheelRotationAngleAddition;
wheelTransform.localRotation = Quaternion.Euler(rotation);

```

However, when I test the game in Unity the wheel rotation does not work:

At slow speeds, the wheel rotation seems to be right, but then it will (seemingly at random) start freaking out rotating back and forth. I cannot for the life of me figure out why! I would really appreciate any help :)

# Answer
Your rotation code looks like this:

```
Vector3 rotation = wheelTransform.localRotation.eulerAngles;
rotation.x += wheelRotationAngleAddition;
wheelTransform.localRotation = Quaternion.Euler(rotation);

```

Unity specifically recommends *not* changing the rotation in this manner, because of the possibility of gimbal lock and other conversion errors when converting back and forth with Euler angles. See example #2 of what not to do in the documentation, which looks almost exactly the same as your code.

A safer way is to use `transform.Rotate()`:

```
wheelTransform.Rotate(wheelRotationAngleAddition, 0, 0);

```
> 1 votes

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


# Question
Title: I'm trying to instantiate game object as a child of canvas in scene but it doesn't work
My problem is that I've prepared a class. Inside of this class i have a function to create a new modal window in scene as a child of canvas. I have another script in this script i am trying to create an object of first class and calling `OpenModalWindow` function through that object. It acctually spawns the modal window in the scene but not as a child of canvas.

The First Class:

```
public class WindowController : MonoBehaviour {
    public delegate void function();

    private Transform canvasTransform = null;
    private GameObject modalWindowObj = null;

    private void Awake()
    {
        canvasTransform = transform;
    }

    public void OpenModalWindow(GameObject modalWindow, string modalText, string button1Text, string Button2Text, function button1Func, function button2Func)
    {
        modalWindowObj = Instantiate(modalWindow, canvasTransform) as GameObject;
        this.modalWindowObj.transform.SetParent(canvasTransform);
    }
}

```

The Second Class:

```
public class ModalBoxTest : MonoBehaviour
{
    [SerializeField] private GameObject modalWindowRef = null;
    private WindowController test = new WindowController();

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            test.OpenModalWindow(modalWindowRef, "deneme", "evet", "hayir", test1f, test2f);

        }
    }

    private void test1f()
    {
        Debug.Log("yes!");
    }

    private void test2f()
    {
        Debug.Log("no!");
        test = null;
    }
}

```

# Answer
> 1 votes
```
private WindowController test = new WindowController();

```

This is not a safe way to create a type descending from `MonoBehaviour`. Unity warns you of this - so be sure you have warnings turned on in your Console window:

> You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all

These components have meaning only when they're attached to a `GameObject`, so creating one in this "free-floating" manner leaves it completely absent from your game scene, and unable to participate in most of the behaviours we expect from components - like having Unity call its lifecycle message functions including `Awake()`.

Since `Awake()` never gets called on this object, the `canvasTransform` variable still has the value `null` by the time you call `OpenModalWindow()`. Instantiating something with the parent `null` means placing it at the root level of the scene hierarchy.

It looks like what you want to do here is attach an instance of the `WindowController` script on your Canvas in the editor when you're setting up your scene. Then get a reference to this existing instance inside your `ModalBoxTest` by one of the usual ways:

* Make a `public` or `[SerializeField]` variable to hold the reference, and assign it at design time in the Inspector.
* Use `FindObjectOfType<WindowController>()` to look up the current instance at runtime.
* Use a singleton pattern or service locator to get the reference at runtime.

Or, if you don't have an existing Canvas that you want to attach to, you can spawn one at runtime like so:

```
// Create a new game object with the components we want.
var canvasObj = new GameObject("Canvas", new System.Type[] {
                     typeof(Canvas),
                     typeof(CanvasScaler) });

// For some reason, the raycaster doesn't seem to be
// created properly unless we do it in a second step.
var raycaster = canvasObj.AddComponent<GraphicRaycaster>();

// Configure your canvas as desired.
var canvas = canvasObj.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;

// Add our controller last, so by the time it gets Awake
// all the other components are configured as we want,
// and it can read any configuration it needs from them.
windowController = canvasObj.AddComponent<WindowController>();

```

---
Tags: unity
---


title: Placing Zones in Cities Skylines

text:
# Question
Title: Placing Zones in Cities Skylines
I'm trying to build a mod that places zones on a keypress. How would I accomplish this?

So far I've detected the keypress. But when I modify m\_blocks in ZoneManager by calling block.setZone(x,y,zone) The block appears to have changed, but only for the moment. When I run the keycommand again, the data appears to have been reset. I never see the zone change in game, only when I print it to the console.

```
string outtext = "";
            uint blockCount = Singleton<ZoneManager>.instance.m_blocks.m_size;
            outtext += "start{\n";
            for (int index = 0; index < blockCount; index++) {
                var block = Singleton<ZoneManager>.instance.m_blocks.m_buffer[index];
                if (block.m_valid != 0) {
                    block.SetZone(1, 1, ItemClass.Zone.Industrial);
                    block.RefreshZoning(0);
                    outtext += " valid:" + block.m_valid + " position:" + block.m_position.ToString() + " zone:" + block.GetZone(1, 1) + " \n ";
                }
            }
            outtext += "}";
            Debug.Log("OUTTEXT " + outtext);

```

I've tried calling block.refreshZoning() as well, but I'm not sure how to calculate the blockid :(.

# Answer
The problem was that the equals operator does a deepcopy. I was able to fix this by forcing it to use a reference. This took forever to find out!

```
string outtext = "";
            uint blockCount = Singleton<ZoneManager>.instance.m_blocks.m_size;
            outtext += "start{\n";
            for (int index = 0; index < blockCount; index++) {
                ref var block = ref Singleton<ZoneManager>.instance.m_blocks.m_buffer[index];
                if (block.m_valid != 0) {
                    block.SetZone(1, 1, ItemClass.Zone.Industrial);
                    block.RefreshZoning(0);
                    outtext += " valid:" + block.m_valid + " position:" + block.m_position.ToString() + " zone:" + block.GetZone(1, 1) + " \n ";
                }
            }
            outtext += "}";
            Debug.Log("OUTTEXT " + outtext);

```
> 1 votes

---
Tags: unity, c#, modding, mono
---


# Question
Title: Default Game Window Size To Take While Making Games
I am planning to make a game for mobiles and tablets, I wanted to know what would be the default resolution that I should set for my game so that it covers all or most of the devices out there.

I read an article someplace that says we should design the game for lowest resolution like 480 x 360 and then scale it according to devicePixelRatio for the target device, Is this the right approach because according to me it will be good only for devices that have 3:2 resolution but what about other 16:9, 16:10 etc

So What should be the base resolution I design my game so that it gets scaled to all mobiles and tablets?

# Answer
> 2 votes
*Disclaimer: talking from Unity game development experience.*

# It is not about resolution...

Base resolution has very little to do with responsive UI. UI elements can be up-scaled or down-scaled. Resolution pretty much only gives you sharpness (or more space if you don't scale your elements accordingly (would not recommend)).

Personally, I choose 1920x1080 (Full HD) as a base resolution. Because it has fairly decent amount of pixels to play with and it used to be a fairly common screen resolution for mobile devices.

# ... it is about layout and design

What makes UI look good on different sized screens is its design.

For example, you want to make your buttons centered. Writing screen coordinates (let's say X: 640, Y: 480) position will make those buttons look different on 720p and 1080p screens. **BUT...** if you make them anchor on center of the screen and have offset from it, they will look identical.

# What to do?

When designing your UI, think of where it should be placed RELEVANT to something. Let's say, I want my buttons to be spaced at UPPER RIGHT CORNER, I will anchor them to top-right corner and then make positional offset from there. This way, when screen size is changed (aspect ratio and/or resolution), my buttons will still stay at top-right corner.

P.S. apparently @Philipp said the same thing just in other words.

# Answer
> 1 votes
Unfortunately there are so many different devices with so many different resolutions and aspect ratios that there is no one default screen size you can assume. So you have to design your game's UI in a way which looks reasonable well on any device some player might own. You will have to create a responsive layout where UI elements are positioned relative to their closest screen corner or screen edge center and which scale with the device pixel ratio. Then you have to continuously test your UIs with lots of different screen sizes to make sure the layout works on any one.

---
Tags: 2d, javascript, mobile, resolution
---


# Question
Title: What causes skating feet in Unity (but not in mixamo or Autodesk FBX review)?
I have uploaded a model to mixamo.com. In mixamo, I've applied an animation, and in the mixamo preview window, the feet are perfectly stable, they don't skate at all.

I have downloaded the resulting fbx animation together with the skin, and I have opened it up in Autodesk FBX review.

In Autodesk FBX review, the feet are also perfectly stable.

I have then imported the fbx in Unity without changing anything.

In the animation preview window, the feet are skating.

Why is that so, and how do I get rid of it?

# Answer
I found out that the skating feet were caused by the option "Anim. Compression: Keyframe Reduction" in the Unity Animation tab.

Once I set Anim. Compression to "Off", the skating feet were gone.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Jumping up quicker? (Paper Mario style jump)
As shown here, Paper Mario's jump takes 8 frames go reach the max jump height and 12 frames to get back to the ground. This is pretty unusual, any idea how to jump up that quick with a rigidbody?

I tried to `AddForce` when `rigidbody.velocity.y > 0`, but that didn't work out.

Any help would be appreciated, thanks in advance!

```
//Jump when pressing button and on ground
//jumpForce is a public float variable

if (Input.GetButtonDown("Jump") && isGrounded)
{
    theRB.velocity += new Vector3(0, jumpForce, 0);
}

```

# Answer
When jumping, set a flag (e.g., `isJumping`) that indicates that the player jump is in action. Then, in update make checks if the vertical velocity is negative (falling down) and player is jumping. If it is:

* for Rigidbody2D - reduce rigidbody's gravity scale to *0.67* (`8 / 0.67 ~= 12`).
* for Rigidbody (3D) - add velocity as such: `rigidbody.AddForce(Vector3.up);`

When player hits the ground, restore gravity scale to *1* and remove `isJumping` flag.
> 1 votes

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


title: Leaderboard not working in Unity

text:
# Question
Title: Leaderboard not working in Unity
I'm trying to create a leaderboard for my game. I have the game created and added the leaderbaord using cloudonce. I have also created the app on google play console and linked the app to the game services. I have followed the following tutorial to create the leaderboard: Leaderboard tutorial

I have followed the exact same instruction as given in the tutorial. Once the game is over, the leaderboard button is activated. I have attached LeaderboardsButton script(this script comes with the CloudOnce package) to the leaderboard button. Here is the code in the game over panel for getting the score:

```
void OnEnable()
{
    DisplayGameOverScore();
}
void DisplayGameOverScore()
{
    gameOverScore.text = ((int)gameManager.playerScore).ToString();
    gameOverHighScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
    CloudOnceServices.instance.SubmitScoretoLeaderboard(PlayerPrefs.GetInt("HighScore", 0));
}

```

This is the CloudOnceServices script as per the tutorial:

```
public static CloudOnceServices instance;

private void Awake()
{
    TestSingleton();
}

private void TestSingleton()
{
    if (instance != null)
    {
        Destroy(gameObject);
        return;
    }
    instance = this;
    DontDestroyOnLoad(gameObject);
}

public void SubmitScoretoLeaderboard(int score)
{

    Leaderboards.HighScore.SubmitScore(score);
}

```

I have attahced this script to an empty game object along with the InitializeCloudOnce script(this is provided with the CloudOnce package).

I have also created an alpha test on googleplay. Once I open the link and start the game, the google play services console open and when I hit the leaderboard button, google play services console loads but after that nothing happens. It just goes back to the game. I read that other people ran into similar issues and the advise given was to check if the SHA1 certificate fingerprint is the same in app signing under release management and the credentials in GoogleApis. They both match. I'm not sure what the issue is?

# Answer
It's probably an authentication problem. In case you're allowing Google to sign your APKs it means only the builds downloaded from the Playstore will be authenticated. If you build any new APKs without uploading them to your developer account you have to add your local build's SHA1 cert to the API console and link it to your app on the Google developer console before it can authenticate users.
> 1 votes

---
Tags: unity, leaderboards
---


# Question
Title: 2D Grid-based Pathfinding with Elevation
I'm creating an isometric game which currently uses A\* Pathfinding on a basic grid representation of the map.

Having elevations and allowing the Players to traverse up-and-down is an integral part of the game - however I'm stuck on exactly how to implement that, whether it be with A\* or something else.

For example,

```
---------------------------------
| 0 | 0 | 0 | X | 0 | 4 | 4 | 4 |
---------------------------------
| 0 | 0 | 0 | 0 | 0 | 4 | 4 | 4 |
---------------------------------
| 0 | 0 | 1 | 2 | 3 | 4 | 4 | 4 |
---------------------------------

```

Assuming `X` is the Player, the numbers are tile elevations, and that the Player can only traverse tiles +/- 1 elevation to the tile they're currently on, is there an accepted/known way of doing this pathfinding?

# Answer
Inside your A\* algorithm, you have a loop where you iterate over the reachable nodes neighbouring the current node under inspection. If the elevation disparity between the two nodes is greater than your threshold, it is not reachable. You skip over that neighbour, so the algorithm doesn't try traversing the edge between these two nodes.

It might help if you edit your question to elaborate on where specifically you've run into trouble incorporating this elevation check into your particular A\* implementation.
> 1 votes

---
Tags: javascript, path-finding, node.js
---


# Question
Title: Mirror/Unet, RegisterSpawnHandler throws invalid asset Id error because assetId is 0 for dynamically loaded assetbundles
Its weird how documentation literally states that

> For more advanced uses, such as object pools or dynamically created Assets, you can use the ClientScene.RegisterSpawnHandler method

But seems like its broken, because dynamically loaded objects' assetIds' are always 0:

(This is true for all other dynamically spawned objects)

My code structure:

I have a "MapLoader" script that loads objects from filesystem using its config file.

MapLoader creates vehicles and assigns them unique UIDs that are same across players.

Vehicles are added into Static dictionary with UID -\> vehicle key/value pairs, and to a list of GameObjects:

```
        VehicleNetworking vehicleNet = spawned.AddComponent<VehicleNetworking>();
        vehicleNet.vehicleScript = vehicleScript;
        vehicleNet.uid = uid;

        spawned.tag = "vehicle";
        spawned.layer = 10;

        GameManager.vehiclesToSpawn.Add(spawned);
        GameManager.AddVehicle(vehicleNet);
    }

```

After vehicles have been added, I call functions on the local Player object to spawn them:

```
  foreach (GameObject vehicle in GameManager.vehiclesToSpawn)
    {
        if (isServer)
        {
            SpawnServerVehicles(vehicle);
        }
        else
        {
            SpawnClientVehicles(vehicle);
        }
    }

```

Spawn scripts:

```
[Server]
void SpawnServerVehicles(GameObject vehicle)
{
    Debug.Log("Server should spawn: " + vehicle.name);
    NetworkServer.Spawn(vehicle);
}

[Client]
void SpawnClientVehicles(GameObject vehicle)
{
    Debug.Log("Client should spawn: " + vehicle.name);

    MD5 md5 = MD5.Create();
    string vehicleId = vehicle.GetComponent<VehicleNetworking>().uid;
    byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(vehicleId));

    Guid result = new Guid(hash);
    Debug.Log(vehicle.name + "-" + result);
    ClientScene.RegisterSpawnHandler(result, SpawnHandler, UnSpawnHandler);
}

```

Spawn handlers:

```
private static GameObject SpawnHandler(Vector3 position, Guid vehicleGuid)
{
    Debug.Log("Called Spawn Handler");
    GameObject go = new GameObject();
    return go;
}

private static void UnSpawnHandler(GameObject gameObject)
{
    Destroy(gameObject);
    Debug.Log("Called UnSpawn Handler");
}

```

If I am doing everything right, and Mirror library is actually broken, then I'd like to know what could the workarounds be?

My goal is to have SyncVars on vehicles working and syncing with the server(But for this, I need to have NetworkIdentity on vehicles, and for them to work, they need to be spawned using `NetworkServer` or `ClientScene`).

# Answer
Didn't really solve this particular problem, but found a much nicer working workaround.

Created a Dummy prefab with my vehicle's netcode attached to it(Note, I separated vehicle physics code and vehicle input netcode, left physics code on vehicle object where it belongs). Saved this dummy as an asset, added `NetworkIdentity` component to it and added it into `NetworkManager`.

Now all is left is to spawn vehicles based on config files locally on each client (like in singleplayer mode, without any NetworkServer interactions, just simple `instantiate`), and spawn this dummy prefab that I called "VehicleNetworkingController" from Player.cs code(Important, make sure you are spawning other networkidentities from local server player) like this:

```
//This is just a VehicleNetworkingController prefab from game Assets
public GameObject vNetControllerPrefab;

GameObject SpawnVNetPrefab(GameObject vNetController)
{
    //Could as well just use [Server] but whatever
    if (isServer)
    {
        if (isLocalPlayer)
        {
            var controller = Instantiate(vNetController);
            controller.tag = "vNetController";
            NetworkServer.Spawn(controller);

            return controller;
        }
    }
    return vNetController;
}

IEnumerator WaitForVehicles()
{
    while (!GameManager.isReady)
    {
        yield return new WaitForSeconds(0.15f);
    }
    foreach (GameObject vehicle in GameManager.vNetControllersToSpawnFor)
    {
        SpawnVNetPrefab(vNetControllerPrefab);
    }
}

```

Basically I am spawning VehicleNetworkingController(Dummy prefab containing vehicles netcode) using NetworkServer.Spawn(If on server), nothing special.

On client, every VehicleNetworkingController(That already will exist in clients' scenes automatically on connection because Server used NetworkServer.Spawn(instantiate) to spawn it) has this function that registers itself:

```
public readonly SyncListItem passengers = new SyncListItem();

public VehicleControllerDynamic vehicleScript;

[SyncVar]
public string bintVehicleId = "";

[SyncVar]
public float forward, sideways, braking;

private void Start()
{
    //Use Static classes like GameManager in my case, for storing and accessing info
    //Anytime and anywhere, very handy.
    GameManager.AddVNetController(this);

    //Registering dummy prefab so now its networkIdentity gets synced with server. Now you can bind it to vehicle's MonoBehaviour physics handling script and sync variables from this spawned prefab to it.

    //Basically we spawned prepared prefab to control dynamically generated assetbundle prefabs

    ClientScene.RegisterPrefab(gameObject);

    //I found using Coroutines with static classes very handy too. Mostly using them to wait for other scripts/objects to load and only
    //then continue execution while not freezing a game.
    StartCoroutine(WaitForBint());

}
...

```

This technique resulted in more organized code I'd say, and it also rendered `ClientScene.RegisterSpawnHandler` function basically useless.
> 1 votes

---
Tags: unity, c#, unity-networking, unet, mirror-networking
---


# Question
Title: Can I bring features of an Android game into another Android game?
Platform : Android

Overview : Fifa 14 by EA sports has a manager mode, kick off and tournament mode in it, which was the last game of its series on android to have these features. Fifa 16 has great graphics, better controls and much more but it lacks the manager mode, kick off, tournament mode and is completely online.

Question : Is it possible to replicate the manager mode, kick off, tournament mode (by replicate I mean to code these features or copy paste them with or without modification from fifa 14 to fifa 16). Fifa 14 has been taken out from play store, so I think it is fine if this mod is made. And yeah, this is only for non commercial use. Please can someone experienced put light to this matter.Also please specify how, I am a complete noob.

# Answer
> 4 votes
> Is it possible to replicate ...

These are two different software. Software like these can change *a lot* from version to version. So you can't assume that you'll be able to "copy-paste" code from a game to another. So no, don't expect it is possible.

> Fifa 14 has been taken out from play store, so I think it is fine if this mod is made.

This does not remove the license that is attached to the software. You would need to look at the specific licenses that come with the games, but here is an excerpt of what is currently available online (emphasis mine):

> You may not access, copy, modify or distribute any EA Service, Content or Entitlements (as those terms are defined below), unless expressly authorized by EA or permitted by law. **You may not reverse engineer or attempt to extract or otherwise use source code** or other data from EA Services, unless expressly authorized by EA or permitted by law.

So no, even if it has been taken out from the store, you cannot dig into the app.

> And yeah, this is only for non commercial use.

This does not matter, a license is a license, and a copyright is a copyright, money involved or not, you are bound by the license, and you don't own the copyright.

> I have both games obb and apk files. I am able to access all the files of both the games.

I suspect that you have assets and binary files. The code, what glues the assets together and displays it on your phone, is compiled; you would need to decompile it and figure out what is going on. It could probably be done. But the license does not allow it.

---

What can you do? Write a new game including the features of both; try to figure out what are the elements that made you enjoy both games, and try to replicate them in your new game.

---
Tags: android, legal, modding
---


# Question
Title: Why does masked animation look so strange?
I have an idle and a shooting animation. Both animations are perfectly tailored to my model.

The idle animation looks like this:

And the shooting animation looks like this:

I have 2 animation layers:

The "Base" layer plays the idle animation. The "Pistol Shooting" layers plays the pistol shooting animation, and it has an avatar mask because it should only influence the upper body.

The results however look like this:

What might be wrong here? What could I check?

# Answer
> 2 votes
I believe the solution was to exclude "abdomen". As far as I could tell it now looks as expected.

---
Tags: unity, animation
---


title: Transform.Rotate is jumping around

text:
# Question
Title: Transform.Rotate is jumping around
Why is the parent that contains 4 children jumping around and then settling into a position instead of rotating once by 90 deg? I can't seem to get it to rotate a single time as expected.

```
using UnityEngine;

public class rotateparent : MonoBehaviour
{
    public Vector3 rotationPoint;
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            transform.Rotate(new Vector3(0, 0, 1), 90);
        }
    }
}

```

Object jumping when mouse clicked

# Answer
`GetMouseButton(0)` returns true *every* frame the mouse button is pressed. So if you hold the button for three frames, you get three rotations. This is very easy to do if your framerate is high, like in a nearly-empty scene like this.

To rotate just once per click, you should use `GetMouseButtonDown(0)` which returns true just once for each time the mouse button transitions from up to down, and not again until it's released and pressed a second time.

In future, you can diagnose this type of issue by adding a `Debug.Log()` to your code to print out a timestamp every time the condition is true, or using a breakpoint to step through each time this piece of code gets hit.
> 1 votes

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


# Question
Title: Unity animation transition with 0 Exit Time doesn't transition immediately
**Question**

Why doesn't an animation transition with an Exit Time of 0 immediately transition to the next state?

---

**Minimal example**

Using Unity 2018.3, I set up an `AnimatorController` with two states: `Initial` and `Next`. I wanted `Initial` to transition to `Next` immediately, so I tried setting an Exit Time of 0. However, this doesn't transition immediately:

As shown above, `Initial` state still runs instead of transitioning immediately to the `Next` state. (There is no `Motion` attached to the `AnimationState`, so perhaps it's using a default duration.)

Below are screenshots of my animation transition settings.

---

**Strange behaviour with small non-zero ExitTime**

I also tried using an Exit Time of 0.01 (i.e. transition after 1% of the animation has played), and it transitions almost immediately as I expect most of the time. However, occasionally it will still play the `Initial` state:

In this case, even though it transitions to `Next` immediately most of the time, it still occasionally waits for the `Initial` state to complete. (It happens much less frequently than the image above suggests, but the issue becomes more frequent if I set the ExitTime even lower, e.g. 0.003).

---

**Workaround**

From searching online, the recommended solution for immediate animation transitions seems to be to turn off Exit Time and use a condition (e.g. bool or trigger) to transition immediately instead.

(Edit: in my case, I've defined an animator bool parameter called `ImmediateTransition` and set it to `true` by default instead of using Exit Time 0.)

This seems to work, but I would like to better understand how Exit Time works and why it's not working the way I expect.

# Answer
I'm trying to focus on the question being about how **Exit Time** might work and WHY this specific behaviour happens.

I think what's likely happening, is that the way Animator States evaluate/tick their logic, including exit time and conditions, is that when a State is updated it's normalized time is incremented first and logic is run only after that. So a State that just starts to play almost never starts at normalized time zero, rather at zero plus whatever the delta time was for the animator that frame.

I tested this by creating a StateMachineBehaviour Script that prints out the **StateInfo.normalizedTime** in **OnStateUpdate**(...) method, but only once per State entry (so only on first frame of it updating) and the results we're like expected, never zero, but always just a tiny bit over.

You can repeat the test yourself, by making a StateMachineBehaviour with these contents and attaching that SMB to some State.

```
    private bool FirstFrameConsumed;

    /// <summary>
    /// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    /// </summary>
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        FirstFrameConsumed = false;
    }

    /// <summary>
    /// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    /// </summary>
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if ( FirstFrameConsumed )
        {
            return;
        }

        FirstFrameConsumed = true;
        Debug.Log(stateInfo.normalizedTime);
    }

```

I think this also explains why exit times like 0.01 and lower *occasionally* seem to cause and immediate transition, but why that behaviour is irregular (the delta time on first frame of state is inconsistent, at least when Animator updates in **Update Mode: Normal**).

Secondly, this brings to light how States seems to handle their conditional checks for Exit Time. Since **Exit Time = 0** won't transition if State starts at **normalizedTime = 0.00056** (random, small increment of delta time at state entry), it's reason to suspect that a transition only occurs if it's conditions (Exit Time being a condition) are fulfilled *before* the normalizedTime passes its Exit Time.

This second assumption I tested by creating a simple AnimatorController setup with empty states (which have some default duration or around a second or so), then slowed down the states so I can manually toggle some AnimatorControllerParameters and observe how the transitions are evaluated.

Transitions:

* Reset (Trigger) parameter immediately transitions to state A, 0-length transition.
* A-to-B: TriggerB Condition, Exit Time 0.5, 0.5 normalized length transition.

Scenario 1: I set TriggerB right at start of A. At 0.5 normalizedTime the trigger is consumed and transition to B starts to proceed.

Scenario 2: I set TriggerB ***after*** Exit Time (normalizedTime \> 0.50), TriggerB remains unconsumed until next loop when normalizedTime just passes the Exit Time.

While this behaviour is handy for guaranteeing you can setup transitions that always start at a fixed point and produce a consistent-looking blend between two states, this does sometimes feel unintuitive (I'd personally expect the conditions to trigger the transition anywhere between exit time and end of state/loop), often making it tricky to create dynamic transitions with the builtin tools.
> 1 votes

# Answer
**Has Exit Time:** Exit Time is a special transition that doesn’t rely on a parameter. Instead, it relies on the normalized time of the state. Check to make the transition happen at the specific time specified in Exit Time.

**Exit Time:** If Has Exit Time is checked, this value represents the exact time at which the transition can take effect. This is represented in normalized time (for example, an exit time of 0.75 means that on the first frame where 75% of the animation has played, the Exit Time condition is true). On the next frame, the condition is false.

**Fixed Duration:** If the Fixed Duration box is checked, the transition time is interpreted in seconds. If the Fixed Duration box is not checked, the transition time is interpreted as a fraction of the normalized time of the source state.

**Transition Duration:** The duration of the transition, in normalized time or seconds depending on the Fixed Duration mode, relative to the current state’s duration. This is visualized in the transition graph as the portion between the two blue markers.

**Transition Offset:** The offset of the time to begin playing in the destination state which is transitioned to. For example, a value of 0.5 means the target state begins playing at 50% of the way through its own timeline.

**Interruption Source:** Use this to control the circumstances under which this transition may be interrupted.

**Ordered Interruption:** Determines whether the current transition can be interrupted by other transitions independently of their order.

**Conditions:** A transition can have a single condition, multiple conditions, or no conditions at all. If your transition has no conditions, the Unity Editor only considers the Exit Time, and the transition occurs when the exit time is reached. If your transition has one or more conditions, the conditions must all be met before the transition is triggered.

A condition consists of:

* An event parameter (the value considered in the condition).
* A conditional predicate (if needed,for example, ‘less than’ or ‘greater than’ for floats).
* A parameter value (if needed).

If you have Has Exit Time selected for the transition and have one or more conditions, note that the Unity Editor considers whether the conditions are true after the Exit Time. This allows you to ensure that your transition occurs during a certain portion of the animation.

For more information please visit: Unity Manuel.
> 3 votes

---
Tags: unity
---


# Question
Title: How to implement the “technological tree” drawing?
I want to make a tech tree at least like in Civilization, but I don't know how to do it. I want to fill in some data structure and then display it on the screen in the form of a technology tree, but I don't know how to implement it in code.

The only way I came up with was:

```
public class Technology1
{
String name;
TextButton button;
LinkedList<Technology1> NextTech;
}

```

TextButton is the libGDX class with which I was going to display each individual technology on the screen.

LinkedList NextTech- all technologies that are accessed after studying the current one are stored here. In other words, "children" are stored here . The problem is how to set the coordinates for all technologies when rendering the tree, so that the technologies do not overlap when displayed and so that the whole looks more or less normal.

If I started to do it wrong, then please tell me a more correct option.

# Answer
> 1 votes
Your implementation looks about right. Just a few code-review changes so it matches Java code styleguide. Remember constructors, getters, and setters:

```
public class Technology {
    private String name;
    private Array<Technology> nextTechnologies; // LibGDX's "Array" is a more efficient list
}

```

As you can see I removed the button from the technology class. It is good practice to separate game logic (the technology tree) from the graphical side (the tech tree graphical layout).

As for the actual layout I would personally manually position all the elements unless you have a massive amount of technologies (100s).

```
public class TechnologyLayout {
    private Sprite sprite;
    private Vector2 position;
}

public class TechTreeDrawer {
    private ObjectMap<String, TechnologyLayout> layoutMapping;
    private Technology root;

    public void draw() {
        draw(root);
    }

    private void draw(Technology tech) {
        TechnologyLayout layout = layoutMapping.get(tech.getName());

        // draw somehow using the sprite and position
        batch.draw(layout.getSprite(), layout.getPosition());
        tech.getNextTechnologies().forEach(this::draw);
    }
}

TechTreeDrawer drawer = new TechTreeDrawer(root);
drawer.addPosition("Computers", new Vector2(100, 100));
drawer.addPosition("Agriculture", new Vector2(0, 0));
drawer.draw();

```

If you are dead set on positioning the graph using an algorithm there are several papers on graph layouts. There are also graph layout libraries written in Java. A simple google should lead you to both.

---
Tags: java, tree
---


# Question
Title: Unity3D URP - How do I approach creating Fog of War for 3D top-down stealth game?
What I try to achieve is a fog of war system for 3d top-down stealth game. I have searched the Internet and it seems that behavior I want to achieve can be done by using secondary camera that is rendering its output to a render texture. Then render texture is applied to a plane which sits above a map with a masking shader. I was following this video: https://www.youtube.com/watch?v=PNAvNeOTnSE however my project is using URP in Unity and the Clear Flags on camera settings is missing. So basically after each rendering loop render texture gets cleared and drawn again which makes impossible to "save" areas that already have been revealed by the player.

Maybe this can be done using another technique? I would like to have fog of war that covers entire rooms with black opaque plane and reveals them upon entering them but remains cleared once visited. However visited areas should be gray once left and enemies should be hidden from the player when not in line of sight. Something like in this video: https://youtu.be/jrK\_Uvwwk9I?t=1247

I would really appreciate if someone pointed my in right direction.

# Answer
> 1 votes
Until recently, camera stacking used to be unavailable in the URP. But with the newest release 2020.1 (released just yesterday), it's available again. Although with two limitations: It's unavailable when using the 2D Renderer or when using the VR Multi Pass mode. But there is a promise that this will change "soon™".

From the documentation linked above:

> 1. Create a Camera in your Scene. Its Render Type defaults to Base, making it a Base Camera.
> 2. Create another Camera in your Scene, and select it.
> 3. In the Camera Inspector, change the Camera’s Render Type to Overlay.
> 4. Select the Base Camera again. In the Camera Inspector, scroll to the Stack section, click the plus (+) button, and click the name of the Overlay Camera.
>
> The Overlay Camera is now part of the Base Camera's Camera Stack. Unity renders the Overlay Camera's output on top of the Base Camera's output.

---
Tags: unity, shaders, compute-shader, fog-of-war
---


# Question
Title: How can I make particles move like a square in Unity?
I would like to implement something like this in Unity:

I searched for how to implement such a functionality but only found stuff for circles which does not work with box shapes. How can I implement this?

# Answer
Create a particle system as a child of the sprite. Set it to create particles in world space, so spawned particles don't move when the system itself moves. That creates a "trail" effect like you see here.

Then create a looping timeline to create an animation to move the position of the particle effect around the sprite in any paths you want. A timeline can also be used to control any other settings of particle effects over time, which allows you to sequence some really neat choreographies for them.
> 0 votes

---
Tags: unity
---


# Question
Title: How to make Rigidbody.AddForce less delayed in Unity3D?
I'm trying to make it so that when the player in my game moves left or right, he lightly jumps from his current position to his new position. The way I have it set up now, the jump occurs once he has arrived at his new position. What can I do to make it so that the jump happens sooner so that it appears that he jumps to his new position? Here is the code I have that controls that part of his movement:

```
if (Input.GetKeyDown(KeyCode.LeftArrow) && transform.position.x > minXPos)
    {
        targetPos = new Vector3(transform.position.x - xIncrement, transform.position.y, transform.position.z);
        rb.AddForce(Vector3.up * jumpForceTwo, ForceMode.Impulse);
        transform.position = Vector3.MoveTowards(targetPos, transform.position, speed);
        isHorizontalingLeft = true;
    }
else if (Input.GetKeyDown(KeyCode.RightArrow) && transform.position.x < maxXPos)
    {
        targetPos = new Vector3(transform.position.x + xIncrement, transform.position.y, transform.position.z);
        rb.AddForce(Vector3.up * jumpForceTwo, ForceMode.Impulse);
        transform.position = Vector3.MoveTowards(targetPos, transform.position, speed);
        isHorizontalingRight = true;
    }

```

Here is a video showing what is happening (sorry it's blurry): https://youtu.be/rPewtb8QywE

# Answer
> 0 votes
I can't tell from a video when you're applying input, but it looks to me like your problem is not that the jump is delayed, but rather that your character teleports instantly instead of moving over a period of time.

Your code moves the player like this:

```
transform.position = Vector3.MoveTowards(targetPos, transform.position, speed);

```

I am assuming your code takes place in an `Update()` function. You are not accounting for `Time.deltaTime` here, so your character may be moving 60x faster than you expect. Normally your speed should be in units per second and you should multiply speed by `Time.deltaTime` like this:

```
transform.position = Vector3.MoveTowards(targetPos, transform.position, speed * Time.deltaTime);

```

This way your movement speed is consistent regardless of framerate. For example, if the speed is 10 and a frame lasts 1/60th of a second, the actual distance moved in one frame would be `10 * (1 / 60)` = `.16667`. If the game stuttered during the next frame and the frame lasted 2/60ths of a second, the distance moved for that frame would be `10 * (2 / 60)` = `.333333`

---
Tags: unity, c#, physics, platformer, rigidbody
---


# Question
Title: does someone know how to fix these errors
```
(1)Assets\ep 7\BRS_ChangeCircle.cs(1,25): error CS1002: ; expected
(2)Assets\ep 7\BRS_ChangeCircle.cs(6,2): error CS1513: } expected
(3)Assets\ep 7\BRS_ChangeCircle.cs(7,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations
(4)Assets\ep 7\BRS_ChangeCircle.cs(8,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations
(5)Assets\ep 7\BRS_ChangeCircle.cs(157,1): error CS1022: Type or namespace definition, or end-of-file expected

```

and here is the coding

```
using System.Collections
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class BRS_ChangeCircle : MonoBehaviour
{
using UnityEngine;
using System.Collections;

public class Score : MonoBehaviour {

    int score = 0;

    void OnGUI () {
        guiText.text = "Score: " + score;
    }

}

    [Range(0, 360)]
    public int Segments;
    [Range(0,5000)]
    public float XRadius;
    [Range(0,5000)]
    public float YRadius;  //THIS IS NOT USED - SHOULD BE ELIMINATED

    [Range(10, 100)]
  public int ZoneRadiusFactor = 50; //default to 50%

    [Header("Shrinking Zones")]
  public List<int> ZoneTimes;

    #region Private Members
    private bool Shrinking;  // this can be set to PUBLIC in order to troubleshoot.  It will show a checkbox in the Inspector
    private int countdownPrecall = 10;  //this MIGHT be public, but it should not need to be changed
    private int timeToShrink = 30; //seconds
    private int count = 0;
    private bool newCenterObtained = false;
    private Vector3 centerPoint = new Vector3(0, -100, 0);
    private float distanceToMoveCenter;
    private WorldCircle circle;
    private LineRenderer renderer;
    private GameObject ZoneWall;
    private float [] radii = new float[2];
    private float shrinkRadius;
    private int zoneRadiusIndex = 0;
    private int zoneTimesIndex = 0;
    private float timePassed;
    #endregion

    void Start ()
    {
        renderer = gameObject.GetComponent<LineRenderer>();
        radii[0] = XRadius;  radii[1] = YRadius;
        circle = new WorldCircle(ref renderer, Segments, radii);
        ZoneWall = GameObject.FindGameObjectWithTag ("ZoneWall");

        timePassed = Time.deltaTime;
    }

    void Update ()
    {
        ZoneWall.transform.localScale = new Vector3 ((XRadius * 0.01f), 1, (XRadius * 0.01f));

        if(Shrinking)
        {
            // we need a new center point (that is within the bounds of the current zone)
            if (!newCenterObtained)
            {
              centerPoint = NewCenterPoint(transform.position, XRadius, shrinkRadius);
                distanceToMoveCenter = Vector3.Distance(transform.position, centerPoint); //this is used in the Lerp (below)
                newCenterObtained = (centerPoint != new Vector3(0, -100, 0));
          }

Debug.Log("New Center Point is " + centerPoint);

            // move the center point, over time
            transform.position = Vector3.Lerp(transform.position, centerPoint, (distanceToMoveCenter / timeToShrink) * Time.deltaTime );
            // shrink the zone diameter, over time
            XRadius = Mathf.MoveTowards(XRadius, shrinkRadius, (shrinkRadius / timeToShrink) * Time.deltaTime);
            circle.Draw(Segments, XRadius, XRadius);

            // MoveTowards will continue infinitum, so we must test that we have gotten close enough to be DONE
            if (1 > (XRadius - shrinkRadius))
            {
              timePassed = Time.deltaTime;
                Shrinking = false;
                newCenterObtained = false;
            }
        } else {
            timePassed += Time.deltaTime; // increment clock time
        }

        // have we passed the next threshold for time delay?
        if (((int) timePassed)  > ZoneTimes[zoneTimesIndex])
        {
            shrinkRadius = ShrinkCircle((float)(XRadius * (ZoneRadiusFactor * 0.01)))[1];  //use the ZoneRadiusFactor as a percentage
            Shrinking = true;
            timePassed = Time.deltaTime;  //reset the time so other operations are halted.
            NextZoneTime();
        }

        // COUNT DOWN
        if (timePassed > (ZoneTimes[zoneTimesIndex] - countdownPrecall)) {  // we need to begin counting down
            if (ZoneTimes[zoneTimesIndex] - (int) timePassed != count)
            {
                count = Mathf.Clamp(ZoneTimes[zoneTimesIndex] - (int) timePassed, 1, 1000);  // this ensures our value never falls below zero

                //FILL IN APPROPRIATE UI CALLS HERE FOR THE COUNTDOWN
                Debug.Log("Shrinking in " + count + " seconds.");
            }
        }
    }

    // ***********************************
    // PRIVATE (helper) FUNCTIONS
    // ***********************************
    private Vector3 NewCenterPoint(Vector3 currentCenter, float currentRadius, float newRadius)
    {
        Vector3 newPoint = Vector3.zero;

        var totalCountDown = 30000; //prevent endless loop which will kill Unity
        var foundSuitable = false;
        while (!foundSuitable)
        {
             totalCountDown--;
             Vector2 randPoint = Random.insideUnitCircle * (currentRadius * 2.0f);
             newPoint = new Vector3(randPoint.x, 0, randPoint.y);
             foundSuitable = (Vector3.Distance(currentCenter, newPoint) < currentRadius);
             if (totalCountDown < 1)
               return new Vector3(0, -100, 0);  //explicitly define an error has occured.  In this case we did not locate a reasonable point
        }
        return newPoint;
    }

    private int NextZoneTime()
    {
        //if we have exceeded the count, just start over
        if (zoneTimesIndex >= ZoneTimes.Count -1) // Lists are zero-indexed
          zoneTimesIndex = -1;  // the fall-through (below) will increment this

        // next time to wait
        return ZoneTimes[++zoneTimesIndex];
    }

    // This is a general purpose method
    private float[] ShrinkCircle(float amount)
    {
        float newXR = circle.radii[0] - amount;
        float newYR = circle.radii[1] - amount;
        float [] retVal = new float[2];
        retVal[0] = newXR;
        retVal[1] = newYR;
        return retVal;
    }
}

```

# Answer
> 1 votes
When you have a number of errors in the same sourcecode file, then it's usually a good idea to fix them from top to bottom, because fixing one error might remove or change the errors below it. So I copied your code to a new file in Visual Studio and went through the errors from top to bottom.

---

The first error is very straight forward: A semicolon is expected on line 1, position 25. So just add a semicolon after the very first line:

```
using System.Collections;

```

Funny thing: Visual Studio now displays that line in gray, which tells us that there isn't actually anything in this file which requires this `using`-declaration. So we could actually just as well remove it altogether.

---

Then you are apparently trying to create two `MonoBehaviour`s in one sourcecode file: `BRS_ChangeCircle` and `Score`. This won't work. The C# language *does* allow you to have multiple classes in one sourcecode file, but Unity requires a separate file for each `MonoBehaviour` in order to allow you to assign them to GameObject's. And even if you would want to create a class inlined in another (which you might want to do from time to time, just not with a `MonoBehaviour`), then the `using`-declarations required by the inner class need to be on top of the whole file. So remove this part and put it into a new file `Score.cs`:

```
using UnityEngine;
using System.Collections;

public class Score : MonoBehaviour {

    int score = 0;

    void OnGUI() {
        guiText.text = "Score: " + score;
    }

}

```

There is also another problem with this piece of code, and that that there is no variable `guiText` in that script. It is likely supposed to be a `public UnityEngine.UI.Text` or `public TMPro.TextMeshPro`.

---

Next error is this line:

```
public List<int> ZoneTimes;

```

This one is simple, and Visual Studio already provides an auto-correction. You forgot to add `using System.Collections.Generic;` to the very top of the script. This package is required for the class `List`.

---

Then there are just two errors remaining, which are related to the class `WorldCircle` being unknown. This is not a Unity or C# standard class, so I assume it's another class from your project. So if you have that class in your project, you shouldn't get that error.

---

**Conclusion:** It looks as if you copied a very long script written by someone else to your project, and then you tried to modify it by adding code you saw in some YouTube tutorial without really understanding what you were doing.

It's hard to get anywhere in Unity when you don't have at least a basic understanding of the C# language and how to interpret its error messages. If my impression is correct, then I would really recommend to do a basic, technology-neutral C# tutorial first.

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


title: How do I draw a ray in Unity?

text:
# Question
Title: How do I draw a ray in Unity?
I am trying to scrape together something for VR in which the locomotion is based the player holding the direction where he wants to go to (basically planning what he is going to do). While the player is holding down the button a ray (aligned to the direction of intended travel) is being drawn. When the player lets go the character moves until he reaches the end of the ray.

I tried looking up something but couldn't find anything regarding something like this.

# Answer
The component you are looking for is the LineRenderer. While you can use it to visualize paths in 3d space with as many points as you want, it is just as well possible to use it to draw a simple two-point line. You can use materials to customize its appearance.
> 2 votes

---
Tags: unity, raycasting
---


# Question
Title: New Unity version copies the settings of previous version
I use Ubuntu 20.04.
When I download a new version of Unity 3D through Unity Hub, this new version automatically takes the settings of the previous version. I have installed Unity 2020.1, and I am facing the same problem. I created a new project, but it written in 2020.1 that I used preview package. I didn't even installed any package in Unity 2020.1. I did install preview package in 2019.4. But I didn't even open the project with 2020.1. I only have one project with 2020.1. The new project I just created.
I asking help because I faced this issue when I first installed 2019.1, 2019.2, etc. How can I flx it? Thanks

# Answer
I also got the preview packages warning when starting my first Unity 2020 project.

Clicking on the drop-down arrow in this warning message allowed me to select the option "Show Preview Packages"

This opened the Package Manager, and showed that the lone preview package was TextMeshPro 3.0.0-preview.10

At the bottom of the window was an option to Update to the current stable version, 3.0.0

Clicking this resolved the warning about preview packages.

I'd recommend following similar steps for any preview packages you have in your project, unless you deliberately want to test out changes only available in the preview.
> 1 votes

---
Tags: unity
---


# Question
Title: mesh gets twisted wildly when trying to use Unreal's mannequin's skeleton
I have modelled a simple mannequine and made a skeleton for it in Blender. As far as I can judge, this skeleton copies the Unreal's standard mannequine's skeleton perfectly...

All the hierarchy and bone names are the same, and Unreal also does not complain when I import this mesh and use Unreal's skeleton asset for it.

However, when I try to play a preview animation on my mesh, it gets twisted wildly.

This is a normal state:

... and this happens when I play an animation on this asset:

I thought it was due to different joint initial transforms, so I tried exporting from Blender with varying bone axes (x-axis along the bone, z-axis along the bone etc.) but it did not help. There is neither imporevement nor mere difference when I change that. Can you tell me possible reasons?

Please find the .fbx here:

https://drive.google.com/file/d/1v1X8t7l-6lwQragO8E0mtC1chdT2p1m4/view?usp=sharing

# Answer
**Problem**

So, there were actually *four* things going wrong about the mesh and the armature:

1. **incorrect scale** \- this has made the model look *stretched*
2. **incorrect bone transforms in the base pose** \- this has made the model look *twisted*
3. **poor weights**
4. **different skeleton proportions**

**Solution**

**1: Incorrect scale**

Regarding the incorrect scale - not sure what has caused it, but, as @DMGregory has explained, if the offset between a bone and a joint is measured in metres (say, 1.3) but the animation thinks it's in millimitres - this would be like offsetting by 1300 metres. Which I think what was happening in the case - so it was kinda wrapping a mesh around a skeleton that is 100 times larger.

**How I fixed it:** in Blender where I was using metric system, I have scaled both the mesh and armature x100 and applied all transforms - after that, the problem of stretching was solved.

**2: Incorrect transforms in the rest pose**

After you fix stretching, you will most probably notice (if you are retargeting like me and using another skeleton) that body parts are all rotated in random directions. This is because every joint in the mesh has its specific transform in the rest pose. If those transforms in the Unreal's skeleton are different from your armature, the offsets will be applied to incorrect initial transforms which would cause distortions:

To put it short (because I don't understand the low-level mechanics properly): because the joint is rotated differently in the rest pose, **animation will not work properly.**

**How I was trying to fix it:** a) in Blender 2.83, activate the following property as shown below to see bone local transforms:

b) import Unreal's skeleton or one of the animations available: in Unreal 4.22.3, you can do that by going to Animations, right-clicking a single animation and exporting as fbx. You can see how different those sekeltons look in regard of rotations:

You see that the bone translations/rotations are completely different for the unreal's skeleton on the left.

c) to fix it, you would have to rotate/move each bone manually in your 3d software. I never had patience to finish it (only did a couple of joints which has partly fixed the problem) but @MostHost LA on Unreal forms has brought it to its end, and it would look like this:

**3: Poor Weights**

As you can see, after fixing scale and joint transforms, this still look bad. The reason is that the weight paint isn't fine. I haven't done this part yet, but I guess you would import Unreal's animation, play on your character, stop at particular frames and fix the weight paint until it looks fine.

**4: Different skeleton proportions**

When you are done fixing weights, this will still look somewhat like the picture above. This is because the skeleton proportions are different. For example, my skeleton has narrower shoulders than the Unreal's skeleton. This means that my mesh would be stretched a bit in the area of shoulders to match Unreal's skeleton. I am pretty confident, there are retargeting tools in Unreal that can fix it automatically: check their YouTube channel if you ever need to go through the process.
> 1 votes

---
Tags: unreal-4, unreal, skeletal-animation, joints, bones
---