18.5 9 Android ratio force to 16 9 problem in Unity I want to my game build in devices with 18.5 9 ratio like Samsung S8 forced to be displayed as 16 9 ratio. I already set Aspect ratio mode to Custom and set it to 1.86 in Player Settings. I also overrided Android Manifest like this lt ?xml version "1.0" encoding "utf 8"? gt lt manifest xmlns android "http schemas.android.com apk res android" package "com.unity3d.player" xmlns tools "http schemas.android.com tools" android installLocation "preferExternal" gt lt supports screens android smallScreens "true" android normalScreens "true" android largeScreens "true" android xlargeScreens "true" android anyDensity "true" gt lt application android theme " style UnityThemeSelector" android icon " drawable app icon" android label " string app name" android isGame "true" android banner " drawable app banner" gt lt activity android name "com.unity3d.player.UnityPlayerActivity" android label " string app name" android screenOrientation "sensorLandscape" android launchMode "singleTask" android maxAspectRatio "1.86" android resizeableActivity "false" android configChanges "mcc mnc locale touchscreen keyboard keyboardHidden navigation orientation screenLayout uiMode screenSize smallestScreenSize fontScale layoutDirection density" android hardwareAccelerated "false" gt lt intent filter gt lt action android name "android.intent.action.MAIN" gt lt category android name "android.intent.category.LAUNCHER" gt lt category android name "android.intent.category.LEANBACK LAUNCHER" gt lt intent filter gt lt meta data android name "unityplayer.UnityActivity" android value "true" gt lt activity gt lt meta data android name "unity.build id" android value "633a700a 7389 4a19 972c ac1f177788f8" gt lt meta data android name "unity.splash mode" android value "0" gt lt meta data android name "unity.splash enable" android value "True" gt lt meta data android name "android.max aspect" android value "1.86" gt lt application gt lt uses feature android glEsVersion "0x00020000" gt lt uses permission android name "android.permission.INTERNET" gt lt uses feature android name "android.hardware.touchscreen" android required "false" gt lt uses feature android name "android.hardware.touchscreen.multitouch" android required "false" gt lt uses feature android name "android.hardware.touchscreen.multitouch.distinct" android required "false" gt lt manifest gt And as you see add attributes like android maxAspectRatio amp android resizeableActivity to AndroidManifest manually. But by installing the app on devices with that specific ratio, the game still running full screen and out of the bounds. I am using Unity 2018.1.4f1 (64bit).


AssetBundles with shaders that contain include to cg hlsl I have a shader that contains some includes to other cg hlsl scripts. If i put that shader into an AssetBundle, how am i suppose to handle the cg hlsl scripts? Are they not necessary anymore because they are compiled into the shader during the AssetBundle build process? Unity version is 5.6.6f2 Or do i have to put the cg hlsl scripts into the AssetBundle too? If that is the case, how do I load them during runtime such that the Shader finds them? Someone suggested me to inline them, but I would like to avoid it if possible.


Unity new Input system lists actions and compare them to current input I have a scriptable object called Move that had a list with keycodes (for example to make a Hadouken) easy to use and compare with the current input made it with the old system, but with the new input system I don't know how to make a list of actions (actions that are in my Input Action Asset not new ones) and compare that with the current inputs (and also I do not have any idea how to make buffering inputs like the last input repeats 3 frames). I already tried and not worked (InputMa is my InputActionAsset generated class) InputActions InputMa InputMa.PlayerActions InputActionReferences this seems the correct option, but I don't know how to get the reference from the current input.


Unity Transforming horizontal distance between two spriteRenderers to set UnityEngine.UI.Button width to this distance In my Unity scene, I have a couple of spriteRenderers and a UnityEngine.UI.Button called thisButton. The spriteRenderers are spread horizontally across my scene. I want to change the button width to span from the leftmost spriteRenderer to the rightmost spriteRenderer. To do this, I have subtracted the x Coordinate of the rightmost spriteRenderer (fRightEndingPosition) from the x Coordinate of the leftmost spriteRenderer (fLeftStartingPosition). float fLeftStartingPosition leftmostSpriteRenderer.transform.position.x float fRightEndingPosition rightmostSpriteRenderer.transform.position.x float fButtonTargetWidth fRightEndingPosition fLeftStartingPosition Then, I try to set the width of thisButton to the value of fButtonTargetWidth by doing RectTransform buttonSize thisButton.GetComponent lt RectTransform gt () buttonSize.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fButtonTargetWidth) However, when I try to use this as the width of my button, the result is not correct. I am pretty sure this has something to do with different types of coordinates being used for the spriteRenderers and the button (world, screen, viewport, etc.), but I haven't been able to figure this out on my own. In one specific example fLeftStartingPosition is 1.1, and fRightEndingPosition is 1.1. In my scene, a button that spans this distance has a width of roundabout 40 on its RectTransform. So clearly, setting the width of this RectTransform (buttonSize) to fButtonTargetWidth (2.2) in code results in a button that is way to narrow. In fact, after setting it's width to 2.2, it is not visible at all. How do I transform this distance of 2.2 to the desired width of roundabout 40, in a way that this distance would be transformed correctly, no matter what the actual value of fButtonTargetWidth is?


Process for Creating Imposters (For Unity) I'm still working on making a sports stadium with crowd etc. I've been reading a lot about 'Imposters' and 'Billboarding'. I want to explore and learn the imposters technique. But I am stuck at step 1 I have a stadium model made which is empty (no seats or people). All I want at the moment is seats. I have the model made in Maya for a seat. Do I need to make (and import to Unity) both a low poly and high poly version of the model. How exactly is an 'imposter' asset stored in data (specifically if used in Unity)? Do I need to make 2d images textures of many angles of the seat? I do have more questions, but these may be enough to get me started. Thanks as always for any help.


Ensuring linear velocity remains constant even when turning I am using Ackermann steering to rotate a vehicle. The code is as follows if (turningLeft turningRight) Rotate around a dummy pivot point float turnDir turningLeft ? 1 1 Vector3 turningPivotPoint dummyPivot.transform.TransformPoint( new Vector3(turningCenterDistance turnDir, 0, 0)) dummyPivot.transform.RotateAround( turningPivotPoint, Vector3.up gasDir turnDir, angleVel Time.deltaTime) The player is pressing the gas if (isGas) angleVel Mathf.Lerp (angleVel, maxAngleVel,Time.deltaTime) if (angleVel 0) turningLeft turningRight false gasVel Mathf.Lerp(gasVel, angleVel Mathf.Deg2Rad turningCenterDistance, Time.deltaTime) dummyPivot.transform.position dummyPivot.transform.position dummyPivot.transform.forward Time.deltaTime gasVel gasDir The issue is that the speed of the vehicle when it is turning does not match its speed when driving straight. Driving the vehicle in circles will be slower than driving the vehicle forward. How do I fix this?


What is the alternative to Time.time for scrolling texture? In my game, I'm using the standard SetTextureOffset method to smoothly scroll texture on background quad. However, on game over, instead of reloading the scene, I'm just reseting all values initial position to give illusion that scene was reloaded. With this approash, i'm unable to use Time.time or Time.timeSinceLevelLoad because, the level was not reloaded and this value stays high. So scrolling is too fast right in the beginning. Are there any time independent methods to smoothly scroll texture? Thanks.


How can I make my camera follow the player movement in a different position Basically my camera follows the character rotation and position, although the position of it its pretty uncomfortable to use, this is what I needed But this is what the I get I used a code that someone suggested me yesterday to use, I got a bit creative with it and changed some stuff to get other camera positions, but no matter how much I tweak the values the camera never gets the position that I need void LateUpdate() transform.position player.transform.position (player.transform.up 10) (player.transform.forward 15) transform.LookAt(player.transform) I have no idea how I can make it show less of the player back


Number Guessing Game How to ensure player cannot be dishonest about their guess I'm building a number guessing game in Unity. The computer has 10 chances to guess the number the player is thinking of. The player interacts by pressing Higher or Lower or Correct Guess. The basic game works fine, as long as the player is honest. I'm now trying to make the game watertight and prevent any user error or dishonesty about their number. I created some test conditions to check if the random number generator has produced a number already used before, or to check if the player is pressing Higher or Lower beyond the max and min guess range. The problem can be demonstrated well by constantly pressing Lower to the point where the final guess is the number 1. Pressing Lower again results in the game freezing. It also happens if the number you are thinking of is displayed and you press Higher or Lower towards a range of numbers which have already been eliminated as possibilities. I am thinking this is due to the game getting stuck in my while loop in MakeGuess(). I think the problem lies in the following test condition in MakeGuess() but any tweaks I make seem to have no effect check if number has been guessed before if (newGuess guess amp amp (newGuess gt max newGuess lt min)) I've uploaded my current playable build to GameBucket.io here https gamebucket.io game 07cc2b61 493b 46ae a446 aeaa98ffac0e All the game logic is handled in the NumberWizard script which is attached to the NumberWizard GameObject in the main Game scene using UnityEngine using UnityEngine.SceneManagement using UnityEngine.UI public class NumberWizard MonoBehaviour int max int min int newGuess public int guess public int maxGuessesAllowed 10 public Text text public Text guessesRemaining Use this for initialization void Start() StartGame() void StartGame() max 1000 min 1 MakeGuess() UpdateDisplay() public void GuessHigher() min guess NextGuess() public void GuessLower() max guess NextGuess() public void GuessCorrect() StartGame() SceneManager.LoadScene("Lose") void NextGuess() if (maxGuessesAllowed lt 0) SceneManager.LoadScene("Win") MakeGuess() maxGuessesAllowed 1 UpdateDisplay() void UpdateDisplay() text.text guess.ToString() " ?" guessesRemaining.text maxGuessesAllowed.ToString() void MakeGuess() guess (max min) 2 old guessing method bool validGuess false while (validGuess false) newGuess GenerateNumber() check if number has been guessed before if (newGuess guess amp amp (newGuess gt max newGuess lt min)) Debug.Log("Number has been guessed before and is already at either range limit.") SceneManager.LoadScene("Lose2") else if(newGuess guess) newGuess GenerateNumber() Debug.Log("Number has been guessed before but is not at range limit.") else validGuess true guess newGuess Debug.Log("Number has not been guessed before.") Debug.Log("Min " min) Debug.Log("Max " max) Debug.Log(" ") int GenerateNumber() int result Random.Range(min, max 1) return result Any help with the code


How to address raycast failures due to tiny holes in a mesh? Problem I have a racing circuit that is made out of tiles, each of which is made out of 2 triangles. I need to know over which tile my craft is hovering on but since there are tiny holes between some of the tiles, casting a ray fails sometimes. Note fixing the mesh from within a 3D modeler is not an option. Question Is there a robust method for approaching this problem ?


How can I avoid jitter when working with a 2D movement system? How can I avoid jitter in Unity? Let's suppose that I want to create a 2D movement system using a Rigidbody 2D(Dynamic), and I want make the camera follow the character (which is a pixel art sprite). How can I create a "jitter proof" 2D movement system for 2D pixel art games in Unity?


Touching screen not working for move object or print message It's simple, i want to move an object when i touch the screen, but code's not working, i tried to just put a console printing on it, but nothing happens void Update() if (Input.touchCount gt 0) Debug.Log("Touch") What am i doing wrong ?, thanks in advance !!


Move parent according to child axis in Unity? Can I ask my parent to move according to the child axis? This means if I turn right, then right again, the parent has to be at 180 from its original position, and not only at 90 (because "Right" would mean "stay on the right axis from the parent axis", and what I want is "move the parent according to the child axis"). The parent has a script to move, and the child has the script to rotate, so I would need to use the new rotation from the child, and not the rotation from the parent. My attempt so far is this one in "MoveBody()", oldTr transform.position works without a bug, but it is using the parent axis. With oldTr this objW , there is a bug, the parent goes somewhere in the scene and move its "z" axis in an odd way this obj GameObject.Find("this obj").transform the child to rotate this objW this obj.TransformDirection(this obj.forward) world ... MoveBody( new Vector3( 3.0f, 0, 0 ) ) ... private void MoveBody( Vector3 vec ) Debug.Log("transform.position " transform.position " this objW " this objW) same value here Vector3(0,0,1) oldTr this objW transform.position newTr this objW transform.position newTr vec transform.position Vector3.MoveTowards(oldTr, newTr, sideSpeed Time.deltaTime) Is it possible to do it this way? Or should I translate each axis by hand? Thanks


Can not connect HTC Vive headset Steam VR plugin error Failed to load IVRRenderModels When I add SteamVR plugin I receive error Failed to load IVRRenderModels interface version IVRRenderModels 005. The plugin works for my other projects, camera and controllers are detected and work fine.


2D character controller in unity (trying to get old school platformers back) This days I'm trying to create a 2D character controller with unity (using phisics). I'm fairly new to physic engines and it is really hard to get the control feel I'm looking for. I would be really happy if anyone could suggest solution for a problem I'm finding This is my FixedUpdate right now public void FixedUpdate() Vector3 v new Vector3(0, 10000 Time.fixedDeltaTime,0) body.AddForce(v) v.y 0 if(state(MovementState.Left)) v.x walkSpeed Time.fixedDeltaTime v.x if(Mathf.Abs(v.x) gt maxWalkSpeed) v.x maxWalkSpeed else if(state(MovementState.Right)) v.x walkSpeed Time.fixedDeltaTime v.x if(Mathf.Abs(v.x) gt maxWalkSpeed) v.x maxWalkSpeed body.velocity v Debug.Log("Velocity " body.velocity) I'm trying here to just move the rigid body applying a gravity and a linear force for left and right. I have setup a physic material that makes no bouncing and 0 friction when moving and 1 friction with stand still. The main problem is that I have colliders with slopes and the velocity changes from going up (slower) , going down the slope (faster) and walk on a straight collider (normal). How could this be fixed? As you see I'm applying allways same velocity for x axis. For the player I have it setup with a sphere at feet position that is the rigidbody I'm applying forces to. Any other tip that could make my life easier with this are welcomed ). P.D. While coming home I have noticed I could solve this applying a constant force parallel to the surface the player is walking, but don't know if it is best method.


Multiple IF statements on Update (Unity) Background I am testing out a "Pause" system for my game. I have a Game Manager script and figured as it's the GM, it's a good place to stick a Pause system. My pause works that on pressing "P" key, the timeScale is switched between 0 and 1. Due to the nature of the game, if the game is paused and then unpaused I want the timeScale to not "jump" to 1 but to gradually increase, taking half a second to reach "normal" game speed again. This aspect is NOT my issue. This is just background. My Code I have the pause detection in the Update script. I figured two if statements to check Timescale values and then to take appropriate action. (SloMoTime is a timescale that kicks in when the player wins or looses the level) My Code using UnityEngine using System.Collections using UnityEngine.UI using UnityEngine.SceneManagement public class GManager MonoBehaviour public float sloMoTime 0.2f public bool ballInPlay false .... void Update() if(Input.GetButtonDown("PauseGame") amp amp ballInPlay true) if (Time.timeScale 0) Game is already paused, so now continue... dactivate "paused" text notice paused.SetActive(false) Becauase we are speeding time up we can't use deltaTime Easy as the timescale we want is 0.5f so 1 0.5 2. So use 2. Time.timeScale Mathf.MoveTowards(Time.timeScale, 1.0f, 2f) if (Time.timeScale gt slowMoTime) Pause the game. Time.timeScale 0 Show "paused" Text notice. paused.SetActive(true) end Update. close class. Now, Can you see any major issues here? My Issue I found running my script from above, that the game did not pause. I expected every frame to load Update, then to check IF number 1, and then check If number 2 (hence in that order). then continue. I found using error logs that by swapping the If statments around that only the first if statement was ever executed. So the game would alternatively always pause but then never unpause. I additionally found with error logs that the values of TimeScale where not causing this inconsistency. What I have trouble with is understanding why this happens. Why do two completely mutually exclusive IF statements not both fire, when in the same method? FAILS Class void Update () if() works if() never works close method. A Solution BUT putting the second IF statement within an else solves this issue. WORKS Class void Update() if() works else if() works close method. Obviously this is impractical for more than a few ifs at once and I find it hard to understand why this logic works and the previous logic never did. I havn't yet dug into if this is Update or timeScale (entity rather than value) specific but Why does this happen?


Moving a top down camera while keeping its height constant I'm currently writing the script for the player to explore the plane below. The camera view is set to be slightly rotated as to look down. And I have set the code to make the camera move. This is the code, and everything is set in the update method. if (Input.GetKey("w")) transform.Translate(Vector3.forward panSpeed Time.deltaTime) , Space.World if want to avoid camera going down if (Input.GetKey("s")) transform.Translate(Vector3.back panSpeed Time.deltaTime) if (Input.GetKey("d")) transform.Translate(Vector3.right panSpeed Time.deltaTime) if (Input.GetKey("a")) transform.Translate(Vector3.left panSpeed Time.deltaTime) The problem is that everytime that the camera goes forward, it goes straight down. And I don't want it to do that. I want to keep the "height" from the plane below to be the same as in the picture below. I want the camera to move along the red axis. I know of the existence of Space.World in order to achieve this, but the problem is that if I do that, whenever I rotate, now the controllers are all screwed up, because if I rotate to the right for example. Now Forward (W) moves the camera to the left, Right (D), moves the camera forward, etc etc. So basically what I need is 1 to make the camera keep the distance to the plane below while moving (not going down). and 2. To make it possible that even with rotations, the controllers are kept, and not having this weird behavior, when forward is not longer forward. Any ideas how to achieve this?


Normals in my skinned model are not animated I have a blender skinned mode with animation. Normals look like they are messed up. This is how it looks in Unity3D before and after animation. As you can see, my model should be lit up just like the cube next to it. When I apply Armature modifier in blender, my model looses animation and its locked in particular position, but the light on that model works. My question is The normals are set as they would be for a static model, not for a animation. Why are normals not animated ?


If statements seem to act as though the condition is always true I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked! I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true. void OnTriggerEnter(Collider other) if(other.gameObject.CompareTag("Player")) working true Extremity false if(Extremity) Instantiate(Cannon, transform.position, transform.rotation) Extremity !true The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.


Bullets doesn't do any damage I have a melee enemy tagged as enemy. enemy has two coliders a capsule(physics) and a sphere(for attacking player in radius and istrigger) and a particlesystem, enemy has enemyhealth script attached. Similarly, bullet has capsule collider and set istrigger, I've attached enemyhealth script to bullet as enemy sphere and bullet capsule are triggers (bullet doesn't have any particle system need fix for this too without raycast), bullets are destroyed on colliding with enemy but doesn't damage the enemy. script used for enemy health using UnityEngine using System.Collections public class enemyhealth MonoBehaviour public int health 40 public int current public int score 10 public AudioSource deathclip public ParticleSystem death CapsuleCollider Collider bool dead Use this for initialization void Start () deathclip GetComponent lt AudioSource gt () Collider GetComponent lt CapsuleCollider gt () death GetComponentInChildren lt ParticleSystem gt () current health dead false void Update() public void Takedamage (int amount ) if (dead) return current amount if (current lt 0) die () void die () GetComponent lt NavMeshAgent gt ().enabled false dead true Collider.isTrigger true deathclip.Play () death.transform.parent null death.Play () Destroy(death.gameObject) Destroy(gameObject) script used for bullet using UnityEngine using System.Collections public class mover MonoBehaviour public float speed public int damage 10 enemyhealth Enemyhealth GameObject ENEMY bool enemyinrange Use this for initialization void Awake () GetComponent lt Rigidbody gt ().velocity transform.forward speed Enemyhealth GetComponent lt enemyhealth gt () ENEMY GameObject.FindGameObjectWithTag ("enemy") void OnTriggerEnter(Collider other) if(other.gameObject ENEMY amp amp Enemyhealth.currenthealth gt 0) enemyinrange true Destroy(gameObject) void OnTriggerExit(Collider other) if (other.gameObject ENEMY) enemyinrange false void Damage() Enemyhealth.Takedamage (damage) Update is called once per frame void Update () if (enemyinrange) Damage ()


Canvas Element Not Render In Proper Position I don't know what's going wrong. The Text and Slider must be on the red square area. Anyone can help to determine this bug ? Thanks


1 bit game How to change the palette for the entire game at runtime? So I'm making a 1 bit color game, and would like to have an option in the menu to change what those two colors are so the player can adjust it to their liking. What is the simplest and or best method to go about this? This would apply to the entire screen, not individual sprites meshes, as I want to preserve the 1 bit color look. Most of my assets are sprites, with a few flat meshes that are rendered without anti aliasing so that they blend in with the sprites. They're all exported with the two standard colors I'm using (a yellow ish off white and a dark grey ish blue), but I can go back and re export them in black and white if that is necessary for the suggested method. My eventual plan is to support the basic black and white, a few monochrome monitor color schemes, and some color combinations that you'd see on 8 bit computers (C64, Apple, etc.).


Why don't variables in a script on a prefab clone store runtime changes? I have a building prefab. There is a simple script attached to it that allows me to store unique data for each prefab instance, such as address. There are hundreds of clones of this prefab. The prefab is instantiated like so instantiate a "building" object multiFamHigh Instantiate(multifamilyHigh,myV3,Quaternion.identity) as GameObject set a reference to the prefab's behavior script BuildingBehavior bldgBhave multiFamHigh.GetComponent lt BuildingBehavior gt () set the information for the prefab bldgBhave.setInfo( mgr.lotsList chose .getAddress(),buildingRef) In the "TownCreator" script, after the prefab is instantiated, I call the setInfo function and pass the address to it. The setInfo looks like this public class BuildingBehavior MonoBehaviour private string address public void setInfo(string useString, int bldgListRef) address useString Debug.Log ("Set Address " address) buildingListRef bldgListRef The debug log correctly displays "you set address 3071 N." meaning at that time, the "address" variable of the prefab script is set to 3071 N. Perfect. However later, when I click on any of the prefabs at runtime (via the mousedown) the UI message box pops up (as intended), and the Text is changed from "New Text" (default) to a blank string. I added a similar Debug.Log, at that point, and it also tells me that "address" on the clone is blank. That code is void OnMouseDown() thisCG GameObject.Find("MainCanvas").GetComponent lt CanvasGroup gt () thisCG.alpha 1 CanvasStuff thisCS GameObject.Find("MainCanvas").GetComponent lt CanvasStuff gt () thisCS.setAddyText (address) Debug.Log ("clicked on " address) This happens Any ideas why the script on the prefab clones is not storing the values? Also when I change (address) to ("Address"), the popup has "Address" above the OK, Thanks! button.


Swap between first person and eagle eye view cameras, hiding the FP controller Not sure what has to be done to correctly swap between a generic fps controller camera, to something like an eagle eye view. The idea is to have the player use the FPS controller, then when he get in a control seat I want to switch to a larger view kinda like a RTS view from the top (I call it "eagle eye", not sure about the technical name). I did check around and from my research, I have to swap active camera parameter but when I do so, the FPS remain active, while I would like to hide it, and also disable it completely, since the player will use the mouse at that point. If I destroy the FPS, that works, but when the player leave the control seat, I have to re create it, which bring a whole level of pain, to restore its state. How do you disable temporarily a FPS, so it won't be neither visible nor it will interact with anything?


Unity GridLayoutGroup children ignoring resizing Can anyone explain why, in the editor I get while, on my Galaxy S6, I get My Panel UI element (which is the parent) has the GridLayoutGroup component, as well as the ContentSizeFitter. The child elements have a LayoutElement component with a FlexibleWidth Height of 120 and all anchors are set to stretch in all directions. The Canvas is set to Scale with Screen size, with a reference res of 320x480 and screen mode is to match height. Regardless of the amount of squares (which is dynamic) the editor perfectly resizes child elements within the parent, but my device makes them tiny. I'm really confused. There is no setting of sizes or anchors within the script, purely an instantiate and an assignment of parent, like so for(int i 0 i lt amount i ) GameObject emptyCell (GameObject)Instantiate(emptyCellObject) emptyCell.transform.SetParent(cellHolder) emptyCell.GetComponent lt RectTransform gt ().localPosition new Vector3(0f, 0f, 0f) emptyCells.Add(emptyCell) I've also checked all docs related to http docs.unity3d.com Manual comp UIAutoLayout.html And even UI tutorial movies, as well as some blog posts about the 'new' UI tools, but nothing changes the dimensions on the physical device, and seems to change nothing in the editor as that remains the same. I'm sure I'm doing something silly, but I've exhausted all avenues and was hoping someone had come across this oddity previously.


Touch input not working well for mobile game made with Unity 2D I made a simple game in unity where the user taps their phone screen and the player jumps up. When I test it on my phone (not sure if this matters but it's a Samsung s9 ), I tap the screen and usually the tap causes the player to jump up and fall back to the platform properly, but sometimes when I tap the screen nothing happens at all it just stays in place. The game on my phones is also very slightly laggy (although, on my computer it runs smoothly) and I'm not sure how to fix that either or if they're related. This is the code attached to the player void FixedUpdate() Jump() Dead() void Jump() if (Input.touchCount gt 0 amp amp isGrounded) gameObject.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0f, jumpForce Time.fixedDeltaTime), ForceMode2D.Impulse) Also, I know that it's the touch input that's the problem, because when I make it so that pressing the up arrow key on the keyboard makes the player jump, it works perfectly fine. If there's some other information about the game you'd need to know to answer my question, let me know. Thanks for your help.


Unity Scaling down a GameObject containing a child Final IK (VRIK) rig I'm currently building a VR AR hybrid in Unity, where I'm controlling an IK rig using VR, then sending the VR controllers positions to an iOS device using network transforms to mirror the IK rig's movement in ARKit. I'm having trouble implementing pinch to scale the scene locally on the iOS device. I'm attempting to uniformly scale down a parent GameObject containing the IK rig which has its Head target connected to SteamVR Vive headset and its Hand targets set hand controllers positions. The vectors that describe the positions of the controllers are being sent over the network, so I'm applying the same scale factor to those, so that the targets match up to the scaled down character. However, the IK rig appears to break when scaling the character down, and in particular the legs appear to be too far apart, and the hand movements no longer look correct Could the problem be to do with the internal relative transforms within the IK rig needing to be modified? And is there a better approach?


How to get past Visual Studio "Setup Error" for Unity development? When I launch Visual Studio from Unity on my laptop, I get the following error Setup Error The setup for this installation of Visual Studio is not complete. Please run the Visual Studio Installer again to correct the issue. As instructed, I've tried reinstalling Visual Studio multiple times, or using the quot repair quot option, but nothing has resolved the error. How can I fix this?


Unity2D Frost Effect Time scale I downloaded this package ("Frost Effect by Steven Craeynest") on Unity Asset Store and altered it into making the effect happen once I click on a button (button 1), I first disabled the frost button (button 1) in my inspector before playing the game and created another button (button 2) to activate the frost button(button1). However I'm having issues with the frost effect. You see when I click on button 2 to activate the frost button (button 1) frost effect works for a bit but then stops at delayBeforeUnfreeze like time.timescale is equaled to 0 and the only way of making time.timescale is equaled to 1 is by pressing my pause button and clicking the resume button. Anyway this is my script private FrostEffect frost float duration 0.2f float delayBeforeUnfreeze 0.34f private float previousTimeScale public GameObject frostbutton public int buttonCount 0 int timesActivated 0 public void Check() buttonCount Use this for initialization void Start () previousTimeScale Time.timeScale public void Activate () frostbutton.SetActive (true) public void CreateFrost () if(timesActivated lt buttonCount) timesActivated GameObject.Find ("Main Camera").GetComponent lt FrostEffect gt ().enabled true Slow timescale Time.timeScale 0.06f Freeze time effect DOTween.To (x gt FrostEffect.FrostAmount x, 0.0f, 0.34f, duration) .OnComplete (() gt Unfreeze tween effect DOTween.To (x gt FrostEffect.FrostAmount x, 0.34f, 0f, duration) .SetDelay (delayBeforeUnfreeze) Set timescale back to previous. Time.timeScale previousTimeScale ) Thank you. ) Second Edit This is my panel animation script public void DisableBoolAnimator(Animator anim) anim.SetBool ("Shown", false) public void EnableBoolAnimator(Animator anim) anim.SetBool ("Shown", true) This Youtube link will show you what my panel animation looks like 31 47. Thank you. )


Make variables public, or make functions to get set variables? Dumb question but I want my game to be secure as possible. Right now I have classes interfacing with each other in order to save load player information. Right now I have all the variables in my classes as public, and saving loading the saved variables into them. But I don't think that's as secure. Code public class PlayerRP MonoBehaviour public string charName public string charRace public string charClass public string charClassSpec public string charBackground public string charGender public class CharacterManager MonoBehaviour public void SaveCharacter() BinaryFormatter bf new BinaryFormatter() FileStream file File.Create(Application.persistentDataPath slotFile) CharacterSaveFile data new CharacterSaveFile() Character RP data.charName playerRP.charName data.charRace playerRP.charRace data.charClass playerRP.charClass data.charGender playerRP.charGender bf.Serialize(file, data) file.Close() LoadCharacter() Would it be safer (or more efficient) to instead make methods in the playerRP class to get set the variables separately, rather than have them as public?


Unity MouseWheel weapon change I am trying to make a simple weapon change in Unity3D. The best way to do this is with the mouse scroll wheel, as far as I can see. I googled on how to do this and found that I have to use Input.GetAxis("Mouse ScrollWheel") I use this piece of code and print it. Still, I always get an value of 0. any ideas? I just need to solve how to get the value first, I'll figure out the rest myself. Code idea function Update () print(WeaponNumber) if(Input.GetAxis("Mouse ScrollWheel")) WeaponNumber Input.GetAxis("Mouse ScrollWheel")


EnemyAI rotating on Y axis in opposite direction After a battle flag has gone off and the player has entered an enemy's battle zone I want to keep track of the player when it moves and make sure the enemy's Z axis is always pointing towards the player. Upon the player entering the battle zone, the enemy automatically marks the player as its target However there is a chance that the Z axis may not be pointing towards the enemy's target when the battle is first initiated. I decided to shoot a ray cast from the Z axis of the enemy when the battle flag goes off and rotate the enemy until the ray and the player intersect thus telling me that enemy's Z Axis is lined up correctly. the enemy always has a reference to its current target. My idea was that as once the enemy spots its target initially, it can save the position of the most recent spotting and then take the delta of the CurrentTargetPosition.x and the LastSpottingPosition.x If the delta is positive rotate right and if the delta is negative rotate left. THE ISSUE my math or logic must be flawed somewhere because although it works sometimes, other times the enemy will randomly rotate itself in the opposite direction and the ray cast will essentially take the long route to hit the player instead of the shortest route as intended. Also the Local Origin of the enemy and the player are at different height respectively but I dont think that should matter in my case Code Below. create ray from enemy position orgin and point it on the Z Axis Ray ray new Ray(CurrentEnemyTransform.position, CurrentEnemyTransform.forward) RaycastHit hit if (Physics.Raycast(ray, out hit, 50f)) Debug.DrawLine(ray.origin, hit.point) ray hits current enemy target if (hit.transform CurrentTargetTransform) check if enemy has seen its target before while in this battle or is it the first time if (enemy.hasTargetLastPosition) replace old last seen position with most recent spotting enemy.ReplaceTargetLastPosition(hit.transform.position) or add the first spotting of target while in this battle else enemy.AddTargetLastPosition(hit.transform.position) ray is not intersectiing with the enemy's current target so rotate to look for it if (hit.transform ! CurrentTargetTransform) check if enemy has seen its target once before in battle if (enemy.hasTargetLastPosition) since last spotting has my target moved more to the left or right? if (enemy.targetLastPosition.value.x gt CurrentTargetTransform.position.x) rotate right CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self) rotate left else CurrentEnemyTransform.Rotate(Vector3.up, 5f, Space.Self) never seen target yet during this battle so default rotation to right till you found it else CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self)


Creating a 2D game on the X Z plane instead of the X Y plane in Unity, any adverse effects or challenges with this? After coming to the realization that some things I wish to do in a 2D RTS are easier to do on the X Z plane instead of the default X Y plane, I'm considering moving my game over to the other plane. What I am wondering, past the scripting changes to accommodate the different plane, is what specific challenges will this cause for a 2D game (using 3d physics, not 2d physics)? I did a test and flipped some assets to the X Z plane and things seemed to work just fine, though I am not sure what unique challenges I will end up facing are. All our objects will have a 90 degree X Axis rotation so that their sprites display.


Get a camera's frame buffer in Unity Is there a way to "record" the display of a camera instead of rendering it on screen? For example, if I want to stream a camera's frame block to an external application.


How do I move many "static relative to each other" objects around? I'm currently building an Elevator Bank simulator in Unity3d and I'm stuck on how to reduce the amount of objects it's going to generate when it's done. The simulator will consist of one player (for now) walking into a building, calling an elevator, picking a floor, going up down and getting out of the elevator again. To illustrate the problem, I'll sketch 2 scenario's. One where there's no problem whatsoever. One where I simply scale upwards and create a mess. But first, a list of what's inside the simulator (excluding the player). One hull of elevator shafts (3D .obj model). One elevator car per shaft (3D .obj model). One group of hall buttons per shaft per floor (one button for the top amp bottom floor, two for the rest). One group of control buttons per elevator car (door open, door closed, etc.). At least 3 buttons. One floor call button per elevator car per floor. Two doors per elevator car. Two doors per shaft per floor. A simple set up of 3 shafts and 4 floors will already create 75 objects of which 30 are moving. Take 20 floors, 2 rows of elevators, 3 cars per row and I'm over 600 objects already. Now. The Empire State building has 102 floors and 73 elevators. Which means multiple banks, a whole lot of floors, a whole lot of buttons and a whole lot of cars. Scaling my current set up to support that will create a mess at best and simply won't work at worst. Since this is an elevator simulator, the whole point of it is to make sure every elevator is active from starting the scene to ending the scene. So no tricks like only spawning what's in range of a camera, hibernating objects, object pooling and what not are out. Now, objects in the same elevator car are static relative to each other. If the car moves up, everything moves up the same amount. So I hope I can move them as a group. Except I have no clue how to do such a thing in Unity. Prefabs may be part of the solution, but that still won't link their movements together. I've considered linking them together like a Snake game, but the amount of objects involved is orders of magnitude more. Luckily, all moving objects (except for the player) will only move on one axis. Doors only slide open closed, elevator cars and their buttons go up and down. All rotations are fixed. How do I move so many objects around in a single scene without creating a mess of variables in a performance wise good way?


Does Unity3D custom shader use its default GPU or CPU skinning automatically? I'm writing my own shader in mobile, but was wondering if it uses default GPU or CPU skinning feature in Unity3D? I'd like to use GPU skinning and already enabled GPU skinning. Is there any way to determine which (GPU or CPU) was actually used? My shader is as below Shader "Mobile Custom Specular Map" Properties ShininessColor("Shininess Color", Color) (1,1,1,1) Shininess ("Shininess", Range (0.03, 1)) 0.078125 MainTex ("Base (RGB)", 2D) "white" SpecMap ("Specular Map", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 250 Cull Back CGPROGRAM pragma surface surf MobileBlinnPhong exclude path prepass nolightmap halfasview interpolateview noshadow nofog nometa nolppv noshadowmask inline fixed4 LightingMobileBlinnPhong (SurfaceOutput s, fixed3 lightDir, fixed3 halfDir, fixed atten) fixed diff max (0, dot (s.Normal, lightDir)) fixed nh max (0, dot (s.Normal, halfDir)) fixed spec pow (nh, s.Specular 128) s.Gloss fixed4 c c.rgb (s.Albedo LightColor0.rgb diff LightColor0.rgb spec) atten UNITY OPAQUE ALPHA(c.a) return c sampler2D MainTex sampler2D SpecMap uniform float4 ShininessColor half Shininess struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 tex tex2D( MainTex, IN.uv MainTex) o.Albedo tex.rgb o.Gloss tex2D( SpecMap, IN.uv MainTex) ShininessColor o.Alpha tex.a o.Specular Shininess ENDCG FallBack "Mobile VertexLit"


Why does my first person camera attached to a rigid body vibrates? I'm trying to make a first person character with a rigid body. I need a rigid body because I want to add areas where the gravity comes from different directions so I also need to rotate the character accordingly. And as far as I know you cant rotate a character controller. So I wrote a script for movement and camera rotation. The problem I now face is that the camera vibrates. I recorded this video to show it. Why do I get this and how do I fix this? Movement code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovementRigidBody MonoBehaviour public float speed 10.0f public Rigidbody rb public LayerMask groundLayers public float jumpForce 7 public CapsuleCollider col float transelation float straffe Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked rb this.GetComponent lt Rigidbody gt () col GetComponent lt CapsuleCollider gt () Update is called once per frame void Update() transelation Input.GetAxis("Vertical") speed straffe Input.GetAxis("Horizontal") speed bool jumping Input.GetKeyDown(KeyCode.Space) transelation Time.smoothDeltaTime straffe Time.smoothDeltaTime if (IsGrounded()) rb.useGravity false else rb.useGravity true if (IsGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) rb.AddForce(Vector3.up jumpForce, ForceMode.Impulse) if (Input.GetKeyDown("escape")) Cursor.lockState CursorLockMode.None void FixedUpdate() transform.Translate(straffe, 0, transelation) private bool IsGrounded() return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius .9f, groundLayers) Mouse look code using System.Collections using System.Collections.Generic using UnityEngine public class MouseLookRigidBody MonoBehaviour public float mouseSensitivity 100f public Transform playerBody Rigidbody rig float xRotation 0f Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked rig this.transform.parent.gameObject.GetComponent lt Rigidbody gt () Update is called once per frame public void Update() float mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime float mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX)


How to manipulate the two variables that rotate the camera with Input.GetAxis( Mouse X Y )? A helpful fellow showed me the script for a free look camera mode that rotates with the mouse. The script is included at the bottom of the page. I want to have a system that right clicks once to enter this camera mode and right clicks again to exit it and slerps back to the original position. I tried to do it, but it seems like when I right click once and then right click again, it works ok because it's the first time I do it. But when I right click again, it snaps back to the rotation that it last left off from in free look (the starting rotation of the slerp). Does this have to do with the way the yaw and pitch variables are stored? I assume that after exiting free look, yaw and pitch still hold the values from the last rotation. Consequently, I tried resetting yaw and pitch, but it still has the same old problem. On the other hand, after playing around a bit, sometimes it resets to a particular rotation no matter what. So does that mean I need to do a bit of testing and say, if (rotation x) pitch y figure out what y should be through trial and error testing) or something like that? using UnityEngine using System.Collections public class FirstPersonCam MonoBehaviour public float speedH 2.0f public float speedV 2.0f private float yaw 0.0f private float pitch 0.0f void Update () yaw speedH Input.GetAxis("Mouse X") pitch speedV Input.GetAxis("Mouse Y") transform.eulerAngles new Vector3(pitch, yaw, 0.0f)


How can I add up the Transform GameObjects in the Array of Waypoints in Unity? I come up with this code and I try to get the waypoint 1 when I reach the waypoint and it adds up till the last waypoint. I get Array is out of Index error. I guess I need and foreach loop of waypoints ? Code public float speed public float turnSpeed public Transform waypoints private int currentWp 0 void FixedUpdate () if(waypoints.Length gt currentWp) return player.position Vector3.MoveTowards(player.position, waypoints currentWp .transform.position, speed Time.deltaTime) var rotation Quaternion.LookRotation(waypoints currentWp .transform.position player.position) player.rotation Quaternion.Slerp (player.rotation, rotation, turnSpeed Time.deltaTime) float distance Vector3.Distance(player.position, waypoints currentWp .position) if(distance lt 10) currentWp


'Edit Collider' exits after every adjustment When I click the Edit Collider button I can see the collider's region and the handles to adjust it. After every adjustment (with the mouse) the collider outline disappears as Edit Collider finishes. It's frustrating to use, having to reclick Edit Collider after every drag click. How do I stop Edit Collider mode from exiting after every change and only exit if I click the button, or press some commit key?


Random Functions in Unity Is their a way to execute or call a random function in unity. Something like void Update() random(func1(),func2()) void func1() print("func1") void func2() print("func2")


Update dependent values of Serializable C classes on Inspector I have some data types' properties that depend on the input given into other attributes, but I haven't found in the Unity's API an elegant way to update them automagically on the Inspector. As an example, let's say I have a struct that has a divider value. Since I want to save division computations, I also have on the class a multiplicative inverse value that depends on the divider's, so I'd rather multiply instead of dividing. Example Code Snippet Serializable public struct SomeNumbers SerializeField private float divider private float multiplicativeInverse When the divider is set, the multiplicative inverse is also set. public float Divider get return divider set divider value multiplicativeInverse (1f divider) public float MultiplicativeInverse get return multiplicativeInverse private set multiplicativeInverse value Constructor. public SomeNumbers(float divider) this() Divider divider public class ExampleScript MonoBehaviour public float value public SomeNumbers numbers void Update() float result (value numbers.MultiplicativeInverse) Instead of (value numbers.divider)... Debug.Log("Result " result.ToString()) What I'd like, is that each time I change the divider's field, the value under the hood (this case the multiplicative inverse) also gets changed, as if I used the Divider's setter. Since the idea is to have an independent data type, the approach of using OnValidate on a class that contains this struct would not be applicable, since that would be a hard case. I could also set the Divider's setter on each class at Start Awake do that for me, but that would be prone to be forgotten. I know about Property Drawers , but I am not sure if that would be the right approach. I hope the question was clear enough, if not make me know so I correct it. Thanks in advance.


Can you use the RangeAttribute to limit the size of an array? I recently found out about the RangeAttribute and how you could use it to limit the values of your parameter when entering them in in the inspector window. However, I needed to use an array for randomly selecting Prefabs so they can spawn randomly at any given time. The problem is Unity lets me have an array size of zero, but I also want to limit the number of possible prefabs. I was wondering if there is a way to use RangedAttribute to limit the size of an array, and if not is there a different way to achieve this? I have extensive experience in Java and C but recently started in Unity, so I don't know if I'm asking the right questions, so any guidance right now would be greatly appreciated. Thanks. P.S. I would be able to attach the script to give an example if needed.


Why is Unity UI Image color not being animated? Animation is changing the color of an UI Image but the color only changes only in the inspector but not Game Scene view. In this video I demonstrate the problem clearly.


Unity Model Construction on the fly So, forgive me if some of the terminology is wrong, I am just getting started with Unity again and I can't remember the proper names. I'm also on my phone, so I didn't have unity in front of me when I posted this question. I am beginning work on a voxel based game. Everything in the game will be models constructed of 64 by 64 cubes. I would like to, with the code given, say, a 4096 bit array, be able to construct a model in the game with those cubes. I know that you can programmatically add models that you have imported into unity, but I want to make contiguous meshes programmatically, with highest performance being the goal. I do not want a certain amount of little 1x1 cube meshes positioned right next to each other, but specifically one model. Is this possible?


Box collider has different behavior in 2 clients I'm new to Unity. I am making my first Game and faced with problem. I have a plane and 4 gameobject that has box collider surrounded this plane. there are a few spheres as players inside of the plane.I built the game. I run 2 instances of the game and add force to a sphere and send this force to other client through node server. But border reflection angle differs in 2 clients. I checked value of the force in 2 clients and that is the same. Any help would be appreciated.


Orientation changed event in Unity3D? I'd like to listen to orientation change events, so for example my UI layout or the components themselves can be changed. All I've found is that I should check the value of Screen.orientation every frame, and check if it has changed since previous frame. But this isn't really efficient, and I wonder why doesn't Unity provide an event for this. This asset seems to have what I need. Anyone knows how is it implemented? As a last resort I could make a singleton behaviour which starts a coroutine which checks every X seconds whether it has changed, and if it has, I fire an event. But this still seems like a suboptimal solution.


Any recommended books resources on component based design? I come from a background with heavy use of the classical object oriented paradigm for software development. The company I am a part of switched to Unity not too long ago, and we're all very excited to get started using it However, one aspect that have sparked my interested, and which I think will become a very important part of our future development, is Unity's approach to component based design with scripting with less focus on typical hierarchical aspect. Question I was wondering if anyone could recommend any good books on this subject? I have had trouble finding any books or books with reliable reviews, and was wondering if anyone more experienced here had something to say on the issue? Any other kind of resource would be excellent too, I'm just interested in getting to learn everything I can about it. This is not meant as a discussion about best books or resources on the topic, but simply a question regarding any resources that any of you find useful. Thank you all for your time!


Editor Window How to create this? I am trying to create this in my editor window but not sure how. Basically a drop down arrow, next to a C icon, next to a toggle, next to a Label with a cog at the end


Unsticking game objects I have used void OnCollisionEnter(Collision collision) collision.gameObject.transform.parent gameObject.transform To stick two players together when they connect. Basically after they have collided the second game object is still stuck to the original object and i need that not to be the case. How do i make the game object not stuck when they come apart ?


Problem with NGUI Unity 2D Sprite across devices I have a problem with NGUI for Unity, using the Unity 2D Sprite objects. First, have this image And then create an NGUI Unity 2D Sprite object in the scene. Apply this image and you get this Very odd. This doesn't happen if you use an Unity UI Image object or a SpriteRenderer component. But I really need to use NGUI's Unity 2D Sprite. Then I ran the scene in several devices. Some of them display the sprite correctly but others do not. Look Top left device iPad Mini 1 The sprite is bad. Top right device iPad Mini 3 The sprite is good. Bottom left device iPhone 5c The sprite is bad. Bottom right device iPhone 6 plus The sprite is good. I fail to understand what is the problem. Again, this doesn't happen with sprites rendered with SpriteRenderer or Unity's builtin UI Sprite system. However, I need to do this with NGUI. NGUI has a "NGUI Sprite" which I believe does work. But I don't want to use that one I need to use the "NGUI Unity 2D Sprite" option. Any ideas? Unity 5.0.0b20


Programatically Build List of Custom Class Objects (prefabs) This seems like it should be a simple thing, but I cannot seem to figure out a method. Currently, I have a public List lt MapGraphItem gt roomList variable, and in the inspector, I add prefabs from Tiled2Unity for a given biome currently a list of nine tiles for my test biome. Map generation works great via this method. MapGraphItem is a custom class that is applied to these prefabs via script. I'd like to programmatically build the list so that I can build it appropriately based on the biome that's being called (dungeon, forest, desert, et cetera). I seem to be having trouble getting unity to put together a list of the items anyhow (they are in a specific assets folder and also have a specific prefix, in this case "dng "). I tried this and some variations on it List lt GameObject gt obj GameObject.FindObjectsOfType(typeof(GameObject)).Select(g gt g as GameObject).Where(g gt g.name.StartsWith("dng ")).ToList() But it seems the objects need to be loaded first (plus, I'd need to convert it to a List lt MapGraphItem gt before using it). I could add another field to the MapGraphItem class for biome type and basically load ALL of the assets, but that's a huge waste of resources. Manually adding these for each biome is really not ideal, and really not efficient. Thanks!


Find range between two signed 180 angles How can I find the angle between two angles that go from 180 to 180 degrees? I would like to do if (angleDiff gt 90) The angle is bigger than 90 degrees... I tried subtracting them but that doesn't seem to work. Thank you


Is it possible to debug a Unity Android game directly on a device? I'm working on my game and every time I make changes to it I send the game to my mobile device to debug it. I want to know how I can directly debug my game using an Android device instead of the MonoDevelop editor?


Why do I get this warning when using a null conditional operator? In the OnTriggerEnter2D function of my Bullet script, I have the following code private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag("Enemy")) var enemy other.GetComponent lt Enemy gt () enemy?.Death() The reason for the null conditional operator (the question mark) in enemy?.Death() is because the Death function actually destroys the Enemy component script, so it suppresses an error when the bullet hits the enemy again. It's supposed to be shorthand for if (enemy ! null) enemy.Death() The code works the error is suppressed. However, the IDE that I'm using, Jetbeans Rider, gives the following warning '?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity object. What does that mean exactly? Should I continue using the null conditional operator?


How to smooth terrain to lower polygon count? I'm using Unity. I've created a simple Beach using Terrain editor. The problem is that Stats show me already a lot of Triangles only for Terrain renderer 40K . So my question is how can I create a Unity Terrain suitable for Mobile game ? How can I smooth terrain edge ? Thanks


Unity separate shapes on a map into individual objects? Okay, I asked this question yesterday anonymously thus I couldn't edit it so I'm remaking it. Short version I have a transparent map with black borders (Colored map) and I want those shapes formed by these borders to become individual objects in Unity. Is it even possible and if it is, how? Long version I want to make a Grand Strategy type game with provinces and countries. However, I'm not really an experienced graphics nor Unity programmer. I already have a map drawn with the desired black borders with each province being defined by these very borders and each has an unique color (sort of an identifier). Having just this seems plain and complicated to use so I'd like for each province to emit a color corresponding with a selected map type (diplomacy, terrain, domains, etc.). Obviously, this would be hard to do with just a single plain texture therefore I need to make objects and this is where my inexperience blocks me from continuing. Is there anything I can do (in Unity and or Photoshop) that could make the provinces be objects without manually isolating, importing and matching (as a puzzle) each single one? I've already looked at countless questions and answers but still none fit my problem. I'm at my wits' end with this to the point where I'm actually thinking about scrapping the project.


How do you exactly implement a Semi Implicit Euler type of movement in a 2D platformer? So I've been following along Sebastian Lague's 2D platformer tutorial, and to understand exactly how the physics of how a jump is done, I dug into the subject and noticed a lot of people, from GafferonGames and Kyle Pittman, all mention using Semi Implicit Euler in making an accurate jump. Now my problem is How do you exactly implement this type of integration scheme in a game? Specifically a platformer. A comment on the tutorial I was following said that the code below uses the Explicit Euler type of integration. Though I'm not exactly sure myself on whether or not this is true another tutorial I found on the topic, specifically Jorge Rodriguez's Math for Game Developers uses the Semi Implicit Euler integration to make a spaceship simulator, but the code used was C and I only have some limited C and I was not able to fully understand parts of the code that went into implementing the integration. Specifically auto v vn, gravity (Vector x, float h) gt Vector return vn gravity(x) h auto a xn, gravity (Vector v, float h) gt Vector return gravity(xn) gravity(xn v h) h from what I understand, this function returns a Vector2, but I don't know if the auto a xn, gravity is supposed to be about declaring a variable or what, or how the vector bit fits in the whole code. All in all, I need help, I'm still pretty new to programming and general and these small nuances confuse me. Any help is greatly appreciated, Thank you. This is the code for the Platformer Character controller I followed from Sebastian Lague. using System.Collections using System.Collections.Generic using UnityEngine RequireComponent (typeof(EntityController2D)) public class PlayerController MonoBehaviour EntityController2D playerController region Y Velocity Fields public float jumpDisplacementDeltaTime 0.75f public float jumpHeight 6.0f float gravity float jumpVelocity endregion float moveSpeed 6.0f Vector2 velocity public void Start() playerController GetComponent lt EntityController2D gt () gravity (2 jumpHeight) Mathf.Pow(jumpDisplacementDeltaTime, 2) jumpVelocity Mathf.Abs(gravity) jumpDisplacementDeltaTime print ( "Gravity gravity ") Update is called once per frame public void Update() Vector2 input new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if (playerController.collisions.below playerController.collisions.above) velocity.y 0 if (Input.GetKeyDown(KeyCode.Space) amp amp playerController.collisions.below) velocity.y jumpVelocity velocity.x input.x moveSpeed velocity.y gravity Time.deltaTime playerController.Move(velocity Time.deltaTime)


How to make legacy animations run in Unity in unscaled time? (Pause game related) I'm relatively new to Unity, and I've been having a very difficult time getting the legacy animations to run in unscaled time. I need to pause my game, and as soon as it pauses, I need to have my boxes for the pause screen come in from the side. This sort of works if I use an IEnumerator, but I have to hard code exactly how long it will take for the animation to come in (.333f seconds) and the game will not pause until the animation fully shifts in. The major problem with this is that I need to use more moving animations while the game is paused that will be called using the onClick() methods in the pause game's buttons. Think of my pause menu as somewhat like an old school RPG's menu like Final Fantasy but with moving GUI animations. Now, I know that unscaled time is the key to solving this issue, but every explanation I've found online seems to involve the Animator which refuses to work with the legacy? animations. Either that, or the code they're using makes little sense to me because it may be above my level of comprehension. Here is what I have as it stands ( note that I have some deltaTime and lastframetime code but I have no idea how to make use of it) Update is called once per frame void Update () deltaTime Time.realtimeSinceStartup lastframetime lastframetime Time.realtimeSinceStartup Press T or Tab to pause the game if (Input.GetKeyDown(KeyCode.T) Input.GetKeyDown(KeyCode.Tab)) If not currently paused, then stop time and show the GUI if (!pauseGame) Debug.Log("Tab T properly pressed to pause game.") pauseGame true showGUI true StartCoroutine(Wait(.333f)) IEnumerator Wait, then stops else if (pauseGame) Debug.Log("Tab T properly pressed to UNpause game.") Time.timeScale 1 pauseGame false showGUI false If we are to show the GUI, play the start animation otherwise, the exit one if (showGUI true) startMenuCanvas.animation. startMenuCanvas.animation.Play ("pause menu anim1") else startMenuCanvas.animation.Play ("pause menu anim1 exit") IEnumerator Wait(float seconds) Debug.Log ("Waited for " seconds " seconds.") yield return new WaitForSeconds(seconds) Time.timeScale 0 Ideally, I want to remove the IEnumerator and be able to call the Play animations using unscaled time. Is there any simple way to do this that I am missing?


Unity Gameobject turned grayed I accidently pressed some key combination which turned all the gameobjects in Unity engine gray and now I cannot restore them to the original form. Any suggestions? Below is the link of what I am talking about https ibb.co izAVRo


Shortcut for empty with collider How to add shortcut key to add new empty already with a box circle collider ? If possible, it would be nice that empties are enumerated.


Unity scene has phantom models in every scene new and existing a like even when deleted I have asked about this over at Unity Forums but have not got a response yet. My issues is that in the image below all there is is a light source but several of my monster models are in the scene somehow. I cannot select them or interact with them in any fashion. The are there whether it is an existing scene or I create a new scene. If anyone has any clue what this is from it would be a great help because it is driving me madd! Thanks!


Dividing Data and Logic in Unity I am currently working on a small side project (as usual), and trying to build up from previous experiences. I have the following elements in the game 1) Region which contain a "food" target that has to be met 2) Location Each region has a few location, where crops can be sown 3) Crop A variety of crops with different effects I currently have a system where I have a Region monobehaviour script that only considers the production of food from the crops. The location monobehaviour, stores the current state of the location, namely what crop is currently on it and how much food is currently available. I also have all the food production logic on that script. The crop scripts are scriptable objects with different food production rates and water consumption values. I run into a problem when I started to want to add other types of elements to the location, or rather, have crops that don't necessarily produce food but have another effect on the game. I decided to build another system, where instead of having the logic that triggers the various methods on the location script (for example the ProduceFood(), SendFood(), ReceiveFood()) within the location script itself or via hard links from UI elements. This new systems is centred on Action scriptableObjects that can be added to the Crop scriptableobjects. The action script contains an Act(Location loc) method as well as a SetUp(Location loc) and Disable(Location loc). I can now customise how and when the ProduceFood(), SendFood(), ReceiveFood(), etc methods on the location script get called. For example the ProduceAction will add the Act method to a delegate event on the location script that triggers when a global OnProduction event gets triggered. Similarly, my hard UI links now point to a method on the location script called UITriggerAction(int index) which triggers the Act method registered to a delegate array on the location script. Now each time a change the crop at a location I call the Disable method on all the Actions of the current crop, then I replace the crop and call the SetUp method on it, which will either register the associated Act method to the array accessible from UI, or to some other custom event. The Act methods would be simple and look like Act(Location loc) loc.Produce() or Act(Location loc) if(loc.HasProduced()) loc.SendFood() By doing it this way I keep the variables specific to the location on the location script as well as the logic on it. In addition I avoid any dependency between the current crop at a location and the rest of the game. For example I could have a method from the Region script, that would check all the currentFood values on the locations, and it would still work even if the crop at that location doesn't impact the currentFood value at that location. int AvailableFood() int availableFood 0 for (i 0 i lt loactions.Length i ) availableFood loactions i .currentFood return availableFood I just control the way in which I call those methods using a more versatile system. My question is Is this likely to lead to a very messy code on the location script where I will have all the variables and all the methods to do everything? Do you have any suggestions on how I can improve that system? Supporting code class Location MonoBehaviour Region parentRegion Crop currentCrop public int currentFood int maxFood public delegate CropAction(Location loc) public CropAction actions new CropAction 6 6 possible actions accessible from UI public void UITriggerAction(int index) actions index (this) public void Produce() Do stuff public void SendFood() Do stuff public void RecieveFood() Do stuff public void UseWater() Do stuff public bool HasProduced() return currentFood gt 0 public AddCrop(Crop crop) loc.Produce()


How do I stop my gun from pointing at the player? I'm making a game where you shoot enemies in Unity, but I can't figure out how to stop the player from pointing the gun at himself. I've tried detecting if the gun is on the left side of the player and if it's rotation on the z axis is less than 0, but no luck Here's the code for the gun using System.Collections using System.Collections.Generic using UnityEngine public class GunController MonoBehaviour public bool testbool public Transform player public CharacterController2D playercontroller public float smoothness 0.125f public float winglength 2 private Vector2 difference bool facingright false public GameObject bullet public int maxammo private int ammo private bool firing public Vector3 bulletspawnpos private SpriteRenderer sprite public Texture2D normalGun public Texture2D emptyGun public GameObject emptyBottle Start is called before the first frame update void Start() sprite GetComponent lt SpriteRenderer gt () player transform.parent.transform ammo maxammo Update is called once per frame void Update() private void FixedUpdate() firing false bool wasfacingright facingright if (Input.GetMouseButton(0) amp ammo ! gt 0 amp !firing ) firing true Instantiate(bullet, transform.position bulletspawnpos, transform.rotation) if (player.transform.position.x transform.position.x lt 0) facingright false sprite.flipY false if (player.transform.position.x transform.position.x gt 0) facingright true sprite.flipY true if (wasfacingright ! facingright) playercontroller.Flip() difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position float rot Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg Vector3 pos Camera.main.ScreenToWorldPoint(Input.mousePosition) player.position pos.z 0 Vector3 desiredpos player.position (winglength pos.normalized) Vector3 smoothpos Vector3.Lerp(transform.position, desiredpos, smoothness) transform.position smoothpos transform.rotation Quaternion.Euler(0, 0, rot) Before you point out that the ammo doesn't go down, just know I didn't add that for testing purposes.


Weird Animation Behavior in Unity I discovered a weird animation bug and have no idea how to solve it. Below you find the script I attached to my humanoid character. using UnityEngine using UnityEngine.AI public class PlayerCharacter MonoBehaviour private Animator anim private NavMeshAgent agent private bool dead false void Awake() this.anim GetComponent lt Animator gt () this.agent GetComponent lt NavMeshAgent gt () public void Kill() this.dead true this.anim.SetBool("Dead", true) void Update() if (Input.GetKeyDown(KeyCode.X)) Kill() public bool IsDead() return this.dead My character makes use of the NavMeshAgent and can walk around and idle everything works fine. But if I want to kill the player the dead animation loops continuously. This also happens if I change the death animation. This is my AnimationController As you can see, the transition has the condition "Death" with is set to true in the Kill() method. The code for walking and idling in combination with the NavMeshAgent is similar, but the script shown above doesn't work as expected and I have no clue why the animation starts to loop continuously (which looks a bit funny btw). Additionally the animation is not played to end, it restarts after a few frames. Any ideas? I could also post a video of the behavior if it would help. Thanks in advance! )


How to select coordinate position within uv texture in a shader Unity first of all I'm sorry for asking noob ish question. This is my fifth day trying to make a shader in Unity. I'm trying to select an area within my UV image as shown below and here's how it looks like on the mesh Basically I'm only selecting the red from the UV and apply it to the mesh. I encountered no problem when trying to select from the RGB, but when i try to use the XYZ for the coordinate position, it turns out that the value of x and r is the same, so is y and g, and z and b. My question is, how to select by the coordinate position in the UV texture? Thanks. here's my code Shader "Custom ASK RGB" Properties tex ("Tex", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Lambert sampler2D tex struct Input float2 uv2 tex TEXCOORD1 float4 pos TEXCOORD1 void surf (Input IN, inout SurfaceOutput o) my variable used to store the UV texture mentioned half4 tex tex2D ( tex, IN.uv2 tex.xy) my attempt to use position which doesn't work half4 texPos half4(IN.pos) half4 tryUV tex2D( tex, IN.uv2 tex.xy) tex.a 1 tex.b tex.r tex.g tryUV.a tex.r o.Albedo tryUV.rgb tryUV.a ENDCG FallBack "Diffuse"


Fix Unity Line Renderer for pointer drawing a jaggy line I think I'm using the standard Oculus setup from the SDK using the OVRCameraRig. I've also got a LaserPointer. But inside VR on my Rift the line looks like this. Any idea what I'm doing wrong? It used to be straight. Now it's not. I don't know what I changed.


How to scale smaller values more Hello it seems like it should be easy and i am missing something but i really couldn't find a solution as i am fairly new to programming. So basically i want to rotate a object faster when its closer to another object. My code is below and i want the rotationSpeed to be a higher value when its closer. rotationSpeed Mathf.Sqrt( Mathf.Pow(sphere.center.X playerSphere.center.X, 2) Mathf.Pow(sphere.center.Y playerSphere.center.Y, 2) Mathf.Pow(sphere.center.Z playerSphere.center.Z, 2)) eg 10 x 50, 5 x 100


How can I ensure a radius variable doesn't get reduced below 0? For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is 1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to 1. using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using System RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 public bool circle true Range(0, 50) public float xradius 15 Range(0, 50) public float yradius 15 LineRenderer line public float drawSpeed 0.3f void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount (segments 1) line.useWorldSpace false private void Update() if (xradius gt 0) if (Input.GetAxis("Mouse X") lt 0) xradius xradius 1 CreatePoints() if (Input.GetAxis("Mouse X") gt 0) xradius xradius 1 CreatePoints() private void CreatePoints() if (circle true) yradius xradius float x float z float change 2 (float)Math.PI segments float angle change for (int i 0 i lt (segments 1) i ) x Mathf.Sin(angle) xradius z Mathf.Cos(angle) yradius line.SetPosition((int)i, new Vector3(x, 0.5f, z)) angle change In the Update I did if (xradius gt 0) But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to 1 not sure how can it be 1 if I set the range in both xradius and yradius to be 0,50 You can see in the screenshot in the Inspector in the right both Xradius and Yradius are 1


Quaternion.AngleAxis smallest value? If I'm using an angle with a value of somewhat below 0.1 degrees in Quaternion.AngleAxis, the quaternion will not apply a rotation at all. Why is this?


Move object along world X Z axes taking account it's own rotation I have a camera 9 units up, tilted down at a 60 angle (rotated around it's X Axis), which means forward for the camera is pointed down at the floor as shown in the picture below Now when I press W, i want the camera to move horizontally forward without changing it's Y coordinate, but not along the world Z axis, as that breaks when the camera is rotated around it's Y axis. Here are a few images demonstrating what I want Side view Top view


Can you call a method from the script of all instantiated prefabs of a cetain object? I am currently trying to recreate chess and the problem I am having is that I need to instantiate all of the pawns in a loop (I could write it out but it seems inefficient) and I need to be able to call a method from all of the pawns to look for a check (I'll probably use raycast but I haven't gotten to that yet). How can I go about calling the method that looks for checks from all of the instances of the pawn? I'm pretty new to unity so please go easy on me if I said something dumb


Unity Raw Image Size scaled to Photoshop I'm just a beginner in Unity, so basically, I want to find out the exact measurement unity of the raw image so that I can now design in photoshop. I tried in Pixels in photoshop but when I import it in unity, it seems that the image is stretched out. I also tried mm, cm, inch but none of these worked. How to scale it so that my designed image's dimensions in photoshop will be exactly the same as the dimensions in unity? How to scale it? I tried pixels in photoshop but the image is stretched out indicating that it is not the right measurement unit.


Most efficient way to create modify terrain in real time? In my game players can modify terrain in real time, but I am not sure what is best practice for this scenario. I have redesigned and refactored the way the player does this a few times, and am feeling at a loss. Initially I created small blocks of terrain as GameObjects, but this I quickly realised was grossly inefficient. Later I devised a system which procedurally generated the 3d mesh by creating vectors and tris for a much larger terrain chunk GameObject, but this is also unfit for purpose. As I would like the player to be able to place new terrain pieces (replacing old) from premade 3d art assets. The question is how should one string these pieces together into one map, so that the player can enjoy a large map with a fine level of control? And for this not to break the game with inefficiency? Consider that the terrain system is composed of blocks of premade terrain segments, like river or cliff sections. I feel like I'm missing some basic knowledge of how and when to merge 3d meshes into GameObjects for this purpose?


Child transform's position not updated as parent moves I have a parent game object Object1. It has a child, which is simply an empty game object called ReferencePoint. ReferencePoint can be any arbitrary point on Object1 itself. I have another game object Object2. It has a public field called RotationReference, of type Transform. In the inspector, the ReferencePoint on Object1 is assigned to the RotationReference field on Object2. As Object1 moves, I expect ReferencePoint to change its position as well. Object2 is supposed to change its rotation to face its RotationReference in this case, the ReferencePoint on Object1 public override void Rotate() Vector3 relativeRotationReferencePosition this.RotationReference.position this.transform.position this.transform.rotation Quaternion.LookRotation(relativeRotationReferencePosition) However, I noticed that Object2 is not rotating at all, even when Object1 is moving. When I step through the call stack multiple times, I discover that this.RotationReference.position always has the same value, even though Object1 is moving. What am I missing here?


Should the interaction between the player and world objects be handled from the player class or as an event from the object classes? Suppose you're making a 3D platformer like Super Mario, if you jump on a Goomba, does Mario (the class) know that it just landed on a Goomba and then tell that Goomba to die, or does the Goomba realize that he is being smashed and dies ? I want to go with the first approach but it will end up with a huge If then (or Switch Case) script, also the reason why this is quot problematic quot is that many objects will make the player have a quot reaction quot , for example if you land on a Goomba, you don't just kill it, but it forces you to jump, that jump event, what's the best way to handle it ? Thanks


Unity RageTools Performance Has anyone used RageTools for Unity? What do you know about the performance? Is it more performant than using raster, for example with "puppet 2d" or the other way? I'm developing mobile games, so performance is very important for me. Thank you!


Is grass object amount limited in Unity? I'm using Unity 2019.3.7f1 free version to create a small game project. I have a large terrain which I want to fill with grass. To achieve that I'm using the grass brush tool provided with the terrain. However I cannot put more than, say 10'000 grass items (arbitrary, I don't know the real limit). Exceeding this amount, the grass objects contained in the first area I filled are removed, one by one, for a reason I cannot figure out. It's like there is a max limit of grass object I cannot exceed, and this is true for both grass textures and detail meshes. On the other hand the amount of tree seems unlimited, which is puzzling me. So my questions are Is there a limited amount of grass objects available in Unity? If yes, how many grass objects are available, and may I increase this limit? Is it a known bug, or a known limitation of the Unity free version? May grass impact the global performances of the game? (I feel that my game is significantly more slow after I added the grass...)


Microphone channel not detected in Unity This is very specific to Unity. A few testers are reporting that their microphone output isn't being detected. The code below works for the vast majority of users, but certain microphones seem to be outputting on the wrong channel (R maybe)? AudioClip current microphone recording clip Microphone.Start(microphone name, true, 30, 16000) How can I capture and analyze output from several channels? I don't see any channels parameter for Microphone.Start


can i show logs in unity with different colors or different icon signs? I'm working on a project that has a lot of logging messages that pass very fast. I can use error logs or warning logs but is there any way to log something with different colors so it is easier to find? Right now, I just use something like this Debug.LogError("show missing gold popup accepted")


How to create a material with variable color I'm new to Unity and trying to create a Carrom game. Since all the White and Black pieces, Queen basically have the same material and physical properties and texture except for their color, I'm trying to create a single material that I could assign to all 3 types of objects but could then set the material color per object type. Can this be achieved in Unity (I'm using 5.3.2)?


Object shrinks at same rate no matter what I am using the following code to shrink a sprite public bool shrinking false public float targetScale 0.1f public float shrinkSpeed 0.1f void Update () if(shrinking) mySprite.transform.localScale Vector3.one Time.deltaTime shrinkSpeed if(mySprite.transform.localScale.x lt targetScale) shrinking false However, no matter what I change shrinkSpeed to, the object shrinks at the same rate. I know it probably has something to do with putting it in the update function but where should I move it to fix the problem?


UI Element only showing in sceneview and not game in Unity3D I have a game and in one part, in the start of a scene its supposed to trigger an animation that shows a UI element that covers the whole screen to make a smooth transition from one scene to another. When I click a button it will trigger a function that triggers an ienumerator (just a function basically) which starts the animation, waits some time, then opens the next scene. The animation it triggers makes the UI show up. The code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class levelLoad MonoBehaviour public Animator transition public float waitTime 1f public void transitionLoad(int li) Debug.Log( quot Message through, activating script. quot ) StartCoroutine(loadScene(li)) IEnumerator loadScene(int levelIndex) the set trigger sets the trigger 'starts' which starts the animation that shows the ui element transition.SetTrigger( quot Starts quot ) Debug.Log( quot animations, go quot ) yield return new WaitForSeconds(waitTime) Debug.Log( quot Loading Scene quot ) loads scene SceneManager.LoadScene(levelIndex) Debug.Log( quot Scene Loaded quot ) So in the animator tab, there is a trigger called quot starts quot that when triggered, activates crossfade end which shows the UI element. crossfade start hides the UI element. I get all the debug logs in the code correctly and in game I checked animator, it says that its playing the animations yet in game I don't see the UI element showing up. Does anyone have a solution? I'm using unity 2019.17.4 lts. Also, the UI element is in a different canvas then the main canvas, a canvas that is in the sceneloader gameobject, which has the code above. Also that canvas is in layer default, and I checked, default layer is set to showing. Can anyone fix my problem of the UI element showing in scene view but not in game? (this isn't build) this is an android game.


Problem with LAN multiplayer game in Unity I'm trying to learn how to make an offline LAN multiplayer game in Unity. So for example, I make something that can send a text message and make a cube XD Now this is my problem (When I send a message, try connecting to the server, or when I try to create a cube I should first click on the other window!) StartServer using UnityEngine using System.Collections public class StartServer MonoBehaviour public Transform Taghsimobj public Transform Makan public Transform CubeOBJ public string MSG public string ResMsg void Ress (string inres) ResMsg inres void OnGUI () if (Network.peerType NetworkPeerType.Disconnected) if (GUILayout.Button ("StartServer")) Network.InitializeServer(10, 25000) if (GUILayout.Button ("Connect")) Network.Connect ("192.168.1.101", 25000) else if (GUILayout.Button ("CreatCube")) Network.Instantiate (CubeOBJ, Makan.transform.position, Makan.transform.rotation, 0) if (GUILayout.Button ("CreatChat")) Network.Instantiate (Taghsimobj, this.transform.position, this.transform.rotation, 0) if (GUILayout.Button ("SendMessage")) GameObject.Find ("GameObject(Clone)").GetComponent lt NetworkView gt ().RPC ("ResText", RPCMode.All, MSG) MSG GUILayout.TextField(MSG) GUILayout.Box (ResMsg) taghsim using UnityEngine using System.Collections public class Taghsim MonoBehaviour void Start () RPC void ResText (string ResIn) GameObject.Find ("Main Camera").SendMessage ("Ress", ResIn)


To Unity Rigidbody move like Character Controller on collision I want to a blue ball moving like a figure. in CharacterController, it was possible. but in Rigidbody, object was stucked. help me.


How To Disable A Select Collider I have a character with 2 2D Colliders, one for the head, and one for the feet, How do I Disable only the Head Collider in C .


Disable spaces in InputField This is straight forward. I have an input field and I want to restrict the user of inputting any spaces. I was thinking to make a script that checks if the user typed in a space and then remove it, but is there a simpler way of doing this?


Event Trigger for sprite not working I have set up a script to set game objects as active inactive depending on a particular number representing the index of a gameObject array. As you can see the image below. I have two buttons as shown on the page, a backward button and a forward button. I have attached event trigger components to each of the buttons so as to turn pages forward backward depending on which button I click The forward button works but this is not the case with the backward button. The function is not even being called. In fact only this sprite which on being clicked does not call the function assigned to it. More details on the backbutton Here is the script for the MonsterRosterManager.cs using System.Collections using System.Collections.Generic using UnityEngine public class MonsterRosterManager MonoBehaviour int MonsterPageNo public GameObject MonsterPages void Start() MonsterPageNo 0 void Update() switch (MonsterPageNo) case 0 MonsterPages 0 .SetActive(true) MonsterPages 1 .SetActive(false) MonsterPages 2 .SetActive(false) break case 1 MonsterPages 0 .SetActive(false) MonsterPages 1 .SetActive(true) MonsterPages 2 .SetActive(false) break case 2 MonsterPages 0 .SetActive(false) MonsterPages 1 .SetActive(false) MonsterPages 2 .SetActive(true) break public void PrevMonsterPage() Debug.Log ("Monster Page No to decrement " MonsterPageNo) MonsterPageNo 1 if (MonsterPageNo 1) MonsterPageNo 0 public void NextMonsterPage() Debug.Log ("Monster Page No to increment " MonsterPageNo) MonsterPageNo 1 if (MonsterPageNo MonsterPages.Length) MonsterPageNo MonsterPages.Length 1 Furthermore, the logs below show that the NextMonsterPage() function is called on clicking the forward button, but no calls to the PrevMonsterPage() are being registered. What am I overlooking here?


Unity animations Is the animation component really deprecated? I was looking for a way to create simple transform animations for 2d objects. As example, I wanted to animate all the objects of the scene when the game is paused (i.e. I just want to move the objects outside the screen boundaries with a nice animation). I think that creating an Animator Controller for something like this is not really useful for two reasons I don't know where the objects are at runtime. Please correct me if I'm wrong, I think I cannot dynamically change the value of a keyframe attached to an animation controller, so if I just start a transform animation the sprite will jump at the first keyframe value and then performs the animation. Terrible result. If I have 200 objects I should create 200 animation controllers with 200 animations. Creating animation programmatically would be great, but I read on forums and here on stackexchange that you cannot dynamically handle keyframes... and that I HAVE to use the Animation Controller, otherwise I can use the Legacy animation system (that to me sounds so... deprecated P) Then I checked this page of the documentation http docs.unity3d.com ScriptReference Animation.html They talk about the "Animation" component... and they don't say this element is Legacy Deprecated. Looking at this page it seems that I have a lot of control over Animation actually... but know I'm completely confused! Is this component deprecated or not? Should I always use the Animation Controller instead?


Moving towards and switching targets in Unity with collision I have these nodes set up for a ship to move towards over time with out looking stops then repeats in a sequence. like so 1 2 3 1 2 3 1 2... THE PROBLEMS i keep having either come from the inability to switch direction or the ship ignores all collision which i would like to be able to shoot it with actual objects. Ignores all Collision Vector3 currentPosition thisShip.transform.position Vector3 directionOfTravel targetPosition currentPosition directionOfTravel.Normalize() thisShip.MovePosition(currentPosition directionOfTravel speed Time.smoothDeltaTime) This one works perfectly but because MovePosition is a kin to translate and actually teleports objects it ignores all collision which i need. Can't Switch Direction Vector3 currentPosition thisShip.transform.position Vector3 directionOfTravel targetPosition currentPosition directionOfTravel.Normalize() thisShip.AddRelativeForce(currentPosition directionOfTravel speed Time.smoothDeltaTime, ForceMode.Force) so in this one i try to stop the rigid body by returning its velocity to zero and it does stop for a second but continues in its original direction anyways. thisShip.velocity Vector3.zero Use this to pause object I believe i need another method of movement (maybe use a CC) or maybe i can make AddRelativeForce work and be able to switch targets like MovePosition does. I'd really like to get this one thing done so i can move on to other parts of the project.


Character blocking when walking on cube edges I have my character walking on a ground made of cube. (scale 1,1,1). There is no space between them. Also, I have a RigidBody with 15 drag and I'm moving with AddForce. When I walk, my character sometimes block when trying to pass over the place where the 2 box meet. Like if my player collider was hitting the collider under him. Any fix for that?


How to sort cards' on screen positions by their suit? I have a 13 cards and sort button. When I click that button, I want all the cards of each suit to be grouped together on screen. So if I have 4 diamond cards in my 13 card hand, all 4 diamonds must be placed together in one part of the hand. If I had 4 spades then all 4 spades must be placed together in a separate part of the hand. Here's an example of a sorted hand of cards note how all the cards of each suit are placed together in a row So far I tried to Sort using Linq. When I inspect the sort order using Debug.Log it seems to be working fine, but I don't know how to position the cards on screen according to their suits. Here is the code I'm using so far. Note UserServedcards is the collection of 13 cards dealt into the player's hand. if (!SortCardOrder) List lt GameObject gt cardOrder null cardOrder this.userServedCards.OrderBy(go gt go.name).ToList() foreach (GameObject userServedCards in cardOrder) if (!userServedCards) Debug.Log("Sorting gt " userServedCards)


How to see the surface arc in Unity? How to see the surface arc in Unity? There is the tutorial and in this tutorial we can see the arc in editor While I can not see it. I checked that all my gizmos are enabled. How can I enable the arc?


How to customize player script with different abilities in each scene? I'm making a game with Unity. I wanted the player script to not have some features in some scenes but couldn't remove them from the script because I needed them for other scenes. So far, I just unpacked those player prefabs, created new scripts for each of them and removed the lines that I didn't want to have. I know this was not the best idea but I don't know any other way. One of its problems is that it makes managing the scripts hard and confusing. Is there a way that I can change them without creating new ones? Since I'm going to switch to the new Input system, I want to avoid the possible problems and headaches around these scripts. I also did this (creating a new script) for pause menu script as well. I provided two examples below to make the situation more clear. Example A) The player can use a shotgun in one of the scenes and I chose to not let him to use the knife in there. So I created a new script for that player and copied and pasted the original script (which had the melee attack ability) and then removed those lines from the new script. Example B) Pause menu can disable the health bar game object whenever the escape button is pressed. But for one of the levels, I don't want to use the health bar, so I pasted the code in a new pause menu script and removed the line that disables the bar.


Unity Photon multiplayer check distance between two players How to get distance between two player in a photon multiplayer game. Condition is both the player is moving. I have tried something like this, in my player control script if (photonView.isMine) pos1 rigidBody.position else pos2 rigidBody.position Distance Vector3.Distance(pos1 pos2) But its not working. For a player the pos2 is always (0,0). Please help.


How to make a script on a prefab act on a particular scene instance? I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it. Actionables are prefabs, which have an Actionable component, with the same setup (at the moment). Once the player is happy with the location of their Actionable, they click LMB, which activates onClick callback, which is supposed to call Planet.Build(), which adds the Actionable on the Planet permanently (saves it into an internal array). I also have a quot Turn Off quot Button, which calls stopBuilding() when clicked, disabling the preview placement. When stopBuilding() is invoked by the button click, everything works as expected. I also want to be able to call Planet.stopBuilding() (which, by removing the actionableModel, disables hover preview on the Planet) from Planet.Build(), such that the player does not need to click the Turn Off button described above after building an Actionable. Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly. How do I access the scene object Planet from Actionable prefab? Here is my Planet and its stopBuilding method so far public class Planet MonoBehaviour private GameObject actionableModel ... public void stopBuilding() For debugging only Planet planet GameObject.Find( quot Planet quot ).GetComponent lt Planet gt () Debug.Log(planet.actionableModel) Debug.Log(this.actionableModel) And here is the Actionable component which has a UnityEvent property onClick, which calls stopBuilding() on a click event. public class Actionable MonoBehaviour public class OnClick UnityEvent lt GameObject gt public OnClick onClick new OnClick() ... void OnMouseDown() onClick.Invoke(gameObject)