How do I generate a random map with islands (like the Earth), using Perlin Noise, on a tilemap in Unity? EDIT I've tried this with Perlin Noise with no success, then with Voronoi diagrams, and now I'm editing the question to reflect the issues I had with Perlin Noise, trying again. I'm developing a game in Unity and trying to build a map generator that is capable of creating random maps like the Earth, on a 2D tilemap. The map should contain 2 types of tiles (let's call them grass and ground), while the grass should be the "main" tile, and there should be islands of ground on top of the grass. This was already asked here. My purpose is to create something like the second picture in the question (that picture is showing water and grass, but it doesn't really matter). This blog post suggested a simple way to fill a map (2d array) with Perlin Noise values (float numbers between 0 1), which I did. Eventually each value was rounded to 0 or 1 to present a grass or ground tile. What I can control now is the frequency of the noise, but it's not enough. The map generated by the code below (frequency of 0.3) The problems with this method No randomness. I know Perlin Noise is NOT a random function, so how can I add random factors to generate a different map each time? How can I control the number of islands (e.g. with a factor that can determine "more islands" or "less islands", not an approx. number)? How can I control the size of each island (again, with a factor. I don't care about exact size)? My code (C ) using System using UnityEngine using UnityEngine.Tilemaps using Random UnityEngine.Random namespace TankMayhem public class GroundTilemapGenerator MonoBehaviour private const string TilesPath "Tiles" private Tilemap tilemap private TileBase possibleTiles new TileBase 2 private void Awake() tilemap GetComponent lt Tilemap gt () var tiles Resources.LoadAll lt Tile gt (TilesPath) possibleTiles 0 Array.Find(tiles, tile gt tile.name "ground") possibleTiles 1 Array.Find(tiles, tile gt tile.name "grass") int i int j int , map new int tilemap.size.x, tilemap.size.y const float Frequency 0.3f PerlinNoiseCave(map, Frequency) float probabilities new float 2 foreach (var position in tilemap.cellBounds.allPositionsWithin) i position.x j position.y var tile possibleTiles map i, j tilemap.SetTile(position, tile) private static int , PerlinNoiseCave(int , map, float frequency) for (int i 0 i lt map.GetUpperBound(0) i ) for (int j 0 j lt map.GetUpperBound(1) j ) Generate a new point using Perlin noise, then round it to a value of either 0 or 1 map i, j Mathf.RoundToInt(Mathf.PerlinNoise(i frequency, j frequency)) return map


Trying to convert Unreal shader graph to Unity, what nodes are a close equivalent in the Unity shader graph? I am trying to convert an Unreal shader graph to a Unity Shader Graph. https api.unrealengine.com udk Three VolumetricLightbeamTutorial.html I am struggling with understanding which nodes to use in the Unity Shader Graph while trying to replicate it. I managed to get something looking Ok using the fresnel node, but if you enter inside the geometry, you lose the effect. I found the above article which is perfect for what I need to do. Here is the first node setup I tried to follow along but a lot of the nodes I don't understand what the equivalent would be in the Unity shader graph. Combine looks to be the equivalent of the Append node I think. Mask node I am not sure about as there are 3 mask nodes in Unity shader graph. Edit Spent most of the weekend trying to learn which nodes to use. Still not sure on what the "Reflection Vector" should be. I think it's something to do with the camera. Here is the graph currently.


How can I make the object when rotating to keep looking on the character camera? Not to look the character camera direction but to look to the character camera. This is a screenshot of the object I'm rotating. And this is the face of the object and he is look at the camera(Looking at me). The object is a child of a Camera and the Camera is child of a RigidBodyFPSController (1) In the top of the script public float rotationSpeed private float x private int damping 2 In Update void Update() if (Input.GetKey(KeyCode.R)) x Time.deltaTime rotationSpeed objectToScale.transform.rotation Quaternion.Euler(0, 0, x) var lookPos transform.position objectToScale.transform.position lookPos.y 0 var rotation Quaternion.LookRotation(lookPos) objectToScale.transform.rotation Quaternion.Slerp(objectToScale.transform.rotation, rotation, Time.deltaTime damping) Now when I press on R the object name NAVI is rotating but when I move the MainCamera around the NAVI object is not facing to me. This is a screenshot when running the game first time the object is facing to me But when I'm pressing on R and the object is rotating it looks like the object is facing to the left and I see the object side Then I move the camera to the right he is rotating like I wanted facing to me And if I move the camera to the left when the object is rotating I see the object back But I want that each time the object is rotating that he will be facing to me. The last screenshot showing the Hierarchy the RigidBodyFPSController (1) and the MainCamera as child and the NAVI as child of the MainCamera. The script Change Scale is attached to the MainCamera and with this I'm rotating the NAVI. The main goal what I want is simple. When I press on R rotate the object and always make the object facing to me. I tried now in the Update when pressing R to do if (Input.GetKey(KeyCode.R)) x Time.deltaTime rotationSpeed objectToScale.transform.rotation Quaternion.Euler(0, 0, x) objectToScale.transform.LookAt(Vector3.forward) But now it's not rotating at all.


Unity Duck volume of audio source inside a boxed area I'm trying to lower the volume of an outside ambient wind sound while the player is inside a building or room. Is there any way in Unity to do this without scripting? Or would I have to script this to check whether the player is in a certain collider to duck (or lowpass filter) the sound? The room is seamlessly in the scene's outside environment. Any ideas on this?


How many directional lights in Unity In Unity, how many directional lights can be active at once? 1, 2, 4, or 8? I thought 2, but I have searched and cannot confirm.


How can I programmatically change a sprite's pivot without it affecting a game objects current position and rotation? Because of the complexity of positions, I am using the centre pivot for my game objects sprite. Can I possibly change the pivot without it affecting the game objects current position and rotation? or in other words, can I change the pivot while the sprite remains unchanged visibly? I would preferably like to do this using c script.


Unity3d Detect a collision between an image and a sphere So, I just realized, an image with BoxCollider2D wont detect any collision with Sphere with SphereCollider. I tried adding a BoxCollider to my image, but it behaves in a weird manner (The Canvas position keeps shifting) So, I can see the only way for it to work is adding a 2D Collider to the sphere? Is there any other better way to solve it? Adding a 2D Collider to the sphere wont cover the whole area


Particle System is not Playing I made a simple spaceship that has a particlesystem. When I press quot space quot button, spaceship should fly and particle system should instantiate and play. But it's not playing. It seems in hierarchy as clone but not playing. As you see, particle effect is instantiating but not playing. It should play at bottom of spaceship Those are codes void FlyShip() if (Input.GetKey(KeyCode.Space)) rb.AddForce(Vector3.up jumpForce) if (!takeoffSound.isPlaying) rocketJetParticle is gameobject. rocketJetParticle Instantiate(rocketJetParticle, new Vector3(transform.position.x, transform.position.y 4, transform.position.z), transform.rotation) takeoffSound.Play() else Destroy( rocketJetParticle) takeoffSound.Stop()


Handling an item database with procedurally generated items? Let's say you have an item database which has every item in your game. This works fine for regular items like a Health Potion, a normal Iron Sword etc, because these items have ItemID's so we can get an exact copy of this item. But what if we have an Iron Sword with an enchantment ' 5 Fire Damage'? (or whatever) If you were to save that item to a player's inventory, exit the game and load the game, the item will load as a regular Iron Sword, because it still has that ID. Specifically, how would you save that item to a file? I'm using Unity, so to save the Player's inventory, I use PlayerPrefs.SetInt("Inventory " i, inventory i .ItemId ) Would you create a custom item ID for every item with enchantments or is there a better way around this?


My colliders keep going through one another? So, I have some platform with colliders and a character with a collider (everything in 2D). The problem is, while there is some noticeable effects (a certain push back) when the colliders collide, they actually intersect each other and can go through each other.. How can I actually put a collider that doesn't let anything pass, it just stands there like a brick wall against anything? By the way, any enlightenment on the inner workings of the colliders behavior will be appreciative as I cannot understand how this could even happen. Demonstration video Demonstration video 2 Bellow I have the images showing the inspector of both the character and platforms wall respectively. 4 Also I'm moving the character using transform.position Vector3.right speed Time.deltaTime


NavMeshAgent is not calculating a new path I have the following code that gets run when a game object collides with a trigger. When the object is created, it is created within an initial trigger which fires the SetNextWaypoint code below and it works fine. protected NavMeshPath path protected NavMeshAgent agent null void Start () path new NavMeshPath() agent GetComponent lt NavMeshAgent gt () public void SetNextWaypoint(Vector3 location) agent.ResetPath() path.ClearCorners() agent.CalculatePath(nextWayPoint, path) agent.SetPath(path) Once the agent enters a new waypoint (it may not have reached its destination yet) SetNextWaypoint is called again and when it does the agent just stops where it is, and doesn't move anywhere.


(Unity) Physics based movement vs Straight position change Unity provides a cool physics engine for game development and I want to utilize it in my game. Shorter version I want to use physics engine for everything else other than character movement because trying to use physics engine for player movement doesn't yield the perfectmovement speed that I want move x units per second. If I use physics engine for character movement, it gets complicated. I would rather just add "moved distance" to the position to have things done simple. Is doing something like this wrong? All the learning sources I read recommend to use physics engine for movement if the game incorporates physics engine. I am nervous am I wrong? Longer version The following description is where I use "physics", why I need physics engine. In my game a player fires a bullet. When enemies collide with bullet, they get pushed back slightly. A strong blast can push enemies far back so that they even bounce back from hitting wall. A recommend, a proper way, I was told, to utilize this physics engine for character movement is to add force to the direction I want to move. But doing so(adding force to the direction I want to move) will result in truck like slowly warming up by adding velocity. To avoid "truck like movement" I was told to apply greater force at the beginning. Doing so result in change in velocity like the below picture. However problem is not over yet, you must consider a situation where you change direction of movement while the character is running. If you started to move backward, all of the sudden while running forward, you will need to slow down forward movement burn velocity by adding backward force. Thus rotation burns velocity. So a solution is to find out perpendicular velocity to your desired direction, then find out needed amount of force to "burn off" the undesired velocity. This seems way too complicated for a character to simply move around. I would rather just move character to desired direction by simply adding "constant X distance" to the character's position. But I can't find a source of example where it utilizes both "simple movement by directly adding moved distance to the position" and "using physics engine for the game". All the sources of learning(using Unity physics) I find say use this complicated way of having character to move around. I wonder is there a reason why people don't just add moved distance to the position?


How i can play movie in unity by script(android platform)? my script is correct in pc platform but when i switch on android platform i have compiler error cs0246, why i can not export my apk file. how i can play movie in unity android platform by other way? public class NewBehaviourScript MonoBehaviour public MovieTexture myMovie void Start() myMovie.Play() void OnGUI() GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), myMovie)


Using Standard Asset RBFP Controller for Universal Windows Platform I was using the rigidbodyfirstperson controller, and it stopped working when I changed the build settings to UWP. Any body know the reason for this or how to solve it? Thanks... Rik


3D visual effects on videos I'm trying to get some hands on experience with 3D visual effects on videos. Similar to those AR apps, I want to add a 3D model with effects, say a dragon, to a video. Something like this famous demo https youtu.be u5hQpRbHERg But I don't really want to make it this fancy with camera tracking. I like to start with the simplest approach probably just placing a dragon on the field (like its last scenes) with fixed camera. What's the best way to do it? Some tutorials would be very helpful.


Why would a property be returning null? I'm working on learning how pass data from one script to the other in Unity and I'm getting a little confused. I have two scripts, PlayerData and CreateCharacter. PlayerData is used to pass persistent data from one scene to another, so it's not going to be attached to any GameObject or Transform. CreateCharacter, however, is attached to a button which gets the information from user input. Here are the two scripts PlayerData public class PlayerData private string playerName public string PlayerName get return playerName set playerName value CreateCharacter public class CreateCharacter MonoBehaviour public InputField playerName public PlayerData playerData new PlayerData() public void AddStats() public void SubtractStats() public void CreateCharacterOnClick() playerData.PlayerName playerName.text Debug.Log(playerData.PlayerName) What's happening is, when I click the button I'm getting a null reference error on playerData.PlayerName but if I just log playerData I actually get the object to return. What I'm trying to see is that the character name(playerName) is logged when the button is clicked. Can anyone explain to me what I'm doing wrong and how to fix it?


Moving spilling water inside a cup of glass I made a glass of water but there are somethings i didnt know how to do well, what i did is i put a mesh on the top of the glass to represent the surface of the water but it doesnt really work well with glass because if you look from the sides you wont really see that there is water in there, this is what i did the glass from the side as you can see it doesnt really work well in my case. I also tried putting an object that has the same shape as the cup inside to represent water but that would make it difficult for what i want to do next, because my next step would be to make the water rotate in the opposite rotation of the cup and make it spill if it reaches the top of the cup, and that is my second question how do i make the water spill from the cup? Any help is very much appreciated.


How To Fix Strange White Edges With DOF and Fog in Unity? I'm using global fog and the standard assets Depth Of Field script but it has a strange effect on the edges of far away objects. How can I make the white edges along the trees blend smoothly into the fog?


How can I reduce a bezier curve using a slider till all points converge to it's original midpoint I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet). I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves. I would like achieve this using a float slider (with values from 0 to 1) in editor mode.


How to get characters to be aware that their path is obstructed? I'm using Unity with Arongranberg's A pathfinding project to move my characters. However, it appears that my characters are contending for a position on the terrain when they are told to move together to a same position. For example, I have 5 characters being told to move to PositionA. They will move together based on their waypoints to PositionA. One of the characters, call it CharacterA, will reach PositionA before the rest. Now, the other 4 characters who arrived later will continue to keep walking and "sliding" around CharacterA. They seem to stop only when CharacterA moves away from PositionA so that they could reach their destination to break out of the loop. Even so, only one character can be in PositionA while the rest will continue to contend for the place. So, how can I get the characters and objects to know that they have reached their destination and should stop beside the other characters instead of contending for the same place? A naive method could be I get the characters to detect if they are blocked by something straight ahead of them. If they are, break out of the loop and stop the walking state. But at times when the character hasn't reached his destination yet and is blocked by an object, say another character, breaking out of the waypoint loop will stop him at the wrong destination. I can't recalculate for a new path from his current position either since the blocking object is another character, which the initial pathfinding grid scanning did not take into account. One way is I re scan the whole terrain for a new grid of nodes with the characters in the scene taken into account. But this wouldn't be efficient and will lag a whole ton.


Can't correct perspective of Main Camera in Unity 3D without losing field of view I have been trying to create a space based rails shooter game following a particular online course and I find a tilt(roll) on my spaceship as I move it towards the left and right ends of the screen. https imgur.com Kkg8hp2 (A normal screenshot of my spaceship at default position) This is due to perspective of the camera as I have been told and apparently dragging the camera farther behind the spaceship and decreasing its field of view helps. https imgur.com 0oXJff7 (The tilted spaceship when it's at an end of the game window) But, doing that neutralizes the illusion of speed caused by a greater field of view. I have found a middle point between the two to balance both aspects of the game but I would like to know if there is any way to get higher field of view without making the ship look like it's tilted. Things I have considered doing Added a positionRollFactor which gives the ship some additional roll in the opposite direction of the tilt. (This still doesn't fix the perspective issue in which one half of the ship is more enlarged than the other). Tweaking the field of view by trading off a little of each feature.


OnTriggerExit2D called multiple times when two triggers touch I have two GameObjects tagged "Point", each with a Collider 2D set to Is Trigger. I have another GameObject, "pencil", which also has a Collider2D set to Is Trigger I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point. My problem is that when the pencil hits a point, it calls OnTriggerExit2D multiple times. How can I only detect first contact with the point? Pencil script private void OnTriggerExit2D(Collider2D collision) if (!collision.isTrigger) if (collision.gameObject.tag "Point") writing !writing


Why are assets (images) in Unity build reported as 28 times larger I'm trying to reduce a Unity WebGL build size which, for the data asset, is currently at 30 Mb. I installed the Build report inspector. On clicking the "Source assets" tab and choosing "Size" it showed the top entries were images. Fine. But all the sizes reported were between 4 and almost 30 times the size of the file on disk. Is this just a bug artifact of the build reporter or a genuine problem which I need to address to reduce the build sizes? Edit Two of the files are text files. Their size in unity build report is the same as that on disk. Why? Edit 2 after Ed Marty's answer Using low quality with crunch compression at 70 results in slightly lower image quality but it went from 10 Mb to 300 kb, i.e. 30 times smaller size (and about 10x smaller than actual file size on disk).


Problem with Rotation clamping in Unity I'm trying to get a simple cannon to rotate to point at the mouse, but I only want it to follow the mouse for 180 degrees and then stop following the mouse, and pick up again when the player re enters the 180 degree area. I got the cannon to follow the user's mouse but when I tried to camp it to the 180 degree area I found it worked for one side, but when I went to the other it "teleported" to the other side. I video to explain my issue https imgur.com a DZYA305 Sorry about the crude graphics, frame rate, and the software doesn't show my mouse making things more difficult, but as you can see, the clamp works fine when I move my mouse to the right, but when I move it to the left it "teleports" or instantly moves to teh right no matter where my mouse is. Here is my code public int rotationOffset 90 Update is called once per frame void Update() var mouse Input.mousePosition var screenPoint Camera.main.WorldToScreenPoint(transform.localPosition) var offset new Vector2(mouse.x screenPoint.x, mouse.y screenPoint.y) var angle Mathf.Atan2(offset.y, offset.x) Mathf.Rad2Deg float finalRotation angle rotationOffset I have tried both the normal Mathf.Clamp and the if statments below and I get the exact same result. finalRotation Mathf.Clamp(180, 0, finalRotation) if (finalRotation gt 89f) finalRotation 89f Debug.Log("Left") else if(finalRotation lt 89f) finalRotation 89f Debug.Log("Right") transform.rotation Quaternion.Euler(0, 0, finalRotation) I don't know if this might be a bug in Unity, But I've spent days trying to fix it, I'm tired, I'm stressed, I don't know how to fix it.


Unity UI Input Field suddenly malfunctioned I'm using Unity 5.0.1f1, and my UI Input Fields are not working as they are supposed to. I have an Input Field that is placed in a Panel and inside a Canvas. It has a Text component in which I can set text that the Input Field will display. When I change value of this Text component, the changes are not reflected on the Input Field, it seems to be reset to the value of Input Field (Script) Text of the Input Field. If I enter Play mode, I can input text normally but when I build and run on my Android phone, I cannot input anything. Has anyone encountered this problem? How can I solve this?


Unity3D object fill shader I've been researching this for a while, and had no luck yet. I figured I'd ask here to see if anyone had any good ideas. Essentially what I want is a shader that can make only part of an object transparent based on a slider. Similar to fill effects on 2D sprites, the object would fill from the bottom up, when the slider was set to 0 the whole object would be transparent, when it was set to 50 just the bottom half would be visible, and when it was set to 100 the whole object would be visible. I've tried various masking effects, but it would be best if I could build this in to existing shaders or have a separate mask. Is there perhaps a way to adjust the alpha on individual pixels used for the diffuse texture without incurring great performance loss?


Selected enemy off camera I'm facing a problem with a game I'm making. Currently I can select an enemy and mark it as shown on the image But now I want to show the position of the selected enemy on the screen when it's off camera. So my questions are How do I know when an enemy is off camera. How can I show in GUI an arrow on the edge of the screen that points to the position of that enemy. Perhaps something related to what I did to point towards the crosshair? Vector3 positionOnScreen Camera.main.ScreenToWorldPoint(mousePos Vector3.forward range) Vector3 targetDir positionOnScreen transform.position Thanks!


Change color of selected polygons I have a "low poly" surface, where the color palette for polygons is low (e.g. 20 distinct colors). Is there a way to change the color (with a smooth transition) for all polygons painted with a certain color? Maybe an analogy would be to smoothly make all polygons of a certain color transparent.. Background I have managed to get a 2D variant working load a bitmap on a canvas and use a shader to change the color.


How to use uv mapping in Unity 2017 I want to create a game with a Minecraft style world. Now I need uv mapping for some cubes in my game. But I could not find any good tutorial in the internet. I want to use the following texture with an uv map Each side of the cube has a texture with 64x64 pixels. The dirt texture on the right side has to be the top of the cube. Can anyone tell me how to use uv mapping in my case?


Why can't I change the size of my spheres in Unity? I started to learn Unity. Now I make something like a solar system. I have one problem. What are the min and max sizes of the sphere? E.g. I have a radius of the Sun 1.5 but it shows like the Sun has radius 1, I can't make bigger. But also I have the Earth with 0.01 size and the Moon with 0.009. But I can't make the Mercury with 0.03 radius. So why when I'm creating a new sphere now I have only radius 1 and can't change it in Scene window?


Materials aren't loading correctly from SketchUp into Unity I imported a SketchUp COLLADA (.dae) file from 2017 SketchUp Make, and imported it into Unity. I then clicked quot Use External Materials quot and the colors began to load. But I noticed quickly that one of the wings of my imported B 29 was Dark Gray, while the other way a proper color. Random parts, such as the front engine housing piece, were also dark gray. Parts of my advanced dials were also dark gray, and I immediately decided that there is now ay that I am going to manually go in and fix every single dark gray material, but at the moment, I found no alternative. I began with the wing. I went to assign the material that I used for the other wing, which was white, to the dark gray wing, but I found out that the other wing already had that material in use. And when I went to assign a different white color, absolutely nothing changed, aside from the fact that the wing now claimed that it had that color in use. Is there a fix for this problem? I could try importing as a .SKP file, if the reason for the issue is something to do with the COLLADA (.dae) file. What I had was 2 wings. they were both components in SketchUp, so whatever I did to one applied to the other, Then I made them unique before importing to Unity. The Wing that won't work right is the one wing that had the USAF Insignia on it. But I doubt this is the problem, because all engines on that wing were also not colored correctly, whereas the other wing was fine. Those engines were also components, but were also made unique before the import. Each wing has 9 groups inside of it. The other wing is identical in this sense. I imported the file from file explorer by dragging the file from file explorer and dropping it into unity. This is what the plane looks like in Unity My apologies for the crude handwriting, it is difficult to draw with a touchpad. In the image, I numbered the incorrectly colored parts visible in the image (Right Left references are perspective to image) 1. Left Wing. Color Dark gray. Color intended White. 2. Propeller blade hub. This is the part that all propeller blades are connected to. Both hubs on the two propellers on the Left Wing are colored incorrectly. Color white. Color Intended Grey. 3. Pistons. All piston components, such as the pistons, securing poles, and piston heads are not colored correctly same on the other engine on the Left Wing. Color White. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 4. Cowl Flaps. In the image, this appears to be a stripe in the engine. Same with the other cowl flaps on the other engine on the Left Wing. Color Dark gray. Color Intended White. 5. Propeller blades. All 4 propeller blades on both engines on the left wing are not colored correctly. Color White. Color Intended Black, with yellow tips. 6. Right Wing Pistons. Most piston components, such as the pistons heads and securing poles are not colored correctly. Same with the other engine on the Right Wing. Color White Piston Heads, Grey Pistons, Almost Black Gray in the lines on the pistons, white securing poles. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 7. Front Engine Casing. The same error is in the other engine's front engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White. 8. Rear Engine Casing. The same error is in the other engine's rear engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White.


Google Play Games Signs Out Automatically without Internet Unity I am using this in my game to implement games saving and loading. I have also tried the basic sign in process by using the following start function PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder () enables saving game progress. .EnableSavedGames () .Build () PlayGamesPlatform.InitializeInstance (config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate () Social.localUser.Authenticate ((bool success) gt if (success) MyAutoSave.isLoaded false ) I can sign in on google play games without any issues. Soon after that if I quit the game and start again without data connection, it gets authenticated without any issue. If my data connection remains off for say more than an hour, and I start the game without Internet connection, there is no authentication whatsoever. If I close the game and start again soon after that, it gives me that google play games sign in popup. So what i can conclude is that it signs out automatically after some time if there is no Internet available. Is there any fix for this.? Thanks


jumping and movement with rigidbody2d.velocity, gravity problem i'm making a 2d platformer and i move my character with rigidbody2d.velocity swiping up to jump and moving while holding the left or right side of the screen. the problem is that when i jump and i try to move left or right in the air, my character falls very slowly. i've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity? my full code is Rigidbody2D rb public float speed 1f public float jumpforce 3.5f private Vector3 mouseDownPos private float startTime 0f public float holdTime 0.15f void Start() rb GetComponent lt Rigidbody2D gt () void Update() if (Input.GetMouseButtonDown(0)) mouseDownPos Input.mousePosition startTime Time.time if (Input.GetMouseButtonUp(0)) if ( startTime holdTime gt Time.time amp Input.mousePosition mouseDownPos) tap Debug.Log("T A P") if (Input.mousePosition.y gt mouseDownPos.y 100 ) jump rb.velocity new Vector2(rb.velocity.x, jumpforce) if (Input.GetMouseButton(0) amp startTime holdTime lt Time.time) move while grounded if (Input.mousePosition.x lt Screen.width 2) Debug.Log("Left click") rb.velocity transform.right speed else if (Input.mousePosition.x gt Screen.width 2) Debug.Log("Right click") rb.velocity transform.right speed if (Input.mousePosition.x lt Screen.width 2) move while in the air Debug.Log("Left click") rb.velocity new Vector2( speed, rb.velocity.y) else if (Input.mousePosition.x gt Screen.width 2) Debug.Log("Right click") rb.velocity new Vector2(speed, rb.velocity.y) the rigidbody2d of my character is


Unity's Quaternion.Lerp slows down when target is directly behind turret Software Unity v5.2.1f1 Personal I am trying to achieve the effect of a turret in Unity. For this I have a turret consisting of 3 parts as well as a target. The problem is that whenever the target my turret is targeting has a z of lt 0, the lerp speed is extremely slow. However, the further away the target is from x 0 (both positive and negative), the faster it will move. This effect only occurs when my target has a transform.position.z of lt 0. When z 0 the transform.position.x has no effect on the lerp speed. My setup is as follows The 3 turret parts are the base, turret and barrel. The base is nothing more than a block for the turret to rest on. The turret is a block holding the barrel in place with base as his parent. The turret rotates around its y axis to always face the target. The barrel has turret as his parent. The barrel rotates around its x axis to always face the target. See the picture below for the end result. Base Blue Turret Red Barrel Green The turret has the following code public class turretRotation MonoBehaviour public Transform target void Update() Vector3 relativePosition target.position transform.position relativePosition.y 0 Quaternion rotation Quaternion.LookRotation(relativePosition, new Vector3(0, 1, 0)) transform.localRotation Quaternion.Lerp(transform.localRotation, rotation, Time.deltaTime) The barrel has the following code public class barrelRotation MonoBehaviour public Transform target public float speed 1 Vector3 relPos Quaternion rot void Update () Position of target relative to my position relPos (target.position transform.position).normalized rot Quaternion.LookRotation(relPos, new Vector3(0,1,0)) Lerping localRotatiot gt rot with speed Time.deltaTime speed (set to 1 by default) transform.localRotation Quaternion.Lerp(transform.localRotation, rot, Time.deltaTime speed) Resetting y and z EulerAngles to 0 This way only the x EulerAngle will be affected. The y rotation is inherited from the parent (turret turret) transform.localEulerAngles new Vector3(transform.localEulerAngles.x, 0, 0) In this picture the Lerp is working as intended Note target.transform.z 0 In this picture the target has a z 5 and x 0 pay particular attention to the Lerp speed It eventually gets there, but it takes a very long time. For some reason, the further away the target is from x 0, the faster the Lerp speed. Note Still slower than intended In this picture the target has a z 5 and x 10 So for some reason when target.transform.z has a negative value, the higher the distance from target.transform.x to x 0 the higher the Lerp speed. I've done a fair bit of searching and came across a post on answers.unity.com describing a similair problem Unfortunately, no reply. http answers.unity3d.com questions 1084067 lerp problem when target is behind.html So my question is "Why is this happening and more importantly, how can I fix this?" Any help would be much appreciated!


Unity3d turn based navmesh algorithm I am developing a game in Unity3d. In this game, 2 teams will fight without any human interaction. The fight results must be always the same, if the same teams are the same. This way, I must reproduce the same fight in many devices, getting the same results in each device. The map where the fight happens is a 3d environment, so, my soldiers can move in any direction. And the soldiers cannot walk in the same space of another soldier, so I need an agent avoidance algorithm. I am having some trouble to find a solution to the problem above. To achieve the 'always the same results' I am treating this fight as Turn Based Strategy game, with little fixed time intervals between the turns. To calculate the pathfind of the soldiers, I am using the Unity3d navmesh framework. And then I move manually my agents according to the 'NavMeshAgent' 'steeringTarget' property. But this method doesn't cover the obstacle avoidance algorithm, and my agents overlaps. So, I am looking for a solution to my problems, It should be a manual obstacle avoidance algorithm, or a way to unity navmesh work in fixed time intervals, or a completely new approach to my path finding problems.


How can I set up a 2D circular boundary in Unity? I wanted to create a virtual analogue stick on Unity. I figured a very simple, 2 part method setting up a tether to the middle of a doughnut container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve. I initially tried to create a 2D circle collider around the doughnut container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut container). Thus was done with multiple if statements if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f However, when testing the code out, the cursor still exceeded the boundaries given Minimum reproducible code for the cursor public class menuScript MonoBehaviour public float speed public Vector2 originPoint private Vector2 currentPoint Start is called before the first frame update void Start() Vector2 originPoint transform.position Update is called once per frame void Update() currentPoint transform.position float step 50 Time.deltaTime float vertical Input.GetAxis( quot Vertical quot ) Time.deltaTime speed float horizontal Input.GetAxis( quot Horizontal quot ) Time.deltaTime speed if (horizontal ! 0 vertical ! 0) transform.Translate(horizontal, vertical, 0) if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f else transform.position Vector2.MoveTowards(transform.position, originPoint, step)


How to select light as sun source I tried to add a sun in the lighting setting. I have a directional light in my scene, but i can't select it as sun source in lighting setting. The light does not appear in the list. Does anyone know what is wrong ?


VSCode doesn't open the specified Unity script I have downloaded Visual Studio Code to edit Unity scripts. When I double click on a script in Unity, VSCode opens but it doesn't open the script, only an empty file called Unity appears. Anyone knows how to solve this?


"lerp" returning value (Shader)? I don't understand the lerp example in this code if(dot(WorldNormalVector(IN, o.Normal), SnowDirection.xyz) gt lerp(1, 1, Snow)) o.Albedo SnowColor.rgb else (Snow is in the range 0..1) The article says We then compare the dot value with a lerp if our Snow level is 0 (no snow) this returns 1 and if the Snow level is 1 it will return 1 (the entire rock is covered). It's quite normal to only vary the snow level between 0..0.5 when we use this shader so that we only have snow on surfaces that actually face the snow direction. Why does it return 1 (with Snow at 0) and 1 (with Snow at 1) ? (source http unitygems.com noobs guide shaders 2 ) Thanks


Why is clicking too fast giving me a missingReferenceException in Unity? I made a small method that will quickly give the player a "flashlike" display when a sheep is killed. However clicking too fast will trigger a missingReferenceException. Because it registers the raycast a second time. Is this due to the delay on the DestroyObject() or something else? private IEnumerator startFlashing(GameObject sheep) sheep.gameObject.GetComponent lt Rigidbody gt ().freezeRotation true sheep.gameObject.GetComponent lt Rigidbody gt ().velocity Vector3.zero sheep.SetActive(false) yield return new WaitForSeconds(theTimeBetweenFlashes) sheep.SetActive(true) DestroyObject(sheep.gameObject, 0.1f)


how can i fix my code in order to get rid of the error that says that the object I want to instantiate is null? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class replicate MonoBehaviour public void replicateCube(InputField T) int H int.Parse(T.text) for (int i 0 i lt H i ) GameObject prefab Resources.Load("Cube") as GameObject GameObject go Instantiate(prefab) as GameObject go.transform.position new Vector3(0, i 5, 0)


Custom shadowmapping in Unity not working properly To experiment with a certain technique, I'm implementing my own shadow mapping in Unity. I'm using a camera for the light "view", which is rendered to a RenderTexture after being post processed with the following shader Shader "Custom DepthGrayscale" SubShader Tags "RenderType" "Opaque" Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D CameraDepthTexture struct v2f float4 pos SV POSITION float4 scrPos TEXCOORD1 Vertex Shader v2f vert (appdata base v) v2f o o.pos mul (UNITY MATRIX MVP, v.vertex) o.scrPos ComputeScreenPos(o.pos) for some reason, the y position of the depth texture comes out inverted o.scrPos.y 1 o.scrPos.y return o Fragment Shader half4 frag (v2f i) COLOR float depthValue tex2Dproj( CameraDepthTexture, UNITY PROJ COORD(i.scrPos)).r return fixed4(depthValue, 0.0, 0.0, 0.0) ENDCG FallBack "Diffuse" With a width and height of 2048 for the Render Texture and the color format R Float for 32 bit precision. The objects in the scene then have the following shader that takes the projection view matrix of the light and "depth" texture as input. (Basic shadow mapping with bias) Shader "Tutorial Display Normals" Properties CameraTex ("Camera texture", 2D) "white" SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform float4x4 lightMatrix struct v2f float4 pos SV POSITION float3 worldPos COLOR0 fixed3 color COLOR1 v2f vert (appdata base v) v2f o o.pos mul (UNITY MATRIX MVP, v.vertex) o.worldPos v.vertex.xyz o.color v.normal 0.5 0.5 return o uniform sampler2D CameraTex fixed4 frag (v2f i) SV Target fixed4 coords mul(lightMatrix, fixed4(i.worldPos, 1.0)) coords coords.w coords.x (coords.x 1.0) 2.0 coords.y (coords.y 1.0) 2.0 coords.z (coords.z 1.0) 2.0 return fixed4(coords.z, 0.0, 0.0, 1) float lightDepth tex2D( CameraTex, fixed2(coords.x, 1.0 coords.y)).r float depth coords.z if (depth lt lightDepth 0.005) return fixed4(1.0, 1.0, 1.0, 1.0) else return fixed4(0.1, 0.1, 0.1, 1.0) ENDCG The result of this is perfect with a plane and cube The red plane displays the shadow map and the camera represents the light. However, when using a more complex model like Sibenik, the following happens When I move it slightly, the shadow on the plane is suddenly correct, but the shadow on the church model itself is still wrong What could be the problem?


GUIText size on 4 3 and 16 9 is different I have a text (guiText) on the screen. It shows correctly when viewed on 16 9 resolution. But it scales up when viewed on 4 3 (e.g iPhone4). I am using following ObjectLabel script to place it on the same position regardless of screen resolution. Which is working fine for 16 9 and 16 10. Object Label


How do I set the exact local position of a RectTransform? I have a game object that creates a keyboard in side of my world canvas. I am working out the offset positions for each key, and appear to be doing that correctly. However, when I set the positions in the actual keys, the values are being offset by anything from 100 1000. This is the basic method I am currently using to set the position public void SetDimensions(Vector2 position) GetComponent lt RectTransform gt ().localPosition position Debug.Log(key " " position) I have also tried using .position and .anchoredPosition, as per the somewhat confusing API reference. I have also tried simply referencing transform.localPosition and transform.position. No matter what, the output is exactly the same. The debug output confirms that I am working out the correct local position, but no matter what I do, that is not the value being set to my transform. As you can see, I have my pivot set to the center though I think this may have an impact, it certainly should not cause an offset of 400 500. As per request, this is my main canvas What am I doing wrong, or more specifically, how do I set the exact local position of a game object using a RectTransform?


Still having problems using Json data in Unity I have the following classes and json file, i thought id followed the documentation exactly but I am clearly wrong. Can anyone see why I get an error just saying INVALID VALUE in my unity console using System.Collections using System.Collections.Generic using UnityEngine using System Serializable public class DataReader public float x public float y public float z GameController public class GameController MonoBehaviour public static GameController instance DataReader dataReader private string gameDataFileName "level1.json" private void Awake() dataReader JsonUtility.FromJson lt DataReader gt (gameDataFileName) instance this void Start () create level print("DATA " dataReader.x 0 ) and the json is stored in StreamingAssets folder (I also tried a copy in Resources folder) "x" 1 , 1 , 1 , 1 , "y" 1 , 1 , 1 , 1 , "z" 1 , 2 , 3 , 4


How can I expose a property to Unity that should be treated like an asset path? I want to be able to do something like this public FileInfo XmlBehaviourFile And then use the asset browser in the Unity editor to select an asset. Ideally, I would like to limit it to XML files but that isn't too important. I am aware of TextAsset but I can only access either a string or byte array of the contents. I can probably make this work, but at the moment, my library takes a FileInfo and handles the reading itself. Is there a Type I can use that will make Unity let me choose a file in the editor and then simply store the path (ideally, it would handle making sure the path is relative and including the asset in the build). Alternatively, would it be possible to write such a type that would work, I've not extended Unity, but I am aware it is possible.


Start timer when button pressed (what is wrong with my code?) I want a timer to start when my rocket takes off and stop when it lands. Stopping works fine (using a collider and state switching) but I can't get the timer to start when I press the boost button. Currently the timer text is displayed at the moment I pressed the button but clearly has been counting from the moment the scene started, not the moment the button is pressed. Any help will be greatly appreciated. If there is a better way to start the timer rather than when I press the boost button then I am open to ideas! Here is the all relevant code (I think). It appears as though it should be working to me, but it isn't. Timer public Text timerText private float startTime private bool started false private bool finished false void Start () startTime Time.time get time since scene started void Update () if (currentState State.Alive) ProcessBoostInput() ProcessRotationInput() ProcessFiringInput() if (started) RunTimer() private void ProcessBoostInput() if (Input.GetKey(KeyCode.A) (CrossPlatformInputManager.GetButton("Fire1"))) BoostShip() PlayBoostSound() if (started ! true) started true private void RunTimer() if (finished) return else if (started) float timeSinceTimerStart Time.time startTime string minutes ((int)timeSinceTimerStart 60).ToString() string seconds (timeSinceTimerStart 60).ToString("f3") timerText.text minutes " " seconds private void StopTimer() finished true timerText.color Color.green


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.


Player losing alignment with tilemap after moving I'm using an isometric tilemap(2 1) and I can't figure out how to make grid based movement on it's surface. I managed to get a code working for the grid based movement, moving my character with 0.5 along the Y axis and 0.86 ( sqrt(3) 2 ) along the X axis since I imagine it should work as if they are diamonds with the side of 1 unit, but it doesn't align with the center of the next tile. Here is my movement code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Assertions.Must public class Movement MonoBehaviour Vector3 pos For movement float speed 5f Speed of movement public float x 0.86f public float y 0.5f void Start() pos transform.position Take the initial position void FixedUpdate() if (Input.GetKey(KeyCode.A) amp amp transform.position pos) Left pos Vector3.left pos new Vector3( 0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.D) amp amp transform.position pos) Right pos Vector3.right pos new Vector3(0.86f, 0.5f, 0) miscare in diagonala if (Input.GetKey(KeyCode.W) amp amp transform.position pos) Up pos Vector3.up pos new Vector3(0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.S) amp amp transform.position pos) Down pos Vector3.down pos new Vector3( 0.86f, 0.5f, 0) transform.position Vector3.MoveTowards(transform.position, pos, Time.fixedDeltaTime speed) Move there


Help with transform.lookat and camera? Vector3 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.LookAt(mousePos) This will actually make the camera follow the mouse, but it goes crazy, the camera seems to spin in circles rapidly here is actually a gif of what is happening. https gyazo.com 952da6c28e644b7b0e6500a597b6804e preview Could anyone help me figure how how to fix it?


Implementing moving animation I faced the problem of attaching animation to the enemy. In the Animator window I added a "moveSpeed" (float) condition, so moving animation should turn on when moveSpeed is greater than 0.001. But after prescribing a reference to an Animator in the code, whatever I write further, a message pops up about the presence of compiler errors. Here's my script public int health public GameObject explosion public float playerRange public Rigidbody2D theRB public float moveSpeed public Animator anim Use this for initialization void Start () Update is called once per frame void Update () if(Vector3.Distance(transform.position, PlayerController.instance.transform.position) lt playerRange) Vector3 playerDirection PlayerController.instance.transform.position transform.position theRB.velocity playerDirection.normalized moveSpeed anim.SetFloat("moveSpeed") theRB.velocity public void TakeDamage() health if(health lt 0) Destroy(gameObject) Instantiate(explosion, transform.position, transform.rotation) What exactly do I need to write for the condition to work and the animation to play? Thanks for any help!


How to calculate the distance from the camera to make a GameObject fill the screen? How do you calculate the distance from the camera so that a GameObject fills the screen? I.e. Without reaching out of the view and regardless of screen orientation.


Why does my model render differently than its preview? I've been importing .fbx files that I made with 3DS Max 2012 into Unity, and it's quite neat to see my models running around in game. However, I can't help but notice that the models, as they're rendered in game, vary substantially from what they look like in the preview (and also what they looked like in 3DS Max). Observe In Game Unity Preview 3DS Max My gut tells me that I'm not setting up Unity's lighting system properly. What, then, do I need to do, to either my scene or my model, in order to get the left most picture to look like the middle one?


Replacing all objects in scene with another object I have around 100 objects (prefab A) in my scene, all in different positions. Is it possible to replace all of these objects with another object (prefab B), so that the prefab B objects are placed in the same position as the prefab A objects were? I want this done in the editor, not in game.


Update android game with new levels without replacing database So I've published a game for android users containing 400 levels and 2k users have completed or are playing it since. Now I'm going to update the game with 600 levels, but I don't want current users to lose their info in database. I just want to add more levels to the database if it exists in their phone. I'm using this code not to let database get replaced if it exists. public DataService() const string databaseName Constants.DbName if UNITY EDITOR var dbPath string.Format( "Assets StreamingAssets 0 ", databaseName) else check if file exists in Application.persistentDataPath var filepath string.Format(" 0 1 ", Application.persistentDataPath, databaseName) if (!File.Exists(filepath)) Debug.Log("Database not in Persistent path") if it doesn't gt open StreamingAssets directory and load the db gt if UNITY ANDROID var loadDb new WWW("jar file " Application.dataPath "! assets " databaseName) this is the path to your StreamingAssets in android while (!loadDb.isDone) CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check then save to Application.persistentDataPath File.WriteAllBytes(filepath, loadDb.bytes) elif UNITY IOS var loadDb Application.dataPath " Raw " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) elif UNITY WP8 var loadDb Application.dataPath " StreamingAssets " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) elif UNITY WINRT var loadDb Application.dataPath " StreamingAssets " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) else var loadDb Application.dataPath " StreamingAssets " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) endif Debug.Log("Database written") var dbPath filepath endif connection new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite SQLiteOpenFlags.Create) Debug.Log("Final PATH " dbPath) Also I've created a filed in database keeping database version to check what version the user has (like the version with 400 levels, the one with 600 levels or maybe more). What I don't know is what is the best solution to add more records to an existing database. Has anyone got a solution?


Colliders slightly intersecting each other any solution? Consider this simple scene In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider. And the problem if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall. This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist. Is there a workaround? How can the box smoothly move across the floor without colliding with the seam? Notes This does occur with capsule colliders but rare and is not very noticeable. A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks. This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity position of the transform.


UI Button OnClick not playing AudioClip on gameObject Basically, I am loading an Audio Clip onto a game object's Audio Source in the Awake function when the game starts. When I click on the game object a UI comes up that basically has a Play button attached and all I want to do is play the Audio Clip on the Audio Source. The problem is I can see that there is an Audio Clip on the Audio Source at runtime and I can play it in the inspector at runtime but, when I click the button nothing happens. I have tried just referencing the gameObject in the OnClick() of the UI button and that doesn't work and I have also tried going through and getting the gameObject through GameObject.Find public void PlayMe() GameObject objs GameObject.FindGameObjectsWithTag("Voice log") foreach (GameObject obj in objs) if (obj.layer LayerMask.NameToLayer("Selected")) Debug.Log("Found it") if (obj.GetComponent lt AudioSource gt ().clip.loadState AudioDataLoadState.Loaded) obj.GetComponent lt AudioSource gt ().Play() Debug.Log("Should Play") Both of my Debugs print when I click the Play button.


Add Rigidbody and MeshCollider at runtime is it a bad practice? Good day. To simulate an explosion of a vheicle, I decided to do this When I need to explode veichle , at runtime, i add rigidibody for every single part of veichle (5 10 part door, wheel, hood etc), and collider (mesh). I detach them from parent I apply an AddExplosionForce to every single part This cause a big lag in my game, so I'm supposing this is not the efficent way. The other way could be to add Rigidbody and Collider in my prefab, with Rigidbody.gravity false, and isKinematic true, then enabling after explosion, but also this is not good for performance. Do you have some suggestions to achive my scope, considering that I could have a lot (5 10) enemy veichles at time on my scene ? Thanks


How can I easily create edit a level for a scrolling shooter game? I've been asking this question over the years many a time, but I still haven't found an answer when i search for one. Now I have slightly more knowledge of how programming is done and want to start making some full games. I want to start with a side scrolling shooter (space style like R Type Gradius). I have many ideas in my head for good levels, and i even have some basic 3d skills in Maya Blender to make the assets, but I do not know how best to formulate the levels. Lets say the space shooter has 30 levels. Each level might have about 10 15 enemy types and a boss on some levels. How best to store the location of all the enemies? (Same scenario for all the background objects,obstacles, powerup locations etc.) Is there a better way than manually building the whole level in a Unity Scene editor view? Another way I have tried is to set spawn positions for every single object as a Vector2 or similar in XML or JSON, but how i did it that seemed even harder to make the levels than just inside the editor (not even accounting for having to write the functionality to get the data from the textfile).


How do I play a particle system when moving? I have a car that I move with a Physics based movement (AddForce(), AddTorque(), etc...) and I have a simple particle system attached behind the car as follows I'd like to play this ParticleSystem whenever the car moves I tried checking if the car's rigidbody's velocity was greater than 0 if(m Rigidbody.velocity.z gt 0) m ParticleSystem.Play() if(m Rigidbody.velocity.z 0 amp amp m ParticleSystem.isPlaying) velocity.z 0 is unreliable, verified with Debug.Log m ParticleSystem.Stop() I then tried using Input if(Input.GetAxis("Vertical") gt 0) the car is moving along the positive z axis m ParticleSystem.Play() if(Input.GetAxis("Vertical") 0 amp amp m ParticleSystem.isPlaying) m ParticleSystem.Stop() These two methods don't work, I'm probably making assumptions on how Rigidbody.velocity behaves (when you stop the car for example, it becomes negative, so the particle system would keep playing until it reaches 0)


Tweaking screen transitions not to fire every time in Unity I'm making a simple screen transition system for my game which consists of two states firing the right clips (one for the starting half od the transition animation, one for the ending one) and a condition between the end and start one which is set to true when user wants to change the level (so that the Start animation would fire in the previous animation and the End in the new one). This is cool and all but poses two problems firstly, the game starts with the End phase animation which looks a bit weird. Secondly, since the Restart button in the main game just reloads the level, it causes the End transition to fire every time too which looks weird and out of place. How would I go about tweaking the Animator so that the End phase only runs when I actually change the level as opposed to when starting the game or reloading the current scene? Maybe there's some way to pass some kind of a parameter when loading a new scene that I'm not aware of? This way, I could just pass a flag like shouldFireEndAnimation so that it does not fire when the game just starts or a level restarts?


Unity2D Sprite Mesh Lighting Issue I am trying to make my 2D mesh render sprites with the same brightness as the original file. On the below picture, the mesh on the left is darker than the UI Image on the right, which is an exact likeness of the original file. How can I make the mesh as bright as the Image? So far, I've been looking into the following potential culprits Shader attached to the Mesh Global lighting settings Mesh renderer lighting settings The above image is with Environment Lighting Ambient Color at FFFFFF. Environment Lighting Ambient Color Intensity doesn't help. Increasing the shader's emissions can offset the darkness but it's not an ideal solution. All other lighting settings both globally and on the Mesh Renderer are default. At this point, I'm lost Any help would be much appreciated!


TextField Add in Editor does not display when put under if statement I've been trying to make a custom editor window in Unity and I needed to make an quot add TextField quot button. When I add a TextField directly (without requiring a button), it works. When I put it under if(GUI.Button()) it does not show up. Here's my code private static List lt string gt s new List lt string gt () private void OnGUI() if (GUI.Button( quot quot ) ) s.Add(GUI.TextField(new Rect(0,50,Screen.width,20), quot field quot ))


What edition of VS is installed by Unity and what are its capabilities? My brother just installed Unity on my desktop, and it seems like it installed Visual Studio 2017 as well. I was planning to install Visual Studio before this, so I was wondering what kind of version is this edition of VS? Is this like a bare bones version? Does it work like a standalone version without lacking features? Can I use it just as a regular IDE to program in? I typically program in C , and I never used Unity before, so I'm not sure if this version of VS is only suited for Unity.


Sending message to all players in room from Photon server? I need to send a message to all players in the room from a Photon server. Sending the message from a player would introduce too much latency so I need the server to collect data and distribute messages at a rate of 16 s without a player's influence. Is there a way to do this?


How to blend motions with Mecanim I'm struggling with Mecanim. My concern is to blend straight turning animations with strafe animation for a humanoid character. I downloaded a SampleAsset from unity and took Ethan character as example. The animator uses a blendtree which naturally blend idle walking running animations with a smooth turning left right animations. In this case the Ethan character cannot strafe. I'm trying to understand how to blend strafe movement with it's actual straight turning blending motion. Was I somewhat clear?


Overlap transparent particles without blending? (Unity) I'm trying to create a continuous output of light from an object (like the exhaust of a space ship), and I thought I'd use particles to achieve this. But I'm running into a problem with alpha blending. I'd like to decrease the particle system's alpha over time, but because there's such a high density of particles, they end up evaluating to a solid color for most of the system's duration. This blog post basically shows what I'm trying to achieve https mispy.me unity alpha blending overlap The idea is to use a stencil test to make sure pixels in a sprite particle aren't gone if they're overlapping another sprite particle. Pass Stencil Ref 2 Comp NotEqual Pass Replace Then the author adds an alpha cutoff to make sure transparent pixels on an underlying sprite don't prevent new pixels from being written. half4 frag (v2f i) COLOR half4 color tex2D( MainTex, i.uv) if (color.a lt 0.3) discard return color But this solution requires you to eliminate soft edges, so I'm thinking it wouldn't look good in a particle system. The author also hinted at an alternate solution involving ZTest, but I can't visualize what that would be.


Board like strategy map I want to make a strategy game like Risk. I want to use C for the mechanics and Unity for the graphics. My problem is that I don't know how to create the map itself and integrate it with C . I don't want a tile map but instead I want to create a customized world map, with different provinces defined by me. The map would be something like Imperial Glory, where you see it top down and then move your generals like chess pieces. I'm not implementing any real time battles at this point, it's just something really simple, like a board game. Could anyone please help me? I'll try to explain it a bit better I need to create a map of the Mediterranean basin that would cover all the land occupied by the Romans at the height of their empire. Next, I'll divide the map into 20 provinces (Italy, Gaul, Germania, etc), each one producing a set ammount of resources and population. I also want them to have their own wheather and buildings (for example, you can only train soldiers in provinces that have a barracks). I guess I'll need a text box popup that appears when you click on a province to display it's information. I'll also need some buttons to open dropdown menus or perhaps whole windows, for other purposes such as diplomacy, statistics, tech trees, etc. I wanted the map to be in 3d because I think it would be much more interesting to look at it in perspective instead of flatten 2d. I'm fairly new into Unity so I really admit that I have no idea where to start. Please, have patience with my ignorance. Thank you very much for all your help. If there are any doubts about my question, please let me know and I'll try to explain it better. PS I think I'll make it a turn based game since I think this would make it simpler to code and faster to run.


How can I instantiate enemies in a 2D game at a set Viewport Position before my camera enters the room? (Or alternative solution!) I'm currently working on a 2D game where I'm trying to pre populate my level with encounters, I want the enemies already in the room when the player enters. Right now the encounter is triggered upon entering the room when the camera bumps into the collider and the enemies are instantiated at the Viewport position, however because it does it while the camera is moving into the room the position is incorrect. Using hard values isn't an option because the maps could of course change and also I may want them randomly generated at some point. So I guess ultimately the problem is the camera not being in the right position when they instantiate and not wanting enemies to quot pop quot in once it is. Is there a way I can I instantiate an enemy at the same point on the screen regardless of resolution in each specific room at the start of the level? Encounters will have up to 3 enemies and they will always hold the same formation (with spots randomized to add diversity) Here is my instantiating code SerializeField public List lt GameObject gt levelEnemies new List lt GameObject gt () GameObject levelEnemy Vector3 enemyPosition Vector3 viewportPosition new Vector3(0.8f, 0.5f, 10f) Place on the screen I decided I want single enemies to appear Camera cam void Start() Debug.Log( quot Enemy Triggered quot ) cam Camera.main enemyPosition cam.ViewportToWorldPoint(viewportPosition) levelEnemy Instantiate(levelEnemies 0 , enemyPosition, Quaternion.identity) instantiate test enemy at the converted position navigation.DisableNavigation() Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3) Here's what should be happening when the enemy is instantiated (triggered manually through the editor once camera has been moved fully) Here is what happens when the camera collider bumps into the encounter collider Any help in the right direction would be much appreciated or a workaround! Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)


Moving spilling water inside a cup of glass I made a glass of water but there are somethings i didnt know how to do well, what i did is i put a mesh on the top of the glass to represent the surface of the water but it doesnt really work well with glass because if you look from the sides you wont really see that there is water in there, this is what i did the glass from the side as you can see it doesnt really work well in my case. I also tried putting an object that has the same shape as the cup inside to represent water but that would make it difficult for what i want to do next, because my next step would be to make the water rotate in the opposite rotation of the cup and make it spill if it reaches the top of the cup, and that is my second question how do i make the water spill from the cup? Any help is very much appreciated.


How can I check if component is enabled? using System.Collections using System.Collections.Generic using UnityEngine public class CameraInformation MonoBehaviour public string currentCameraState Start is called before the first frame update void Start() var components new List lt Component gt () foreach (var component in GetComponents lt Component gt ()) if (component ! this) var fullName component.GetType().FullName if (fullName.StartsWith( quot Cinemachine quot )) currentCameraState component. Update is called once per frame void Update() private void OnEnable() private void OnDisable() At this line I want to assign the string the component status if it's enabled true or false.


How do I procedurally animate a cell eating another cell? The entities in my game are soft body, amorphous cells. I'd like to create an animation where enemies are engulfed by the player's cell. That is, I want to generate a "cell eating another cell" effect. See this video for the type of motion I want https www.youtube.com watch?v iO vOFFf1uQ I'm considering using fluid dynamics to achieve this, but I'm lost as to where to start. I'm working in Unity2D, and Fluvio doesn't seem to provide what I need. Does anyone have advice on the best way for me to proceed?


Unity Failed to create decoder for ScreenSelector.png My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not. How it should look and how it looks I checked the logs and this is the error I am served Failed to create decoder for 'C Users Hamuel The First Documents Jetplatformer Builds Builds Data ScreenSelector.png' 0x80070002 Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity. Any help would be much appreciated!


How can I load multiple scenes in background? I want to queue the loading of multiple scenes in background and show all of them at the same time when all complete their loading. The only idea I have by reading the docs is to root all objects in every scene I want to load this way in a single GameObject that is disabled by default and when all my LoadSceneAsync finishes its work, I can them activate each scene root GameObject. Without doing that, I have all related scenes being loaded and being showed in the screen at different times and this is just not acceptable. I'm creating this question because I believe there must be a better way to accomplish that rather than rooting all the scene into a single game object.


Unity crashes when opening a project Why does this happen? I'm new to Unity development. I have installed Unity yesterday (2015 09 06). This is the error that I get


How can I scale a color component by Time.deltaTime and still fit it into a byte? I am confused about this issue, and I can't find why I get this and how to fix it properly from the Google searches I've tried. This is a short version of my code byte redtarget 70 byte greentarget 222 byte bluetarget 255 byte opacitytarget 1 byte redcurrent 0 byte greencurrent 0 byte bluecurrent 0 void OnMouseOver() redcurrent redcurrent redtarget Time.deltaTime greencurrent greencurrent greentarget Time.deltaTime bluecurrent bluecurrent bluetarget Time.deltaTime if(redcurrent gt redtarget) redcurrent redtarget if(greencurrent gt greentarget) greencurrent greentarget if(bluecurrent gt bluetarget) bluecurrent bluetarget theobject.GetComponent lt Renderer gt ().material.SetColor(" EmissionColor",new Color32(redcurrent,greencurrent,bluecurrent,opacitytarget)) Please ignore the other errors that could have been introduced when I copy pasted it to here. And this is the error I get As you see the error, "cannot implicit convert type float to byte", the problem is caused by Time.deltaTime that returns a float value, and I need a byte due to Color32. Is there any way to turn Time.deltaTime to byte? Or should I use another type of color that use floating point numbers? I'm a beginner with Unity so I'm sorry if this has already been asked somewhere as I said, I can't find it on the Internet.


Unity Sprite vertices in 3D world Rookie here, still learning the basics of Unity. I've been using a quad as a cursor sitting flat on top of a hilly terrain mesh. I've been getting the terrain angle by raycasting down at all four corners of the quad and finding where it hits the floor, then editing the quad vertices to shape it to the terrain angle. Probably not the ideal way but it works great for what I needed. So the next step is replacing it with a sprite. I changed from quad to a sprite renderer, and added a little animation to it. I went to edit the vertices and the setup is completely different (it seems to have 20 vertices now instead of 4). I did notice the SpriteRenderer has 4 triangles, but the points are Vector2s rather than Vector3, so I guess that won't work either since I'm applying it to a 3d world? Can anyone with experience point me in the right direction with this?


File operation(s) failure on game crash kill by OS User in Android My game saves its state after fixed interval on a file in game app internal storage. When my game is killed or crashed by user or OS respectively, We write current game state on that file. File writing after fix interval is working fine but when game is crashed killed by OS or user, file writing operation fails. Operation failure results incomplete game state or empty game state i.e. no data written on file at all. I have tried multiple solutions using android service, In case the service is NON STICKY service is killed with the app. On the other hand if service is STICKY then it is restarted but intent that was attached initially with service is null or new one. The question is that how can i save my data (could be 2 3MB) completely on file in internal storage when my game app is killed by user OS ?


Getting mousemovement despite mouselock unity I have lockcursor so the cursor doesn't leave the screen, but now i have to rotate an object based on mouse movement (think garrys mod item rotation) but the mouse cursor is obviusly locked to the center, is there anyway of getting the input from the mouse? public void GetRotated() Debug.Log(Input.GetAxis("Mouse X").ToString() ", " Input.GetAxis("Mouse Y").ToString()) gameObject.transform.localRotation new Quaternion(Input.GetAxis("Mouse X") RotationSpeed Time.deltaTime, Input.GetAxis("Mouse Y") RotationSpeed Time.deltaTime, 0, 0)


Unity Easier way to resize group of buttons to the same size I have a canvas with buttons, with a script attached to each button. This script creates an array for buttons and resizes every button to the same size as the longest one in that array (the button with the longest line of text in it). Everything works, but I was wondering is there is an easier, more automatic way for this instead of having to drag every button in every array in the Inspector tab? Any ideas would be greatly appreciated UnityPackage https transfer.sh 6BCDG buttonwidth.unitypackage public Image otherbutton void Start () for(int i 0 i lt otherbutton.Length i ) if (otherbutton i .rectTransform.sizeDelta.x gt gameObject.GetComponent lt Image gt ().rectTransform.sizeDelta.x) gameObject.GetComponent lt ContentSizeFitter gt ().enabled false gameObject.GetComponent lt Image gt ().rectTransform.sizeDelta new Vector2( otherbutton i .rectTransform.sizeDelta.x, otherbutton i .rectTransform.sizeDelta.y)


Rendering a distant star field in Unity using a separate camera for near stars I'm currently working on a hobby project which is a universe simulator (exclusive to stars) built in unity3D. In order to deal with the raw scale of the universe I'm trying to implement two co ordinate systems. In my project I have two cameras camera1 is the first co ordinate system where all stars are loaded as high detail 3D objects. While camera2 is used for gathering a list of points within this "extended" frustum. I want to display these stars from camera2 on the farplane of camera1 in a lowdetail 2d manner. I'm new to game development so this may be completely wrong my plan was to generate a mesh from all the points in cameras2 frustum (this mesh now respresents my points in world space). I have a variable that represents the conversionFactor between the two co ordinate systems. I will convert this mesh into projection view using the my conversionFactor in the translation component. I will display this projection view on my camera1 farplane selling the illusion of far away stars? Please let me know the flaws in my deisgn! any help is much appreciated


Calcluate Mesh top, bottom, left and right position relative to mouse click position on the mesh I have a mesh (suppose it can be circle, or rectangular,square or an arc). The geometry of the mesh can be anything. I can click on mesh at any position. From relative to the clicked position, I want to get its right, left top and bottom position of the mesh. Maybe the picture explain it better then my words Update I tried to apply a quick dirty solution. It is incomplete Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) Ray r Ray(Input.mousePosition) RaycastHit rayHit Ray r Camera.main.ScreenPointToRay(Input.mousePosition) if(Physics.Raycast(r,out rayHit,1000)) Debug.Log(rayHit.transform.name) Debug.Log(rayHit.point) Debug.Log(rayHit.normal) StartCoroutine(MoveToDirection(rayHit.point)) IEnumerator MoveToDirection(Vector3 startPosition) GameObject go GameObject.CreatePrimitive(PrimitiveType.Cube) go.transform.position startPosition while (true) go.transform.position go.transform.position go.transform.up Time.deltaTime speed yield return new WaitForEndOfFrame() On click i instantiated a gameobject and start moving in upward direction and when it leaves the mesh bounds i will get the position but it have differet problems, like 1. It will not work with arc object or maybe with non rectangular geomerty. 2. I have to apply onTrigger and onExitEvent that can be skip when the cube move with fast pace.


How can I extend the FindObjectsByTag to filter multiple parents of the found objects? private List lt GameObject gt FindDoors(string parents) GameObject doorsLeft GameObject.FindGameObjectsWithTag(c doorLeft) GameObject doorsRight GameObject.FindGameObjectsWithTag(c doorRight) List lt GameObject gt allDoors doorsLeft.Union(doorsRight).ToList() List lt GameObject gt toRemove new List lt GameObject gt () for (int i 0 i lt allDoors.Count i ) for (int x 0 x lt parents.Length x ) if (allDoors i .transform.parent.name ! parents x ) toRemove.Add(allDoors i ) foreach (var it in toRemove) allDoors.Remove(it) foreach (GameObject door in allDoors) Debug.Log("Door Parent " door.transform.parent) return allDoors Usage var allDoors FindDoors(new string "Wall Door Long 01", "Wall Door Long 02" ) But in the function FindDoors the return allDoors is empty. I think the problem is at this IF if (allDoors i .transform.parent.name ! parents x ) Once it's Wall Door Long 01 so if it's Wall Door Long 01 it will not remove the item but next it's Wall Door Long 02 so now the it's true and will remove the even if the parent name is Wall Door Long 01 and same if it's Wall Door Long 02 And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall Door Long 01 and not Wall Door Long 02


Making an RTS game how to handle player created units interacting with each other I'm making an RTS game in Unity with C . However, the interaction I'm going to have with player created units interacting with other player created units is what has me stumped. The player and his opponent can purchase units when they have the resources, and it instantiates them in the game. The main thing is checking whether an opponent's unit is within range to attack. Obviously, you can't have every unit asking every other unit what its position is, or it would get exponentially more CPU consuming the more units are built, right? I'm trying to figure out how I'm going to go about this. I figured I could have every unit report its position to a sort of master 'tracker', and then every unit could ask the tracker if any opponents' units have a position within X of their own. How I would actually implement this in Unity, though, I'm not sure about. Moreover, I'm trying to get my head around Instantiated objects. If every unit is telling its position to the master 'tracker', what does it call itself? And let's say a unit asks the tracker if an enemy is in range and one is, what does the tracker tell it so it can locate the right GameObject and attack it? Sorry if I'm talking about it all wrong, I'm sure there's a simple methodology that exists on how to do it, but I can't think of any. Thank you.


How to make a merge animation in Unity? I've seen a merge animation in a mobile game which you can check here https youtu.be G7l24Wtdcxw You can observe the animation when the tiles combine. Can it be done in Unity3d, may be using shaders? Or, do I need to use a 3d app like Blender?


Can you adjust the proportions of a 3D model via scripting? We are developing a game in Unity where the character is different ages in different levels. Would it be possible to use a single 3D model asset, and alter its proportions via scripting to achieve this effect? For example, stretching the head to make it more oval for older self, or increasing head size for toddler self? We don't have a model yet. We are envisaging a simplistic, cartoony look rather than something realistic. Is this doable?


how to detect touch on instantiated prefabs in unity I have instantiated objects (that have collider2D attached) in a grid of 9x13. Now I want to detect a touch on each object individually. I am confused about how to do it. Either write script separately on prefab or do it in my gameController script? Also what is the method to do it? Here is my code for instantiating public GameObject bubble int row int col float x float y void Start () x 2.4f y 2.95f row 13 col 9 Vector2 position new Vector2(x, y) for (int i 0 i lt row i ) for (int j 0 j lt col j ) Instantiate(bubble, position, Quaternion.identity) position.x 0.6f position.x x position.y 0.6f


Unity material has shiny white outline I have two different projects open in Unity. But my grass material appears different in each project, despite all the parameters being the same. See this image On the left is the desired appearance. But on the right my material has a strange white ish outline. How do I get rid of it? I have tried copying the material between the projects, and the problem seems to be independent of the available lighting


Unity Collision detection issue with CharacterController I am making an isometric game (3d scene, using 2d sprites). Currently I am trying to add collision to the enviroment to prevent the player from walking through everything. However no matter what I do the player seems to simply ignore the and walks through the object. Below are some combination I have tried and the results I got. For this instance I am looking at the windmill object NOTE Player has a character controller , no rigidbody. Scenario 1 Windmill has Rigibody IsKinematic false No rotation amp Position constraints Boxcollider isTrigger false result On touching object it start flying around. So collision is there. Scenario 2 Windmill has Rigibody IsKinematic false has rotation amp Position constraints (all axis) Boxcollider isTrigger false result I can walk through the object and somehow the collision is gone. the reason for constraints is so that the object wont move. (its a windmill) Scenario 3 Windmill has Rigibody IsKinematic false both with and without rotation amp Position constraints (all axis) Boxcollider isTrigger true result Debug.Log shows that there is collision Now what I would like to achieve is that the windmill can't be moved yet also can't be moved through.I am willing to programm collision if needed, but i rather do it with the unity provided tools. Any idea what I am overlooking? EDIT 1 Since it was asked how I moved the player, I use the Fingers asset. We make use of the joystick to move the player around. Below is our JoystickExecuted method depicting what exactly I do. private void JoystickExecuted(FingersJoystickScript script, Vector2 amount) if (amount.x gt 0 amp amp ! facingRight) FlipXAxis() else if (amount.x lt 0 amp amp facingRight) if (amount.x gt 0 amp amp ! facingRight) FlipXAxis() else if (amount.x lt 0 amp amp facingRight) FlipXAxis() var pos transform.position pos.x amount.x 8 Time.deltaTime pos.z amount.y 8 Time.deltaTime transform.position pos anim.SetBool("isWalking", true) if (amount Vector2.zero) anim.SetBool("isWalking", false)


In GameCenter realtime multiplayer how to identify who is host? In GameCenter real time multiplayer how to identify who is a host?


How can I continue to rotate a 2D UI Object using OnPointerEnter when object is on its side? (OnPointerExit is triggered) I have been wracking my brain on this for days. I'm trying to create a nice looking hand of cards, when the card is hovered over, it bobs up and down and rotates. This is triggered by OnPointerEnter, however, whenever it turns on its side and out of the mouses path OnPointerExit triggers, I've tried MANY things, including a bool that triggers the hover effect OnPointerEnter but it is just toggled off when it's turned on its side. Is it possible to use the collider on my card with OnPointerEnter? Because that would probably solve my problem but haven't found anything on this. Since the card is on UI, I have some placeholder code in there in order the have the inspected card render on top and return to its place. void Update() if (inspect) transform.localScale cardUpscale posOffset transform.position transform.Rotate(new Vector3(0f, Time.deltaTime degreesPerSecond, 0f), Space.World) Float up down with a Sin() tempPos posOffset tempPos.y Mathf.Sin(Time.fixedTime Mathf.PI frequency) amplitude transform.position tempPos public void OnPointerEnter(PointerEventData eventData) zoomPlaceholder new GameObject() zoomPlaceholder.name "zoomPlaceholder" zoomPlaceholder.transform.SetParent(this.transform.parent) binds the placeholder to the hand zoomPlaceholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex()) LayoutElement cardProxy1 zoomPlaceholder.AddComponent lt LayoutElement gt () cardProxy1.preferredHeight this.GetComponent lt LayoutElement gt ().preferredHeight cardProxy1.preferredWidth this.GetComponent lt LayoutElement gt ().preferredWidth cardProxy1.flexibleHeight 0 cardProxy1.flexibleWidth 0 zoomPosition transform.parent transform.SetParent(transform.parent.parent) inspect true public void OnPointerExit(PointerEventData eventData) inspect false this.transform.SetParent(zoomPosition) this.transform.SetSiblingIndex(zoomPlaceholder.transform.GetSiblingIndex()) transform.localScale cardNormalScale Destroy(zoomPlaceholder)


In Unity how can I know which direction is the screen auto rotated? From the Screen.orientation description I get If the value is set to ScreenOrientation.AutoRotation then the screen will select ... automatically as the device orientation changes. This seems to imply that if the screen does auto rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation. If that's so, how can I know in which direction it has been auto rotated? Disabling the auto rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either. This should be cross platform, without including any kind of non C plugin. (the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)


How can I use height patches to generate terrain such as what was used to create Abzu? Last year's GDC was pretty inspirational for me and Matt's talk about GiantSquid's landscape creating workflow was the best of all. If you haven't seen it I highly recommend you to check it out. I'm a Unity dev and I'm aware of the fact that Abzu was done with UE and the tools they used in this landscape creation and customizing was custom built. Although I'd eventually like to create similar tools for terrain generation via mashing height patches and enabling different surfaces blending, terrain stamps, and such, the first thing I should ask should be about the level terrain bit. How can I use height patches to generate a terrain (like sand) and then blending them together with something else without extra sculpting (like rock protruding from the sand surface)?


How to add high score? I wanted to add a high score to my game but I don't know how I already tried to find some videos for it but I just can't find the right one. I already have a scoreUI on my game I just wanted to add a high score. Here is my UIManager's script which consists of different functions including the score system. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.SceneManagement public class uiManager MonoBehaviour public Button buttons public Text scoreText int score bool gameOver Use this for initialization void Start () gameOver false score 0 InvokeRepeating("scoreUpdate", 0.5f, 0.25f) Update is called once per frame void Update () scoreText.text "" score void scoreUpdate() if (gameOver false) score 1 public void gameOverActivated() gameOver true foreach(Button button in buttons) button.gameObject.SetActive(true) public void Play() SceneManager.LoadScene("level1") public void Menu() SceneManager.LoadScene("Menu") public void Retry() SceneManager.LoadScene(SceneManager.GetActiveScene().name) public void Pause() if (Time.timeScale 1) Time.timeScale 0 else if (Time.timeScale 0) Time.timeScale 1 I got the score system from Charger Games. Here is the link to the Video and here is what my game looks like


Animation inside a .obj file? Ok, so yesterday I understood that "rigging (bone and joints)" are things that are use inside a 3D animation software like maya. By that I mean that those bones and joints are not inside the .obj file but only inside the software to help you animate the model. My plan was to create my own voxel model using my own editor, then load it up into maya to animate it and then put it inside Unity to use the animation but from what I understand, its impossible to put multiple frame inside a file to use the pre made animation inside a software like Unity. Does that mean that I will have to load my voxel model inside unity and animate it using the Unity Animation Engine ?


Set up Blob shadow projector My game completely uses baked lighting in URP and because of URP's forward renderer, point and spot lights can't cast realtime shadows on moving characters if I set their types to mixed lighting, and my game mostly takes place indoors, so directional lights wouldn't make sense. So now, I thought I'd use the blob shadow projector from the standard assets pack and it didn't work then I found out that it does not support URP. Does anyone know how I can recreate the blob shadow projector for URP? Or is there another way to create fake shadows for non static characters?


How to synchronize a parent and child position? When watching this video of Unity development, I was following along trying to learn Unity and for the most part understood everything conceptually. Where I got lost was when I tried using some of the same code and setup in Unity. I got the code working fine, but I got in trouble when I tried to implement the parent child behavior seen in the video at around 7 minutes regarding the Enemy objects. The solution described is set up as follows (someone correct me if I didn't understand it properly from the video). Parent Object Contains the script which drives behavior and movement Is located at the origin of the scene (reset the transform in other words) Child Object Contains the graphics renderer which draws the actual sprite or 3D object Is located at the enemy spawn point For me to get this setup working, I had to run the Translate function explicitly against the child object transform.GetChild(0).Translate(dir.normalized distThisTurn) However, in the video, it appears to work just fine with only transform.Translate(dir.normalized distThisTurn) Once he fixes the rotation issue, at about 7 minutes in, this works beautifully, and the enemy travels the path exactly as expected. When I tried this exact same approach, my enemy sprite jumps all over the place. It took me several hours to figure out that I needed to add the .GetChild(0) part. The behavior I saw with the setup from the video is that the invisible parent object moved correctly along the path, and the child went crazy and followed some alternate version of the same path, as if the origin was different or offset, or the path was reflected across some axis. My question is what did I do wrong? Can anyone spot how my setup is different than the one used in the video? Did I miss some detail of how he set up his parent child objects, particularly for the enemies? Or could this be some different behavior due to the version of Unity he is using (I believe mine is newer as I installed it just this week). I think it could also be some small gizmo or feature he neglects to mention that allows you to synchronize the movement of a parent object with its children. The reason for this setup (at least as given in the video) is it allows you to easily swap out the graphics. The scripting is tied to the parent, so all you have to do is exchange the child for one with different graphics and you're done. That part makes sense, I just don't understand why the exact same code he uses did not work for me. I'm talking only about the Enemy object here the creeps that move along the path (it's a tower defense game). I just want to know because I may have to use this extra GetChild call quite a bit, and I feel like it shouldn't be necessary, especially after seeing it work so well in the video. Doing this would also make my scene design a little easier. I have already read the comments on that video for additional info, as well as looked through Unity forum posts, other posts here on Game Dev.SE, and Google results. It would seem as if this is either old behavior, or there is some small detail neglected to explain in the video of how to synchronize movement of parent and child objects.


Unity. Draw mesh without a mesh class Is there a way to draw an array of vertices traingles directly from code, above 65k verts? I looked at Graphics class but it can only render a Mesh object.


How to access Lit shader properties through code? Currently i'm using HDRP in my project, so i have a question. How can i access Lit shader properties through code ? Or where i can see names of variables in this shader ? For example


FBX exported from C4D and imported into Unity creating new materials When importing a FBX model created in C4D, unity is creating new materials for certain meshes. For example, I have a material in C4D applied to my model called Metal. When imported into unity a new Material called Metal.1 is created and assigned to the mesh. I have no idea why this is happening.


Moving a platform left to right with continuous movement I made a 2D game with Unity, and I am trying to create a platform that will move from left to right continuously, but I don't know how to make the platform move a greater distance then 1 to 1 units because I use the Mathf.Sin function. I can only control the speed of the platform. Here is my code private Vector2 startPosition private int speed void Start () startPosition transform.position speed 3 void Update() transform.position new Vector2(startPosition.x Mathf.Sin(Time.time speed), transform.position.y) Here is what the code actually does How can I control the distance that the platform can move to each side? For now, it can only move 1 unit to each side.