Changing the RotateAround center point dynamically Black circles are static Red player Blue line path I'm trying to achieve a constant movement of the red dot like on the image below. For now, I have something like void Update() target firstCircle here I need to perform some calculations this.transform.RotateAround(target.transform.position, Vector3.forward, speed Time.deltaTime) As you can see in the code, it rotates around the upper circle now. I need to switch the target variable to the secondCircle when the player comes back to it's initial position (or is near it). I came up with something like if(Mathf.Abs(Mathf.DeltaAngle(360f,this.transform.rotation.eulerAngles.z)) lt 5f) change target and it works but has two issues. First the epsilon value. If I set it to 5f the above if is true like 7 times (depending on the player's speed). Of course I could make a lock to run it only once per cycle, but there's a second problem. If the object is moving too fast, the if will be false each time, cause the speed step is always higher than the epsilon. How is this done in 'gravity' games like AngryBirds when the bullet changes it's attraction point?


How to instantiate a sprite from a sprite sheet using script in unity? We are creating a 2D top down rpg, and we have multiple textures, and we need to be able to change which sprite sheet its reading from in order to change the look of the walls and floor in each room. It has the same basic tiles just they need to look different. Like the corner of a cabin, to the corner of an office building. At the moment we are taking the sprite sheet, splitting it up, and making prefabs out of it for placement by script in the game. Is there a way to do this automatically because we have a lot of textures, and its too many to make into prefabs.


Can I use a SkinnedMeshRenderer animation in a Canvas? I just downloaded an asset from the store https www.assetstore.unity3d.com en ! content 67122 They're just animated characters. If you drag amp drop the prefabs on the scene, it works fine. The thing is, I work exclusively with Unity's new 2D Canvas Image Button etc. These prefabs instead use a SkinnedMeshRenderer so it's not like you can put them inside your Canvas. I want to have the prefabs work in my Canvas. For all intents and purposes I want those animations to act like a Image inside the Canvas. This is what one of those prefabs looks like I want to take advantage of the Unity's canvas because it makes a lot of things easier like scaling for all devices, scroll views, easy masks, etc.


How would I edit .anim files in Blender? I absolutely cannot stand animating in Unity. I am making an FPS game with many weapons, and each weapon has four animations running, jumping, aiming, and shooting. I would like to create a .anim file in Unity with the keyframes of the character and the weapon, and then edit that .anim file in Blender. How would I edit .anim files in Blender?


Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?


Why does AudioSource not initializes itself? Why does AudioSource not initializes itself? Here is my code using System using System.Collections using System.Collections.Generic using UnityEngine public class CameraConfig MonoBehaviour public GameObject objToFollow public bool followRabbit Use this for initialization void Start() followRabbit true LevelController.current.cameraWhichLooksForRabbit this setMusicSource() setSoundSources() public AudioClip music, rabbitWalksSound, rabbitDiesSound, rabbitFallsSound, enemyAttacksSound private AudioSource musicSrc, rabbitWalksSrc, rabbitDiesSrc, rabbitFallsSrc, enemyAttacksSrc private void setMusicSource() setClipForSrc(musicSrc, music, true) private void setSoundSources() setClipForSrc(rabbitWalksSrc, rabbitWalksSound, false) setClipForSrc(rabbitDiesSrc, rabbitDiesSound, false) setClipForSrc(rabbitFallsSrc, rabbitFallsSound, false) setClipForSrc(enemyAttacksSrc, enemyAttacksSound, false) private void setClipForSrc(AudioSource src, AudioClip clip, bool loop) src gameObject.AddComponent lt AudioSource gt () src.clip clip src.loop loop void Update() checkMusicAndStopOrStartIfNecessary() if (!followRabbit) return Transform rabit transform objToFollow.transform Transform camera transform this.transform Vector3 rabit position rabit transform.position Vector3 camera position camera transform.position camera position.x rabit position.x camera position.y rabit position.y camera transform.position camera position public void playSoundRabbitWalks() if (!rabbitWalksSrc.isPlaying) rabbitWalksSrc.Play() public void playSoundRabbitDies() rabbitDiesSrc.Play() public void playSoundRabbitFalls() rabbitFallsSrc.Play() public void playSoundEnemyAttacks() enemyAttacksSrc.Play() public void stopSoundRabbitWalks() if (rabbitWalksSrc.isPlaying) rabbitWalksSrc.Stop() public void stopSoundRabbitDies() rabbitDiesSrc.Stop() public void stopSoundRabbitFalls() rabbitFallsSrc.Stop() public void stopSoundEnemyAttacks() enemyAttacksSrc.Stop() private void checkMusicAndStopOrStartIfNecessary() if (SoundManager.Instance.isMusicOn() amp amp !musicSrc.isPlaying) musicSrc.Play() else if(!SoundManager.Instance.isMusicOn() amp amp musicSrc.isPlaying) musicSrc.Stop() Here are screenshot of the exceptions in console and inspector view


Screenshot preview freezes a game for a few seconds I have a screenshot preview at the end of the level, but when I show it my game freezes for a bit(low fps for a few seconds). This is code I use to load screenshot and crop it(for a little preview sample). Please, help me to solve this lag issue private IEnumerator ShowScreeshotPreview() yield return 0 screenshotTexture new Texture2D(2, 2) byte fileData File.ReadAllBytes(destination) yield return 0 screenshotTexture.LoadImage(fileData) yield return 0 Rect croppedSpriteRect new Rect() croppedSpriteRect.height screenshotTexture.height croppedSpriteRect.width screenshotTexture.height croppedSpriteRect.y 0 croppedSpriteRect.x 0 croppedTexture new Texture2D((int)croppedSpriteRect.width, (int)croppedSpriteRect.height) yield return 0 croppedTexture.SetPixels(screenshotTexture.GetPixels((int)croppedSpriteRect.x, (int)croppedSpriteRect.y, (int)croppedSpriteRect.width, (int)croppedSpriteRect.height)) yield return 0 croppedTexture.Apply() Memory leak occurs here yield return 0 screenshotPrview.mainTexture croppedTexture yield return 0 ScreenshotPreviewAnimator.SetBool("visible", true) screenshotLoaded true


Variable value in inspector is not updating automatically? Something weird is happening when I change a variable value in script and hit play the var value doesn't update I have to reset the script in inspector. Is this normal? Aren't the values suppose to update when we hit play? The Simple Code I used to test this var a int 0 function Start () print(a)


Why isn't occlusion culling working correctly? Occlusion culling doesn't seem to be behaving the way I was expecting. I've set the yellow wall as static and have baked an occlusion map using the occlusion window in unity. However when visualising the occlusion the red cylinder behind the wall is still visible despite not being seen in the camera preview. Any clue what I'm doing wrong?


How to detect whether a transform has rotated left or right I have a game object in my scene, and I want to know how can I calculate whether this game object rotating to the right or to the left. For example if(check whether the transform rotated to the right) print("rotate to right") else if(check whether the transform rotated to the left) print("rotate to left") else print("no rotation")


Why the break point is not working with the unity3d editor? The visual studio version is 16.8.3 Visual studio community 2019 The editor version is 2019.4.15f1 personal On other project I have opened it's working fine. It also worked fine on this project but then something went wrong now not sure why the break point s are not working with this project ! In the editor I did double click on a script attached to gameobject and it opened the visual studio then I clicked on the left side to add a break point and did Attach to Unity but the break point on the left is broken with yellow warning. I tried to close and re open both visual studio and the editor. In the editor I did Edit gt Preferences gt External Tools and this is the settings I also clicked on the Regenerate project files. But nothing worked so far.


Why won't Unity drop objects to the origin position? It seems that my objects drop to the middle of the scene, not a global position of (0, 0, 0). Why is Unity behaving like this?


Problem when trying to use rb.MoveRotation in Unity OK so I learned that rb.MoveRotation is different from rb.transform.Rotate(). But I am having trouble using it and hoping you can help me. I usually use transform.translate(Vector3.forward) (after using transform.Rotate(x,y,z)) , so that I know that will always make object move in the direction its facing. But this isnt working when I use rb.MovePosition. The object rotates when i remove the MovePosition line, but then for some reason doesn't when its there. I've tried multiple things as you'll see in the code. I cant understand also why, if I use the bottom commented attempt in my code, and then press D in game, it will go in the direction its facing and then get stuck. I've commented in my code to try to explain whats happening. What is the correct way to move the position of the player now I am using MoveRotation? I want to base my movement of the direction that the object is facing and not in world coordinates. Thanks void HandleKeys() if (Input.GetKey(KeyCode.A)) if (!facingLeft) rb.MoveRotation(Quaternion.Euler(0, 90,0)) facingLeft true rb.transform.Translate(Vector3.forward speed Time.deltaTime) if I remove this line, the character does turn and face left . But when its in he doesn't and both keys make him move right (and face right) also tried rb.MovePosition(transform.position Vector3.forward speed Time.deltaTime) this results in it going Vector3.forward in world coords rb.MovePosition(transform.position rb.transform.forward speed Time.deltaTime) this makes him go RIGHT gt ?? and the objects facing RIGHT why???? if (Input.GetKey(KeyCode.D)) if (facingLeft) rb.MoveRotation(Quaternion.Euler(0f, 90f, 0f)) facingLeft false rb.transform.Translate(Vector3.forward speed Time.deltaTime) if i leave this in, and the one marked above, then it works but only once, so if I press A then, D he heads right but wont turn round, if I press D first he just goes right if (Input.GetKeyDown(KeyCode.Space) amp amp IsGrounded()) rb.AddForce(Vector3.up jumpForce, ForceMode.Impulse)


Can we create same name class for different objects in unity? I have four similar objects in my game. As they are all similar therefore I have created a single script that defines mash for all of them. The script that defines mash for these objects uses a variable called radius which I have imported from other file (by classname.radius). The radius updates on every frame and it is the only property that is different for all objects. To allow different radius for different objects, What I thought would work was, making four different classes of same name classname. Creating variable radius in all of them and giving them different values. Dragging first file to the first object, second file to second object and so on.. When executed, every time the script that generated mash considers classname.radius from the file which is dragged to that object. But that isn't working. What is wrong and how can I implement it? Seems I'm messing with OOPS concepts!


(Unity) Shortest way to instantiate an object and obtain it script Normally I use ScriptName script ((GameObject)Instantiate( Resources.Load("Prefab"), new Vector3(x, y, z), Quaternion.identity )).GetComponent lt ScriptName gt () It is a little too long and too much of brackets, so I wondering if there is any other way to get instantiated object's script without break it in two statements.


How to find the participation id corresponding to a sender id I am creating a real time multiplayer game in unity 3d using Google Play Game Services. In my function where I deal with the positioning of players based on information that is sent from other players, I get a sender id. The sender id is a long string of characters that does not match any participation ids. My participation ids are just strings such as "Player 1234." I keep the participation ids in an array so I can reference them and compare them to the sender of the information that I am receiving so I know which player it is from. If the sender id and participation id are two different things, how do I make the connection between the two? Here is a link to the tutorial I have been following for Google play services in unity https www.raywenderlich.com 87042 creating cross platform multi player game unity part 2


Question about references I have an enemy game object and an item game object. Enemies have an ItemDrops script attached. Items have a DisplayItemLabel script attached. Attached to each enemy public class ItemDrops MonoBehaviour public Transform itemPrefab private EnemyHealth enemyHealth private float originToGroundDistance private Vector3 offset private bool itemDropped private bool numberGenerated private float randomNumber private ItemData itemData public string nameOfDroppedItem void Start() enemyHealth GetComponent lt EnemyHealth gt () itemData GameObject.Find("Item Manager").GetComponent lt ItemData gt () void Update() Initialized in Update instead of Start because enemy floats to 1.083333 on the Y axis after some time after Start originToGroundDistance transform.position.y 0.25f offset new Vector3(0f, originToGroundDistance, 0f) if (enemyHealth.isDead amp amp !itemDropped) if (!numberGenerated) RandomNumberGenerator() Debug.Log(randomNumber) if (randomNumber lt 1) SpawnItem(itemData.coin) private void RandomNumberGenerator() numberGenerated true randomNumber Random.value private void SpawnItem(Item item) itemDropped true nameOfDroppedItem item.itemName Instantiate(itemPrefab, transform.position offset, Quaternion.identity) Attached to each item public class DisplayItemLabel MonoBehaviour private GameObject itemLabel private Text itemNameText void Start() itemLabel transform.Find("Canvas Item Label").gameObject itemNameText itemLabel.GetComponentInChildren lt Text gt () itemNameText.text "Item Name" itemLabel.SetActive(false) void Update() ClampLabelToItem() private void ClampLabelToItem() Vector3 offset new Vector3(0f, 16f, 0f) Vector3 desiredPosition Camera.main.WorldToScreenPoint(transform.position) offset itemLabel.transform.position desiredPosition itemLabel.SetActive(true) Item is not a child of enemy for multiple reasons I can think of. One is that enemies are destroyed when they are killed. With that said, how do I get the item to know who dropped it or get the enemy to know which item it dropped? MY GOAL is to get itemNameText.text "Item Name" to say something like itemNameText.text itemDrops.NameOfDroppedItem but I can't use GameObject.FindGameObjectWithTag("Enemy").GetComponent lt ItemDrops gt () because it won't always grab the correct enemy and thus the correct ItemDrops script. I also can't set DisplayItemLabel.itemNameText.text nameOfDroppedItem in the SpawnItem function because it wouldn't know which item's DisplayItemLabel script to get. So clearly, I'm having issues with references. What should I do?


Unity2D Rendering multiple sprites as a single one I'm creating NPCs in Unity 2D using C , and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet. I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way? Thanks in advance!


How can I find and get all enabled cameras and switch between them? I have 5 cameras in the scene. In the Inspector I added to the cameras array 3 cameras. In the script I store this cameras using storedCameras array. In cameras array there are 5 cameras. I added a flag allCameras to change between the stored cameras mode and all cameras mode. And I'm using the G key to switch between the cameras either the stored or the all cameras. But when I press on G I see in the Inspector that each press on G remove one camera from the array cameras in the end I left with one camera. And the idea is to press G and switch between the cameras either if it's on stored cameras mode or all cameras mode depending on the flag. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class SwitchCameras MonoBehaviour Header("Cameras Init") public Camera cameras public Vector3 originalPosition HideInInspector public Vector3 currentCameraOriginalPosition, currentCameraPosition public bool allCameras false private Camera storedCameras Space(5) Header("Cameras Switch") public string currentCameraName public Vector3 lastCameraPosition private int currentCamera 0 void Start() storedCameras cameras if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras lastCameraPosition new Vector3 cameras.Length if (cameras.Length gt 1) originalPosition new Vector3 cameras.Length for (int i 0 i lt cameras.Length i ) originalPosition i cameras i .transform.position if (cameras.Length 1) Debug.LogError("Need more then 1 camera for switching..") else Debug.Log("Found " cameras.Length " cameras") for (int i 0 i lt cameras.Length i ) cameras i .enabled false cameras 0 .enabled true currentCameraName cameras 0 .name currentCameraOriginalPosition originalPosition 0 void LateUpdate() if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras else cameras new Camera storedCameras.Length cameras storedCameras if (Input.GetKeyDown(KeyCode.G)) cameras currentCamera .enabled false if ( currentCamera cameras.Length) currentCamera 0 cameras currentCamera .enabled true currentCameraName cameras currentCamera .name currentCameraOriginalPosition originalPosition currentCamera lastCameraPosition currentCamera cameras currentCamera .transform.position currentCameraPosition lastCameraPosition currentCamera


The jumping height changes randomly, and it is not due to the fact that I press the space bar longer. It is just random Sometimes, the jump height will be so high, and sometimes it jumps normally. How do I solve this? Code using UnityEngine public class PlayerController MonoBehaviour SerializeField private LayerMask platformsLayerMask public Rigidbody2D rb public float MovementSpeed 100f public float JumpingHeight 100f public BoxCollider2D bc public float fallMultiplier 2.5f public float lowJumpMultiplier 2f public Animator anim void Awake() rb transform.GetComponent lt Rigidbody2D gt () bc transform.GetComponent lt BoxCollider2D gt () void Update() if (IsGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector2(rb.velocity.x, JumpingHeight Time.deltaTime) Debug.Log("Jumping") HandleMovement() private bool IsGrounded() RaycastHit2D raycastHit2d Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask) Debug.Log(raycastHit2d.collider) return raycastHit2d.collider ! null void HandleMovement() if (Input.GetKey(KeyCode.A)) rb.velocity new Vector2( MovementSpeed Time.deltaTime, rb.velocity.y) Debug.Log("Going Left") transform.localScale new Vector2( 1, 1) else if (Input.GetKey(KeyCode.D)) rb.velocity new Vector2( MovementSpeed Time.deltaTime, rb.velocity.y) Debug.Log("Going Right") transform.localScale new Vector2(1, 1) else no keys pressed rb.velocity new Vector2(0, rb.velocity.y) Debug.Log("No key pressed") if (rb.velocity.y lt 0) reponsive jumping and falling rb.velocity Vector2.up Physics2D.gravity.y (fallMultiplier 1) Time.deltaTime else if (rb.velocity.y gt 0 amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity Vector2.up Physics2D.gravity.y (lowJumpMultiplier 1) Time.deltaTime


Why does physics not behave consistently in Unity? I'm making a game in which AI players throw a ball. In the screenshot, you can see the arena which is separated by a net in the middle. Each side of the arena has 6 players belonging to one of 2 teams. Right now, one of the players on the right side has the ball (the top right player). He is going to throw the ball to the left side. According to my code, the ball should always land on the same place, because the player always applies the same force to the ball. However, I have noticed that the ball doesn't always land in the same place. I have marked where I've seen the ball land with several red circles. Interestingly, on my main PC, the ball almost always lands on the right most circle. It rarely lands on the other circles, although that does happen. On 3 other PCs I've tested this game on, however, the ball most often lands on the legs of the top left player, sometimes on his head or behind him, but never on the right most circle (in front of him). My game relies heavily on physics. The AI is supposed to calculate how to throw the ball to get it to land on a very specific location, as well as guess where it'll land depending on the ball's position and movements. If the physics don't behave consistently on all machines all the time, how is the AI supposed to calculate all of this accurately? Here is the code in charge of throwing private IEnumerator Serve() var ball GameObject.Find("Ball").GetComponent lt BallController gt () if (ball.ServingPlayer ! this) yield break yield return new WaitForSeconds(3) Vector3 shootDirection transform.forward.normalized var q Quaternion.AngleAxis( 45, transform.right) ball.RigidBody.AddForce(q shootDirection 20f, ForceMode.VelocityChange) As you can see, the ball is always thrown "forward" (facing the net) at a 45 upward angle, using a normalized vector and a constant speed (20f). Before each throw, the position of the players is reset to the exact same location (and rotation) they are seen on the screenshot. player.transform.localEulerAngles new Vector3(0, playerRotation, 0) player.transform.position startingposition posOffset In this case, playerRotation is either 90f or 90f depending on which side the player is on, startingposition is their "horizontal" position (relative to the net), and posOffset is their "vertical" position. The ball has its velocity and angular velocity reset, but not its rotation (since it's a sphere, its rotation shouldn't influence anything). Its position is also set to a fixed location relative to whichever player has to serve the ball. rb.velocity Vector3.zero rb.angularVelocity Vector3.zero transform.position ServingPlayer.ServingPosition Here, rb is the ball's RigidBody. Finally, I am not influencing the ball's movement in any way. I simply apply a force to it when serving, which happens only once. 3 seconds after the ball lands, the match is reset and everything repeats. The flow is basically like this (pseudocode) Start() ResetCourt() StartCoroutine(Players 0 .Serve()) event BallLanded() wait for 3 seconds repeat starting with ResetCourt() I really need the ball's trajectory to be reproducible every single time on every possible machine. Obviously I'm doing something wrong here, but what?


How can I loop over waypoints to move all the objects between them? using System.Collections using System.Collections.Generic using UnityEngine public class Waypoints MonoBehaviour public enum RotationMode Normal, Curved public GameObject objectToDuplicate public Transform waypoints public float movingSpeed public bool randomSpeed false private GameObject prefabsToMove private void Start() prefabsToMove GameObject.FindGameObjectsWithTag("FrameLine") DuplicatePrefabEffects(prefabsToMove.Length) private void DuplicatePrefabEffects(int duplicationNumber) for (int i 0 i lt duplicationNumber i ) var go Instantiate(objectToDuplicate) go.tag "Duplicated Prefab" go.name "Duplicated Prefab" private void WaypointsAI() for (int i 0 i lt waypoints.Length i ) if (randomSpeed) movingSpeed Random.Range(1, 20) prefabsToMove i .transform.position Vector3.MoveTowards( prefabsToMove i .transform.position, waypoints i .position, movingSpeed Time.deltaTime ) void Update() WaypointsAI() The problem is inside the loop there might be less or more prefabsToMove then waypoints so it will throw exception. Then doing prefabsToMove i is wrong.


Why doesn't this movement script work, while the other one does? Im trying to get a rigidbody2D to move around and got it working with this script public class RubyController MonoBehaviour public Rigidbody2D rigidbody2d public float speed 5.0f Vector2 movement void Start() rigidbody2d GetComponent lt Rigidbody2D gt () void Update() movement.x Input.GetAxis( quot Horizontal quot ) movement.y Input.GetAxis( quot Vertical quot ) private void FixedUpdate() rigidbody2d.MovePosition(rigidbody2d.position movement speed Time.deltaTime) but not with this, and I can't understand why public class RubyController MonoBehaviour public Rigidbody2D rb2d float horizontal float vertical public float speed 5f private void Start() rb2d GetComponent lt Rigidbody2D gt () private void Update() horizontal Input.GetAxis( quot Horizontal quot ) vertical Input.GetAxis( quot Vertical quot ) private void FixedUpdate() Vector2 position this.rb2d.position position.x position.x speed horizontal Time.deltaTime position.y position.y speed vertical Time.deltaTime rb2d.MovePosition(position)


How do I run a headless Unity server in a Windows Docker (without GPU)? I am trying to run a headless Unity server on a Windows Docker. On Linux, there is Xvfb, but I don't know how I could get similar results on Windows. How would I do that?


Rotating UI element using touch for mobile Unity 2D I want to create the above object that will rotate on z axis following the direction of a finger. Like a dial. I have written the following code and attached it to that element private float rotationRate 3.0f void Update() get the user touch input foreach (Touch touch in Input.touches) Debug.Log("Touching at " touch.position) if (touch.phase TouchPhase.Began) Debug.Log("Touch phase began at " touch.position) else if (touch.phase TouchPhase.Moved) Debug.Log("Touch phase Moved") transform.Rotate(touch.deltaPosition.y rotationRate, touch.deltaPosition.x rotationRate, 0, Space.World) else if (touch.phase TouchPhase.Ended) Debug.Log("Touch phase Ended") But the element does not move at all. Any ideas? EDIT Here is a gif for better understanding


How do you make small icons look good? I am running into an issue with my UI. Basically I need to have a lot of small icons, similar to many other games, here is an example With Mip maps As you can see, these look awful. This is simply a UI Image with size 15x15, it seems when they get too small it simply does not look good. It has nothing to do with import options or anti aliasing, I have tried everything there. I submitted it as a bug but according to Unity it simply will not look good when images are scaled down too much.I have tried both PNG with large resolutions and small, I have exported the .SVG vector image and tried using that, all look bad when scaled down. So what are my options then when I need small icons? How do other games do it? Here is a link to the actual .png file https ibb.co nDG0hmD For reference, here are the same icons zoomed in, as you can see, they look fine Im developing for PC.


My mesh has holes in it. How do I make those invisible faces show? I have a mesh. A perfectly normal mesh, without any artefacts at all. However, when I import it into Unity, there are holes in it. After going through my UV mapping and normals, they are all mapped, have no faces with the normals going the wrong way (facing inwards) and have non transparent textures over each mapped UV face. Oddly enough, this mesh hasn't been split, despite its poly count and is one whole object, but yet It has missing polygons. Is there any way to get Unity to recognise these faces? Also, it is worth noting that these holes happen to be all the tris faces on this model, and are all (mostly) along the UV seames. Question How do I make the invisible faces show? What's going on?


Unity3D Touch and Objects have different coordinate systems I would like to associate the same script to different empty objects I just use as placeholders in the game. The aim is to exploit their positions so that when the user touch a point in the screen, close to one of these objects, a dedicate GUI appears. The problem is that though the two objects are different their scripts seem to influence each other so that when the game is running and I touch one of these two objects both the gui appears. What am I doing wrong? Some hours later... This happens because the object and the touch are in two different coordinate systems. For instance though I touch the object I get ( 0.77, 0.46) for the object and (12.1,95.2) for the touch which, I guess, is measured in pixel. How to transform one into the other? .... private var check boolean var topCamera Camera var customSkin GUISkin function Update () if (Input.GetMouseButtonDown(0)) if(Input.mousePosition.x gt this.transform.position.x Screen.width 0.20 amp amp Input.mousePosition.x lt this.transform.position.x Screen.width 20) if(Input.mousePosition.y gt this.transform.position.y Screen.height 0.2 amp amp Input.mousePosition.y lt this.transform.position.y Screen.height 0.2) check true if(check) the camera zooms forward else the camera zooms backward function OnGUI () if (this.check) var w Screen.width var h Screen.height var bw 0.083 var bws 0.001 w GUI.skin customSkin GUI.Box(new Rect(w 0.6,h 0.3,w 0.38,h 0.45), "Stuff") customSkin.box.fontSize 0.04 h customSkin.textField.fontSize 0.08 h customSkin.button.fontSize 0.04 h textFieldString GUI.TextField (Rect (w 0.62, h 0.39, w 0.34, h 0.1), textFieldString) if (GUI.Button (Rect (w 0.62,h 0.50, w bw, h 0.1), " ")) if (this.check) this.check false else this.check true ... ...


Audio slider doesn't change value For some reason, my slider and audio resets back to 0 when I stop and play the game after I changed the value. Here is the code, I can't spot anything wrong with it using UnityEngine using System.Collections using UnityEngine.UI public class MainAudio MonoBehaviour public Slider slider void Awake() PlayerPrefs.Save () GetComponent lt AudioSource gt ().volume PlayerPrefs.GetFloat ("CurVol") if (slider) slider.value GetComponent lt AudioSource gt ().volume public void VolumeControl(float volumeControl) GetComponent lt AudioSource gt ().volume volumeControl PlayerPrefs.SetFloat ("CurVol", GetComponent lt AudioSource gt ().volume) PlayerPrefs.Save ()


Unity "Text Mesh Pro UGUI" component rewrites my text! Make it stop? I'm having this terribly annoying problem where my text is being overwritten by Unity. This Happens regardless of whether I am using tags or not. Here is what I want to appear (more or less, I don't think this example is using the tag) And here is what happens when I try to include a monospace tag Since you might not see it here, the text I inputed is lt mspace 64px gt A lt mspace gt This works FINE for regular TMP objects, which the other 3 are (and are using). I am trying to implement dropdown (and left, and up, and right) menus. You can see that Unity overwrites it as "Option A", like it has a clue what I'm doing. What can I do?


Multiplayer VR art gallery using different headsets I'm creating a VR art gallery using Unity3D (like a VR Museum Views with more freedom) and would like to have an environment where 1 or more users can gather together, communicate and move around (similar concept to SecondLife except in this case would be first person view (by default) with only one room location and users would be in VR). From a user perspctive, the initial screen would be a door and the user would have a mini map and a menu, turned to him herself, with specific actions. Once inside of the gallery, the users would be able to see others, "walk" or "teleport" to different locations and see the canvas The overall environment is rather simple so I've decided to get feedback from potencial users. Turns out the majority doesn't want to be alone in such environment. So, I've considered adding multiplayer (one of the users could even be guiding the others, which is interesting). Now, multiplayer makes more sense when we can more inclusive. That's where the problem starts. In this specific case, inclusive is being defined as the possibility of users to be able to be present in the environment using at least one of the following devices Android Phone (Cardboard) Oculus GO Samsung Gear VR Google Daydream Oculus Rift HTC Vive I've done some research and couldn't find someone doing it or a way to do it (considering all of the requirements). If that's possible to do, how can i do it? One thing I found was that if I didn't want the users to move around and just be watching the gallery like watching a webinar presentation in different devices, I could use VR Sync (they basically synchronize video playback on multiple VR devices). So, at the moment I can either have the environment with just one user at a time and develop the environment for all the different headsets or use VR Sync.


Unity Profiler How do I correct Audio (WASAPI) Feeder issues? I've got the following data after running the Unity Profiler If I'm reading this correctly, the thing that's driving me down to 1 FPS is the CPU Audio. I can't understand what's going on here, though, because there isn't any audio in my game right now.


How to move objects across a canvas with consistent speed on different screen resolutions? I am making a rhythm game in Unity. I have been using Transform.Translate for moving images on a canvas as the music notes. However, I cannot consistently use this method on different screen widths. The notes move the same amount each frame. I want to use interpolation for my music notes. I want to have the notes reach the center of the canvas at the same time despite the width of the screen. How can I write such a script?


Bullet is not instantiating properly in Unity So I'm trying to make a simple weapon where I just instantiate a bullet at the Shoot Point's gameobject position. For some reason when I press down on my mouse the bullet just flies up. Any ideas on why this could happen? Vector3 velocity bullet.transform.forward 1000 GameObject bulletGameObject Instantiate(bullet, shootPoint.transform.position, Quaternion.identity) Rigidbody bulletBody bullet.GetComponent lt Rigidbody gt () bulletBody.velocity velocity Destroy(bulletGameObject, 4f)


What are the correct steps to add Admob to Unity? The official documentation leaves out really important steps. Adding 'cocaopods' and 'Google Play Services' They are just listed as prerequisites without even any links. Another confusing thing is that, elsewhere I have seen that apparently I don't also need the Unity Google Play Games Services SDK for Admob to work. But in that case then why is 'Google Play Services' listed as a prerequisite on the official docs?


How to fade in and out a game object with two child game objects I have been fading game objects in and out using the following code. Now I want to fade out a game object with two child game objects. How can I do this? IEnumerator FadeToForGO(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) Cache the current color of the material, and its initiql opacity. Color color material.color float startOpacity color.a Track how many seconds we've been fading. float t 0 if (isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled while(t lt duration) Step the fade forward one frame. t Time.deltaTime Turn the time into an interpolation factor between 0 and 1. float blend Mathf.Clamp01(t duration) Blend to the corresponding opacity between start amp target. color.a Mathf.Lerp(startOpacity, targetOpacity, blend) Apply the resulting color to the material. material.color color Wait one frame, and repeat. yield return null if (!isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled


Physics Determine how much thrust to apply at each thruster for linear angular acceleration I have a question somewhat similar to this one 2D Spaceship Thruster Movement Turning. I have a ship with thrusters placed randomly on it (not necessarily symmetrically), and I need to know which thrusters and how much to fire them to have a perfectly linear acceleration, as well as how much they contribute to the angular acceleration of the ship to know which ones to fire when you want to turn the ship. What I know the position and orientation of the thrusters, the center of mass of the ship. Basically I just need a way to make the ship obey the commands as best as physically possible, the commands being 'move' (apply acceleration on thrusters so if results in a linear acceleration), and 'rotate' (apply differential acceleration to maximize angular and minimize linear acceleration). The game is 2D. Thank you very much in advance.


UnityEditor.SyncVS.SyncSolution putting wrong language version in generated files I'm working on getting our Unity projects building in bamboo for our build server. We have a cli step that runs through the Unity commands for creating a build. It works fine on several projects, but for some reason this particular project I'm working on I'm getting an error that states I need to use c version 7.2 or newer. If I log in to the build server and open the .csproj files in notepad and check the language version, it's setting them to 7.0. However, if I deactivate the cli step so that the build job only clones the project, then manually log in and open unity and go through the process so it generates the .csproj files, then check them, the language version is set to 8.0. The project works fine locally on my own pc. And it works when setup manually on the build server pc, but when ran through the cli step, it generates them at an earlier c version. This leads me to believe there is a problem with the UnityEditor.SyncVS.SyncSolution step in my commands. I'm just not sure what it could be, or why it's behaving differently for this project as opposed to other projects that are using the same code base (where the problem is said to occur), same Unity version, same build server, etc. Anyone else experience this issue or have any thoughts on a solution?


Unity Instantiate 2 copies at same time?? (Asteroids clone) C I haven't been at my computer learning code or game dev in a few months and am just starting again. I am trying to make a game very similar to Asteroids. In 3d but fixed camera from above so basically disregarding the Y Axis at the moment. I have everything working fine so far such as the rocket stays in middle and can rotate, and fire weapon. The Asteroids for now all come from the top side of the screen, and have some code to randomise the X location and speeds. When the laser hits the Asteroid I want it to destroy that Asteroid and create two more that are half the size and with a Rotation added of 45 45 degrees. I have the code that I thought would work but it is only creating one more and not two. (note as you'll see I have tried making tempAsteroid2 and even asteroidPrefab2, before this I just had the one which I tried to instantiate twice). What am I missing? why does this code not make two more appear upon laser collision?? Any help massively appreciated as always. Many thanks public class Asteroid MonoBehaviour float speed public GameObject asteroidPrefab, asteroidPrefab2 public int sizeKey 2 Use this for initialization void Start () if (sizeKey lt 1) Destroy(this.gameObject) transform.position.Set(transform.position.x, 0f, transform.position.y) speed Random.Range(0.5f, 2f) Update is called once per frame void Update () GetComponent lt Rigidbody gt ().transform.Translate(Vector3.forward speed Time.deltaTime) private void OnTriggerEnter(Collider other) if (other.tag "Laser") BreakAsteroidInHalf() Destroy(other.gameObject) void BreakAsteroidInHalf() GameObject tempAsteroid asteroidPrefab tempAsteroid.transform.position transform.position tempAsteroid.transform.Rotate(0, 45, 0) tempAsteroid.transform.localScale 0.5f tempAsteroid.GetComponent lt Asteroid gt ().sizeKey 1 Instantiate(tempAsteroid) GameObject tempAsteroid2 asteroidPrefab2 tempAsteroid2.transform.position transform.position tempAsteroid2.transform.Rotate(0, 45, 0) tempAsteroid2.transform.localScale 0.5f tempAsteroid2.GetComponent lt Asteroid gt ().sizeKey 1 Instantiate(tempAsteroid2) Destroy(this.gameObject) Debug.Log("Asteroid destroyed and replaced by 2 more")


Emit particles from only some parts of a mesh I have a 3D mesh with 3 sub meshes in it, for 3 different materials. I would like particles to spawn from the mesh, but only from location where one of the material is assigned. How can I make this happen?


How can I copy an asset folder programatically depending upon a constant? I have a Unity project in which I have 200 games and some 350 scenes. Now I want to make separate builds for each game. All my assets are present in Assets IgnoredAssets ABC folder. To include these assets in my current build the assets of the current game (say ABC) needs to be in Assets Resources ABC. I want Unity to take these Assets IgnoredAssets ABC files and copy them to Assets Resources before making build depending upon a constant defined in some file. I want a kind of automation so that when I mention in my constant file string gameName "ABC" it automatically picks its assets, paste them in Resources and builds for me. How can I do this?


Double jump, without allowing two jumps after falling down a cliff I created a script that allows the player to double jump, which works like a charm. The problem is if the player walks off a cliff, they will still be able to jump twice. But that isn't how double jump works, right? Can someone tell me how to make it so that if the player falls down a cliff, they will be able to jump only once? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody2D rb private Animator anim private float movementInputDirection public float movementSpeed 10f public float jumpForce 16f public int amountOfJumps 1 private int amountOfJumpsLeft private bool isFacingRight true private bool isWalking private bool isGrounded private bool canJump public float groundCheckRadius public LayerMask whatIsGround public Transform groundCheck void Awake() rb GetComponent lt Rigidbody2D gt () anim GetComponent lt Animator gt () void Start() amountOfJumpsLeft amountOfJumps void Update() CheckInput() CheckMovementDirection() UpdateAnimations() CheckIfCanJump() private void FixedUpdate() ApplyMovement() CheckSurroundings() private void CheckMovementDirection() flips sprite if (isFacingRight amp amp movementInputDirection lt 0) Flip() else if (!isFacingRight amp amp movementInputDirection gt 0) Flip() if(rb.velocity.x ! 0) isWalking true else isWalking false private void UpdateAnimations() anim.SetBool("IsWalking", isWalking) private void CheckInput() movementInputDirection Input.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() private void ApplyMovement() player movement rb.velocity new Vector2(movementSpeed movementInputDirection, rb.velocity.y) private void Flip() isFacingRight !isFacingRight transform.Rotate(0f, 180f, 0f) private void Jump() if (canJump) rb.velocity new Vector2(rb.velocity.x, jumpForce) amountOfJumpsLeft private void CheckSurroundings() isGrounded Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround) private void CheckIfCanJump() if (isGrounded amp amp rb.velocity.y lt 0.01) amountOfJumpsLeft amountOfJumps if (amountOfJumpsLeft lt 0) canJump false else canJump true private void OnDrawGizmos() Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius)


In Unity, can I load a local ( Resources folder) website to safari on an ipad In Unity, can I load a local ( Resources folder) website to safari on an ipad? This works fine on a Mac, opening up a wepage from my Resources folder. string path "file " (Application.dataPath) " Resources testsite.html" void OnGUI() if(GUI.Button(new Rect(20, 20, 100, 100), "site")) Application.OpenURL(path) but when I try to load this on an iPhone or iPad, it doesn't seem to work. Am I accessing the address incorrectly for iOS using "file "? If this is not possible, is there an alternative way I can load a locally stored website on an iOS device?


GameObject walk onto platform Unity2D I currently am working on a 2D game designed for android and iOS. I have a repeatedly spawning enemy game object which comes in from the left. I want the enemy game object to walk onto a slope which leads to a platform. I've tried adding physics rendering but it doesn't seem to work. I tried adding colliders to both and still nothing. The enemy object just goes straight through the slope and doesn't actually climb it.


Vibration duration for mobile devices in Unity I'm used the Handheld.Vibrate() method. I know that if you call it several times, you can increase the vibration time, but when it is called once, the vibration lasts about 1 second. But I would like to make an imitation of clicking on the android keyboard. (Vibration 0.2s) How to set the duration of the vibration?


Foreach list loop problem I am having a problem with a foreach loop. When my AOE ability hits an enemy it creates a CircleCollider2D and puts all the enemies on a list, which then the loop goes through and adds damage to their scripts. private void OnTriggerEnter2D(Collider2D other) if(other.tag "Enemy") targets.Add(other) foreach (Collider2D enemy in targets) EnemyHealth hp enemy.GetComponentInChildren lt EnemyHealth gt () hp.TakeDamage(abilityConfig.baseDamage) print(enemy.name " takes " abilityConfig.baseDamage "damage!") But as you can see from the picture below the loop goes 3 times over one enemy, 2 times over the second one and once over the third. As these enemies are the same type they all have the same EnemyHealth script. If anyone would point me in the right direction I would greatly appreciate it.


GraphicRaycaster on the child object containing buttons blocks Raycast from the parent object containing GraphicRaycaster. How to solve it? What I'm trying to achieve is to detect clicks on buttons in UI. Here is the tree I have a parent object SlotMachineScreen containing GraphicRaycaster with a script detecting clicks attached to it if (Input.anyKeyDown) Set up the new Pointer Event m PointerEventData new PointerEventData(null) Set the Pointer Event Position to that of the mouse position m PointerEventData.position Input.mousePosition Create a list of Raycast Results List lt RaycastResult gt results new List lt RaycastResult gt () Raycast using the Graphics Raycaster and mouse click position m Raycaster.Raycast(m PointerEventData, results) foreach (RaycastResult result in results) Debug.LogWarning( quot Hit quot result.gameObject.name) And there are a bunch of child objects with a GraphicRaycaster (red ones) with buttons in it, that I want to detect a click on. But there is no response from my sprit at all when I click on them. I found one solution so far, but its not what I need the solution is to move all buttons from child containers to SlotMachineScreen. Are there any different ways to solve this problem?


Implementing Galaga Style Enemy Behavior in Unity I've been trying to work on a space shooter with the idea of having enemies behaving like it is shown in this video https www.youtube.com watch?v 3p7u8uCR6yw In the video above, enemies fly from different portions outside the view area of the screen doing elaborate movement before finding a spot to form an organized formation. I've been thinking of ways how this could all be done. One way is by having either the enemies and or a manager use a Finite State Machine that will control when there is a "performing" state and when there is a "FindingSpot" state. but at as far as implementing the complex patterns, I'm at a loss. Is there some sort of Math formulation that's used to generate those movement patterns?


Selecting Dictionary item based on custom classes instead of keys I am attempting to write my own path finding code for a game I'm working on that will implement a form of the A algorithm. I store my nodes of the path finding system as a class called nodes and add these to a dictionary with their position in world space as the key for the dictionary. Here's the problem. At one point I need to test the dictionary and return from it the node with the lowest "f" value. I came across the morelinq MinBy function with seemed promising, but so far have not had any luck getting it to work. Here is a stripped down version of the code using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using MoreLinq public class GMove MonoBehaviour public Dictionary lt Vector3, Node gt vectorNodesOpen new Dictionary lt Vector3,Node gt () public Dictionary lt Vector3, Node gt vectorNodesClosed new Dictionary lt Vector3,Node gt () private KeyValuePair lt Vector3, Node gt currentNode new KeyValuePair lt Vector3,Node gt () private bool goal private bool findingPath void Start() goal false findingPath false public void addNodes() several nodes get added to the dictionary based on the A algorithm ending way point and beginning waypoint are stored as Vector3 public class Node public int h get set public int g get set public int f get set public Vector3 pos get set public Vector3 parentNodeVector get set void Update() if(findingPath) while (!goal) currentNode new KeyValuePair lt Vector3, Node gt (vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) This is the line in which I'm attempting to get the node in the open list with the smallest f value. vectorNodesClosed.Add(vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) vectorNodesOpen.Remove(vectorNodesOpen.MinBy(x gt x.Value.f).Key) remove current from open. if (currentNode.Value.pos waypointEnd) if current node end position we are done. goal true addNodes(currentNode.Value.pos, waypointEnd) Add and update nodes The line that is giving me trouble is the first line inside the while loop. I need a way to return the Dictionary item with the smallest "F" value, this would be pretty easy if it were an integer but the F value resides in the Node class. I don't have to use MoreLinq, I would be happy to do it any other way that someone can come up with. Cheers! One more note the code above is incomplete in an effort to minimize it down to only what is necessary to understand the problem more complete code can be provided if necessary.


How to keep a round body rotating without rotating it's center I want to make a game in Unity in which the Player is a sad star. I want to have the points (The "arms and legs and head") of the star to rotate like a circle but to keep it's face (which is in it's center) still. How can I do that ? The body should rotate and it's center should stay still. Many thanks in advance!


How to place grass on custom terrain mesh I made a custom terrain mesh and textured it, now I want to place grass on it, but I don't know how. I only find info about grass with the unity terrain. I am not even sure what exactly to look for. What is the best easiest way to place grass on a terrain? I'd like to do it in the shader if possible, but I guess I will need additional geometry if I want it to "stick out"? (Random example picture http www.beamng.com attachments stuff png.16516 ) I'd appreciate a general outline on how to tackle this problem and maybe some links for further reading. Thanks.


strategies for detecting regressions I know writing tests would be a good way to catch regressions. But what are some other strategies? TDD and game dev don't suit, but catching regressions is obviously something desirable. I would love to find some cheap and easier ways to catch regressions without having to invest a lot of effort or writing tests after the fact. Strategies suggested don't have to be perfect, if they can give rough ideas or things to playtest rapidly then that would also be beneficial. Please advise.


Black and white textures load as turquoise? I have some black and white, and some grayscale textures, that are loading in unity as turquoise and white textures. What is causing this and how can I fix this? Also, can somebody verify that I am supposed to load roughness textures into the "Metallic" slot of the Standard shader? That feels so weird. I was using Principled Shader in Blender to make the original materials. EDIT "Autodesk Interactive" shader has a "Roughness" input but most of my roughness textures and some b amp w textures are still turquoise, what is happening... Here is one of the problem textures (the others are too big, 6mb)


Best approach for destructible car in Unity I'm developing a simple racing car game. I'm wondering what is the best approach to manage visually car destruction. For instance i think one option (expensive) is to build car 3d model with 'separate' mesh, each for any component (bump, door, glass) and relative cooliders.. Other options ? Thanks


Prefabs moved to before position when zooming scene I have build some pipes for waterline drawing, like following screencast https youtu.be WnJb1JwOW78 As you can see, when I zoom in the scene, Pipes moved to lower position. When i zoom out, Pipes moved to higher position. Actually I have changed the position and moved down the pipe position before, the unexpected higher position was the pipe before position. So i guessing this problem might about cache clean. So I I try to clear the GI cache, but the problem still exist. And then I try to build a windows executable file and run game again, problem still. How to fix it? I am using Unity 2018.4


Roofs not appearing in Unity My buildings are fine until I import them to Unity. None of the formats I've come across( FBX, DAE, 3DS Max, Blender Files, any of the Autocad formats, OBJ, PRJ, WRL etc.), have roofs when importing the buildings as one cohesive file into Unity. In Sketchup, Blender etc. they all appear fine. Does anyone have suggestions?


Use eyeray trigger to speak with NPC in Unity3D for Vive I'm developing a first person player game in Unity for HTC Vive. Basically, I want my NPC to speak when my player looks at him for more than a second. I didn't find any eyeray tutorials to achieve this for Vive. Please help.


Unity RTS Multiple Selection Approacah I've recently solved the single selection problem but now I want to do multiple selections. I know I need to find two points with the mouse position to draw a box but it just won't work for me. void Update() if (Input.GetMouseButtonDown(0)) bool dragging true Debug.Log("Multiselect active") MultiSelect(dragging) private void MultiSelect(bool dragging) mouseDownPoint Input.mousePosition if (Input.GetMouseButtonUp(0) amp amp dragging) mouseUpPoint Input.mousePosition Debug.Log("First pos " mouseDownPoint " Second pos " mouseUpPoint) dragging false What is a better way to achieve what I'm trying? If someone can tell me a way that can also detect any units inside the area that'd be nice too.


How do you manage versioning across platforms in Unity? I'm just beginning to look into versioning games in Unity and noticed that Unity seems to offer different things depending on the platform you are building for. For instance, Android and iOS seem to have their own individual properties for versioning while Desktop has no versioning functionality at all out of the box. Since I'm working on a game that has builds for PC, Mac, Android, and iOS, I need to determine how we want to manage version numbers within our game without having to manually manage individual version for each platform. How do you solve this?


DontDestroyOnLoad() doesn't work in Unity I have a problem with DontDestroyOnLoad() in Unity. It does not work! My code private static PlayerSpawningScript instance public void Awake() Debug.Log ("PlayerSpawningScript awake") Debug.Log ("Instance " instance) if (instance null) Debug.Log ("Initializing PlayerSpawningScript instance") instance this DontDestroyOnLoad (gameObject) if (instance ! this) Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.") Destroy (gameObject) Debug.Log ("PlayerSpawningScript instance " instance) public void OnDestroy() Debug.Log ("Destroying PlayerSpawningSceript instance " instance.ToString ()) Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?


How can zoom into my object when that object is being clicked? Suppose that I have the three game(cube,Quard,sphere) object. When I click on a particular game object suppose think I have clicked on the cube,the cube object should get zoomed in on the screen. how can I do that? How do I center and zoom into my cube game object after selecting the cube? I think it has something to do with the camera but how do I center the view with the camera? I have used the below code for zooming the object.For one object its working.But when I place different object and apply this code then when i click on one object all the three object is getting zoomed. Can anyone help me out in solving this issue Here is the code function OnMouseDown() OrthoZoom(1.5) function OrthoZoom(size float) var cam Camera.main while (cam.orthographicSize ! size) cam.orthographicSize Mathf.MoveTowards(cam.orthographicSize, size, speed Time.deltaTime) yield


Unity Assets folder is empty after opening package from the asset store I downloaded the following Survival Shooter Tutorial from the Asset Store https www.assetstore.unity3d.com en ! content 40756 I was prompted to open it in Unity so I did and began following this tutorial https www.youtube.com watch?v lP6epjupJs I am only 2 minutes into the first video and am stuck. In the tutorial there are lots of folders in the assets folder. I took a screenshot of what my screen looks like to show that it is empty.


Directional light shadow on terrain When player is walking on terrrain, around him Unity is rendering shadow coming from directional light. But after some radius in the distance, shadows are not rendered. Only when player walks close to some prefab, shadow is being drawn. This is not very realistic. I would like that shadows are visible in the distance as in real terrain. How to fix that ?


Difference between Update method and FixedUpdate in Unity? i am starting to learn Unity3d and one of the confusion i get is difference between Update() and FixedUpdate(). I am following Lynda Unity 2D game development tutorial there, the instructor uses Update method, the player has RigidBody2D component and Box collider, he uses the Update method to translate the player, but when i do same in Update the player doesn't move but when i do it in FixedUpdate, everything works. He is giving tutorial from Unity 4.3 and i am taking the course in Unity 4.6. Where should i use Update and FixedUpdate?


SocketException No connection could be made because the target machine actively refused it I am working on connecting a client to a server using socket connection. I have a button, when I click on the button, it's giving the below exception in Unity. "SocketException No connection could be made because the target machine actively refused it.". What will be the issue? Can anyboady help me out? Below is the code I have written for connecting to the server internal Boolean socketReady false NetworkStream theStream StreamWriter writer StreamReader reader try connect new TcpClient (host, port) theStream connect.GetStream () writer new StreamWriter (theStream) reader new StreamReader (theStream) return true socketReady true catch(ObjectDisposedException) return false


Unity Input System On Screen Button doesn't work with touchscreen 2019.3.2f1 I am trying to make my player jump whenever the space button is pressed (if a keyboard is present), and I'm adding a on screen button for players on mobile. The on screen button works fine in the editor but when I try the game in a device the on screen button doesn't work. Here's how things are set up Change the Active Input Handling to Input System Package (New) on the player settings. Create the Jump action for the Player action map. Bind lt Keyboard gt space to my Jump action. Add a PlayerInput component to my player object, pass my actions file to it, and set up the events to call for each action. Change the StandaloneInputModule to an InputSystemUIInputModule in my event system object. In my canvas I add an image and add OnScreenButton component to it (I do NOT add a Button component). Set the control path to lt Keyboard gt space. When I try the game on the device the rest of the UI buttons work fine except the on screen button. On the editor though (using mouse input), the on screen button works fine. This is my first time using the Input System, I had actually found it somewhat nice to work with, however this does seem really strange. It is either a really strange bug (unlikely), or I messed up some setting (the setup process feels really convoluted actually).


Making a gameobject move back and forth in Unity So i have this enemy gameobject and i want it to move in a certain pattern like a patrol. So i want him to move from A to B to C then Back to B to A. The script I worked out makes him go from C to A directly but I dont want that. Can someone please help . The Length of PatrolPoint Array in 3 using UnityEngine using System.Collections public class EnemyPatrol MonoBehaviour public Transform patrolPoints An Array of path points to be followed private int currentPoint public float enemySpeed void Start() currentPoint 0 transform.position patrolPoints currentPoint .position Starting Point void Update() if(transform.position patrolPoints currentPoint .position) currentPoint if(currentPoint gt patrolPoints.Length) currentPoint 0 transform.position Vector3.MoveTowards(transform.position , patrolPoints currentPoint .position , enemySpeed Time.deltaTime)


How can I make a trail renderer flat with the normal of the nearest face? I'm making a basic skid system for a car model using a trail renderer. I have everything setup and working properly except that the trail renderer always faces the camera. I want the trails to be perfectly flat with the ground. So I thought if unity can make the faces all rotate towards the camera, then would it be able to rotate towards the normals of the nearest faces?


How do I roll a ball with a Rigidbody? I have a ball in a game that rolls around just fine with Rigidbody.AddForce(). I have other non physics balls, however, that I control directly with Rigidbody.MovePosition(). It seems that no matter what I do, no matter how interpolation and collision detection are set, the ball does not "roll" when moved with Rigidbody.MovePosition(). It teleports, but IsKinematic is not set , as instructed by the documentation. How do I get the ball to roll properly with Rigidbody.MovePosition()? Alternatively, if that's not possible, how do I calculate the rotations manually?


Unity 3D, Making contiguous looking worlds Im currently involved in making a third person cooperative mobile game in Unity and in said game there will be an area for players to walk around in with various elevations and whatnot throughout the field. Its designed to be set up with 4 biomes in the area to go along with the games theme but I was wondering what would be the best way to mask the "boundaries" or "cut off points" in this area? From certain vantage points its pretty obvious that the terrain used to make the world simply stops and I was wondering if anyone knew any tips and insights on how to best mask these boundaries without too much "padding" in the game area in order to keep it relatively less taxing on a mobile device. Thank you in advance.


In Unity, how to hide objects from specific cameras without using Layers The situation is that there are multiple players that can collect items. When a player collects an item, the item will disappear from that player's screen but still be visible to other players. I know I can use LayerMask to achieve this effect. However, what if there are more than 32 players? (Unity Layer has 32 bits). How can I still hold this effect? I tried using OnWillRender() to check which camera is rendering the object in order to disable its renderer. This does not work because once the renderer has been disabled, OnWillRender() will not be called again for other cameras.


Unity3d CarController character positioning issue I use the unity standard asset components CharacterController and Car and put an empty gameobject onto the car where the camera should be placed when i am inside the car. The empty gameobject is called "Driver". The character controller has an empty called "Head" where its head is. When i get in the car i perform the following operation GameObject car GameObject.Find("Car") transform.position car.transform.Find("Driver").transform.position Vector3.up 1 transform.parent car.transform.Find("Driver").transform Camera.main.transform.position car.transform.Find("Driver").transform.position Camera.main.transform.rotation car.transform.Find("Driver").transform.rotation and to get out of it, i use the following GameObject car GameObject.Find("Car") transform.position car.transform.position transform.parent null transform.rotation Quaternion.identity Camera.main.transform.position transform.Find("Head").transform.position My problem is when i get into the car and out again, the character is positioned at the position where i have entered the car, so it doesnt seems to update its position with the car movement. What am i doing wrong? Thanks in advance


Simple cartoon water shader shoreline I'm currently attempting to create a cartoon ish water shader with a shoreline. After looking around trying to find out how other games do it i figured out it has something to do with getting the distance from the depth map (which doesn't include the water when it's render queue is set to transparent) and the and the world position of the current pixel. From certain angles i'm actually getting very close to the desired result as show here The topmost island almost has the desired result, but as you can tell, the closer it gets to the camera, the more out of place the effect becomes. here's a zoomed out top down view illustrating the problem as per request, here's what the terrain looks like beneath the water surface (animated gif) and of course, here is my shader code Shader "Custom CartoonWater" Properties Color ("Color", Color) (1,1,1,1) Glossiness("Smoothness", Range(0,1)) 0.5 ShoreFade("Shoreline Distance", Float) 1 SubShader Tags "Queue" "Transparent" "RenderType" "Transparent" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf StandardSpecular Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D CameraDepthTexture struct Input float3 worldPos float4 screenPos half Glossiness fixed4 Color float ShoreFade void surf (Input IN, inout SurfaceOutputStandardSpecular o) o.Albedo Color.rgb o.Smoothness Glossiness fixed4 depth tex2Dproj( CameraDepthTexture, UNITY PROJ COORD(IN.screenPos)) o.Albedo Color if (distance(LinearEyeDepth(depth), distance( WorldSpaceCameraPos, IN.worldPos)) lt ShoreFade) o.Albedo fixed4(1, 1, 1, 1) ENDCG FallBack "Diffuse" any help is greatly appreciated ) thanks in advance.


Clicking in a UI Button activate another I'm new to unity and creating my first game to learn more about it. Now i got a problem wich i click on a button and sometimes another button active, for example i press "Options" on pause menu and it active "Restart" or the "Main Menu". if someone can help me, I appreciate it. I set them up like this, if there's any error or need more info please let me know. And in the first image i tried split in 2 canvas, but didn't work. P.S. It happens even with buttons with no actions or scripts on them. public void OnPause() Time.timeScale 0 isPaused true unPauseButton.SetActive(true) pauseButton.SetActive(false) PauseGameMenu.SetActive(true) GameObject.Find("PowerUpSpawner").GetComponent lt PowerUpManager gt ().enabled false public void UnPause() Time.timeScale 1 pauseButton.SetActive(true) unPauseButton.SetActive(false) PauseGameMenu.SetActive(false) GameObject.Find("PowerUpSpawner").GetComponent lt PowerUpManager gt ().enabled true isPaused false


Swiping with rigidbody My character moves continuously forward with rigidbody.velocity v3Force strength My Swipe script is based on a youtube tutorial from https www.youtube.com watch?v 9ZIHx09GevI I just changed the end result with rigidbody.AddForce(v2Force strength1) For Right Swipe and below for Left Swipe rigidbody.AddForce(v1Force strength1) Here are the vForce variables var v1Force Vector3 transform.right var v2Force Vector3 transform.right var v3Force Vector3 transform.forward The swipe works fine, but the result isn't what I'm aiming for because when I swipe left right my character seems to be moving only one frame left right. And then continues moving forward. When I disable the forward movement, the swipe works great and makes my character move right left for a period of time, after I swipe. My question is how do I reach this result(moving sideways more than just a frame) with my continuous forward movement enabled?


Making NavMeshAgent to look the direction it was moving when it stops I'm currently using NavMeshAgent as my player character controlled by keyboard or gamepad input. Also, I'm flipping my character instead of turning via controlling localScale as below. private void FixHeadRotation() float dir (myAgent.velocity.normalized.x gt 0) ? 1 1 transform.localScale new Vector3(1, 1, dir) However, since I'm relying on the velocity I'm getting the direction(flip) right when moving, but not when I'm not moving(x should be 1 but 1 since no velocity). I've noticed the NavMeshAgent has built in function displaying an arrow gizmo over the agent's head. Perhaps I could use that(don't know how atm)? or any other suggestions to this?


NullReferenceException until tile is spawned I have a tile and tile has enemies spawn positions, and spawner script in it. Everything works fine when tile is spawned, my ray hits the collider in tile and enemies get spawned, but my spawn script is in tile my ray script is in my player so im reaching from my PlayerMove script to spawner script, but until my tile is spawned i get this error NullReferenceException Object reference not set to an instance of an object because tile is not spawned yet after its spawned error stops, but after tile is deleted it starts again how can i get rid of this error. PlayerScript private Spawner spawner private RaycastHit hit private void Update() spawner GameObject.FindGameObjectWithTag("Spawner").GetComponent lt Spawner gt () DrawRay() private void DrawRay() Ray ray Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)) if(Physics.Raycast(ray,out hit)) if(hit.collider.tag "SpawnerCollider") if(hit.distance lt 5) Destroy(hit.collider) spawner.Spawn() SpawnerScript public Transform spawnPos public GameObject fireBall public void Spawn() for (int i 0 i lt spawnPos.Length i ) Instantiate(fireBall, spawnPos i .position, Quaternion.identity)


How do I set a scene up for two players? I m finishing a game in Unity, but I have a new requirement make it multiplayer. I will do this by splitting the screen and running two instances. Is there a way to instance a scene twice at the same time, and render them two a different part of the screen? Alternativley, what is the best approach to achieve this?


How would I go about adding a tooltip to a Unity UI Image? I'm going to try out the community here once more, I haven't had very good look in the past with getting help. I'm iterating through a series of List() and I'm creating a bar graph and a line graph based on those values, Later I'll replace the List with a file which it retrieves the values from. I'm having a problem though with creating a tooltip. I know how to add them to buttons created under OnGui() but that's about it. I've spent the past 2 days trying to figure this out and I'm just not sure how to go about making the bar images and dot's show up under public void OnPointerEnter(PointerEventData eventData) and OnPointerExit() I know that print(eventData.pointerCurrentRaycast.ToString()) will display the item I'm hovering over and it seems to work fine for everything except the GameObjects that are created by my script private GameObject CreateBar(Vector2 graphPos, float barWidth) GameObject gameObject new GameObject( quot bar quot , typeof(Image)) gameObject.transform.SetParent(graphContainer, false) gameObject.GetComponent lt Image gt ().color barColor RectTransform rectTransform gameObject.GetComponent lt RectTransform gt () rectTransform.anchoredPosition new Vector2(graphPos.x, 0f) rectTransform.sizeDelta new Vector2(barWidth barWidthMultiplier, graphPos.y) rectTransform.anchorMax new Vector2(0, 0) rectTransform.anchorMin new Vector2(0, 0) rectTransform.pivot new Vector2(.5f, 0f) return gameObject If anyone could give me a hand on how to make this show up under eventData I can figure the rest out from there. Or if you have a better method you wouldn't mind sharing I would appreciate that.


Very less vertical transformation Im using pretty basic code here charcter.transform.Translate(Vector2.up speed Time.deltaTime) Im using rigidbody 2d and I'm creating a platformer. When i press the button the character transforms very little in y axis.


Loop through multidimensional array in C (Unity) I have this data As you can see there's a 2nd board there. Now what i want is something like this PSEUDO CODE If the first boards table 1,1 is not NULL then I will need to find out now if table 0,1 and table 0,0 has the same length as table 1,1 and table 1,0 then display in the 2nd board a blue circle if it is the same in length if not red circle But if the table 1,1 is NULL then I need to know compare 1st column and 2nd column if they have the same length then display in the 2nd board a blue circle if it is the same in length if not red circle END PSEUDO CODE I tried doing the following COLUMN for(int col 0 col lt table.GetLength(0) col ) int sum 0 ROW for (int row 0 row lt table.GetLength(1) row ) if (table col, row ! null) Debug.Log("Column 1 has this value " table col, row ) Debug.Log("table column " col " has " sum " data") For now I can only get the whole Row and Column but I don't know how to do that pseudo code.


Prevent VS Code opening the Unity scripts twice Is it possible to prevent VS Code opening the Unity scripts twice? E.g. I opened Unity project, double clicked a script and got my project (Assets folder) opened in VS Code, now I go to Unity make a few changes and open another script file. The script file opens another instance of the VS Code. I would like to have the file opened in the currently opened instance instead of opening a new one. Is it possible? Thank you.


Loading next scene when counter is down to 0 I am trying to let my Unity project load next scene when the counter I have is down to 0. However I am unable to do that for some reason. The way I am trying to do it by int i SceneManager.GetActiveScene().buildIndex void Update () if (GameObject.FindGameObjectsWithTag("Birds") null) SceneManager.LoadScene(i 1) In the editor I have created a folder where I have made 3 scenes. Have called them Level 1, Level 2 etc. What am I doing wrong?


How do I set up a bullet to fire towards the mouse pointer? I am making an FPS, in Unity. I have a player with a gun, and I have a bullet prefab. I changed the mouse pointer to look like a crosshair, but I don't know how to place the bullet where the crosshair is aiming. The player movement is on the x and z axis. I have done lots of research on the Internet, and couldn't find anything suitable most of what I found, I could not understand enough to change it according to my needs. How do I set up a bullet to fire towards the mouse pointer?


Jenkins CI with Unity on local machine I have seen some people using Jenkins CI with Unity, would it be wise to install Jenkins locally and use it with Unity? I've never used Jenkins, so I can't imagine why not. Is this ill advised? I would have set up Jenkins on my old laptop, but I don't have windows on it. Is there any harm in using it locally?


Transactions on lists of coins of different values For learning purposes, I am developing the first steps of an idle game with exponentially higher income numbers. Usual int, long, etc. can't store big enough numbers for that. I looked through many threads which I found on google and using a list (or an array) which is separated in e.g. bronze coins, silver coins, gold coins, etc. seems to be the cleanest version. In my first approaches I created this list namespace Coins public class script coinHandler MonoBehaviour public List lt Coin gt coinList new List lt Coin gt () list based on the quot Coin quot class new Coin() Name quot bronze quot , new Coin() Name quot silver quot , new Coin() Name quot gold quot , new Coin() Name quot diamond quot , public class Coin public string Name get set public int Amount get set public int Multiplier get set I want each coin type to go up to 999999. This means 1 silver 1000000 bronze, 1 gold 1000000 silver. I can't get my head around a way to do maths with this list. Example Player has 3000 GOLD, 320000 SILVER, 524321 BRONZE Player wants to buy something for 20 GOLD, 120000 SILVER, 300000 BRONZE Just subtracting 20 from GOLD, 120000 from SILVER, and 300000 from BRONZE won't always work. For example when a Player has no BRONZE but some SILVER you can't subtract 300000 BRONZE without converting SILVER to BRONZE first. Q What would be an efficient function to subtract the price from the total amount? What about multiplying and dividing? Accuracy is not important. When spending a few GOLD, nobody will care about 10000 BRONZE.


Which collider to use on "island" situation? I have a 2d top down unity game where the player is on an island. The shape of the island is random generated and he is not able to "escape" from the island. So which Collider should I use for realizing this? Is there some form of an "inverted" collider? Are colliders able to have a hole in them? Or should I create a polygon collider with a small gap (This could be quite difficult if the polygon bends the wrong way)?


Unity3d crash on Launching on Ubuntu I have a problem that bugged me for quite some time now I'm trying to Install Ubity3d on Ubuntu I Followed some instructions that i've found after some research I downloaded and installed UnityHub and the latest release (UnitySetup 2019.1.0f2) that i found on Unity on Linux Release Notes and Known Issues and i moved the installed unity file from Home to opt folder and made it run on command unity3d and here is what i did exactly sudo mv Unity 2019.1.0f2 opt Unity3D sudo ln s opt Unity3D Editor Unity usr bin unity3d and the problem is that every time i open Unity editor (via both the command line and UnityHub) the unity Launcher appears for moments to proccess and then crashes and the editor doesn't open and the error changes everytime i try to open the program here are 3 forms of errors that appeared to me, here is the first Gtk Message GtkDialog mapped without a transient parent. This is discouraged. Gtk Message GtkDialog mapped without a transient parent. This is discouraged. Gtk Message GtkDialog mapped without a transient parent. This is discouraged. Gtk Message GtkDialog mapped without a transient parent. This is discouraged. Unity Package Manager (Upm) Parent process 5258 was terminated Segmentation fault (core dumped) and the second Gtk Message GtkDialog mapped without a transient parent. This is discouraged. Gtk Message GtkDialog mapped without a transient parent. This is discouraged. (unity editor 6651) Gtk CRITICAL gtk file chooser widget set current name assertion 'priv gt action GTK FILE CHOOSER ACTION SAVE priv gt action GTK FILE CHOOSER ACTION CREATE FOLDER' failed Gtk Message GtkDialog mapped without a transient parent. This is discouraged. Unity Package Manager (Upm) Parent process 6651 was terminated Segmentation fault (core dumped) the third is Gtk Message GtkDialog mapped without a transient parent. This is discouraged. 0616 110743 ERROR browser main loop.cc(161) Running without the SUID sandbox! See https code.google.com p chromium wiki LinuxSUIDSandboxDevelopment for more information on developing with the sandbox on. 0616 110744 ERROR browser main loop.cc(207) Gtk gtk window present with time assertion 'GTK IS WINDOW (window)' failed ATTENTION default value of option force s3tc enable overridden by environment. USER USER Unity Package Manager (Upm) Parent process 7583 was terminated and stuck on that.... well i know that there's something wrong with GTK but i have no experiace with it and i didn't find anything useful on this matter on google OS Ubuntu 16.04 LTC


How to use rigid bodies for characters? First off, I am making a game similar to SSB, which relies heavily on physics, even though it is a sidescroller. I am currently using Unity. In Unity there are quot character controllers quot which are used for characters that move, but they don't interact with other physics objects. There are also rigid bodies, which are completely realistic physics components. I can't figure out how to use rigid bodies for human humanoid characters. Here's some questions I have How should I move the character? Applying forces is not the way to do it, right? Would you set velocities or pixel by pixel movement, perhaps? What kind of collider should I use? I've been using a capsule collider. But is that the best way? How do you make him not fall down!? After some experimenting, I discovered that the character falls over (from applying force velocity and from the capsule collider tipping it over). Would you constrain the rotation in the Z axis? What do you do when he gets hit? If you've ever played SSBB you'll be familiar with this topic. I'm thinking that applying a force would be best in this condition? If you did constrain the rotation, would you un constrain it?


Execute function every X points In my game, the score can go up quite rapidly and by varying amounts, depending on the action taken. For instance, at the start of the game, one could climb from 1 50 one by one, or they could rocket past 50 by getting a score of 10, 25, and 40. My question is How do I call a function every time they pass a factor of 50 (50, 100, 150, 200, etc.)?


Find the coordinates between two points based on third You can see two points in this picture. Points are surrounded by collider which is set to trigger. Points can either be Vector3 or Vector2, shouldn't make any difference. I need to get the coords on gray line if mouse enters the trigger, at the exact point where mouse and gray line form 90 degree angle. Gray line is just an straight line between 2 points. All the data left point coords right point coords mouse coords Is it possible with the data I have and how?


Understanding Torque in Unity This is (hopefully) a simple question that should avoid me asking a more complex question. This is in Unity (2D) but hopefully this is a general physics principle I am not getting. I am applying a torque to a 2D object. The object has a scale of 1, a RigidBody2D with a mass of 1 and no angular drag or undergoing gravity. It is a CircleCollider2D with a radius of 1. There is nothing else attached to the object. In the following code I apply a torque of Pi for one second. In linear motion (and from my understanding of torque) I would expect the angular velocity, after one second, to be Pi (or 180deg s). However, running this code and printing out the speed at t 1.0, the speed is 90deg s. void FixedUpdate() if (time lt 1.0f) rigidbody2D.AddTorque(Mathf.PI) This is consistent, applying a torque of 2Pi gives me a velocity of 1Pi after the time. Where is this factor of 2 coming from?


Does transparency work with SSS in Unity's HDRP Lit shader? I am using Unity's HDRP Lit shader in Shader Graph (all are version 4.8.0 preview) on Unity 2018.3.0b12. I am trying to use both transparency and subsurface scattering on the material. However, it appears that the visual appearance loses SSS when transparency is introduced. Example The cube on the left has transparency enabled, and has no visible SSS. The cube on the right has the same SSS settings as the left cube, however the right cube has no transparency enabled. I need transparency to fade in the cube depending on its position, like this And here is my master node If anyone has an alternative solution that sidesteps this potential limitation, I am all ears. Cheers!


Unity Vector3 position inside collider I am trying to create a "wander" action that will make my NPC walk to a random position. The catch is that the NPC should only go positions inside of a collider. I have a huge Sphere that has a collider on it now I only want my NPC to go to positions that are inside that Sphere collider. My question is how do i find a random position inside of a colider? Update So after testing i am unable to use colliders because the sphere is too big here is an image of my gameobject As you can see from the image I have a huge sphere that my NPC's will have to stay inside when wandering In order to use the Collider.ClosestPoint() the collider has to be a Box, sphere or a mesh collider with a convex. Sadly this is not feasible for me because the sphere should not collide with other objects. So my question is how do I find a point inside this gameobject?


Unity blur on one camera effects the other as well I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly. So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render. I have the cameras like Cam 1 Clear flags Don't clear (this is the main, sharp cam) Culling mask sharp layer has no blur effect (or any other post proc effect). Cam 2 Clear flags don't clear (this is the blur cam) culling mask blur Has Blur (optimized). Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground. The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it. Question is, how to set this up so only the desired layers get the blur?


How do developers implement custom systems (lighting, physics, etc.) in premade game engines that already have these systems, like Unreal or Unity? Unreal has built in systems for stuff like lighting, for example. If a developer wanted to create and use their own lighting system in Unreal, how do they go about doing that? Or are these systems already so customizable that creating a custom system isn't necessary?


Unity move Vector3 position with transform How can I move a new Vector3 position with a Transform? Like the transform is the parent the vector. Example if I want to push the x position for example by 10 value and I rotate the transform its push in world coordinate but I want to push by the rotation too. void Update () temp transform.Find("Transform").position temp new Vector3(temp.x 10.0f, temp.y, temp.z) Debug.DrawLine(transform.Find("Transform").position, temp)


How do I prevent floating and jittering when on the ground and using spherical gravity? TL DR My ship floats and jitters when it lands on a sphere. To elaborate on the title I'm experimenting with a 3D space game. I have created a sphere, which in turn has a larger sphere overlapping it, within which, gravity will take place. However, once my player's ship (currently using an arrowhead) lands on the planet, it doesn't actually make contact with the surface of the sphere, and then the ship begins to rotate erratically and jitter. Code below. private void OnTriggerStay(Collider other) if (other.CompareTag("SoI")) inSoI true This trigger checks to see if the ship is in the larger overlapping sphere. I have another identical block for OnTriggerExit which sets inSoI to false. I also have a OnCollisionEnter which sets another variable, landed to true, and a OnCollisionExit which sets it to false. private void FixedUpdate() if (inSoI amp amp !landed) gravityVector (planet.transform.position transform.position) rb.AddForce(gravityVector.normalized planetrb.mass rb.mass gravityVector.sqrMagnitude) Simply, if in the larger sphere, then accelerate towards the planet. I tried disabling gravity if in contact with the sphere. It removed a lot of the jitter, however it still floats, and it still rotates side to side. The sphere by the way, is the standard Unity sphere, scaled 10000x in every axis. I don't need code (though it would help), any solution is fine, even if it means abandoning the project.


Emit particles from only some parts of a mesh I have a 3D mesh with 3 sub meshes in it, for 3 different materials. I would like particles to spawn from the mesh, but only from location where one of the material is assigned. How can I make this happen?


Game is darker on build I've been recently doing test builds of my game. In Unity, I worked on baking the lighting to ensure everything looked fine. However, upon building, the game level becomes far darker and much of the lighting and baking is ineffective. Here is how the scene looks in the editor And here is how it looks in the built game It's much darker than intended. Here are my lighting settings which I've baked in Unity's Editor. These settings and lightmap parameters were designed to, at least in the editor, provide decent quality while making light bake times relatively quick. However, I've noticed that newer Unity's Lighting settings are way different now, so perhaps something is amiss here? I've been at my wits end trying to figure this out for the past while, but I can't figure out why this is happening or how to fix it. Any ideas?


Animator.SetTrigger does not trigger an Animation I have a basic animator setup for my Unity Character which has a "block" functionality when pressing the E key. So far, so good. However I've made a transition from "Blocking Idle" to "Blocking React" (which means that the character was hit) using a Trigger "tookDamage" (default to false). The problem is that the character gets hit but does not transition to "Blocking React" animation. Code Sample From Character Controller script if (Input.GetKeyDown(KeyCode.E) amp amp ! isBlocking) animator.SetBool("isBlocking", true) isBlocking true else if (Input.GetKeyUp(KeyCode.E) amp amp isBlocking) animator.SetBool("isBlocking", false) isBlocking false From my Character script public void TakeDamage(float damage) health damage this.GetComponent lt Animator gt ().SetTrigger("tookDamage") And this is my transition Am I missing something?


How to check if a test ad is ready I was going through UnityAds for Unity3D, and came across this setting AD TEST MODE Force all So as I understood it states that I will be able to see real ads, in test mode, without monetizations on my testing tool, which in my case is Unity3D IDE, but I am still getting that blue sample ad screen quot Here would be your ad screen quot . Is there anything that I can do to check if any ad is placed for my app, and check this via code before Advertisement.Show() statement? Or am I missing something?


Iterating through all animator layers in Unity Mecanim I'm aware of how SetAnimatorLayerWeight works, I'm looking for a way to iterate through all layers of my controller at runtime. I've four layers and expect more, and need to update them at once, in essence, what I'm trying to do is something like this. To clarify The code below is boilerplate of what I'm trying to do. void SetCurrentWeaponLayerWeight(int index) animator.SetLayerWeight(index, 1) foreach(AnimatorLayer l in Animator.Layers) if (l.index ! index) animator.SetLayerWeight(l.index, 0)


Is wireframe effect possible without geometry shader? I am trying to write a shader that highlight the edge between each pair of vertices, much like the UCLA Wireframe Shader. All implementations I came across require geometry shader support. I am wondering if this is possible with just vertex and fragment shaders? (Of course, I can use texture to workaround it but I am trying to avoid create custom textures for each model that I need this effect. On the other hand, I could just use geometry shader but it presents quite a problem when porting to iOS, which lacks support.)


Build includes sprite packer atlas and its original textures I use Unity's Sprite Packer, it's working great. However, when I looked at the build report (in the Editor.log) it turns out that the build often includes the generated atlas texture and its original textures too. It wastes too much space. I checked the size of the unzipped APK and the build report was correct. I tried several configurations (adding and removing textures) but I could not find any regularities. Some observations I could reproduce this only if I use 25 textures in an atlas with variable sizes. Texture compression settings did not matter. Packer policy could modify the result but did not solve the problem. Has anybody had similar experience? I can upload my test project if necessary.


Why does my tile palette not arrange nicely? I made my own Hex Point Top Tile sprite sheet, ensuring it's pixel perfect and align well. Slicing in Sprite Editor has no problem too. However, when I drag the sprite sheet to a new Palette in the Tile Palette panel, the tiles show up with random spaces. See screenshot below What did I miss? The sprite sheet is here, 30 x 30px offset, 24 x 24px padding, 66 x 66px tile size I'm using Unity 2019.3.10f1.


How to know my lighting shaders matches famous models? I have some diffuse and specular lighting shaders based on famous models like lambert etc. Thing is, how can I know that my shader is actually implementing the correct formula? I can see my materials does reflect light but how can I be sure that my formula matches the models. Any way to test this?


Unity c How to slow down rotation over time? I am making a space combat game, in which the player can press q and e to roll their ship. I did this by adding torque to the rigid body when the player press q or e. However, after they do so, they keep on rotating. How do i make the angular velocity slowly go back to zero? I tried using angular drag, but that does not work. public float TurnSpeed public Rigidbody rb float currentturn Vector3 turn float turnEnabler bool iszero public float dampener Update is called once per frame void Update() rb.AddTorque(new Vector3(0, 0, turnEnabler)) if (Input.GetKey("e")) turnEnabler TurnSpeed if (Input.GetKey("q")) turnEnabler TurnSpeed rb.angularDrag dampener


Unity store data in database Is it possible to store assets used in a Unity game (2D or 3D) in the database? I think it is less efficient but want to have single source of truth and maybe have the game contact the database everytime it loads to get the new updates.


Why are cube map axes sometimes labelled incorrectly? In both 3ds Max (which uses a right handed coordinate system) and Unity (which uses a left handed coordinate system), the cube map faces labelled "left" and "right" show the view facing the opposite direction. This is not the case with the front, back, up, or down directions. In 3ds Max, this is in the context of rendering cube map images from a Reflect Refract map. In Unity, both cube map textures and skyboxes exhibit the same left right "confusion". Oddly, however, the GUI labels for cube maps indicate that left is the X direction and right is the X direction which is correct in Unity while skyboxes indicate the opposite (all other axial labels are consistent between the two). The upshot of this is that cube map images rendered by 3ds Max (which each have a suffix indicating their viewing direction) can be assigned to the texture slots in Unity with the same name and everything will work, but only because both programs label the left view as "right" and vice versa. The only discussion of this I was able to find online was in a blog post on floored.com (search for "Unity Skybox Weirdness" and it should come up I'd post a link but I lack sufficient reputation to include more than two). Here's an image from the post that illustrates the issue Is there a reason why the left right axes of cube maps are mislabelled in both of these programs? Although it's trivial to ignore once you're aware of it, it seems like there should be a good (or at least historical) explanation for it, unless it's simply a case of a long overlooked bug in 3ds Max that the Unity developers decided to accommodate. Any thoughts would be appreciated!


How to disable animation root motion I downloaded some animations with root motion from Mixamo and the corresponding character model. After created an animator with those animations and added it to the character game object, the root motion was causing the transform to move around, which was not supposed to happen. I tried to uncheck "Apply Root Motion", and set "Motion Root Motion Node" to "None", but neither of them worked. The only thing that worked is checking "Loop Time Loop Pose", but it doesn't make much sense to mess with root motion, someone even proposed it shouldn't disable root motion. So, how to disable animation root motion? Also I'm confused, is root motion optional? Must I get animations without root motion if it's not needed?