3D game with Pre rendered background So a friend of mine and myself are starting to create our first game together. We descided on doing a 2.5D kind of game, so a static camera that moves with the player but cannot rotate. I got the collisions object from my friend which in unity looks like this Now I'd like to create an overlay with a JPG image which is going to cover the entire viewport and is going to "be" the map itself. I want to use this JPG as a kind of background image and then hide the collisions so the player will walk into the collisions and stop there but can't actually see them. In stead, he will see the image with buildings on it. How can I do this correctly? I've gotten as far as creating a second camera which will show me the image and then trying to create an Image (Create gameobject UI Image). But I cannot find any way to continue on this. Is this a good way to do this whole 2.5D kind of thing? We want lightweight maps in our game and thought this was a good idea to go about this. Edit My friend and me are trying to create an isometric game like this. The reason behind this is that the amount of work for the map is going to be massively reduced if we can do it like this since he can then just work in photoshop, in which he's super good. This was he does not have to bother with the 3d design in detail and can make the collision blocks much faster. So does anyone know how to get this to work? Maybe someone has a partial guide on this because I cannot seem to find anyone doing it like this but I imagine that ie Commandos is made like this. It would be much appreciated!


My GameObject keeps spawning when it shouldn't I'm trying to instantiate a new gameObject when the current gameObject gets to a select point. The problem comes when the program gets to the second if() statement. It sets the floorsSpawned to 1 and when it does, the game object instantiates a bunch of times. Shouldn't the floorSpawned be set to 2 in the first if() statement and only instantiated once? public class FloorMovement MonoBehaviour public GameObject floor SerializeField int speed 10 public int floorsSpawned 1 Start is called before the first frame update void Start() Update is called once per frame void Update() transform.Translate(Vector2.left Time.deltaTime speed) if (transform.position.x lt 18.0 amp amp floorsSpawned 1) floorsSpawned 2 Instantiate(floor, new Vector2(11.5f, 2.0f), Quaternion.identity) if (transform.position.x lt 40.25 amp amp floorsSpawned 2) floorsSpawned 1 Destroy(floor, 3)


Spawning large numbers of navmeshagents causes them to jump position Cross posted on StackOverflow I'm making a tower defense style game in 3D using Unity. I'm experiencing a frustrating issue with spawning large numbers of characters in an area of navmesh where if I spawn too many near the same location many of them will 'teleport' immediately after instantiation to near the navmesh destination. Here's a doodle of one of the levels The black spot is the player base the NPCs have to get to. The green scenery has no navmesh and uses mesh colliders. Scenery is mostly steep hills forming a valley the NPCs should path through. It is composed of multiple meshes marked Unwalkable in navigation. The large blue spot is the first spawn location I tried, I later tried a larger area indicated in the right side of the image (see 'things I've tried' below). When instantiating at the original spawn location if I spawn more than about 20 NPCs at once many of them will jump to the the area indicated by the red spots. The NPCs have a radius of about 1.5m, as do their colliders and navmeshagents avoidance property. Things I've tried Spawning to a random position inside a circle with a radius of 50m. Adding a large new hidden area of navmesh as in the image above, defining an array of vector positions spread well apart and spawning at each position in turn so no two navmeshagents spawn near each other. Adding a delay to navmeshAgent.SetDestination(playerBase) after instantiation hoping this would prevent the immediate jump to near the destination. Reducing navmeshagents avoidance radius. This sometimes reduces the problem a little but still, even with a radius of 0.1 any more than around 50 NPCs triggers the problem. Turning avoidance off althogether (setting to none in navmeshagent), again, can spawn more but problem still happens Turning off auto traverse links and auto repath in navmeshagent Increasing the time between instantiations, a large gap of several seconds works but makes the game too easy Not setting a destination oddly they still teleport to near the player base, so I guess destination is not a factor How can I spawn large numbers of navmeshagents in a short timeframe, avoiding this 'teleporting' behaviour?


Canvas overlapped by scene objects I am doing a space game and I have a little problem when doing the GUI. As you can see here the objects from the scene overlap the text from the GUI. From what I've seen on other topics, it seems that using Camera screen space any object closer than the Plane distance overlaps, but if I decrease the plane distance I can't see the canvas. I've also tried setting the screen space to overlay, which should fix this, but then the GUI is not shown in the screen. Anybody knows how to prevent the overlapping or at least what should I do for being able to use screen space overlay? Thanks!


How to make sure an object NEVER passes through an edge collider (2D)? In my top down perspective game, I have a ball that bounces off of walls. The ball should behave in a way where it will always bounce off in a 90 degree angle. The ball can only move up, down, left and right and the walls are slanted so that they should always (theoretically) bounce a ball up, down, left or right. On the ball object, I have a small circle collider 2D and a Rigidbody 2D attached, the walls have a single edge collider 2D attached. Approximately one time out of twelve times, the ball will simply pass through the edge collider, so it's not consistent. How can I make sure that the ball always registers the collision? Here's my setup The script I use to move the ball void Update () switch (direction) case 'u' transform.Translate(0f, ballSpeed Time.deltaTime, 0f) break case 'd' transform.Translate(0f, ballSpeed 1 Time.deltaTime, 0f) break case 'l' transform.Translate(ballSpeed 1 Time.deltaTime, 0f, 0f) break case 'r' transform.Translate(ballSpeed Time.deltaTime, 0f, 0f) break Additional info every wall is it's own object with it's own edge collider. the ball always hits the center of the wall because I center the ball object using the center of the wall it touches. Note I had issues with the ball passing through walls even before I implemented the centering.


How can I switch between texture atlases based on the iOS version? How can I switch between atlases (with different resolutions) in Unity based on the runtime iOS version?


problem on enable and disable GameObject I'm trying to enable and disable GameObject (canvas) using this code public int canvaslevel 1 public GameObject one public GameObject two public GameObject three void Update() if(canvaslevel 1) one.SetActive(true) two.SetActive(false) three.SetActive(false) if(canvaslevel 2) one.SetActive(false) two.SetActive(true) three.SetActive(false) if(canvaslevel 3) one.SetActive(false) two.SetActive(false) three.SetActive(true) but it doesn't work!!! error Cannot implicitly convert type int' tobool'


In Unity's Shader Graph how do you access parameters from code? I recently rewrote a shared I was using into Shader Graph. As an example I carried out the color as an external parameter. In my traditional shader to set the color I would call something like MyMaterial.SetColor(" NewColor", color) In the new code, I could not figure out the name of the parameter until I looked at the generated code. Turns out my Color parameter was actually named "Color D027E98" So now my code is MyMaterial.SetColor("Color D027E98", color) Not very pretty and I don't know how constant D027E98 is. Is this the correct way of changing a shader's parameter? Should I be doing something different using Shader Graph Is this number going to change on me as if I update my shader?


Attach a method to every GameObject or use a manager script I'm new to Unity but not new to development so I'm wondering what the standard way of doing this in with Unity. In the scene from the start is an empty GameObject that has a script that contains all of the items in the game. Once the game starts, chest prefabs are going to be spawned in the game and upon interaction they will reveal some random loot from the items script. Is it better practice to have a script on all of the chests that accesses the items script or should I create another empty GameObject as a sort of a chest manager that accesses the item script and keeps track of all of the chests in the game and what all of their loot is.


How to always land a square box in 90 degree How can i Always Land a box in 90 degree Here What i want Here what i don't want public Rigidbody2D boxRb public float jumpSpeed public Vector3 rotation public float rotationSpeed public bool rotationEnabled public float gravityMultiplier void FixedUpdate() if (Input.GetMouseButtonDown(0)) boxRb.velocity jumpSpeed Vector2.up if (rotationEnabled true) transform.Rotate(rotation rotationSpeed Time.deltaTime) if (Input.GetMouseButtonDown(1)) boxRb.velocity Vector2.up Physics2D.gravity.y (gravityMultiplier 1) Time.deltaTime void OnCollisionEnter2D(Collision2D collision) rotationEnabled false Debug.Log("Collided") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX transform.Rotate(0, 0, 90f) void OnCollisionStay2D(Collision2D collision) rotationEnabled false Debug.Log("In collison") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX void OnCollisionExit2D(Collision2D collision) rotationEnabled true Debug.Log("Free") rotationSpeed 10f


How can I convert an html5 web game to an android app? I have already made an html5 game and it is in service. I want to service this at Android app too. I know little about Java or Kotlin, so I think the least risky way is to use a webview. There is already a function to save game data with Oauth authentication. I thought this part should be replaced with google play Oauth. However, there is a problem that the app does not run when the player is offline. (Run the app fails to load any html document) However, if you load a local html file, it will be rejected from the existing firebase SDK because there is no domain. In fact, I know very little about native app development, so I don't know that what I don't know, what I need. What should I do in this situation? Do I need to rebuild my app in Kotlin or Java from scratch? Do I have to use the same engine as Unity? Do I have to rebuild with a framework like cordova? The question may not fit here, but I need help. Please.


How can I get Unity to tell me the battery status of my OS X laptop? How do I get battery status on an OS X laptop in Unity? This is un Googlable I keep finding either mobile stuff (iOS or Android) or people complaining about laptop battery life.


Unity Re import doesn't re import fbx So I have an fbx file with animations and materials on it. Simple stuff. But when I change something on the fbx, like adjusting some animation, then re export as fbx, Unity does not re import the fbx when I do RMB gt Re Import. It shows the loading bar but doesn't actually effect the current mesh by re importing. Is this normal? Is there a way to re import the fbx while keeping the modification I made on the mesh. Like, I changed the Scale Factor and some other things, so I want to keep these while re importing.


Water drops on camera How can I create water drops on camera something like we see in Ripitude GP, I tried using Unity's default GlassStainedBumpDistort shader though its performance heavy on mobile plus it do not let animate water drops.


How can I use Unity AR without cloud services? From what I've read so far, it looks like if I want to build AR apps with Unity, I need to use some kind of cloud service. Is there a way to use AR without sharing my (and my users) data to some 3rd party? If so, how do I do this?


Appropriate use for prefabs in Unity in a coordinate based game? I am wondering how exactly to use prefabs in Unity for my discretely coordinate based game. Should they only be for gameObjects that are exactly the same? Or can they have small variations? Example a treasure chest is interactable and it holds items, so I would make it an empty gameObject, add an interactable component and then an itemContainer component and then drag and drop it into my prefabs folder and delete the instance in the scene. But the question remains, if I make this treasure chest a prefab, how do I edit the itemContainer component of this treasure chest? Moreover, how would I serialize it for later use, and organize my data? Would I have to use external data files and reconstruct the ItemContainerComponent, just for a treasure chest? That sounds like a lot of work. If I edit the itemContainer component as a prefab, then all treasure chests will have the same items. Obviously this is not feasible. Do I drag my treasureChest prefab from the prefabs folder and then simply drop it in the game? That's how most people use it, right? I would prefer not to just drag and drop the prefabs, because I want a more industrialized approach, and I do want some way of saving what is in each treasure chest. I can't for the life of me figure out a good way. Help appreciated! EDIT I see the link provided that marks this as a possible duplicate. However, none of the answers in that link are clear enough to be useful to me, e.g., the "factory." It would be nice if someone could explain the factory idea in more concrete terms.


What is best for 2D movement velocity or AddForce? So I have tried both Velocity and addForce but I'm not getting the result I was expecting which makes me wonder if I fully understand what they do. Move script (test script 1) void Update () if(Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector2(rb.velocity.x, jumpHeight) if(Input.GetKeyDown(KeyCode.A)) rb.velocity new Vector2( moveSpeed, rb.velocity.y) if (Input.GetKeyDown(KeyCode.D)) rb.velocity new Vector2(moveSpeed, rb.velocity.y) Move2 script (test script 2) void FixedUpdate() float x Input.GetAxis("Horizontal") float y Input.GetAxis("Vertical") rbody.velocity new Vector2(x speed, y speed) Both scripts are used independently. Velocity when I press the key down (D or A) it stops after short time but addForce seems to do the same while that is set in FixedUpdate() or Update(), which is confusing as I thought it would keep it moving till the key was released? I have also found that if I press D it moves then stops but if I release D and press again and repeat the player does not move until I press a different move direction. Any ideas?


How people get their game ideas? One thing that always stop me when I want to start making a game is having no idea what to do. How do people get ideas for their game ? I mean realistic ideas for people who are alone with the minimum ressources (no money for assets, blender and unity). I will never stop being impressed by all new concept, mecanics or crazy ideas of game indie developpers come up with, like making game out of random everyday objects. I wish I was able to do that. Do developpers get their inspiration by looking at other games and trying to mix them or change the concept ? Do they look outside trying to come up with what they wish was a game ? Or do they simply walk around and try to imagine a game with whatever they see or reallife situations or concept ?


Runtime Access to Unity 2d Tiles I'm trying to use Unity's 2017 tilemap features. What I would like to do is push a tile's sprite up (change its offset), so that the sprite moves up pixel by pixel and the top of the sprite loops (wraps) back around to the bottom. Basically, I want to animate my "Water" sprite without having to build 20 different versions of the sprite to achieve the same effect. I was able to do this in Rotorz tiles by accessing its Atlas' MainTexture Offset or something like that but this product is discontinued. This animation is similar to the water in classic RPG games like Ultima 4. More than that, I would just love to have runtime access to the tiles to do other things change out the entire sprite on a single tile, change the color, etc. I have made a custom Tile class using this example https docs.unity3d.com Manual Tilemap ScriptableTiles Example.html But this only seems to affect tiles at the time of placement. Is this possible and does anyone have a good example? Docs on this feature are scarce.


How to make an object jump an equal height whenever it hits the ground? So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried Used Physics.CheckSphere isGrounded Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer) if(isGrounded ) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) Used Raycast bool groundHit Physics.Raycast(rayPoint.position, transform.up, rayDistance, groundLayer) if(groundHit) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?


add random force and direction to rigidbodies every x seconds i need to add a windForce to multiple rigidbodies, with random direction and random force every x lapse of time. I'm using InvokeRepeating to update the windDirection so that the rigidbodies can be pushed in a different direction every x seconds. Here's the code void windRotate() windDirection.y Random.Range(0, 360) transform.Rotate(windDirection smooth) if (objectsInWind.Count gt 0) foreach (Rigidbody rigid in objectsInWind) rigid.AddForce(windDirection 10) This way the rigidbodies don't receive any force. I guess the system does not recognize the Vector3 Update of windDirection, so I need to recalculate it, bit I was not able. On the other hand if I use this rigid.AddForce(Vector3.Up 10) the rigidbodies moves but in one direction only, and it's not updated on the next windDirection change. I tried playing with the various Vector3 values (up, right etc..) and different force methods (AddRelativeForce) but nothing changed. By using Debug.Log(windDirection) i know that windDirection is updating correctly ever 3 seconds, so it should also be updated in my methods when i apply the force, but id does not work. Any suggestion? Thanks


Unity Scripting Runtime Version Option Missing I have been trying to open and run my couple months old project in Unity3D, and I'm getting about 500 errors. So idecided to reinstall Unity. On the tutorial for the project, it tells us to make sure the "Scripting Runtime Version" is set to 4.x equivalent. Only problem for me is I cannot see such an option in Unity5.5.4p4. How can I set .NET 4.x in Unity for good?


Conditional Variables in Scriptable Objects While using ScriptableObjects, how can I make some variables conditional? Example Code System.Serializable public class Test ScriptableObject public bool testbool public string teststring public int testint Goal When testbool true then teststring is available to edit, when testbool false then testint is available to edit while the other one is "grayed out".


Unity Guitext object always triggering a collision 2D I have a guitext object which I can drag. I have attached a 2d rigid body. I have also attached the collider with the following code void setCollider() Rect box this.guiText.GetScreenRect () BoxCollider2D boxCollider (BoxCollider2D) gameObject.AddComponent (typeof (BoxCollider2D)) var boxX box.width var boxY box.height Debug.Log ("boxX " boxX "boxY " boxY) boxCollider.size new Vector2(boxX, boxY) I have a sprite with a collider set as trigger. However, it triggers as soon as the game starts and is not anywhere near the trigger sprite. It will only trigger the one time when it starts. My Trigger on my sprite is as follows void OnTriggerEnter2D (Collider2D other) Debug.Log ("Order Right Arm") Debug.Log (other.bounds) EDIT based on answer I have changed the size of the collider to account for the pixel unit difference void setCollider() float pixelRatio (Camera.main.orthographicSize 2) Camera.main.pixelHeight Debug.Log ("Pixel Ratio " pixelRatio) Rect box this.guiText.GetScreenRect () BoxCollider2D boxCollider (BoxCollider2D) gameObject.AddComponent (typeof (BoxCollider2D)) float boxX box.width pixelRatio float boxY box.height pixelRatio Debug.Log ("boxX " boxX "boxY " boxY) boxCollider.size new Vector2(boxX, boxY) Any ideas on how I can get this to trigger only when I drag the guitext over the sprite?


How to make a custom event system framerate friendly? I have a simple event system class GameEvent float executionTime Action action class EventMgr MonoBehaviour List lt GameEvent gt events new List lt GameEvent gt () void Update() float timeNow Time.time for(int i events.Count 1 i gt 0 i ) if(timeNow gt events i .executionTime) exents i .action() events.RemoveAt(i) public void ScheduleEvent(float delay, Action action) events.Add(new GameEvent() action action, executionTime Time.time delay ) Then, I schedule events like this eventMgr.ScheduleEvent(0.1f, () gt EVENT A should be fired first eventMgr.ScheduleEvent(0.15f, () gt EVENT B should be fired second Everything works fine when I play on 60 FPS. Update() is fired once every 0.016s. When I play the game on a device with 20 40FPS things got a little bit tricky. Events seem to run in an incorrect order (Event B fired before event A). The only possible cause is of course the framerate itself. If the game runs at 20FPS, Update() would be called less frequently and both of these events would be fired in the same frame and then, the order of their execution depends on the list itself. What to do here? Is there any trick to prevent this, is there any pattern for accurate, ordered event system in games which is FPS friendly?


NavMeshAgent fails to find paths in certain areas in NavMesh I've been using Unity for about 2 days, and I have a scene with a navmesh. I can click on the NavMesh and get the NavMeshAgents to move to that position most of the time. However, there is a region of the NavMesh where it fails to generate a path to. I technically have two NavMeshes, because I have two different sized NavMeshAgents, but both fail in the same region. Since I'm very new to Unity, I don't know how to diagnose this, much less fix it. How should I go about learning more about this problem? I can path through the affected area, as long as the destination point is on the other side of it. Also, when I put a cube in the middle of the affected area and rebake the NavMesh, the problem area moves to a new location, so it must have something to do with the geometry.


Unity how do I play an intro only the first time the player starts the game? I have an intro animation scene in my game that I want to play the first time the player hits play from the main menu. How do I do this?


Unity How to calculate max distance (range) of a Projectile taking drag into account? I am able to calculate the projectile max distance, but it only works when there is no drag applied on the spherical projectile. I used the formula for range of a projectile as follows void OnCollisionExit(Collision other) if(other.gameObject.name "bat") initVel ballRigidbody.velocity.magnitude lineObject.transform.LookAt(transform) angle Mathf.Abs(lineObject.transform.eulerAngles.x 360) radianAngle Mathf.Abs(Mathf.Deg2Rad angle) maxDistance (initVel initVel Mathf.Sin (2 radianAngle)) g This works well if there is no drag. But as I add drag, the range ends up being far away from where the projectile actually lands. I looked up https en.wikipedia.org wiki Projectile motion Trajectory of a projectile with air resistance but can't quite understand how to use it. Here's a solution I tried if(ballHeight gt maxHeight) maxHeight ballHeight else if(!flag) maxHalfDistance Vector3.Distance(ballFollow.transform.position, centerPoint.position) maxDistance maxHalfDistance Mathf.Clamp(maxHalfDistance, 1f, 1.75f) flag true Basically calculating horizontal distance at max height and multiplying it a value between 1 and 1.75. ballFollow is horizontal position of ball and centerPoint is the launch position. This works perfectly but there is a problem that actual range isn't calculated until the ball reaches its maxHeight. So, how can range of a projectile be calculated taking air resistance in account?


Lerp vs Vector math one better than the other? In Unity3D (all versions, I believe), there is a static function for the Vector3D class called "lerp". It interpolates a point between two points a point, based off a provided percentage related to the desired distance between the two. Alternatively, I could just get the direction I want to go as a point, subtract it from my current position, Normalize() the resulting vector, then multiply that times a speed value. So Is one way faster than another? and Is there a third better faster easier more efficient way I don't know about? Thanks.


How to implement Fog Of War with an shader? Okay, I'm creating a RTS game and want to implement an AgeOfEmpires like Fog Of War(FOW). That means a tile(or pixel) can be 0 transparent (unexplored) 50 transparent black (explored but not in viewrange) 100 transparent(explored and in viewrange) RTS means I'll have many explorers (NPCs, buildings, ...). Okay, so I have an 2d array of bytes byte , explored. The byte value correlates the transparency. The question is, how do I pass this array to my shader? Well I think it is not possible to pass an entire array. So what technique shall I use to let my shader know if a pixel tile is visible or not?


Voxel terrain generation performance problems I am trying to create a minecraft clone to practice some stuff in Unity including Raycasting, terrain generation and player controlls. Terrain is generating without any problem with a perlinNoise. My problem is the then following performance problems. The terrain is only 1 block high with no underlying blocks. Each block constist out of 6 quads with a 64x64 texture. I generate terrain at 200 x 200 size. I can't imagine why 4000 voxels with such simple textures can lag out whilst my pc runs objects with 50k tris and complex textures without any problem. My code ... public int xVoxels 200 public int zVoxels 200 ... for (int x 0 x lt xVoxels x ) for (int z 0 z lt zVoxels z ) voxel script parameter GameObject newVoxel GameObject.Instantiate(voxel) Vector3 position new Vector3() position.x xVoxels 2 x position.z zVoxels 2 z PerlinNoise stripped out for testing position.y 0f newVoxel.transform.position position Solutions I tried Combining meshes Combining all meshes to a single one per material worked wonderfully... until I wanted to interact with each voxel determined by Raycasting from the Camera, I had a raycast hit to the combined mesh and not to my determined voxel Generating the planes myself Instead of using the unity plane object I generated all vertecies myself, same performance problems


Unity Save load in a sandbox game, how to instantiate saved objects I have a game where a player can place GameObjects. I can save load this GameObjects data with using JSON, for example its position, but I cannot think of a good way to tell my save file (and my load) what Prefab it needs to instantiate at position X. How I could this be done in a clever way?


Are there drawbacks to resizing mesh renderer bounds? I had a problem yesterday where some of the meshes were not visible. I figured out the problem, which was that the mesh renderer bounds were not in the cameras field of view. So, in order to make the mashes visible, I'm thinking of either making the bounds of the mesh renderer larger, or moving them forward so they are in the camera view. If I do this, are there any drawbacks, like potential glitches, problems, more strain on the system, etc that might happen?


Rotate meshes with different pivots, equality If I have multiple equal meshes but with different pivots and I make a rotation on the first, is there a way to replicate this rotation to all meshes using a rotation Matrix? For example, if I have a cube, one with it's pivot in the center and another with the pivot outside of the mesh, how can I rotate the first one 90 degrees on the X axis and use it's rotation Matrix to have the second model rotate on itself and not on his pivot? Assuming that when I pass on the rotation matrix to other meshes I can't pass the vector of the pivot, is this possible?


Unity Behavior Designer get gameobject I am trying to create my own action in Behavior Designer. However i cannot seem to get the game object that designer is attached to. if i attempt to do protected Combatant enemyCombatantObject public override void OnAwake() enemyCombatantObject GameObject.GetComponent lt Combatant gt () base.OnAwake() It gives me an error the property or indexer 'Task.GameObject' cannot be used in this context because it lacks the get accessor Can anyone tell me how to get the GameObject that the script is attached to?


is GameObject.Find() a bad idea even for one frame? as I searched GameObject.Find and GameObject.FindwithTag are heavy to work with and for reall projects its better to find repalcements. for a NPC that get instantiated in game it first needs to find player character. for this issue I only can use GameObject.find() . for a scene with lots of objects maybe its heavy for even one frame if there is lots of objects in the scene. is there any way to set the researching object in head of hierarchi and the NPC to only get that?


When to use a blend tree vs state machine for animation Im an experienced game dev hobbiest making my first game with 3d animated characters (in Unity) and am struggling to figure out when to use blend trees vs animation state machines. I understand both conceptually but have seen both blend trees and animation state machines used for character animation in a bunch of tutorials both from Unity and from other sources. I am not sure when why one is better than the other am hoping someone can point me in the right direction. My game is a 3rd person action rpg a'la WoW or KOTOR or Mass Effect (different systems I know but the perspectives and combat styles are kinda close at a high level). I have tons and tons of animations for attacks, blocks, feigns, deaths, walking, running, jumping, shooting etc but I am unclear on how to sequence them together naturally. I have seen blend trees used for locomotion which makes sense to me when trying to keep character motion fluid, but I dont understand how to go from that blend tree to an attack state and nothing I have seen so far has gone past locomotion (no attacks etc). Do I need to make blend trees from my motion states to attack death dodge states? Do I have more control using just state machines? Im a little cautious of state machines because of the transition bloat that is so common with them and because I suspect there is greater potential for janky animation sequencing without blending. I am planning to use the Unity character controller and write my own logic scripts to drive it. For the AI I will be using the built in nav mesh agents. Are character controller animations handled differently than the AI ones? Any insights would be more than welcome! Thanks


Is coroutine as good as a delay() function I'm new to Unity and I was learning the usage of coroutines. Is calling a coroutine as good as a delay() function? Does Unity have a delay() function?


How to efficiently implement a 7 segment display? I want to construct a 7 segment display (as shown below). When you input a number, the script will read the input number and light up the respective segment (change the spriterenderer color to red) to display the number. But I think the code has become too long, since there is 0 9 digit to display, I need 10 if statements, 8 scripts and the function of each statement is to light up the respective segment so it displays the number correctly. Is there any better way to make the code shorter? using UnityEngine public class ClockController MonoBehaviour Rect1 rect1 Rect2 rect2 Rect3 rect3 public GameObject othergameobjectrect2 public GameObject othergameobjectrect3 void Start() int x 1 if (x 1) rect1 GetComponent lt Rect1 gt () rect1.Rectangle1() rect2 othergameobjectrect2.GetComponent lt Rect2 gt () rect2.Rectangle2() rect3 othergameobjectrect3.GetComponent lt Rect3 gt () rect3.Rectangle3() using UnityEngine public class Rect3 MonoBehaviour public void Rectangle3() GetComponent lt SpriteRenderer gt ().color Color.red using UnityEngine public class Rect2 MonoBehaviour public void Rectangle2() GetComponent lt SpriteRenderer gt ().color Color.red using UnityEngine public class Rect1 MonoBehaviour public void Rectangle1() GetComponent lt SpriteRenderer gt ().color Color.red


place sprites in grid pattern within an area I have been trying to do this for a few hours in unity now but cant get my head around it. basically i have 4 points(vector3) 1 each for the 4 corners topleft, topright, bottomleft, bottomright. now i have a sprite that i use as a block what i want to do is basically fit X number of blocks within the four points. see the image below. Icant think of a way to do this right now. I would really appreciate any help in how to achieve this. thanks for helping.


How to add to a MonoBehavior array from an Editor script in Unity I've made an editor which makes a list of tags and splits them into two rows of true or false values (selectable by the user). I then compile this list into a dictionary, and each entry is like so "tag", bool, bool On my MonoBehavior script, I have two arrays string depth tags string angle tags My goal is to essentially save the dictionary data and be able to recall it also have it affect the script. To do this, I've been trying to add to these arrays according to the values found in the Editor script's dictionary. I've done quite a bit of searching and this was the only potential solution I could come up with, but sadly it did not work. EDIT Ok, I can now edit the list (added and subtracted from arraySize when doing operations on them), but I have a new problem The array reports as being twice as large as it should be. The first half of the arrays are correct and as they should be, but the latter half is made up of empty values. When I try to access beyond the first half, Unity throws an error saying that I exceeded the array's max range. EDIT 2 FIXED Answers telling you to increase and decrease arraySize are WRONG OUTDATED. Clearing, inserting, and deleting from the table does that for you! Quick Tip Inserting at index 0 in a serialized table takes care of the element bumping for you! No need to cycle through the table and move each array. void update tags() SerializedProperty depth tags serializedObject.FindProperty("depth tags") SerializedProperty angle tags serializedObject.FindProperty("angle tags") depth tags.ClearArray() angle tags.ClearArray() foreach (string tag in tag list values.Keys) if (tag list values tag 0 true) depth tags.InsertArrayElementAtIndex(0) depth tags.GetArrayElementAtIndex(0).stringValue tag if (tag list values tag 1 true) angle tags.InsertArrayElementAtIndex(0) angle tags.GetArrayElementAtIndex(0).stringValue tag serializedObject.ApplyModifiedProperties()


How to import animation from MotionBuilder to Unity? I have an animation (https i.imgur.com VZcdgHs.mp4) working in MotionBuilder. I have tried exporting the whole thing as an FBX, and also have tried exporting as a Motion File. Either way, when I import it into Unity and set up the Mecanim and Animation Controller and set the animation as the quot Entry State quot animation... My character moves to one pose and then stays frozen. Does anyone know how to correctly get an animation from MotionBuilder to animate a character in Unity?


How can I play and stop a Visual Effect Graph effect through script? Can anyone please give an example lines of code one could use to play stop a VFX through C script.


How to show a float with no decimals I want to show the current health and stamina of the player using GUI.Label. All is working fine however it shows the values with decimals to the millionth (example http gfycat.com SkeletalSinfulKouprey). How would I go about showing only the whole number? My code var cur stamina float var cur health float var staminaRegenRate float 5 var healthRegenRate float 1 regen if(cur stamina lt max stamina) cur stamina staminaRegenRate Time.deltaTime if(cur health lt max health) cur health healthRegenRate Time.deltaTime function OnGUI() GUI.Label(Rect(1,1,100,20), "Health " cur health) GUI.Label(Rect(1,15,1000,20), "Stamina " cur stamina) GUI.Label(Rect(1,30,100,20), "Ammo " cur ammo)


How do I set something when 2 or more touches are pressed? I currently have a working controller with left and right but I want to set the velocity of the character to 0 Stop when 2 or more touches are detected. This is my current working code but I want to make the player stop when 2 touches are detected. void TouchMove() if(Input.touchCount gt 0) Touch touch Input.GetTouch(0) float middle Screen.width 2 if(touch.position.x lt middle amp amp touch.phase TouchPhase.Began) MoveLeft() else if (touch.position.x gt middle amp amp touch.phase TouchPhase.Began) MoveRight() else SetVelocityZero() This is how my game looks like


Objects do not stop when colliding each other while using mouse drag I work on a 2D game and I have multiple objects that the player can control. The objects each have a RigidBody2D and a Collider, and a method OnMouseDrag() with which I can drag the objects. I want the dragging to stop when the objects hit each other. I tried by using this rigidbody2d.velocity Vector3.zero rigidbody.isKinematic true But the objects do not stop. I want exactly like this video. I tried this but it isn't work too. https www.youtube.com watch?v ZfjVR 0ZFHU amp t 270s using UnityEngine using System.Collections public class NewBehaviourScript1 MonoBehaviour bool allowDrag true void OnCollisionEnter(Collision collision) allowDrag false void OnMouseDrag() if(allowDrag) float distance 7 Vector3 mousePosition new Vector3 (Input.mousePosition.x, Input.mousePosition.y , distance) Vector3 objPosition Camera.main.ScreenToWorldPoint (mousePosition) transform.position objPosition if ((transform.position.x lt 0)) Vector3 tmp transform.position tmp.x 0 transform.position tmp if ((transform.position.x gt 4.5f)) Vector3 tp transform.position tp.x 4.5f transform.position tp void OnMouseUp() if ((transform.position.x gt 0) amp amp (transform.position.x lt 0.375f)) Vector3 tr transform.position tr.x 0 transform.position tr if ((transform.position.x gt 0.375f) amp amp (transform.position.x lt 1.25f)) Vector3 fs transform.position fs.x 0.75f transform.position fs if ((transform.position.x gt 1.125f) amp amp (transform.position.x lt 1.875f)) Vector3 tr2 transform.position tr2.x 1.5f transform.position tr2 if ((transform.position.x gt 1.875f) amp amp (transform.position.x lt 2.625f)) Vector3 tr4 transform.position tr4.x 2.25f transform.position tr4 if ((transform.position.x gt 2.625f) amp amp (transform.position.x lt 3.375f)) Vector3 tr6 transform.position tr6.x 3 transform.position tr6 if ((transform.position.x gt 3.375f) amp amp (transform.position.x lt 4.125f)) Vector3 tr7 transform.position tr7.x 3.75f transform.position tr7 if ((transform.position.x gt 4.125f) amp amp (transform.position.x lt 4.875f)) Vector3 tr8 transform.position tr8.x 4.5f transform.position tr8 void Start () void Update() Please help!


Change the min width height of a LayoutElement to scale with the screen size I want to change the Min Width and Min Height configured in my LayoutElement so that they scale proportionate to the screen size. For example, at a screen resolution of 1920x1080, the min width is 300. Then if I reduce my screen size to 1280x720 (one third smaller), then the min width should become 200. How can I do this?


How do I check if animation is of Animation Type "Humanoid"? One can set the Rig Animation type of an animation to quot Generic quot , quot Humanoid quot , etc. How could I check by script if an animation rig has been set to type quot Humanoid quot ?


GameObject with Audio File called with FindGameObjectWithTag returns "Object reference not set to an instance of an object" I'm puzzled with this error because in a different file (see below), I'm doing exact same process to an object to enable disable and works fine. But this new object throws the error, the object has a Script calling an audio file. Enabling manually the Object, and playing the game the audio is fine. I hit the check box to disable it and I get the error "Object reference ..." This audio object is attached to another GameObject which is the character of the game. using UnityEngine using System.Collections using UnityEngine.UI RequireComponent(typeof(BoxCollider2D)) public class carController MonoBehaviour public float carSpeed public float maxPos 4.17f Vector3 position public ParticleHit pr public AudioManager cr public Blast cb audioObj GameObject.FindGameObjectWithTag("policeAuTag") audioObj.SetActive (true) cr.carSound.Play () What am I doing wrong.? I have closed and reopened unity but nothing. I have changed the tag name but same error. I have tried also "FindWithTag" and doesn't work. What is causing the code to throw errors?


My bullet changes the velocity depending on where I click I want to build a little 2D Sidescrolling shooter and I'm now at the shooting script. I already figured out how to shoot a bullet towards my mouse pointer. I got something like this Vector3 shootDirection shootDirection Input.mousePosition shootDirection.z 0.0f shootDirection Camera.main.ScreenToWorldPoint (shootDirection) shootDirection shootDirection transform.position shootDirection.Normalize () Rigidbody2D bulletInstance Instantiate (rocket, transform.position, Quaternion.identity) as Rigidbody2D bulletInstance.velocity new Vector2 (shootDirection.x speed, shootDirection.y speed) Now obviously the bullet goes faster if my Direction coordinates are big and slower if they are smaller. Have you some better code for me or how can I fix that issue? I added now some loop like this, which brings a horrible performance, but kinda works out for the problem, but I'm still looking for a better solution. while (((shootDirection.x speed) (shootDirection.y speed)) lt 20) speed 0.1f So the loop makes sure that the overall speed is always almost the same, but this solution ends in an infinity loop if the values get too small.


Instances in the Unity Profiler Timeline What do Instances mean when you click on an operation in the Timeline section of Unity Profiler? In this example Total 11.90 ms (10 Instances)


Alternate Answer for collision problem? I am building a top down game in unity which works well. In this game, I have a 3D object (red cube) which a player has to control and there are other cubes like white, yellow and black cubes which spawns in the interval of 5 seconds. In each 5 seconds, prefabs of these three villain cubes instantiates and follows the player. There is also a text that says yellow, black and white and changes constantly. For instance, the text is now white and it changes to black within certain interval of time and changes to white in certain interval of time (this is random) So, the player has to collide with the cube same as the the text otherwise the player will die. Now, the problem is I have built the game just fine and can't get to deactivate player when the player hits the unrelated cube. The script is(for instantiating ) public class ColorChecker MonoBehaviour public GameObject text public int hold public float startTime public float startTimebtwSpawn Use this for initialization void Start () Update is called once per frame void Update () startTimebtwSpawn Time.deltaTime if (startTimebtwSpawn lt 0) startTimebtwSpawn startTime hold Random.Range (1, 4) if (hold 1) text 0 .SetActive (true) text 1 .SetActive (false) text 2 .SetActive (false) else if (hold 2) text 1 .SetActive (true) text 0 .SetActive (false) text 2 .SetActive (false) else if (hold 3) text 2 .SetActive (true) text 0 .SetActive (false) text 1 .SetActive (false) The script for destroying the object is public class DestroyCubes MonoBehaviour public ColorChecker colorchecker Use this for initialization void Start () void OnCollisionEnter (Collision col) if (colorchecker.hold 1 amp amp col.gameObject.tag "CubicMonster1") Destroy (col.gameObject) else if (colorchecker.hold 2 amp amp col.gameObject.tag "CubicMonster2") Destroy (col.gameObject) else if (col.gameObject.tag "CubicMonster3" amp amp colorchecker.hold 3) Destroy (col.gameObject) Now, I can obviously check if it is unrelated by a long code like if (colorchecker.hold 1 amp amp col.gameObject.tag "CubicMonster2" amp amp so on) Destroy (gameObject) Rather than writing a long if statement like this, Is there a better way that I can handle this ?


Actions abstraction in Goal Oriented AI I am back with another question about Goal Oriented AIs. To explain my problem, I will use a specific example. In my game, population nodes are spawned on a world map, and important characters called "Migration leaders" can spawn, take in migrants, lead them to a good spot, and then establish a new population node there and finally despawn as they have served their one time purpose. What I want to achieve is having only one action called "MoveToTarget" which has no pre conditions apart from having a target location, and has the effect of setting the fact "Reached target location" to true, which itself is the precondition for other actions. Not sure this is the right way to structure that in the GOAP but that's not exactly my problem, at least I do not think so. My problem is that, since you can't work with actions that take in an argument, I have little notion of how the AI should determine the location which it will move to when the "MoveToTarget" action triggers, for the following reasons Depending on the character type and generally what is happening, each character will think differently about where they're interested in going. Furthermore, what happens when I have to interrupt the AI's "plan" for some reason ? The original target location for, say, transporting migrants is lost ! I do not which to make different actions like "MoveToMigrationTarget" because then I'll have to make many MANY more actions, like "MoveToCombatTarget" or "MoveToRessources" and I do not think that will work as that will make me have to keep a "Migration target", a "Combat target".. in memory even for characters that have nothing to do with either of those. So my question exactly is, where is the AI supposed to do the "practical thinking" in a GOAP ? The Actions themselves must be abstract, and can't take in any argument so I have to somehow have target location(s) in memory and have the GOAP planner know which target corresponds to which action. I could also extend that question to basically any action that need a specific target object to work.


Unity2D Horizontal Scaling to Support Various Aspect Ratios? I am trying to work out how to support various resolutions for my Android game. I have come up with a solution, but do not know how to implement it. Automatically, I am told that Unity vertically scales the screen to match the screen, leaving more room at the sides. How can I change this behaviour? I am hoping to shrunk the game down till it fits horizontally, and filling it the background above and below with more decorative features. How can I achieve this? I'm sorry if there is an obvious answer, I'm quite new working with the Unity UI system. If it makes it any easier, my game is heavily based on UI, and is locked in landscape. BIG EDIT I completely rephrased this question because it was so broad and messy.


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


Unity WebGL Build Why it shows only Empty Folder? i'm trying to built my game, made in Unity 2018.3, and i'm trying to built it in WebGL, but the problem is this built was succeeded, but the Folder is still Empty, and here is the problem occured This was never happened to me before. anybody know how to fix it?


How to make one material on object with many parts inside? I have a weapon witch have many parts, it also have many materials. Do I really need to make it like that? It's like about 8 mats! (


Simulate parallel dimensions subspaces in Unity without colliding coordinate systems I've built an online game with Unity with a very large open world. The server (which can be a local player, or run as a standalone application without a local player) simulates everything around players so for example if there is an object or NPC at coordinates (100,34,20) but there aren't any players nearby then the object is not simulated. Objects are streamed dynamically from a database or generated procedurally depending on the object. Problem I want to enable players to go to other worlds. Of course it is impractical if not impossible to have global coordinates shared across all of these different worlds due to floating point limitations. I'll have to share the limited coordinate system for each simulated world. The issue is the server would still need to render and handle physics of multiple worlds but could now potentially have conflicts with objects and or people on one world appearing in other worlds. Essentially I need a way to divide up these "worlds" into parallel dimensions that are executed simultaneously on the same server (in one Unity scene). Parallel Dimensions A partial solution would be to have some sort of indicator, such as an integer (I'll call it "worldIndex") on each object to indicate which "world" that object exists in. This would work for clients since the server would be able to tell the clients only about objects that are on their world. There would still be a problem on the server itself. Every world needs to be simulated in the same coordinate space. For a local player I could use the "worldIndex" to hide objects that aren't in the local player's current "world". But I still need to simulate physics for every world. Unity's Layers could be used to mask physics interactions between objects. However I would then need to have at least one layer per world and I already use multiple layers for various different interactions. My thoughts are I would need something like a layer I could specify on each GameObject or some way to group a bunch of GameObjects together and instruct the physics system to only allow interactions within the group. But as far as I know no such mechanism exists within Unity. Subspace Pockets Another thought I've had is rather than using the Unity coordinate space directly, I could slice it up into "subspaces" or pockets. Each player would be in their own subspace, unless a player physically enters the same space that is already being simulated by another player, in which case that player would join the same subspace. But then I would have shift around the coordinate systems and it would increase complexity of merging players into and out of these subspaces. I would also have to generate subspaces dynamically as players enter new areas that are not currently being simulated. Even if each world is extremely large, it is not necessary to use the entire Unity coordinate system around each player a few thousand kilometers is more than enough. Overall I think something along these lines is probably the best solution. Multiple Servers I could run one server per "world" and have a hand off process to make it transparent to players. But then I'd have to run multiple server instances and players would not be able to host their own server at least not without a lot of additional overhead. Question So my question is what is the best method for essentially running multiple, parallel simulations within a single Unity scene?


Orthographic Camera settings for a 2D game I'm starting out a 2D wrestling game in Unity 5 and i need some help. The default resolution of game needs to be 320x240. The background sprite that i would be using is 640x480. The camera would move over the background to give it a hovering look. I want the Camera to cover exactly 320x240 resolution. I tried setting the Camera size to 1.2 and it looks approximate but i wanna be sure that the camera is exactly 320x240. By default all the images are set to 100 Pixels per Unit. So my question is How to set the camera to cover exactly 320x240


Simple Car Animation Acceleration Too Slow I am trying to make a very simple car animation where using the arrow keys, I can make a car move around. I am using wheel colliders and some code that goes like this using System.Collections using System.Collections.Generic using UnityEngine public class Car My MonoBehaviour public float Motorforce, Steerforce, Brakeforce public WheelCollider FR L Wheel, FR R Wheel, RE L Wheel, RE R Wheel Start is called before the first frame update void Start() Update is called once per frame void Update() float v Input.GetAxis( quot Vertical quot ) Motorforce float h Input.GetAxis( quot Horizontal quot ) Steerforce print(Input.GetAxis( quot Horizontal quot )) RE L Wheel.motorTorque v RE R Wheel.motorTorque v FR L Wheel.steerAngle h FR R Wheel.steerAngle h if(Input.GetKey(KeyCode.Space)) RE L Wheel.brakeTorque Brakeforce RE R Wheel.brakeTorque Brakeforce if(Input.GetKeyUp(KeyCode.Space)) RE R Wheel.brakeTorque 0 RE L Wheel.brakeTorque 0 if(Input.GetAxis( quot Vertical quot ) 0) RE L Wheel.brakeTorque Brakeforce RE R Wheel.brakeTorque Brakeforce else RE R Wheel.brakeTorque 0 RE L Wheel.brakeTorque 0 When I do this, the car moves but it accelerates too slowly. I changed all the values but I cannot get it to start at a faster speed. Any help is highly appreciated.


Controlling resolution in Unity 3D. Beginner's problems i started working on developing games one month ago. I really like it, although it isnt easy. The problem i have now, is with display resolution after i build game. So far i have been working with 2D Space Shooter game (getting help from the tutorial), everything is working smoothly. The only thing that i hardly understand is the resolution, aspect ratio thing. I have made a game that looks like this I have drawn a gizmos around the allien formation, and written a script with some calculations that everytime formation hits the edge, it goes to the other edge, hits the other edge, and goes to the other edge, and so on and on. In the free aspect movement looks great, but however, then i change the resolution to any other, movement is stuck, or it barely moves. Now here is my question. What should i do, to make the game look and work smoothly on every resolution like it works on the free aspect display? I tried to change formation height and width and so on, but i assume this is not an option. I will add my formation controller script as well(it contains several other things so i printscreened only the code that helps formation to move) Thank you for your time, and sorry if you can't understand everything or something is unclear to you, i'm beginner at game development and English is not my first language.


Character stuck on box collider 2.5D I'm having trouble with my character on a 2.5D platformer. The character get stuck if it collides without reaching the platform's top. Here is a gif showing it http i.imgur.com jmZ6O1K.gifv Both colliders (platform and character) has a physics material with no friction (or minimum). So I don't know why is this happening. Character Collider Physic Material


Why this if logic isnot short circuiting? I've this script in UNITY to check if the hit RayCastHid2D variable has some gameobject with hole tag or a parent gameobject with hole tag when I Raycast... if (hit.collider ! null amp amp (hit.collider.gameObject.tag "hole" (hit.collider.gameObject.transform.parent.gameObject ! null amp amp hit.collider.gameObject.transform.parent.tag "hole"))) Everything is fine until if (hit.collider ! null amp amp (hit.collider.gameObject.tag "hole" but when I enter (hit.collider.gameObject.transform.parent.gameObject ! null amp amp hit.collider.gameObject.transform.parent.tag "hole") it throws a NullReferenceException.... But why? It supposed to short circuit here hit.collider.gameObject.transform.parent.gameObject ! null amp amp if there's no parent gameobject!


Random.range giving me the same value at the same time I created a random direction in x and y axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y axis. How do I not let this happen, I only want one axis to have a value, not both? ERROR HOW I WANT IT TO HAPPEN CODE public Vector2 randomDirection void Awake() void Update() randomDirection new Vector2(Random.Range( 1, 2), Random.Range( 1, 2))


Resize rigidbody in runtime, Box collider OnTriggerEnter not work Scene setting Object A Rigidbody, kinmeatic Box collider, is trigger true. Object B Box collider, is trigger true. Script is on Object A void FixedUpdate() if(increaseScale) transform.localScale transform.forward speed when to stop if ((AEForward transform.localScale.z).sqrMagnitude gt range range) increaseScale false void OnTriggerEnter(Collider other) Debug.Log(other.transform) No log message when part of object A is inside B. And the funny part is if I use it on a sphere collider, it works. (use transform.localScale new vector3(1,1,1) speed instead )


How can I start a new row when instantiating UI elements in a grid? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() int counter 0 imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.Find( quot Slots quot ).transform slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () if (counter 3) raw.anchoredPosition new Vector3(1 , 0.3f, 0) counter 0 else raw.anchoredPosition new Vector3(1 counter gap, 6, 0) counter Update is called once per frame void Update() Now it's creating a line of 3 objects but then when it's filled with 3 objects in a line I want it to move one step down and start a new line of 3 and so on. The problem is I can't make it automatic move one step down with the right gap on the Y and start a new line. I'm doing the new line with this raw.anchoredPosition new Vector3(1 , 0.3f, 0) but the result is that the fourth object is too much down And it should be like this


Building an Octree for terrain generation I've previously implemented marching cubes tetrahedra to render an IsoSurface. It worked (YouTube), but the performance was dire as I never got around to implementing variable Level of Detail based on view distance (or even removing old, distant chunks). I decided to have another go and do it properly this time. I've started by creating an OctreeNode that works as follows when Build() is called. If the chunk is too small to build, return immediately. Work out if the surface passes through this chunk's volume. If so, then decide if we want to raise the LOD (because the camera is close) If so, then spawn 8 children and call the same process on them If not, build the mesh using the current node's dimensions Some PseudoCode OctNode Build() if(this.ChunkSize lt minChunkSize) return null densityRange densitySource .GetDensityRange(this.bounds) if(densityRange.min lt surface lt densityRange.max) if(loDProvider.DesiredLod(bounds) gt currentLoD) for(i 1 to 8) if(children i null) children i new OctNode(...) children i children i .Build() else BuildMesh() return this As well as returning density at a point, the density source can determine the possible density range for a given volume. The LoD provider takes a bounding box and returns the max desired LoD based on camera position frustum, user settings, etc... So... This all works fairly well. Using a simple sphere as the Density source, and showing all nodes And just the leaves However, there are a couple of issues I have to define the initial bounding volume (and the larger it is, the more processing I need to do) At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes qualities. I've thought of a couple of options but both seem flawed Maintain a collection of Octrees and add remove depending on distance. Can't see how I'd mesh across nicely , plus I'd need a list of known empty nodes, especially if I want arbitrary 3D surfaces (to avoid re calculating empty volumes repeatedly) Add a parent Node to the current root, then add seven siblings for the original node. This would work and be on demand but it seems complex to shrink back down sensibly as the player moves through the landscape. It would also make LoD numbers even less meaningful. In clarification to Q below At present, if 2 physically adjacent nodes in the tree are at different LODs, I have some code to coerce the verts such that there's no seam when the meshes are generated. I'm able to do this by knowing the the density for multiple of surrounding nodes. In a scenario where I have 2 independent octrees side by side, I'd have no easy way to retrieve this information, resulting in seams. What's an optimal way to approach this?


How to make UI text longer? I'm working on a menu that needs a wordy description, but I've noticed that it only shows 4 letters, then cuts off and this doesn't seem right. I right click, select UI text and again, it only displays 4 words, even though I can write a lot more there. Am I doing something wrong here? I'm not sure how to get past this and I want to ask if anyone knows how to get past this? It seems like such a strange limit to put on the UI canvas.


How to get Unity's 4.6 UI images to layer over each other perfectly? I've been noticing that if I have two images, lets say squares. I have A as the parent of triangle B. Triangle A and B both have their offsets at their anchors, which are on the 4 corners of it's "box". Triangle A should be behind triangle B, since it renders from top to bottom in the hierarchy (the last item being on top). However as I re size my screen, sometimes triangle A will poke out from behind triangle B. Even if they both are using the same image, and have the exact same dimensions. Whats causing this, and how do I fix it? Additionally, I noticed that while the anchors and offsets can be finely adjusted, the image is not. You have to adjust by certain interval sizes and the image will just snap to that new size rather than adjusting finely as you change the offset or anchors.


How to play a video with audio using an image marker I want to play a video with audio using an image marker. In other words, user scans image marker with phone and a video with audio plays. I am finding plenty with vuforia but how can I do this with AR Foundation?


Importing fbx models made in Cinema4D in unity at runtime In my app I have requirement that I will be given a url and using this url I have to download a fbx model and then show it in the scene. I am able to download the model from the url using the below code. IEnumerator loadModel(string modelName) if (!isDownloaded) string targetUrl "http XXX.XXX.X.XX 3000 " modelName Debug.Log("targetUrl" targetUrl) WWW www new WWW(targetUrl) yield return www if (www.isDone) Debug.Log("downloaded " www.bytesDownloaded) var path System.IO.Path.Combine(Application.dataPath " Resources", modelName) System.IO.File.WriteAllBytes(path, www.bytes) isDownloaded true LoadAndAttachModel(imageTargetTransform, modelName) else Debug.Log(www.bytesDownloaded) And with the below code I tried using loading the model in the scene public void LoadAndAttachModel(Transform parent, String modelName) Debug.Log(modelName) var path System.IO.Path.Combine(Application.dataPath " Resources", modelName) String name modelName.Substring(0, modelName.IndexOf(".")) GameObject load Resources.Load(modelName) as GameObject Debug.Log(load.name) if (load ! null) load.transform.parent parent load.transform.localPosition Vector3.zero load.transform.localRotation Quaternion.Euler(new Vector3(90, 90, 0)) load.transform.localScale new Vector3(0.5f, 0.5f, 0.5f) else Debug.LogWarning("Can't find boneName " parent) but this code always gives exception that the gameobject load is null. I tried with the obj model and that was working fine but with fbx models this is giving exception every time. So how can I instantiate the downloaded gameobject in my scene ?


Can I add non trees to terrain.terrainData.treeInstances on Unity 3D? I need to create a brush in which there will be stones, poles, bushes and other elements of the environment. I bought a Prefab Brush. Whether it is possible to add the objects that I draw on the Prefab Brush scene to terrainData.treeInstances, as regular trees add? Is it possible to use a not prefab tree as an object for the TreeInstance class?


How do I restart tweens in DOTween and Unity? I am trying to restart a couple of tweens when I load a new scene. So far, I have this in MainMenuController.cs void Start () if (currentScene.name "MainMenuScene") Debug.Log("In current scene") tweenList 0 mainMenuText.transform.DOShakePosition(5, 10) .SetAutoKill(false).SetRecyclable(true) tweenList 1 playGameButton.transform.DOShakePosition(5, 10) .SetAutoKill(false).SetRecyclable(true) tweenList 2 exitGameButton.transform.DOShakePosition(5, 10) .SetAutoKill(false).SetRecyclable(true) DOTween.RestartAll(false) However, this does not start when I reload the scene using public void ExitToMainMenu() SceneManager.LoadScene("MainMenuScene") The above is called from another script. Is there some way to restart my tweens when the scene is loaded again?


How to make mobile movement using CharacterController How can i change my movement for mobile i think left and right gonna work but i don't know what should i do for jump private void Update() vector Vector3.zero if (characterController.isGrounded) verticalVelocity gravity Time.deltaTime verticalVelocity 0.5f if (Input.GetKeyDown(KeyCode.V)) verticalVelocity jump else verticalVelocity gravity Time.deltaTime vector.x Input.GetAxisRaw("Horizontal") speed if (Input.GetMouseButton(0)) if (Input.mousePosition.x gt Screen.width 2) vector.x speed else vector.x speed vector.y verticalVelocity vector.z speed characterController.Move(vector Time.deltaTime) I solved the problem this way if (characterController.isGrounded) verticalVelocity 0.5f if (Input.GetMouseButton(0)) if (Input.mousePosition.y gt Screen.height 2) verticalVelocity jump else verticalVelocity jump else verticalVelocity gravity Time.deltaTime vector.x Input.GetAxisRaw("Horizontal") speed if (Input.GetMouseButton(0)) if(Input.mousePosition.y lt Screen.height 2) if (Input.mousePosition.x gt Screen.width 2) vector.x speed else vector.x speed


NavMesh going in the ground I'm trying to do a navmesh. Everything seems to work fine exept that my character in almost completely under the ground. The ground is a plane with a mesh collider. I have baked it and checked my heigth mesh. My character has a rigidbody and a collider. What could be the problem ?


Check If a 2D Collider Is Completely Inside Outside of a Polygon Collider How can I check if one 2d collider (circle, capsule, polygon etc.) is completely inside outside of a polygon collider?


Unity3D multiple objects user rectangle selection I wish to allow the user to select multiple units by click and drag as most RTS do. The issue I have is that the tutorials are either in 2D or only use the transform.position such as this one. Using the transform.position will work for most cases but will not allow the user to select easily as selecting the head or feet of a unit will not work in this instance. It also means I have to do an other script using raycasts for single click selections as it is almost impossible to get the single point of the transform.position with one click. How can I do a proper rectangle selection for a 3D game? By looking at 3D RTS games I own, I noticed that they use a simplified hitbox (usually a cube or capsule).


InvalidOperationException in build only, when trying to select object in a dynamically loaded scene using Linq Here is the relevant code private void Awake() StartCoroutine(LoadScenes()) private IEnumerator LoadScenes() this.sceneLoad1 SceneManager.LoadSceneAsync(Scene1, LoadSceneMode.Additive) while (!this.sceneLoad.isDone) Debug.Log("Loading scene 1...") yield return null this.sceneLoad2 SceneManager.LoadSceneAsync(Scene2, LoadSceneMode.Additive) while (!this.sceneLoad.isDone) Debug.Log("Loading scene 2...") yield return null private void Start() SceneManager.GetSceneByName(Scene1) .GetRootGameObjects() .Where(root gt root.GetComponent lt God gt () ! null) .Select(root gt root.GetComponent lt God gt ()) .Single() .SpreadGospel() (Scene1 and Scene2 are const strings.) The program works fine when running in the Unity editor. However, when I make a development build, I see the follow error message InvalidOperationException Operation is not valid due to the current state of the object at System.Linq.Enumerable.Single God (IEnumerable 1 source) 0x00057 in Users builduser buildslave mono build mcs class System.Core System.Linq Enumerable.cs 1968 at MySolution.GodInitializer.SpreadGospel () 0x00001 in D repos MySolution SourceCode SourceCode GodInitializer.cs 100 at MySolution.GodInitializer.Start () 0x00012 in D repos MySolution SourceCode SourceCode GodInitializer.cs 77 ... which indicates that the scene wasn't fully loaded before I tried to access the God singleton. What changes should I make to fix the problem?


Intellisence doesn't show the ECS API Summaries I am not sure if this is more of an ECS topic problem or packages in general. but it would be really helpful for ECS programming with all the summaries the Unity has provided. For unity engine methods, intelligence show me descriptions and summary of classes and methods, but it doesn't work on packages I guess. I have tested this with all IDEs, AutoComplete doesn't show the description for methods and classes. However, I can go to the declaration of packages source code and see the summary. for example, Below you can see a screenshot in the Jetbrain Rider IDE, as you see when I mouse over OnCreate method it doesn't show the description.


Unity Default Shader Greyed Out I created a pland in Unity 3D and then tried to alter the material. I looked at it's material component, but all the options are greyed out! how do I fix this problem?


How to always land a square box in 90 degree How can i Always Land a box in 90 degree Here What i want Here what i don't want public Rigidbody2D boxRb public float jumpSpeed public Vector3 rotation public float rotationSpeed public bool rotationEnabled public float gravityMultiplier void FixedUpdate() if (Input.GetMouseButtonDown(0)) boxRb.velocity jumpSpeed Vector2.up if (rotationEnabled true) transform.Rotate(rotation rotationSpeed Time.deltaTime) if (Input.GetMouseButtonDown(1)) boxRb.velocity Vector2.up Physics2D.gravity.y (gravityMultiplier 1) Time.deltaTime void OnCollisionEnter2D(Collision2D collision) rotationEnabled false Debug.Log("Collided") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX transform.Rotate(0, 0, 90f) void OnCollisionStay2D(Collision2D collision) rotationEnabled false Debug.Log("In collison") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX void OnCollisionExit2D(Collision2D collision) rotationEnabled true Debug.Log("Free") rotationSpeed 10f


Unity Can not select Desired unity version I'm coming back to Unity after around a 4 month break and finding that opening my past unity projects creating a new project will not create it in the unity version I select(v2018.4), and rather always creates it in v2018.1, regardless of having both installed.(image attached below, file I speak specifically of is RPGprojr) If anyone has a clue to why this is happening any solution would be very much appreciated. I have tried reinstalling 2018.4 version and deleting the 2018.1 version altogether, to no avail.


Unity MenuItem disappears when priority is 100 Create these classes public class MyTestComponent MonoBehaviour CustomEditor(typeof(MyTestComponent)) public class MyTestComponentEditor Editor MenuItem("GameObject XXX DoTest", false, 100) private static void DoTest() Debug.Log("DoTest") save, and check if there is a new menu item in the context menu and it won't be there. Now change the priority parameter to 10 or 1 and try again it won't appear anyway. Sometimes even commenting uncommenting and reloading the editor doesn't help. Is this a bug or am I doing something wrong?


I'm Dragging object by using touch (mobile) it doesn't stop when hit collider I want to make object stopped when it hit collider of another object. But it doesn't stop. How can I fix this? Unity my code is public class move MonoBehaviour public float speed 0.5f Update is called once per frame void Update () if (Input.touchCount 1) Touch touch Input.GetTouch(0) float x 7.5f 15 touch.position.x Screen.width float y 2 transform.position new Vector2(x speed, y)


Multiple viewpoints in Unity3D? I'm working on a 3D game in Unity. The primary view is a top down view, but I am also looking to do target profiles that are true animated versions that reflect the actions of the target. The easiest way to do this, as far as I can see, is to create a second camera, a set offset from my target, facing at it. But how do I show the view from that camera in a small area of the screen? A possibly related question how to handle a mini map? I considered doing this the same way with a camera fixed high above the character that would show the area around him, but there may be a better way to do this, I'm open to any suggestions.


How to animate a MeshRenderer color in Unity 3D? I need to animate MeshRenderer.material.color.a, but fail. Code private void Method() AnimationClip clip new AnimationClip() AnimationClipPlayable playable AnimationClipPlayable.Create(clip) AnimationCurve alpha AnimationCurve.Linear(0, 1, 1, 0) clip.SetCurve("", typeof(MeshRenderer), "Material. Color.a", alpha) gameObject.GetComponent lt MeshRenderer gt ().material.SetColor(" Color", Color.red) Works gameObject.GetComponent lt Animator gt ().Play(playable) Doesn't work


Gameobject rotation around anchored pivot I'm looking for the best way to rotate the Camera(EYES) around a center of my character (Player Prototype) because if I turn around, the Camera enter inside the character. My FPS script is attached to Player Prototype, but the Camera isn't because i have to make particular rotation. So I don't know what I have to do. Have will I make the parent? If I will make it, Eyes will sum rotations to those of the parent. Or maybe I have to handle this in LateUpdate()? With RotationAround() I don't understand how to pass the second argument which is a Vector3, but I have a Quaternion.Euler. So at this point I accept all the advice or examples of what I can do to solve it.


Bug with OnColliderEnter Exit when colliding with multiple objects at almost the same time Unity Version 2017.4.1f1 I currently have a game with a jumping mechanic. I only want the jump to work where you're on ground, so I have planes on top of everything, which, if you are on a plane, then you can jump. This works, however if you are in a position where you are falling and then in quick succession, hit one plane, fall off that plane (like when your centre of mass is hanging off the edge), then land on another plane, at the end of it all, it still thinks you are on the air. Note I don't think this is an error with the velocity of the player, at no point do you go through a collider. So my question is, is there an error in my code (shown below) which I can fix, or should I take another approach towards jumping, thanks. Relevant code below. private bool canJump private Rigidbody rb public float jumpStrength private void OnCollisionEnter(Collision collision) if (collision.collider.CompareTag("Jumpable")) canJump true private void OnCollisionExit(Collision collision) if (collision.collider.CompareTag("Jumpable")) canJump false private void Update() if (canJump amp amp Input.GetKey(Keyode.W)) rb.velocity new Vector3(0, jumpStrength, 0) canJump false Safety measure to ensure consistent jump height Thanks


Any way to combine instantiated sprite renderers into one texture so I can apply into a plane at runtime? So I am procedurally generating a tile set in Unity by instantiating different tiles that only have a transform and sprite renderer components. I managed to pack the sprites using unity sprite packer assigning them a packing tag so that I reduce the draw calls drastically. But Im still having to deal with a great amount of game objects in the scene when the camera zooms out, increasing the batching and giving me problems when I try to apply light to them for example. So I am trying to find a way to combine all these sprite renderers into a texture.So I can then apply this to a plane and Ill only have to deal with one plane gameObject for the map. But I cant figure out how to do this. I cant really use the combine meshes way as they are sprites only, not meshes. I tried taking a screenshot at run time but It comes up a bit blurry. Any idea how can accomplish this? Thank you for your help.


Integrate Stripe with Unity I'm trying to install the Stripe API Library through NuGet Manager in Visual Studio but it installs it inside packages folder of the Project (I.E. before Project's Assets folder) doing this I cannot use the library Using UnityEngine Using Stripe Doesn't recognise this Then I Moved those installed files from packages to Assets folder Uninstalled Stripe from NuGet (as I could now access them in my script by using Stripe) Now these are the main errors that I'm getting PrecompiledAssemblyException Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included for the current platform. Only one assembly with the same name is allowed per platform. Assembly path 0 Assembly 'Assets Temp lib netstandard2.0 Stripe.net.dll' will not be loaded due to errors Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform? Assembly 'Assets Temp lib netstandard1.2 Stripe.net.dll' will not be loaded due to errors Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform?


Organizing objects into groups of 20. C I am building a game where players can build their own airplanes and fly them around. When the vehicle is spawned, all the buildables used to construct the airplane should be placed into groups of 20 to be merged as a submesh to the airplane. When one of the buildables is hit by a projectile and is destroyed, the mesh is reloaded, this time without the buildable that was hit creating the illusion that it was destroyed. I have a few scripts Airplane Core using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class AirplaneCore MonoBehaviour public GameObject airplaneCore public List lt AirplaneBuildable gt buildables public List lt AirplaneChunk gt chunks void Start () AirplaneChunk airplaneChunks airplaneCore.GetComponentsInChildren lt AirplaneChunk gt () foreach (AirplaneChunk chunk in airplaneChunks) chunks.Add (chunk) AirplaneBuildable using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class AirplaneBuildable public string buildableName public GameObject buildableObject public GameObject buildableNormalPrefab, buildableEditorPrefab, buildablePreviewPrefab public Vector3 pos, rot public bool destroyed false public float health 100f, maxHealth 100f And Airplane Chunk using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class AirplaneChunk MonoBehaviour public List lt AirplaneBuildable gt buildablesInChunk Anyone know a way I can take the buildables from AirplaneCore and place them in groups of 20 and assign each group to an AirplaneChunk's buildablesInChunk list? For those who don't know, the gameobjects that are in the AirplaneBuilder script are Buildable Object The actual object representing the component that was placed on the airplane. Buildable Normal Prefab The buildable that is spawned when spawning the plane. Buildable Editor Prefab The buildable that appears on the airplane in the vehicle builder editor. Buildable Preview Prefab Is simply a preview of the buildable and shows what it will look like when placed on the airplane.


Rotate camera around point of view I'm trying to rotate the camera around the view point of the camera. So when the user looks at a build the camera rotate around that building. But the camera does not need to have the building to rotate around. So therefore I want a camera that can rotate around his own point of view. So that the camera behave everywhere the same in the game. How can I achieve this in Unity 5.6?


How Do I Play An Animation In Unity 5.3.4? I am confused on how to play an animation with the new unity version because the flag "Automatically Play Animation" is gone. I cant have the animation connected to my GameObject because it plays right away. using UnityEngine using System.Collections public class FPSCamera MonoBehaviour public float lookSensitivity 5 private float xRotation private float yRotation private float currentRotationX private AnimationClip walking void Start() DONT KNOW HOW TO FIND AND START WALKING ANIMATION CLIP void Update() yRotation Input.GetAxis("Mouse X") lookSensitivity xRotation Input.GetAxis("Mouse Y") lookSensitivity xRotation Mathf.Clamp(xRotation, 90, 90) transform.rotation Quaternion.Euler(xRotation, yRotation, 0)


WebGL .NETCoreApp 1.1 UnityLoader.js SyntaxError expected expression, got end of script After creating a release build of my game using Unity 5.6, I could navigate to the created folder and open the 'index.html' file and my game would load and play normally. However, when trying to integrate it into my WebApp (.NETCore 1.1), I would continually get this error in Chrome, Firefox, IE, etc.. UnityLoader.js SyntaxError expected expression, got end of script Invoking error handler due to TypeError UnityLoader r is not a function


Always operate at Time.timeScale 1? How do I make a specific script always operate at Time.timeScale 1 no matter what? I want it to override even when another script calls Time.timeScale 0 for example.


Build and Run results in an empty window Out of nowhere my builds are broken. The .exe just always gives me this little blank window but it runs fine in the editor. Here are some things I have tried Deleted the previous build files Deleted the Library folder Upgraded to 2020.2.4f1 Uninstalled Reinstalled Unity Deleted AppData Files Deleted branch and pulled it back down (the branch works fine for other people) Here are my resolution and presentation settings


How to store the co ordinates traced by a character in unity C script? I have a navmesh agent with a trail renderer component attached to it, who travels to a pre determined destination based upon user input using unity's built in Navigation system. I want to store the (x,y,z) cordinated of the path traced by the character in some kind of data structure and then I want the camera to trace that exact path, but at some height above so the path(trail renderer) is visible.


Find points inside a closed area I have a 2D rectangular grid (100x100) with 3 types of cell (Empty, Base and Outline). I need to find cells inside the territory formed by Base and Outline cells. For example, in this scheme I need to find the yellow cells. The same algorithm, but with hexagonal grid, was implemented in the game in this YouTube video https youtu.be 6zyMHnBM5x8. Any help on how to achieve that would be very helpful. Thanks.


Chroma depth shader unity I'm trying to reproduce a post effect with unity seen in the answer here. Chromadepth answer For the moment I just manage to reproduce the wave effect with a quick edge detection. I tried multiple textures but can't find one that fit do the same effect. I am using this texture The result for far. Shader "Unlit ChromaDepthEdge" Properties MainTex ("Texture", 2D) "white" Ramp ("Texture", 2D) "white" Threshold("Threshold", Float) 0.1 SubShader Pass ZTest Always Cull Off ZWrite Off CGPROGRAM pragma vertex vert pragma fragment frag pragma target 3.0 include "UnityCG.cginc" struct appdata float4 vertex POSITION sampler2D MainTex sampler2D Ramp Request camera depth buffer as a texture. Incurs extra cost in forward rendering, "just there" in deferred. sampler2D CameraDepthTexture float4 MainTex TexelSize float4x4 InverseViewMatrix float Threshold void vert ( float4 vertex POSITION, out float4 outpos SV POSITION) outpos UnityObjectToClipPos(vertex) fixed4 frag (UNITY VPOS TYPE screenPos VPOS) SV Target Convert pixel coordinates into screen UVs. float2 uv screenPos.xy ( ScreenParams.zw 1.0f) uv.y (uv.y 1) 1 Depending on setup platform, you may need to invert uv.y Sample depth buffer, linearized into the 0...1 range. float depth Linear01Depth( UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv))) float2 uvDist 3 MainTex TexelSize.xy float depthUp Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(0, 1)))) float depthDown Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(0, 1)))) float depthLeft Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2( 1, 0)))) float depthRight Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(1, 0)))) float mean ((depthUp depth) (depthDown depth) (depthLeft depth) (depthRight depth)) 4 Compressing the range, so we get more colour variation close to the camera. depth saturate(2.0f depth) depth 1.0f depth depth depth depth 1.0f depth return depth Use depth value as a lookup into a colour ramp texture of your choosing. fixed4 colour tex2D( Ramp, depth 6 Time.y 4) return lerp(colour, colour 6, mean gt Threshold) ENDCG What did I miss ? Thanks in advance.


How can teams collaborate on Unity 3D projects? With a friend of mine, we are planning to develop a small game to get the hang of game development and teamwork. But since Unity 3D barely supports version control (or at least the free version lacks of it) we have no idea how to efficiently manage teamwork. Sharing tasks in a small project is also seems like a challange for us. I would also appreciate any advice that could be useful for beginner indie developers related to teamwork. )


Unexpected scaling of UI elements after build Unity Web I have an unusual scaling of UI Elements after my build in unity for WebGL Game in Unity Engine Game in Itch.io Has anyone seen this kind of behaviour? any suggestions on what I should look into? Happy to provide more info on the matter. Thanks!


Unity Instantiate GameObject from client on Network I am building a game where a weapon shoots prefab bullets. I am trying to make this a multiplayer game, so the bullets need to be spawned into the Network. What happens right now is that if I shoot a bullet from a host, the bullet is shot, but doesn't appear on the client screen. If I shoot the bullet from the client, the bullet doesn't appear on either screen. In fact, the function CmdShoot() isn't even called, as the Debug.Log("Hello") is not called. Here is the current code public class Gun MonoBehaviour private GameObject bulletPrefab void Update() if (Input.GetMouseButtonDown(0)) owner.GetComponent lt PlayerSetup gt ().CmdShoot(bulletPrefab, transform.position, owner.name, GetComponentInParent lt Weapon gt ().angle) public class PlayerSetup NetworkBehaviour void Start () Disable components if not local player Command public void CmdShoot(GameObject bulletPrefab, Vector3 position, string playerName, float angle) Debug.Log("Hello") GameObject bullet Instantiate(bulletPrefab, position, Quaternion.identity) bullet.name "bullet " playerName bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) Vector3.right bulletPrefab.GetComponent lt Bullet gt ().force) Destroy(bullet, 10f) NetworkServer.Spawn(bullet) Edit This piece of code doesn't work either, gives the same result. No error, but the function is also not called. The Input is detected though void Update() if (Input.GetMouseButtonDown(0)) CmdShoot() Command void CmdShoot() Debug.Log("Shoot") GameObject bullet Instantiate(gunComponent.bulletPrefab, gun.position, Quaternion.identity) bullet.name "bullet " transform.name bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(GetComponentInChildren lt Weapon gt ().angle, Vector3.forward) Vector3.right gunComponent.bulletPrefab.GetComponent lt Bullet gt ().force) Destroy(bullet, 10f) NetworkServer.Spawn(bullet)


Is there a way to display navmesh agent path in Unity? I'm currently making a prototype for a game I plan to develop. As far as I did, I managed to set up the navigation mesh and my navmeshagents. I would like to display the path they are following when setDestination() is fired. I did some researches but didn't find anything about it. EDIT 1 So I instantiate an empty object with a LineRenderer and I have a line bewteen my agent and the destination. Still I've not all the points when the path has to avoid an obstacle. Furthermore, I wonder if the agent.path does reflect the real path that the agent take as I noticed that it actually follow a "smoothier" path. Here is the code so far GameObject container new GameObject() container.transform.parent agent.gameObject.transform LineRenderer ligne container.AddComponent lt LineRenderer gt () ligne.SetColors(Color.white,Color.white) ligne.SetWidth(0.1f,0.1f) Get def material ligne.gameObject.renderer.material.color Color.white ligne.gameObject.renderer.material.shader Shader.Find("Sprites Default") ligne.gameObject.AddComponent lt LineScript gt () ligne.SetVertexCount(agent.path.corners.Length 1) int i 0 foreach(Vector3 v in p.corners) ligne.SetPosition(i,v) Debug.Log("position agent" g.transform.position) Debug.Log("position corner " v) i ligne.SetPosition(p.corners.Length,agent.destination) ligne.gameObject.tag "ligne" So How can I get the real coordinates my agent is going to walk throught ?


Screen Space Camera improper scaling on iOS device only I've reproduced the issue in a simple setup where I have two canvas's, one overlay and one camera. I put an image under both set to maintain aspect ratio, and set them to use anchors for sizing instead of pixels. On iOS the camera space canvas stretches the image improperly, and the overlay is fine. Both have identical settings, with Canvas Scaler set to screen size and to match width. This only seems to happen on older iOS devices, but my sample size is too small to say that for certain. I expect both images to maintain aspect ratio on device, but the image under Screen Space Camera stretches out of aspect ratio. Local Scale on all objects is what I would expect it to be so nothing interesting there. Has anybody run into this issue before or have any idea what might be causing it?


Why when drawing a circle using linerenderer the circle is not complete? using UnityEngine using System.Collections using System.Collections.Generic using System.Linq RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 Range(0, 50) public float xradius 5 Range(0, 50) public float yradius 5 LineRenderer line void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount (segments 1) line.useWorldSpace false private void Update() CreatePoints() void CreatePoints() float x float y float z float angle 20f for (int i 0 i lt (segments 1) i ) x Mathf.Sin(Mathf.Deg2Rad angle) xradius z Mathf.Cos(Mathf.Deg2Rad angle) yradius line.SetPosition(i, new Vector3(x, 0, z)) angle (360f segments) In the screenshot in the left of the circle there is a gap the circle is not perfect completed.


3D infinite platform generation Can't increase space between platforms. (Unity) As seen in the images, changing the value of 'spawnZ' affects the distance between the initial platform and the first generated platform but afterwards it has no affect whatsoever. public GameObject tilePrefabs public float spawnZ 10f public float tilelength public int amnTilesOnScreen 5 public Transform playerTransform Use this for initialization void Start () for (int i 0 i lt amnTilesOnScreen i ) SpawnTile() Update is called once per frame void Update () if(playerTransform.position.z gt (spawnZ amnTilesOnScreen tilelength)) SpawnTile() private void SpawnTile(int prefabIndex 1) GameObject go go Instantiate(tilePrefabs 0 ) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward spawnZ spawnZ tilelength


Help with OnTriggerEntered Canvas UI This seems like it should be incredibly easy and I know there are other posts out there with a similar title, but I promise you I have looked at all of them. All I want is for my canvas that simply says "you win" to appear when I enter an invisible box collider that I have . My canvas is by default set to disabled. public class YouWin MonoBehaviour public Canvas myCanvas private void Start() myCanvas GetComponent lt Canvas gt () void OnTriggerEnter (Collision Collider) myCanvas.gameObject.SetActive(true) This script seems incredibly simple and straightforward, but for whatever reason, when I enter my box, nothing at all happens. Why might this be? What am I missing? As per an answer I also tried public class YouWin MonoBehaviour public GameObject canvas void OnTriggerEnter (Collider Collider) canvas.gameObject.SetActive(true) But had no luck with this either. I've been tinkering to no avail, can you please give me some suggestions?