how do I instantiate a prefab that adds to the score text in c ? Hello I'm working on a game with random generation, a dungeon crawler of sorts. i need to be able to have an object that when instantiated, adds to the score(the goal is to find all of them as the dungeon is created around you)this is the script for the orb cube. public Text score public int scores Use this for initialization void Start () scores score.text scores.ToString() public void Update() score.text scores.ToString() public void OnMouseDown() Destroy(gameObject) scores when an object is added it won't add to the score.


Turning around an enemy when hitting a wall or after x time I have an enemy that is supposed to go in one direction and after hitting the wall or if a certain amount of time passes, it should turn around and go back. After hitting another wall, it should turn around again and keep doing this in a loop.


Is it allowed by social platforms to promote a game in exchange for in game currency? I have a mobile game that uses a a hint system. If the user needs help to solve a puzzle they can get a hint by watching an ad. I'm interested in offering some hints, let's say 5, if the user presses a Facebook Twitter button and posts some predefined text on those platforms something like quot I've been playing X game, check it out quot . I haven't seen many games that have something like this. For those more familiar with App Store and Play Store publishing guidelines, is there anything against such behaviour?


Unity2D jumping inconsistancy I'm tinkering with a unity2D sidescroller, and am trying to make a player controller to jump. However, when I tell my character to jump, it sometimes jumps twice the distance, and I don't know why. Below is my controller script using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public float playerSpeed 10 public float jumpForce 20 private bool ableToJump false public GameObject groundCheck place an empty object slightly below the character where it will collide with any ground Update is called once per frame void Update() if (Input.GetKey("space") amp amp ableToJump) ableToJump !ableToJump GetComponent lt Rigidbody2D gt ().AddForce(new Vector3(0,1,0) jumpForce) if (Input.GetKey("a")) transform.Translate( playerSpeed Time.deltaTime, 0, 0) if (Input.GetKey("d")) transform.Translate(playerSpeed Time.deltaTime, 0, 0) The player is grounded if a linecast to the groundcheck position hits anything on the ground layer. ableToJump Physics2D.Linecast(transform.position, groundCheck.transform.position, 1 lt lt LayerMask.NameToLayer("Wall")) Here is the glitch as it appears when I am previewing the game (watch how the third jump seems to be twice as high). There is no consistency to when it occurs, but it has occurred any time between two in a row and 10 12 between times it happens. I have tried long versus short presses of the jump key (space bar), moving versus standing still, and jumping on different locations. I have also tried disabling animations and waiting between presses versus pressing and holding space, versus pressing space rapidly. The only consistent thing is that sometimes I jump about three blocks (200 x 200px each) high, and sometimes I jump about six blocks high. Any tips are appreciated. Thanks!


How to move a player (with camera) towards a target object until camera fill target object? I'm trying to solve this 'algorithm' problem. I have a player and a camera on it. I want to automatically move this player towards a target object and stop it when target object completely quot fit quot my camera. So my question is how can I find target Vector3 player position, and camera rotation (up down) to perfectly quot view quot an object ? Consider that my target objects are simple Box. Thanks Edit X is the quot right quot transform.position to quot full quot see target object


Moving panel between two positions smoothly? I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script public GameObject gunsWindow private Vector3 a, b public bool open use inspector void Start() a gunsWindow.transform.position b new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z) void Update() if(open) gunsWindow.transform.position Vector3.MoveTowards(a, b, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(a, b, Time.deltaTime) panel shaking else gunsWindow.transform.position Vector3.MoveTowards(b, a, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(b, a, Time.deltaTime) shaking


Unity 3D rotating object around 2 axes rotates it around 3 I am developing a 3D space shooter and I've fount that when triying to rotate the ship using X and Y axes it also rotates on the Z axe. The answer here helped me a lot, but now when I try to rotate on 3 axes I have the same problem on the 2 axes sharing local space. The code I have right now is this float rotZ 1 float rotLeftRight Input.GetAxis("Mouse X") mouseSensitivity float rotUpDown Input.GetAxis("Mouse Y") mouseSensitivity transform.Rotate(0, rotLeftRight, 0, Space.World) transform.Rotate( rotUpDown, 0, 0, Space.Self) transform.Rotate(0, 0, rotZ, Space.Self) Anybody knows how to make all 3 rotations independent from each other? Thanks!


How to force Game Center submit score failure What would cause a failure to report a score to a Game Center leaderboard? Currently, score reporting succeeds almost all the time, so I'm trying to force failure so I can fix it. The Game Center documentation says it would fail to report a score if there are network issues. Are there any other scenarios where reporting a score would fail? I'm using Prime31's Game Center plugin for Unity3D.


OpenXR device not present in Start or Awake methods in Unity C script I'm developing a VR game using OpenXR in Unity (specifically developing on a Valve Index). When I try to access the input devices through the InputDevices.GetDevices() function, I get 0 devices back when I call this function from my script's Awake() or Start() methods. But when I call the same function from my script's Update() method, I see all the devices (e.g. head set, left controller, right controller). Why can't I see the devices in the Awake() or Start() methods?


convert clock input into 24 hour format I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24 hour format) to show dayNight effects in scene My code is to transform 12 hours clock cycle into 24 hours is if (todsky.Cycle.Hour gt 0 amp amp todsky.Cycle.Hour lt 11.97) Debug.LogError("1st") var degree 360 hourniddle.transform.eulerAngles.z var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes ConvertMinutesToHours(degreeToMintues) else if (todsky.Cycle.Hour gt 11.97 amp amp todsky.Cycle.Hour lt 23.97) Debug.LogError("2ndt") var degree 360 hourniddle.transform.eulerAngles.z as rotation is anti clock getting rever degree var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes var MintuestTo24HoursMintueCoverstion 720 degreeToMintues add 720 mintues into current minute in order to get 24 hour format ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion) void ConvertMinutesToHours(float mintues) result TimeSpan.FromMinutes(mintues) Debug.LogWarning(result.Hours " " result.TotalHours " " result.Minutes " " result.TotalMinutes) todsky.Cycle.Hour (float) result.TotalHours Debug.LogWarning("setted hours " todsky.Cycle.Hour) But it is not working correctly . have made a clock GUI(360 degree) and as you know it only show 12 digits format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping.


Is there a difference between using one large mesh with 100k polygons and using 1000 meshes with 100 polygons each? I'm planning on creating a first person shooter for mobile. Now I know that fps games usually have a lot of meshes in the scene (trees, buildings, terrains, etc.). So I've been looking at a lot of Unity optimization tips. One thing I've noticed is that they always say "If you have a lot of objects in your scene, then each mesh must have low polygon count". But how exactly does this help? If I have a lot of houses in my scene and I ensure that each house has very few polygons, wouldn't the total number of polygons in my scene be affecting the performance anyways? Or will my scene be rendered differently now that I've broken up the total polygon count into multiple parts?


How can I scale my UI elements to the lesser screen dimension in Unity 5? I want to create a custom mobile pad for my game. The mobile pad consists of two parts (both inside an ui canvas) The D Pad, which will be anchored to the bottom left side. The button group will be anchored to the bottom right side. I would like to resize the element on different resolutions, so that the element (in my case, the D Pad is an image) Has a size of 20 of the minimum of the width and the height. Has pivot of x 0.5, y 0.5. Having anchor of left bottom, its coordinates are (15 , 15 ) wrt the minimum of the width and the height. What I tried is to use an Aspect Ratio Filter in the D Pad image with ratio 1, but it did not work as intended (the coordinates led the image to an unexpected place). Note I am a n00b to Unity. I don't know whether it is right but my Canvas Scaler scales by Constant Pixel Size These images should illustrate what I want to achieve What should I do to make it work like in the pictures? Edit I attached this behavior, based on answer, to handle the change by runtime RequireComponent(typeof(UI.CanvasScaler)) class CanvasSmartScaler MonoBehavior private CanvasScaler scaler void Start() scaler GetComponent lt CanvasScaler gt () void Update() OMITTED CODE here I set the scale mode as in the Editor but right now i am in my mobile device and cannot remember the exact lines if (Screen.currentResolution.width lt Screen.currentResolution.height) scaler.matchWidthOrHeight 0 else scaler.matchWidthOrHeight 1 And attached that behavior to the canvas. However, for my debug exe (just for debug purposes) it always picks the 1 case regardless how do I resize the window. What am I missing?


Unity scene performance better to use one scene and toggle what is active? Unity scene performance questions In Unity, were one to have a scene that is basically identical in all but a few ways, would it be better to keep them as separate scenes, or to have them be one scene and have a script run during init to make all the modifications? Such as change the ground material from green to white to make it snowy, and such? If you went the separate scene route, would that drastically bloat the project? would all things be stored twice?


Unity Determine direction vector3 from a point in space and an angle in eulers I have a ball positioned as Vector3(x, x, x). I was able to get the direction of the ball to the mouse clicked position with Code (csharp) Vector3 direction Direction (clickPos2 startPos) Where the method is Code (csharp) public Vector3 Direction(Vector3 position) return new Vector3(position.x Length(position.x, position.y), position.y Length(position.x, position.y), position.z) Now I have an angle in eulers and I want that the ball goes to the direction of the angle. But how I calculate it? The game is played in 2d so actually only x and y is needed, z stays the same. Mirza


Scaling HUD and Camera I wanted to display an HUD, similar to the strategic games' one (like in DotA 2, Warcraft III, Starcraft II or Age of Empires). I didn't really know how to do it, so I managed to create a Texture Object and placed it in front of the scene. The image attached is the HUD itself, with some transparent "holes" in which I placed the cameras. I don't know if this description explains well what I'm trying to say, so I made this screenshot The HUD is just a png image with a greater z index. The image has three "holes" one for the gameboard, one for the dice, and one for the spells you can see on the right. The holes are filled with the cameras, so we can see the objects beyond the transparency. Everything looks quite nice. But if I change aspect ratio (which was Free Aspect), my layout gets completely screwed up. Notice that the HUD borders are not fully displayed the spells on the right are misplaced, and so are the dice. I managed to get the free aspect resolution, it is 1440x720, a perfect 2 1. But, even if I change my resolution to 800x400, things are not getting better. I've read something about pillarboxing and letterboxing, but I'm not sure that those techniques will help me with this issue. Is there something I can do to resize my objects and my cameras dynamically to fit the screen for every resolution like in the first screenshot? Of course, if you have any other solutions for the HUD, I'll be glad to learn!


Simulate wind in a powder game I would like to create a game similar to powder game. I've got a 2d array that stores different types of powder such as sand, water, gas, and fire. I've managed to get these to all move around successfully. I would now like the powders to react to wind. For example if there is fire it should push air upwards. If the air is moving upwards it will move other bits of powder around. The way I've been trying is to have two more 2d byte arrays. One for the wind x direction and another for the wind y direction. The fire will then add an amount to the cells and each update will add the wind x and y to the piece of powder that is on that cell. This almost works but pushes the powder much to fast. The difficulty in doing this is that the powder is on a grid while the wind could be going a variety of directions. What is the most efficient way of doing this?


Recognize hand drawn shape I want to ask player to replicate a simple shape (triangle, square, star, anything that can be done in single stroke) with mouse or on a touchscreen. Orientation matters, size does not. Example Can anyone give me directions to what techniques can be used?


Both Trigger and Collision BoxCollider2D My Player sprite needs to collide with some objects and be unable to pass through them and in other cases detect when it passes through some object (e.g. some non fatal enemies and some one way barriers). How do I test what an object is and make enforce one collision type or the other?


What causes this z position change? This is a follow up on the following thread. I'm applying a code that will move an object just outside the camera's frustum. I have used the same code in other projects, and it worked fine. However, I'm using it with URP now, and I'm experiencing a z position change while I expected only a x position change. And I just don't see why it does that. I have recorded a video here. If I press the button, the cube should be moved to the left only. But it also moves to the back (z position). And this is the script that I have applied to the cube in the video using System using UnityEngine public class PlaceOutsideCamera MonoBehaviour public void PlaceOutsideFrustum(Transform uTransform, bool uLeft) uTransform.position pPlaceOutsideFrustum(uTransform, uLeft) public static Vector3 pPlaceOutsideFrustum(Transform uTransform, bool uLeft) var frustumPlanes GeometryUtility.CalculateFrustumPlanes(Camera.main) Ray ray Plane plane if (uLeft) 1. ray Camera.main.ScreenPointToRay(new Vector3(0, Camera.main.pixelHeight 2f, 0)) plane frustumPlanes 0 else ray Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth 1, Camera.main.pixelHeight 2f, 0)) plane frustumPlanes 1 float fDistance Mathf.Abs(Camera.main.transform.position.z uTransform.position.z) 2. var borderPoint ray.GetPoint(fDistance) 3. var frustumOutside plane.normal Bounds b BoundsFromTransform(uTransform) 4. var halfDiameter b.size.magnitude 2f return borderPoint frustumOutside halfDiameter public static Bounds BoundsFromTransform(Transform uTransform) try Bounds bounds new Bounds(uTransform.position, Vector3.zero) wir h tten auch einfach new Bounds() nehmen k nnen, meint Manfredas foreach (Renderer renderer in uTransform.GetComponentsInChildren lt Renderer gt ()) bounds.Encapsulate(renderer.bounds) Vector3 nOff bounds.center uTransform.position return new Bounds(nOff, bounds.size) catch (Exception ex) UnityEngine.Debug.Break() return new Bounds() public void OnGUI() if (GUI.Button(new Rect(0, 350, 100, 50), "DoThis!")) pDoThis() private void pDoThis() this.PlaceOutsideFrustum(this.transform, true) Can anybody tell me why my code does this? I just don't see it. Thank you very much for the help! Edit Here is another video that shows the camera position in the Inspector.


Best Practices for Locating Clicks I am building a 2D board game in Unity with a static camera pointed down at the game board. During the active phase of each player's turn, I want to detect where they click on the board. Fortunately, the board is laid out in an easy rectangular grid. (Essentially a trio of 5x5 grids). Which of the following would be best practice to implement this? Create invisible colliders for every square on the board and create a translation function that translates those back to board positions (5,3) with Raytracing? Get the translated coordinates of the click and use a function to figure out which square (if any) the click is in using the mouseclick event handler (by calculating which square the grid coordinates fall in)? Make each square a button with its grid identity encoded and use that in its OnPressed function? Edit 4) Some other idea I haven't thought of yet? Experience level I'm just learning Unity, but have written a lot of C (and tons of other code).


Unity can't build AssetBundle for iOS From http docs.unity3d.com ScriptReference BuildPipeline.BuildAssetBundle.html, I am using the sample code using UnityEngine using UnityEditor public class ExportAssetBundles MenuItem("Assets Build AssetBundle From Selection Track dependencies") static void ExportResource () Bring up save panel string path EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d") if (path.Length ! 0) Build the resource file from the active selection. Object selection Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets) BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies BuildAssetBundleOptions.CompleteAssets) Selection.objects selection MenuItem("Assets Build AssetBundle From Selection No dependency tracking") static void ExportResourceNoTrack () Bring up save panel string path EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d") if (path.Length ! 0) Build the resource file from the active selection. BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path) To build an AssetBundle. However, whenever I run this on a prefab, I noticed that Unity switches the platform to WebPlayer and THEN builds the bundle. But I need the AssetBundle to be built for iOS and Android I don't need WebPlayer bundles. Why does it keep switching to WebPlayer platform whenever I run this? How can I build for iOS and Android? My prefab is just an object with a Sprite Renderer.


Mesh contents get flipped I am using below shader with my mesh object that is showing a webpage. It is showing fine but the problem is the web page has flipped Shader quot UI Default OverlayNoZTest quot Properties PerRendererData MainTex ( quot Sprite Texture quot , 2D) quot white quot Color ( quot Tint quot , Color) (1,1,1,1) StencilComp ( quot Stencil Comparison quot , Float) 8 Stencil ( quot Stencil ID quot , Float) 0 StencilOp ( quot Stencil Operation quot , Float) 0 StencilWriteMask ( quot Stencil Write Mask quot , Float) 255 StencilReadMask ( quot Stencil Read Mask quot , Float) 255 ColorMask ( quot Color Mask quot , Float) 15 SubShader Tags quot Queue quot quot Overlay quot quot IgnoreProjector quot quot True quot quot RenderType quot quot Transparent quot quot PreviewType quot quot Plane quot quot CanUseSpriteAtlas quot quot True quot Stencil Ref Stencil Comp StencilComp Pass StencilOp ReadMask StencilReadMask WriteMask StencilWriteMask Cull Off Lighting Off ZWrite Off ZTest Off Blend SrcAlpha OneMinusSrcAlpha ColorMask ColorMask Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct appdata t float4 vertex POSITION float4 color COLOR float2 texcoord TEXCOORD0 struct v2f float4 vertex SV POSITION fixed4 color COLOR half2 texcoord TEXCOORD0 fixed4 Color v2f vert(appdata t IN) v2f OUT OUT.vertex mul(UNITY MATRIX MVP, IN.vertex) OUT.texcoord IN.texcoord ifdef UNITY HALF TEXEL OFFSET OUT.vertex.xy ( ScreenParams.zw 1.0) float2( 1,1) endif OUT.color IN.color Color return OUT sampler2D MainTex fixed4 frag(v2f IN) SV Target half4 color tex2D( MainTex, IN.texcoord) IN.color clip (color.a 0.01) return color ENDCG I am using above shader so that the mesh should be shown on top of everyting.


How can I create a walking zone logic for my player? First I will show a screenshot and explain the logic I think of and what I'm trying to do In the diagram the circle is the player the big rectangle is the zone area for increase decrease speed movement of the player and the small black rectangle is the target. What I'm trying to do is to add some rules for this case. I'm controlling the player in third person movement with the keys WSAD and the mouse to rotate around looking around. This is the player structure screenshot in the Hierarchy There are few rules I'm trying to set for the player in this specific situation in the game and I want to make it generic so I can add the rules or create this behaviour in any place in the game when I need to. The idea is when the player is getting inside the green zone rectangle facing the target make the player slow down to stop smooth. The green zone is the distance from the target to start slow down only if the player is facing the target. If I rotate the player back facing away from the target in the green zone at any time increase the player speed back to normal speed. The idea is that if in the green zone I rotate the player at any time and move hi he will decrease increase the movement speed. Facing target decrease slowly to stop facing away from target increase the speed slowly to normal.


How to create a line renderer with end point as the mouse position, but with a fixed direction I have two objects with a line going from one to the other, like this I want to create another line with a starting point one of the objects and an end point the mouse position, however still facing the second object, which will look like the first line is filling up to where the mouse is. For example, I want to connect the blue shape with the green shape, so I move my mouse from one to the other. The game finds the nearest white line from the cursor and creates another line on top of it that follows my cursor, like this The current script is this. It draws a line from the origin shape to the mouse position, but it doesn't stay on only one direction and instead moves where my mouse goes public class SelectionLine MonoBehaviour private LineRenderer lineRenderer private void Awake() lineRenderer GetComponent lt LineRenderer gt () private void Update() if (ShapeSelection.instance.selectedShape ! null amp amp ShapeSelection.instance.draggingFinger ! null) var originPosition ShapeSelection.instance.selectedShape.transform.position var destinationPosition ShapeSelection.instance.draggingFinger.ScreenPosition lineRenderer.SetPosition(0, new Vector2(originPosition.x, originPosition.y)) lineRenderer.SetPosition(1, new Vector3(ShapeSelection.instance.draggingFinger.GetWorldPosition(1f).x, ShapeSelection.instance.draggingFinger.GetWorldPosition(1f).y, 0)) There is no way (as far as I know) to set a direction of a line renderer in Unity, so how can I achieve this?


How to always draw a child mesh in front of its parent mesh I need to display a gizmo like mesh at runtime, and it must be always in front of its target mesh. How can I achieve that?


Mouse drag rotation script doesn't work when attached to OBJ model I am new to Unity. I imported an OBJ model and assigned materials to it. I want to rotate it using the mouse in the game, using this script using UnityEngine public class MouseDragRotate MonoBehaviour float rotationSpeed 0.2f void OnMouseDrag() float XaxisRotation Input.GetAxis("Mouse X") rotationSpeed float YaxisRotation Input.GetAxis("Mouse Y") rotationSpeed select the axis by which you want to rotate the GameObject transform.RotateAround (Vector3.down, XaxisRotation) transform.RotateAround (Vector3.right, YaxisRotation) I tried to apply this rotation script to the OBJ asset in my Project folder, but I wasn't able to find an Add Component option in its Inspector. So I dragged it to the Hierarchy panel to create an instance of the object in my scene. I applied my materials again to this instance. Then I added the rotation script using the Add Component button in the Inspector. But when running the game in play mode, I can't rotate it. I verified that the script above works perfectly for the default Cube or Plane primitives in Unity, but not for this imported object. How can I make this script work with my OBJ model?


Increment grid by rotation I'm currently working on a grid for snapping objects side by side. My current script is working fine, but only for game objects which haven't been rotated. Here is an example video of the problem https vid.me jN6D The cube at the right has a rotation of Vector3.zero, the left one has been rotated on the Y axis. As you can see snapping works perfectly for the right one, but at 0 15 you can see that the snapping doesn't work well for the rotated cube, that's because I've currently no idea how I can add the rotation in my current script. Here is a snippet of the most important part of code I'm currently using to calculate the grid Vector3 pivotToPoint hit.point nearestGameObject.transform.position float positionX nearestGameObject.transform.position.x Mathf.Round(pivotToPoint.x nearestGameObject.transform.renderer.bounds.size.x) nearestGameObject.transform.renderer.bounds.size.x float positionZ nearestGameObject.transform.position.z Mathf.Round(pivotToPoint.z nearestGameObject.transform.renderer.bounds.size.z) nearestGameObject.transform.renderer.bounds.size.z Vector3 origin new Vector3(positionX, 0, positionZ) Vector3.up 100 if (Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity, layerMask)) previewGameObject.transform.position new Vector3(positionX, hit.point.y, positionZ) previewGameObject.transform.rotation nearestGameObject.transform.rotation Maybe some of you guys have an idea how to solve this, it's driving me crazy. p.s. Here is some guy with a similar problem, but I'm very lost when in comes to adding the solution into my code.


Multiple updates for Unity animation per one method call I'm trying to do some simulation where I move objects procedurally in a loop within one method call. So instead of using Update(), method I do for example void Simulate(float deltaTime) real logic look a lot different, this is just an example for(int i 0 i lt 1000 i) transform.position direction speed deltaTime ..... The reason I'm doing this is because I want consistent 'framerate' by passing that deltaTime parameter Which is for example 0.01f And each step of that loop I'm taking snapshots on multiple cameras with calling Render() method on them before taking a picture. The movement works fine and I see it on snapshots, but some objects has an animation which should also be updated procedurally. I've tried to do animator.speed 0 and then in the same loop, to test it for (int i 1 i lt 1000 i) ... animator.Play("WalkFWD", 0, i 1000f) for example But animation does not change over that loop. It only works with that Play method when I either make this Simulation() method a coroutine and pass one frame (yield return null), or if I use in Update(). So, my question is it possible to procedurally update redraw animation after normalized time of that animation is set. (without waiting for another frame)


Is there a way to run Unity without rendering the scene on the monitor (headless)? I am doing some machine learning and I get my environment from Unity in the form of images but the training is taking too long and it keeps me from doing anything else on my system. Is there a way to hide the simulation rendering? Any help will be highly appreciated.


How to write on a Tilemap using a C script? I loaded my tileset asset TileSheet.png using the Tile Palette (Window gt 2D gt Tile Palette). This created the folder "grass tiles" with multiple asset files, one named "TileSheet 168.asset". My goal is to write a script that randomly generates grass tiles within my 128 x 128 tile map. I envision the code looking something like this tilemap.SetTile(new Vector3Int(x, y, 0), "TileSheet " TileNum ".asset) ...where TileNum is a randomly generated integer between 1 and 750 (assuming that's what SetTile even does). Current code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Tilemaps public class drawMap MonoBehaviour public Tile grassTile public Tilemap ChessMap Start is called before the first frame update void Start() RenderMap(GenerateArray(128, 128), ChessMap, grassTile) public static int , GenerateArray(int width, int height) int colorControl 0 int cellFig 0 int , map new int width, height for (int x 1 x lt map.GetUpperBound(0) x ) cellFig x 16 if (Mathf.Floor(cellFig) cellFig) if (colorControl 0) colorControl 1 else colorControl 0 for (int y 1 y lt map.GetUpperBound(1) y ) if (colorControl 0) map x, y 0 else map x, y 1 Debug.Log("Map Coordinates x " x) Debug.Log("Map Coordinates y " y) Debug.Log("color " colorControl) if (colorControl 0) colorControl 1 else colorControl 0 return map public static void RenderMap(int , map, Tilemap tilemap, TileBase tile) Clear the map (ensures we dont overlap) tilemap.ClearAllTiles() Loop through the width of the map for (int x 0 x lt map.GetUpperBound(0) x ) Loop through the height of the map for (int y 0 y lt map.GetUpperBound(1) y ) 1 tile, 0 no tile if (map x, y 1) tilemap.SetTile(new Vector3Int(x, y, 0), "TileSheet " TileNum ".asset) Where I need help is the loading of the asset, referencing the asset, and setting of the asset. I only need this script once, because after it's done, hopefully the GameObject can remember (as if I used the Tile Palette tool).


Prevent player from jumping on a mesh I am working on a game and I have a mesh that I use to block hallways and prevent the player from going that direction. They are placed vertically with slight angles. I'm having a problem that the player can jump up on these. The player needs to be on the ground all the time otherwise they will be able to avoid dying indefinitely. I have tried moving and rotating and no matter how its placed I can always seem to jump on it. I want to avoid adding more to the scene then what is necessary so I don't want to add another mesh or extra collision of some kind just to keep the player away from those points as that mesh already has collision. Unless it turns out that is actually a good way to handle this. Is there a way I can prevent the player from jumping on these items? Or is there some other way I can handle if the player does jump up on them. Like maybe start damaging the player after a few seconds until they get down? What is a proper way of handling this?


Player disappears when it collides with a tagged object I am working on a simple game where the goal is to help a Player catch specific objects with a tag "Present". After taking care of the models, animations I am now working on the collisions and counting UI. For the collisions, on my Player Controller (I am using the ThridPersonUserController from the player Unity Standard Assets which simplified the whole animation process), I added the following functions void OnCollisionEnter(Collision other) if (other.gameObject.tag "Present") Destroy(gameObject) count count 1 SetCountText() void SetCountText() countText.text "Count " count.ToString() if (count 0) winText.text "Thanks to you the Christmas will be memorable!" However, like this, when the Player hits an object with the tag "Present", even though the counting is working properly, the player disappears. I have tried to change the OnCollisionEnter to an OnTriggerEnter, like this void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag("Present")) Destroy(gameObject) count count 1 SetCountText() However when the Player hits the objects with the tag "Present", they don't disappear. My Player has a Capsule Collider and a Rigidbody. The objects with the tag "Present" have a Box Collider and a Rigidbody. Any guidance on how to make my Player stay in scene while removing the other objetcs and reducing the count is appreciated.


Assets bundles have higher size than uncompressed sprites I've created a script that generates assets bundles by compressing sprites using LZ4 compression. I need this in order to generate smaller files that I'll download from a server at runtime but after taking a look at those bundles. I've found out that they actually have a higher size than the uncompressed sprites. For example, I've generated a bundle from three sprites that have a size of 201KB together, but if I take a look at its generated bundle, its size is 300KB. This is only one example, there are other bundles that are 6MB but their original files are only 500KB and that doesn't make any sense to me. Can someone point me in the right direction?


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


Need help understanding this script I found this script on a tutorial that I want to implement into my game, but I first want to understand what it does and how it does it. The script is attached to a Joystick UI, which has the inner ring button of the joystick as its child. The script makes the inner button of the joystick move within a certain confine, when the player uses the joystick. quot joystickButton quot is the child object. public class Joystick MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler public Image joystickButton public Vector3 inputDirection void Start() inputDirection Vector3.zero public void OnDrag(PointerEventData drag) Vector2 position Vector2.zero RectTransformUtility.ScreenPointToLocalPointInRectangle (joystickButton.rectTransform, drag.position, drag.pressEventCamera, out position) position.x (position.x joystickButton.rectTransform.sizeDelta.x) position.y (position.y joystickButton.rectTransform.sizeDelta.y) float x position.x 2 float y position.y 2 inputDirection new Vector3(x, y, 0) inputDirection (inputDirection.magnitude gt 1) ? inputDirection.normalized inputDirection joystickButton.rectTransform.anchoredPosition new Vector3(inputDirection.x (joystickButton.rectTransform.sizeDelta.x 3), inputDirection.y (joystickButton.rectTransform.sizeDelta.y) 3) public void OnPointerDown(PointerEventData drag) OnDrag(drag) public void OnPointerUp(PointerEventData release) inputDirection Vector3.zero joystickButton.rectTransform.anchoredPosition Vector3.zero I did some research and some tests, and from what I understand, if I tap a point within the Joystick UI's RectTransform, the point I tap, quot drag quot , gets converted to a position in the RectTransform of joystickButton. The position is then converted to a vector, inputDirection, which represents the direction and location of my tap. The vector is then normalized, and the joystickButton is moved to (inputDirection.x (joystickButton.rectTransform.sizeDelta.x 3), inputDirection.y (joystickButton.rectTransform.sizeDelta.y) 3), where the vector is pointing to the direction of my tap, and has a magnitude that is 1 3 the length of the side of joystickButton's RectTransform, since all the anchors are centered, and the RectTransform is a square. What I don't get is why I need these lines RectTransformUtility.ScreenPointToLocalPointInRectangle (joystickButton.rectTransform, drag.position, drag.pressEventCamera, out position) and float x position.x 2 float y position.y 2 Is there any purpose to these lines? Converting the 1st one to position drag.position and the 2nd one to float x position.x float y position.y doesn't seem to mess anything up. Also, I didn't notice at first, but not dividing on by sizeDelta on these lines position.x (position.x joystickButton.rectTransform.sizeDelta.x) position.y (position.y joystickButton.rectTransform.sizeDelta.y) does change the result slightly, so if anyone can tell me what function dividing the values does, it would be greatly appreciated.


Pausing game with State machine and handling jumps I am adding pause functionality to my upcoming racing game.The players can jump in it. Time.timeScale 0 is obvious solution to pause game.I am avoiding this solution as users can do in app purchases in pause menu and with timeScale to 0 its somehow preventing them. So to overcome that problem I have added state machine pattern to start,pause,resume,finish game. The thing is when I pause game with my state machine pause behaviour it pauses the game properly without any hesitation until the player is Jumping and pause occurs. When player is jumping everything gets pause perfectly,just player falls to ground. So to overcome that problem what I tried was if user pauses game and player is on air the isKinematic on player gets set to to true and game gets pause with player halt on air. The problem with this approach was that when user resume the game ,unexpected jump movement happens, i.e., player does not land on expected position . Example if player on y 10 and game gets pause, with Time.timeScale player will always land on Z 17 ,but with my this second approach player sometimes land on Z 20 ,Z 21 Z 19 etc so my question is how will I do properly pause game with state machine without causing unexpected jump movement.


Why is perlin noise generating flat terrain in Unity? I am trying to generate terrain using perlin noise however the terrain being generated is a plateau. Here is the code that I'm using var xlength 65.0 var ylength 65.0 var scale 4.1f var heights new float xlength, ylength function Start () for (var i 0 i lt xlength i ) for (var j 0 j lt ylength j ) heights i,j Mathf.PerlinNoise(Time.time i xlength scale 1000,Time.time j ylength scale 1000) i j gameObject.GetComponent(Terrain).terrainData.SetHeights(0,0,heights) What am I doing wrong here?


Is it possible to render project flatten a 3d model onto a 2d plane in Unity? If I have a 3d Object (character) could I use a renderer shader camera mode to essentially render the 3d object as a 2d sprite? Not looking for a full tutorial on this one, I realize its a large question just looking for a direction to head in. My thought on this one is that it would be easier to create a 3d model and move it to a position for a book style game. The character could be posed in a number of different positions. I'd add some sort of outline and Cel shader and outline to get the affect, but in order to get it to view properly on my otherwise 2d game, I would need it to be in a panel or something that could have a quot Sorting Layer quot added to it.


If my camera does not change position but rotates, Does adding lerp do anything? If my camera does not change position but rotates, Does lerp do anything? cameraposition Vector3.Lerp(Camera.main.transform.position, Camera.main.transform.position, Time.deltaTime cameraLerp) Camera.main.transform.position cameraposition Camera.main.transform.LookAt(gameobject.transform.position)


Is it better to load all of the scene at once or load small parts of it as the player moves? I want to create a lot of detail in my game but I don t want to kill the frame rate tracking all the models and movements (like all the grass). Will loading them in pieces save the frame rate or will constantly loading and unloading models with every step negate any benefits of loading in pieces? I want to only load what the player will see at that moment and nothing else until the player either moves the camera or walks. I also want to know if loading a scene on Unity uses the gpu or the cpu?


Unity or Monogame or Gamemaker 2 for an experienced application developer? So i know this question has been hammered down several times but please bear with me. I used to be a C .Net application developer but i am no longer employed, i am pretty good at C . I want to get into serious game development and i dunno where to start, i used to work with unity occasionally which is a very little and i kinda find it clunky, like it works but somehow it does not feel right and feels kinda clunky. But it works with tiled map editor without much of a hassle. I Remember using Game maker studio when i was back in college and i found it very good, its a breeze to work with and even have its own tiled map editor, even seems to have some good tutorials, the only con is its price. I was initially inclined towards Monogame cause of my C background, but i neither have time nor money and resources to support me for long enough time to be able to code every single thing from scratch and i am kinda in a pretty bad situation overall right now. It just takes too much time to do anything even to make it work with a tiled map editor, and there are very few tutorials or documentation to start with. It seems like the only option for me is Unity at the moment, cause of ease of access and how easy it is to work with tiled map editor and lots of tutorials. which one do you guys think is good overall? Please keep in mind that i am currently unemployed and have very little resources to support myself, and i am a programmer so i don't even know how to compose music and do art for the game and i'd prefer if it provides some asserts to be used so i wont waste time in learning stuff when i cannot afford to spend time. I will eventually learn them but not now, its not happening now so i prefer something that comes with some sorta free asserts that can be used (mainly music and art), I mean does it even matter if all i am trying to do is earn a decent minimum living? I just want to make simple 2D NES Snes style games with multiplayer support. Thank you.


Interfacing with bill note acceptors in unity What ways are there to interface a unity game with a bill acceptor validator? Usually this type of devices are connecting to a computer using a serial port and communicate over ccTalk protocol. But what ways exist of incorporating this type of devices in Unity?


Learning to think like a programmer I'm pretty interested in game development and I've tried a couple of platforms and languages. Including libgdx and game maker studio, all without any real success. I'm currently using unity and it's the farthest I have ever gotten, but it just doesn't feel right. I follow tutorials and learn how to do certain things, but it just feels like I'm a parrot learning a new word I don't really understand what I'm doing just kind of memorizing stuff. I'm trying to become a good game developer, but I just don't know how to practice c in a way where I will gain actual understanding and not just memorize a bunch of syntax. Thanks in advance I really need help.


Unity tilemap tiles animation I am beginner in Unity and I have created tilemap using new tilemap system in unity which looks like this I created a script that lets me swap tiles. First I click on some tile and than I choose second tile, after I click second time, tiles swap their positions. Which will than look like this How can I apply some animation to this process? Seems like I have no control over tile object as it is. I can only access TileBase which as I understand is not all information about tile. I can't create any animator controller or access its transform object. I want to add some custom animation when tiles swap their places. Thank you!


Create a normal map using a script? Unity I don't have a software that can create normal maps from an image so I usually make a grayscale image and then let unity make the normal map from that image. But I can't save the image to use for later, Instead I have to convert it to a normal map every time I use it. So how would I make a normal map from a greyscale using a script? i prefer c but js works fine.


How to differentiate between instantiated objects in Unity? I'm currently trying to solve a way to go about the following problem before I start writing any code (the old fashioned pen and paper way) but I'm not sure how I could achieve the following. I'm going to have an object with a Collider attached to it in my scene. As my instantiated enemies pass through this Collider they will be added to an ArrayList which lets the object in question keep track of the enemies. The problem I can't figure out is how to determine which object is which. I will have a script attached to my main camera which will be responsible for spawning the enemy units, I'll be using a while loop in sudo code it would look something like this. public Transform (Attach the prefab in the inspector) Somefunction() int i 0 arraylist goes here while (i lt 10) arraylist i Newly instantiated object. My object with the collider will then have something like the following OnTriggerEnter() get specific object somehow add to arraylist I can't use the tag function because all the objects will have the same tag, the only thing I assume will be different is the position of the object in the spawn array (ie arraylist 1 arraylist 2 etc.) If I created a public accessor method on the trigger object could I call this method to return a string name or something special that identifies the object uniquely compared to the rest of the objects in the scene or does Unity already do this somehow natively?


What's the difference between Update and FixedUpdate in Unity, and should I bother? I was told to use Update() for graphics and FixedUpdate() for physics, but sometimes my inputs won't register when I use FixedUpdate(). It works fine if I use Update() for everything though. Should I bother with FixedUpdate(), or am I doing something wrong?


Unity GameView Differrent with CameraView Dont have 3D environments Now on my existing project, if i create new scene, automatically i got my gameview like below above game does not have 3d environments outlook, i'm expecting like below (my old existing scene) Any Idea to solve this ? thanks


Game launcher updater download delta diff I'm making a launcher for my game (using Unity3d). I want it to have the following features Compare game version to latest version and update if necessary Check files integrity and update if differences are found Download patch needed files So comparing the game version is easy I just parse a version.txt file and compare it's value to the latest server version. Checking file integrity sounds easy too Make a list of all files in the game folder, order the list, get a checksum and check if it corresponds. Now here's the difficult part Downloading the required files. My first idea was If a file checksum is different, download that file. But unity assets are compressed into large files, so even a simple change will lead to the download of a 2gb file... So I'm now looking for a way do download only the different parts. I heard about VCDIFF xdelta, apparently they can be useful to get a "delta patch" of different binaries. Cool. But how can I compare two folders if one of them is distant, without downloading it all before ? Could torrent be an answer ? How are game unity devs doing this ? Maybe rsync can be useful, but is it safe if hundreds of clients are simultaneously updating using rsync ? I heard about Unity's AssetBundles. Is that useful and is it ok to put ALL my assets in bundles ? How would I display a progress bar in unity showing the rsync progression ?


Capsule collider triggered unexpectedly I have an object with a capsule collider on its root, with IsTrigger true (triggered by the player). The trigger works fine, but is also triggered unexpectedly some times when the player walks near the collider, but still way out of its range. See attached image the capsule collider limits are wel within the round circle object. On the right you see that the player has triggered the trigger, while it was far away from the collider. When I run circles around the collider, this will happen sometimes. Location appears to be random and it doesnt happen if the player is further away than say 10 meters. Anyone else have this issue or can tell me what is causing it?


How to keep sprite on screen while increasing its width to screen width I have been able to increase the width of a sprite to the width of the screen size, but the sprite exceeds the borders of the screen width to the right or left when I try expanding it when it's not at the center. How can I scale the sprite in such a way that it's width increases on both sides till it occupies the screen width without exceeding it's bounds, regardless of the sprite's initial position? Please see my code below bool isScaling false IEnumerator scaleToX(SpriteRenderer spriteToScale, float newXValue, float byTime) if (isScaling) yield break isScaling true float counter 0 float currentX spriteToScale.transform.localScale.x float yAxis spriteToScale.transform.localScale.y float ZAxis spriteToScale.transform.localScale.z Debug.Log(currentX) while (counter lt byTime) counter Time.deltaTime Vector3 tempVector new Vector3(currentX, yAxis, ZAxis) tempVector.x Mathf.Lerp(currentX, newXValue, counter byTime) spriteToScale.transform.localScale tempVector yield return null isScaling false


Change texture settings for each object So I'm kinda new to Unity, but I've used it a couple of times before. Here's my issue I have two cubes with a random texture applied to them (drag'n'dropped something from the Asset Store). These cubes have different sizes, where one is a square and one is a rectangle. I want to set the tiling size to be different on them (because they are obviously stretched on the rectangle), but when I click on one and change it, the settings changes for both of them. This is how it looks right now http i.imgur.com JtubBle.png Is it possible to make these settings unique for each object somehow?


Why do I have render problems happening frequently in my Unity scene? I am making vertical endless runner. My platforms are moving down, and the camera and players are remaining in the same location, resulting in the effect of player movement. The obstacles are generated and move in same direction as platforms. The problem is obstacles rendered by the camera is not right. I mean that the obstacles are in camera's FOV but are still visible after some time when they reach the player to close.


What method could I use to avoid using a lookup table for each item when loading a players inventory? Let me explain a little about the pickup items and inventory to make this much clearer. Every in world item that can be picked up has a ScriptableObject assigned to it that contains all the information about that item (id, name, description, maxstacksize, sprite etc). When a player picks up an item it gets added to a List lt InventoryItem gt . InventoryItem is a class that gets populated with some of the data pulled from the ScriptableObject (id, name, description, maxstacksize), and also gets an amount property. I want to save the players inventory, but want to simplify the InventoryItem data. So I created an InventoryItemSimple struct that holds the id and amount for each item in the inventory, and then save that list to file. When loading the player inventory, currently I have a BIG list of ScriptableObjects that map to the id. So I am looping over the saved inventory list and matching against the id in the lookup table, and then adding the item to the inventory. I want to avoid this as over time their could be 2,000 unique objects that could be in the world. What's a better method to handle this? If I stick with the lookup table, do I need to worry about how much memory is being used? I don't think my lookup table will ever contain 2,000 elements. But the thought of having one massive list to manage doesn't appeal to me.


Why can't I put a source image in my Image component? I can't put an image here as source image, and I have trouble figuring out why. What did I miss?


How to make wall tiles overlap floor tiles a bit in Unity3D? Currently my tiles are very strictly placed, there are wall tiles, and floor tiles, and they don't overlap at all. What I want to achieve is to have my walls overlap my floors a bit. So their inner edges doesn't have to be a stright line, but a free shape, with "transparent holes" which show the floor below. Resulting in a much better feeling. My current approach is to have multiple layers. One for the floor and wall (single) tiles), and one above this, which will have the overlapping, decorative parts of the walls. But this methods feels slow and clunky For one wall tile I have to place 9 tiles tileparts to make it look nice. (the tile itself plus the neighbours). It would be better to place just one tile which got overlapping parts


Should I be concerned about assets being accessed by dumping VRAM? I have heard many people tell me that a user can dump the VRAM on their GPU and get all the images in my game. Including all "Streamed" images. This includes most of my Menu graphics. How would a user dump their VRAM and get the images? Is there software that does it? Do I need to be concerned that this is possible and should I protect my game from it?


Instantiate prefab button inside of panel I have a Canvas GameObject with a panel inside of it and a button prefab of the default button. When I drag the button from my resources folder onto the Canvas in the hierarchy, it places itself where I expect it to, into the panel. However when I instantiate it like below GameObject button Instantiate(Resources.Load("UI Dialogue Button"), new Vector3(0, 0, 0), Quaternion.identity, MyCanvas.transform) as GameObject it gets placed into the center of the screen because of the second parameter. However, I can't set it as a child of the parent because that doesn't happen until the last parameter. It also doesn't feel right to figure out the exact Vector3 to plug in so that it looks like its on top of the panel. Is there a way to instantiate the button onto the panel in code as it works when dragging it from the resources folder onto the Canvas in the hierarchy?


Unity3d "random" transform position values on editor Run into some strange behavior on editor position values. https youtu.be DUBpbOUkbfo As you can see we have two cube object with colliders on both and rigidbody on parent. After start play mode parent object editor values sets to some random numbers while transform.localPosition and transform.position is still (0,0,0). This somehow related to parent child physics hierarchy but can't understand how.


Replicating Flight Mechanics of Star Wars Battlefront (2015) I'm trying to replicate the flight mechanics from Star Wars Battlefront (2015) in Unity and I can't get my head around what exactly is going on. Specifically, how do I get the camera to behave like this using Unity and C https youtu.be gxZdOUiEiyY?t 1m1s I don't mind if you don't give code, I'm just struggling to understand what happens and when in terms of camera movements and rotation.


How to stop rendering a gameObject that has no rendering component in unity I want to stop rendering this gameObject. But the all available renderer.enabled false is not working. Is it because it has no rendering component attached? If so, how can I see it when it is not rendered?!


UNITY I want to make my UI text fade in after 5 seconds I know this question has been asked and asked but none of the topics i visited gave me an answer. I'm making a game programmed in c where you control a boat and i want my UI to appear smoothly by fading in after X seconds. May someone help me?


Unity Admob EEA checking The Admob plugin for Unity Android does not supply an EEA permission request form like the standard Android plugin does. So, I have created my own and it works great. My only problem is how do I check if I am in the EEA and need to request permission? Again, this feature is supplied for a standard Android app. I know I can make a simple Android plug in and call it but that seems a bit over the top.


Building a game project in C for Unity in VS? Say that a project needs to be created from scratch for later use in Unity, for scripts. What is the ideal way to setup this without using a template in Visual Studio? Can this be created in C with some simple classes and one or two game loops?


Saving settings when exiting the application I created a static class CustomPlayerPrefs, it has a WriteToDisk() method that writes the saves to disk. For saving I am using Application.quiting event RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen) static void Init() Application.quitting WriteToDisk But on android it never works. I know that applications are not closed but paused, but it doesn't even work when I restart the device or force the application to stop. How to fix this or how to make it better? Need IOS and Android support.


How do I correctly set up a Unity animation to move? I downloaded a custom .fbx model from the asset store, imported it to my project and placed it in my scene. I then created an animator controller and added it to the object. To get the animations (that came with the model) into the animator tab, I dragged them onto the model in the hierarchy. I then set the one animation to default and pressed play, but in the game window, the model didn't move. What might be going on? The only time it did something was when I set it to "play from start" but that made it go through all the animations. I'm quite new to Unity 4. If you need any extra information, please ask.


Jerky Character movement after adding mouse orbit script I added a custom mouse orbit script to my project. When the right mouse button is clicked, the camera can be rotated around the player. The issue, after this change, is my player movement has become jerky choppy and not smooth. If I remove my mouse orbit script, player moment is back to normal i.e smooth. I can't seem to pin point what is causing this jerky movement withing MouseOrbit script Video demo Code This is where we initialize our script void Start() Initialize() This is where we set our private variables, check for null errors, and anything else that needs to be called once during startup void Initialize() h this.transform.eulerAngles.x v this.transform.eulerAngles.y cameraTransform this.transform cam Camera.main smoothDistance distance timerot TimeSignature((1 rotationDampening)) 100.0f NullErrorCheck() We check for null errors or warnings and notify the user to fix them void NullErrorCheck() if (!viewTarget) Debug.LogError("Please make sure to assign a view target!") Debug.Break() if (collisionLayers 0) Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!") This is where we do all our camera updates. This is where the camera gets all of its functionality. From setting the position and rotation, to adjusting the camera to avoid geometry clipping void Update() if (!viewTarget) return if (Input.GetMouseButton(1)) Cursor.lockState CursorLockMode.Locked h Input.GetAxis("Mouse X") horizontalRotationSpeed Time.deltaTime v Input.GetAxis("Mouse Y") verticalRotationSpeed Time.deltaTime h ClampAngle(h, 360.0f, 360.0f) v ClampAngle(v, minVerticalAngle, maxVerticalAngle) Debug.Log ("value of h " h) newRotation Quaternion.Euler(v, h, 0.0f) else Cursor.lockState CursorLockMode.None if (Input.GetKeyDown(KeyCode.D)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) if (Input.GetKeyDown(KeyCode.A)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) We set the distance by moving the mouse wheel and use a custom growth function as the time value for linear interpolation distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 10, minDistance, maxDistance) smoothDistance Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed)) We give the rotation some smoothing for a nicer effect smoothRotation Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 rotationDampening) 100.0f)) newPosition viewTarget.position newPosition smoothRotation new Vector3(0.0f, height, smoothDistance) Calls the function to adjust the camera position to avoid clipping CheckSphere() smoothRotation.eulerAngles new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f) Vector3 dir new Vector3(0, 0, distance) cameraTransform.position newPosition cameraTransform.position viewTarget.position smoothRotation dir cameraTransform.rotation smoothRotation Time Signature with speed as input private float TimeSignature(float speed) return 1.0f (1.0f 80.0f Mathf.Exp( speed 0.02f))


UI clicks hitting game objects below I have a canvas with a panel with set width height inside. The canvas rendermode is set to ScreenSpace Overlay. My clicks on the panel are falling through and hitting the game objects below triggering their mouse events. The little green circle is a Sprite with the following event public void OnMouseDown() Debug.Log("click") Vector3 newPos Camera.main.WorldToScreenPoint (this.transform.position) newPos.x panel.GetComponent lt RectTransform gt ().rect.width 2.0f newPos.y panel.GetComponent lt RectTransform gt ().rect.height 2.0f panel.transform.position newPos I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?


get back unity default interface i installed unity recently .and interface of unity looks like that see the image in all tutorials i see on the internet. but this is my one(I'm not in the game tab I'm in the scene tab)it's look like brown and i don't like it.i want default interface the interface in first pic which is black .how can i get black interface back ?


C in Unity with dependencies I am currently creating a c program to eventually use in Unity. This c program contains references to libraries like OpenCV and dlib, referenced with a include statement which calls in other files, which are installed on my machine. My question is How do you compile your c project so that it runs in Unity completely self contained? i.e no reference to external files are needed, and all that are references are included within the program. Is there a specific tool to use, or a useful tutorial on the net? Thanks for the help.


Nested Coroutine Movement is slugish So I have a few AIs walking between waypoints. What I want to accomplish here is to have my AI move to the waypoint, when he reaches it, he must stop, wait for a few seconds (Not walk just stand still), then move to the new waypoint. Lets pretend he was observing while at this point. Issue right now He moves to the waypoint with a twitchy behavior where he would usually avoid objects, sometimes gets stuck while moving to objects or its like the AI cant decide what to do, move or stand still. Without the Waitforseconds method the AI avoids objects perfectly. Please note I want to use Coroutines for this even if you wouldn't use recommend it for this. If you have a suggestion for using Unity's Random to decide when he stands still after reaching a point or not, that would be a bonus for me. We define all fields and call the FSM() Coroutine with a default patrol state in the Start Method, from Here, This is my Code Update Implemented A Boolean IsMoving variable This works to some extent. The AI now moves perfectly to the waypoint. The Twitching however continues once the AI reaches the waypoint vicinity until he leaves the waypoint radius The movement then continues to a normal state. IEnumerator FSM() while (alive) switch (state) case State.PATROL StartCoroutine(Patrol()) break case State.CHASE Chase () break default break yield return null lt summary gt Patrol will move to a waypoint if too far, otherwise move to a next waypoint if one is reached. lt summary gt IEnumerator Patrol() Sets a common speed for the agent to move in. agent.speed patrolSpeed Now we want to check the position the character is at vs the waypoint location If i am too far, move closer My Position Waypoint Indexes We Set Multiple if (Vector3.Distance (this.transform.position, waypoints wayPointIndex .transform.position) gt 2) Telling the navmesh agent where to go. agent.SetDestination (waypoints wayPointIndex .transform.position) false, false Specifies if we are jumping or crouching character.Move (agent.desiredVelocity, false, false) Now we want to check the position the character is at vs the waypoint location If i am at a waypoint, move to a new index else if (Vector3.Distance (this.transform.position, waypoints wayPointIndex .transform.position) lt 2) character.Move (Vector3.zero, false, false) yield return new WaitForSecondsRealtime (6.0f) wayPointIndex 1 Move towards a new waypoint in the waypoint indexes flags Move to a random waypoint wayPointIndex UnityEngine.Random.Range (0, waypoints.Length) else Doesn't move, plays the idle movement We know this point wont be reached but if so... character.Move (Vector3.zero, false, false) yield return null


Unity HDRP draw order doesn't change when asset is set to higher priority? I don't like the way that light got baked into part of my mesh. It might make sense for me to try to blacken that area of the lightmap in Photoshop, but first I tried to just hide it with a probuilder object that uses an unlit black material I changed the priority of this object from 0 to 1, higher than any object in this scene, or at least the floor object, but it does not draw over the floor in Game View. I tried using a higher number and setting it beneath the floor instead of intersecting it, but it is just being rendered the usual way. Also note that I have a UI Canvas component being drawn in ScreenSpace, in case that has anything to do with it. How can I get this object to render in front of the floor while it is intersecting the two front faces, like in the picture?


Gravity well shader for Unity2D I'm trying to find or create a gravity well distortion shader for Unity. I've been looking around and all I can find are "lenses" which bend space around a black hole. I'd rather have a distortion that "pulls" or "bends" the image behind into a small hole. Essentially, what this would look like if viewed from above (ignoring the sphere) I can't seem to find any examples or a common terminology for it.


Unity 5 Virtual Reality Supported Text shimmering aliasing in GearVR I've spent the last 2 days trying to figure this out but have not come up with a conclusion. I'd appreciate if anyone has experienced the same and any thoughts. Basically, I'm noticing that if I have a scene with text in it (world canvas and UI text component), when I build for GearVR with Unity's VR support, the text aliases like crazy. To be honest I'm not even sure 100 if it is plain old aliasing. The text just constantly shimmers. I tried moving things around in case it was z fighting but it seems it is not. I tried enabling anti aliasing from the quality settings and neither does it seem to make a difference. I tried tweaking the Canvas Scaler Dynamic and Reference pixels unit settings (which are not entirely clear to me from the docs btw). But at most, I was able to make the text slightly blurry as mentioned in the Unity VR guide and it barely helps. I tried making the canvas and text huge and then scaling the canvas down to 0.05. finally I tried making my text bold and bigger. And that seemed to mitigate the shimmering to a certain extent but not 100 . But I've seen Unity apps for GearVR that don't exhibit this shimmering issue. So I am wondering what else might I be missing. I'm on 5.3.3.p3 if it makes any difference.


How do you actually build once you encounter the 'Too many method references' error? I'm making a very simple mobile F2P arcade game in Unity After adding SDKs for facebook, gamesparks, firebase, and appodeal I coud not build, getting the "Too many method references 76221 max is 65536" error. The solution from Too many field references 70613 max is 65536 is apparently to export an ADT project, import it into Android studio and go from there. I built following these instructions, and after building my Android studio project had errors relating to the facebook SDK similar to here Unity exporting android project with Facebook SDK issue The solution proposed there is to copy all the .aar from your Unity project to files to the Android studio project and add lines to the build.gradle file referencing them, which I did. After doing all that the 4 facebook related errors are gone but one new one appears Error more than one library with package name 'android.support.v7.appcompat A proposed solution for that is to search for the offending file and delete it in windows explorer but there is nothing with that name in my Android studio project folder. I tried removing some .aar files with appcompat in the name but I ended up reverting to the previous 5 facebook errors This whole thing has been a bit of a nightmare and I have no idea what I am doing. I would love to hear from someone who encountered this error and got past it and was able to build their game again. Surely this must be a common issue for anyone making a commercial mobile game in Unity?


Unity Cube edges are jagged I am new to Unity. I have a basic setup following Brackeys tutorial. When in game mode, I see the red cube having jagged edges. I tried increasing the antialiasing in Unity to 8x but it did not work. I also tried turning on antialiasing in my Nvidia control panel. But the issue still persists.


How to find an object which is added to a scene only when game starts? I'm looking for some advice how to find an object which is added to scene only when the game starts? Before start it isn't in Scene hierarchy. It's prefab.


Player going out of boundaries So, I been following up the Space shooter tutorial on Unity, I had an issue where the project was acting up with an alpha version, so I was able to get a version that worked on a old release and applied all the new things I developed But suddenly, my ship is acting up when getting closer to the boundary of its movement This is the player movement code public class playerMovement MonoBehaviour public float speed 0.0f public float tilt public Boundary boundary void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") var movement new Vector3(moveHorizontal, 0.0f, moveVertical) var rigidBody GetComponent lt Rigidbody gt () rigidBody.velocity movement speed rigidBody.position new Vector3 ( Mathf.Clamp(rigidBody.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rigidBody.position.z, boundary.zMin, boundary.zMax) ) rigidBody.rotation Quaternion.Euler(0.0f, 0.0f, rigidBody.velocity.x tilt) System.Serializable public class Boundary public float xMin, xMax, zMin, zMax And this is the player boundary properties It used to work previously moving forward to the alpha, now I'm working on 2019.2.0f1, but since working on the alpha this is the behaviour I'm having As you can see, getting closer to the player boundary, takes the player out of the play area, and I can't determine why this might be happening. I already tried removing the Math.Clamp, as I though there migth be bug with the function in this version, but even without it, the problem is present.


Unity directional light for a day night cycle on a hex sphere So I am trying to create a Day Night cycle on a sphere but it doesn't work the way I want it to. As the model is hex tiled, you see the edges of the hex tiles also lit up like below. I am using a directional light source for the same. I don't want the above effect. I want it to ignore the edges and just be a straight line instead. Something like below Is there a way inside Unity that I could achieve this effect just using the lights?


Making plane with quad I'm a beginner Unity 3d developer. I want to keep quads one aside another touching each other and use that as a road for making an endless runner game. The problem is each of the quads have their own box collider thus the car bounces a little bit sometimes. Is there any way to get those stuff connected with each other and make the whole thing behave like a single plane? I know using a big box collider covering all the quads in the repeating unit is gonna work but I don't want to use that.


current value of x for vector2 game object I just need to push my game object in y direction not in of its x position,I need to assign it a new position but unable to access its current x position value so that can make it fix on its x position... please help I tried this Vector2 curScreenPoint new Vector2 (need the current x position of game object , Input.mousePosition.y) Vector2 curScreenPoint new Vector2 (0, Input.mousePosition.y) Vector2 curPosition Camera.main.ScreenToWorldPoint (curScreenPoint) transform.position curPosition


Get the tile in unity tile map I am trying to get the sprite of a tile in unity from where a raycast hits. Right now it only works in some cases, and always in positive x. This is my current code. Vector3Int LocalPos new Vector3Int((int)hit.point.x, (int)hit.point.y,0) Sprite spr tilemap.GetSprite(LocalPos) From what I can tell it gets the correct sprite. Edit I removed pointless code


How to offset a 2D GameObject by a pixel amount? I'm extremely new to game creation. I'm playing around with creating a 2D Unity game. The scene is setup from the default Unity 5 2D template. Following a tutorial, I've created a TerrainManager GameObject and Script. The script instantiates tiles and sets their position using a standard double loop. I've found a 2D isometric tile set. Each tile is visually rendered as rotated around the vertical axis by 45 degrees, creating more of a diamond shape rather than a square. This requires that every second tile be offset by half the tile width on the x axis, and half the tile height on the y axis. As each tile is of a different height, one can not simply offset the tile on the Y axis by half its height. Each terrain "layer" is 16px tall in the PNG. Some PNGs have a single "layer", some have multiple "layers". (For instance, a single layer water tile is 83px in height, while a dual layer "grass on top of dirt" layer is 99px in height. As the game object expects the transform.position as a Vector3 in (I assume) game units, I do not know how to compose this using pixel values. So the question I have is, how do I achieve the 16px y axis offset of the game object? I'm more than happy to provide additional details if needed.


Unity WebGL Canvas only loads on select machines https herbertjoseph.com There is a WebGL build in the background of this site, and it doesn't seem to laod on my iPad. I've asked a few people to visit and check it out, and some have said that the scene doesn't load on their workstations either... I've checked the console of the builds, and found no egregious errors. Most browsers, even mobile, support webgl now... How can I ensure it'll work across most all devices?


How to split 2 teams for a FPS death match game in Unity? I'm making a playable one level only FPS death match game in Unity. I'm in the part where the AIs now can find and shoot their own target and keep looping to find targets until nothing left. Every AIs and including player were tagged with tag "Target" for the AIs to randomly find their target. (I already excluded self finding). Now I want to split them in 2 teams. And here is the thing that I keep wondering. Should I use 2 tags for 2 teams (like team red, team blue for ex) then make and attach 2 scripts separately for each AI in the team (the logic in the script will be like "team red" will find game object with tag "team blue" and vice versa). Is that how it works? Is there more efficient way or should I say, "smarter" way to work around this problem? Here is the script if you need to know more about what I am trying to say https github.com Bezari0us FPS AI Behaviour


How can I make all the objects to move between the waypoints? using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public List lt Transform gt objectsToMove new List lt Transform gt () public List lt Vector3 gt positions new List lt Vector3 gt () public int amountOfPositions 30 public int minRandRange, maxRandRange public bool randomPositions false public bool generateNewPositions false public float duration 5f public bool pingPong false private void Start() if (generateNewPositions (positions.Count 0 amp amp amountOfPositions gt 0)) GeneratePositions() StartCoroutine(MoveBetweenPositions(duration)) private void GeneratePositions() for (int i 0 i lt amountOfPositions i ) if (randomPositions) var randPosX UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosY UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosZ UnityEngine.Random.Range(minRandRange, maxRandRange) positions.Add(new Vector3(randPosX, randPosY, randPosZ)) else positions.Add(new Vector3(i, i, i)) IEnumerator MoveBetweenPositions(float duration) for (int i 0 i lt positions.Count i ) float time 0 Vector3 startPosition objectsToMove 0 .position while (time lt duration) objectsToMove 0 .position Vector3.Lerp(startPosition, positions i , time duration) time Time.deltaTime yield return null objectsToMove 0 .position positions i Now only the first object in objectsToMove is moving between the waypoints but I need all of the elements of objectsToMove to move between the waypoints. If I try this objectsToMove i .position Vector3.Lerp(startPosition, positions i , time duration) I will let out of bound index exception because the size of objectsToMove is not the same the size of positions i


Unity objects behaving different when NetworkTransform is used to sync movement I am experimenting with some simple multiplayer networking in unity. Currently I have a plane object as the ground, and a cube prefab as the player object. I have a network manager with round robin spawn and the built in HUD. The cube has simple movement control (up down is forward backward, left right turns the cube). I can successfully start a game, build it, and add a client from the built app. However, when movement gets sent over the wire, the non local player cubes in the game appear to "tilt forward," seemingly from the drag that the cube creates against the plane while moving. Strangely, when moving the local cube, no such tilt is experienced. Here is a gif which illustrates In the above gif, the cube being moved is in the foreground window. Notice how the cube is only tilting in the other window. Here is Update function of the Cube controller script Update is called once per frame void Update () Change translation float moveAmount CrossPlatformInputManager.GetAxis("Vertical") Vector3 deltaTranslation transform.position transform.forward movementSpeed moveAmount Time.deltaTime localRigidBody.MovePosition (deltaTranslation) Change rotation float turnAmount CrossPlatformInputManager.GetAxis("Horizontal") Quaternion deltaRotation Quaternion.Euler (turnSpeed new Vector3 (0, turnAmount, 0) Time.deltaTime) localRigidBody.MoveRotation (deltaRotation localRigidBody.rotation) MoveCamera() The ground is a plane with a rigid body and doesn't have a network identity or transform. How do I stop the dragging from occurring and have the behavior be consistent across both instances of the game? The full code to this project as it is right now is here https github.com andyperlitch blocks multiplayer Thanks!


Unity mailchimp Klaviyo subscription form Hey everyone so i want to add a subscription form on my game. so far i can send data to a database and display them on a leaderboard, i found a similar question here but its a bit outdated. Ideally i would like to use klaviyo but since this is the only lead i have i might want to get familiar with how it works! using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class MailingScript MonoBehaviour public InputField emailField public InputField nameField public void onClick() StartCoroutine(SendToMailChimp()) private IEnumerator SendToMailChimp() WWWForm form new WWWForm() form.AddField( quot EMAIL quot , emailField.text) form.AddField( quot b 0f079b7af1cef143021ff4236 6cd74c0a6a quot , nameField.text) form.AddField( quot subscribe quot , quot Subscribe quot ) UnityWebRequest www UnityWebRequest.Post( quot https slaga games.us1.list manage.com subscribe post?u 0f079b7af1cef143021ff4236 amp amp id 6cd74c0a6a quot , form) yield return www.SendWebRequest() if (www.isNetworkError www.isHttpError) Debug.Log(www.error) else Debug.Log( quot Registered quot ) this is my code so far but it wont do anything. i have a same code for the database which works!


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


How to adapt my mobile game for different aspect ratios? Before I start, I'd like to note that I work in the Unity Engine, but the basic theoretical stuff should be similar just about anywhere. It's not really hard to get the game's camera World view or UI to scale to many types of devices with different pixel counts as long as they have the same aspect ratio. But devices in general, and especially mobile phones, have all sorts of variables, aspect ratios can be anywhere from 16 9 to 20 9, and there are all sorts of different types of notches too. For this question I'm primarily going to ask about the aspect ratio and not touch on notches for now to stay on topic, but if you could explain how I can handle notches, that would be a good bonus. So, how do I make a game for a mobile device, that can be played in portrait and horizontal mode, on anything from small 16 9 screens like the Samsung Galaxy S5, to larger 19 9 aspect ratio (A notch) in the Google Pixel 4? Unfortunately due to IP restrictions, I can't show art, and I can't reveal the core mechanic of the game. but I have created a general mock up of what the ideal world UI scaling would look like The UI needs to be able to scale to the edges of the display like any other game. But the edges of the world need to be the edges of the screen (There needs to be walls that appear at on all 4 edges of the screen), however because the game is physics based, the walls can't actually move else it would cause inconsistencies between in the game from device to device. I know what I'm talking about here is primarily theoretical, but as someone who doesn't know much about aspect ratios (or notches), how can I ensure my game works consistently on this range of devices?


OnTriggerEnter is it called in both collider object? I've 2 object a Player and a Bonus object. In both script I've "OnTriggerEnter" script. In Player OnTrigger I Take Bonus value and add it to my Player (health, point, ammo) In Bonus OnTrigger I Play audio (when take it), Play Particle System and so on... But, it seems it's called only Player's OnTriggerEnter ... Why ? In Unity, if I have OnCollision OnTrigger enter in both object, which event is called ? Both ? Thanks


Unwanted rotations with transform.RotateAround I didn't tough i would have issues with this, but unfortunatly I did. I have a Character (which is more a pile of cube) with a body, a empty GameObject for each leg attached to the body with a join and 2 cubes for leg too. The body and the two empty gameobject are child of a Empty gamebject. The 2 cube that represent leg are both child of one of the empty gameObject. What I want to achieve is to rotate the leg around the position of its empty parent by doing this if(Input.GetKey("l")) l leg.transform.RotateAround(l leg.transform.parent.transform.position, new Vector3(1,0,0), 75 Time.deltaTime) unfortunatly, I only want it to rotate on x, but all of the axis are changing, which lead to unwanted rotation. Now, I know rotations aren't independant like translations, but I don't know how to fix this. If possible, i'd prefer to rotate locked joint via script but I have now idea how, I haven't seen anything about it when I looked up 2


Understanding pixel art in Unity 2d I am struggling to understand the basics behind pixel art in Unity. I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16. Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)? What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game? The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite. So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non square value, when my tiles are 16x16


Unity What does the green line gizmo signify? When I place a point light it shows this green gizmo that ends in the terrain. What's the name of this gizmo? What does it signify?


How can I create a pressure pad in order to open a door? I'm making a 2D platformer with Unity. I want to create a pressure pad in order to open a door and I want the door to open when the player is on the pressure pad and close in few seconds after the player leaves the pressure pad. I've tried different ways but none of them worked. In this case, the door should be open upwards and close downwards. Also, I already created some animations (idle, open and close) for the door but don't know how to make a connection between these two objects then play the animations at the proper time. Thank you in advance. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PressurePad MonoBehaviour public UnityEvent OnActivate public UnityEvent OnDeactivate int objectsInContact IEnumerator Timer() yield return new WaitForSeconds(6) OnDeactivate.Invoke() void OnTriggerEnter2D(Collider2D other) objectsInContact if (objectsInContact 1 amp amp OnActivate ! null) OnActivate.Invoke() void OnTriggerExit2D(Collider2D other) objectsInContact if (objectsInContact 0 amp amp OnDeactivate ! null) OnDeactivate.Invoke() StartCoroutine(Timer())


Digital Speedometer wrong update Unity Hi I am making a digital speedometer and I want it to change like a normal meter like if speed is 10 on meter and the new speed is 50 it does not just show 50 on text instead gradually increase it. here is what I have done int speed int textSpeed int speedfinal public Text text Update is called once per frame void Update() speed GameObject.Find("gamePlayManager").GetComponent lt gamePlayManagerScript gt ().userSpeed textSpeed int.Parse(text.text) speedfinal (int)Mathf.Lerp(textSpeed, speed, 0.1f) text.text speedfinal.ToString() I am not sure if lerp is a good choice here to change text but that is what I know but it is adding 9 less then the orignal speed. Any idea how to do this. thanks.


How do I switch between different Update behaviour states in Unity? I have a bird entity that needs different update rules when it's moving or dying (among potentially other states). I want to avoid making my Update method a clutter of if else branches like this void Update() if(state movingState) Do moving logic. else if(state dyingState) Do dying logic. else if... Instead, I thought I could make a base class for all my bird behaviours, then derive classes for each state with their own update functions, and use the appropriate derived version based on the current state. public class BirdBaseModel MonoBehaviour void Update() ... public class BirdMoving BirdBaseModel void Update() ... public class BirdDying BirdBaseModel void Update() ... My BirdBaseModel is attached to the bird game object. Based on game states, I want to dynamically reference it in the GameController class. BirdBaseModel b if(State 1) b new BirdMoving() else if(State 2) b new BirdDying() Based on the above logic, I want to call the Update function of that particular class. How do I invoke the Update of the subclass?


Make an animation repeat X times I am using Unity Mecanim and I would like an animation ( walking animation about 2 seconds longs ) to repeat X times before moving to the next animation. How can I achieve this?


Accessing vertex Input in surf directly without vert's out parameter In Tessellation Shader I can get the vertex Input in vertex shader as follows o.worldPos v.vertex.xyz But how do I get the worldPos directly without filling the out parameter in the vert function. Asking this because the shader is a DX11 Tessellation one and out parameter in vert function is not available at all. basically I want Initialize my Input shader and pass It to surface shader In vertex shader.I can do It but It's different In Tessellation shader so I need to Accessing vertex position in surf directly without vert's out parameter. Shader "Tessellation Sample" Properties EdgeLength ("Edge length", Range(2,50)) 15 MainTex ("Base (RGB)", 2D) "white" DispTex ("Disp Texture", 2D) "gray" NormalMap ("Normalmap", 2D) "bump" Displacement ("Displacement", Range(0, 1.0)) 0.3 Color ("Color", color) (1,1,1,0) SpecColor ("Spec color", color) (0.5,0.5,0.5,0.5) SubShader Tags "RenderType" "Opaque" LOD 300 CGPROGRAM pragma surface surf BlinnPhong addshadow fullforwardshadows vertex disp tessellate tessEdge nolightmap pragma target 4.6 include "Tessellation.cginc" float EdgeLength float4 tessEdge (appdata full v0, appdata full v1, appdata full v2) return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, EdgeLength) float Displacement struct Input float4 position POSITION float3 worldPos TEXCOORD2 Used to calculate the texture UVs and world view vector float4 proj0 TEXCOORD3 Used for depth and reflection textures float4 proj1 TEXCOORD4 Used for the refraction texture void disp (inout appdata full v, out Input o) UNITY INITIALIZE OUTPUT(Input,o) o.worldPos v.vertex.xyz o.position UnityObjectToClipPos(v.vertex) o.proj0 ComputeScreenPos(o.position) COMPUTE EYEDEPTH(o.proj0.z) o.proj1 o.proj0 if UNITY UV STARTS AT TOP o.proj1.y (o.position.w o.position.y) 0.5 endif sampler2D MainTex sampler2D NormalMap fixed4 Color void surf (Input IN, inout SurfaceOutput o) o.Albedo float3(0,0,0) ENDCG FallBack "Diffuse" but I have error Shader error in 'Tessellation Sample' 'disp' no matching 1 parameter function at line 173 (on d3d11)


Why do I get compile errors in every project, even new ones, and how do I fix them? I downloaded the latest version of Unity as you can see in the snap. I just created a new project and when I press the play button it shows compile error even if I have not created anything nor any script. I receive 4 blank errors in Unity and one non critical. I am not able to clear them except the non critical one.


How to create a wind tunnel sky diving effect like in Fortnite? I am using Unity and I want to create a sky diving effect, as if you were looking directly down while falling and have the wind fly past you. My guess is I have to do something with the particle system. How can I do this? An example is this video of Fortnite https youtu.be JFHs3uNJ9Cw?t 23s, you can see the wind flowing from the characters hands and feet.


How can I resolve this error I'm getting in my movement script? For my player controlling script, I have attempted to do it so the player can only jump two times, I've not had any errors in the script itself but when I save it and go back on Unity, the error I keep getting is this error CS0120 An object reference is required for the non static field, method, or property Collision.gameObject This is my code using System.Collections using System.Collections.Generic using UnityEngine public class playerController MonoBehaviour public float speed public float power private Rigidbody2D rb int numberofJumps 0 public int doubleJump 2 void Start() rb GetComponent lt Rigidbody2D gt () numberofJumps doubleJump void Update() if (Input.GetKey(KeyCode.D)) rb.AddForce(Vector3.right speed) if (Input.GetKey(KeyCode.A)) rb.AddForce(Vector3.left speed) if (Input.GetKeyDown(KeyCode.W)) if (numberofJumps gt 0) Jump() public void Jump() rb.AddForce(Vector3.up power, ForceMode2D.Impulse) numberofJumps 1 void OnCollisionEnter2D(Collision2D col) if (Collision.gameObject.tag "ground") numberofJumps doubleJump The error seems to be specifically regarding this line if (Collision.gameObject.tag "ground")


Can I apply a force to particles from a script? I'm working on a game which involves streams of electrically charged particles, being manipulated with electric and magnetic fields. Since I want a large number of small objects coming from an emitter and lasting a limited amount of time, a particle system seems like the way to go. My only problem now is how to apply the force? Suppose, for example, I have a charged object somewhere in the scene I want to apply a force toward it, varying with the radius squared. If my particles were Rigidbodies, applying this force in the FixedUpdate would be easy is there a way to do the same to an individual particle?


Changing coordinates of the object with velocity preservation In Doodle jump, if a player jumps over one side of the screen he appears on another side with preserved velocity and other physical parameters. I made two trigger colliders on the sides of the screen with OnTriggerEnter2D method. private void OnTriggerEnter2D(Collider2D collision) collision.transform.position new Vector3(collision.transform.position.x 0.95f, collision.transform.position.y, collision.transform.position.z) If I multiply collision.transform.position.x by 1f then on collision some glitching occurs. It gets stuck for a second. I believe this happens because when player is moved to the other side there is another collision detected and he is thrown back. Is there a more elegant way of handling this instead of multiplying by 0.95f? Final solution Tooltip("Controls where is the edge of the level where player is trasfered on the opposite side of the level.") SerializeField private float xAxisMovementConstraints private void DetectBoundryCross() if (transform.position.x lt ( xAxisMovementConstraints)) transform.position new Vector2(transform.position.x (xAxisMovementConstraints 2f), transform.position.y) else if (transform.position.x gt xAxisMovementConstraints) transform.position new Vector2(transform.position.x xAxisMovementConstraints 2f, transform.position.y)


Is it wrong to be creating new objects in Update()? I'm using Unity and sometimes I'm using th new keyword in Update, like new Vector3() etc... I wonder is this causes memory leak? I mean in every frame a new Vector3 is created. If this is the way of working that means there are thousands of Vectors created in memory. Is it true or do I think wrong?


How can I fix a GameObject along one axis only when it is part of another object in Unity? Hello I have an Object player and inside player, I have an object Boundary which is supposed to follow the player as he moves up or down only? (As the player moves right or left I don't want the boundary object to move. How can I do it?


I'm having resolution issues does my math suck? There are a lot of scripts involved so I'm just going to give a generalized description of the process. First, a 1x1 square tile is created. Second, that tile is placed out of the way, and 16 x 10 (160) new tiles are created starting at the (0,0) position and building outward in positive numbers. Now, the camera is a 16 10 display. At this point, I wanted to scale up the tiles. If I want to scale the map up I start by scaling the camera by 100, and then I scale the tiles, and align their position (edge to edge). At this point, scaling the tiles by 100 seems logical, but that didn't work correctly, for some reason. Scaling by 50 almost works, but the resolution is no longer a 16 10 grid like it was before the scaling. What am I doing wrong? I am using Unity.


How can I move game objects using keyboard in the Unity scene editor? I know I can click on the "move" button and use my mouse to drag the object around. How can I do the same using my keyboard?