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


Awake with ExecuteAlways sometime is not called in edit mode I'm trying to use the ExecuteAlways attribute to have a singleton both in edit and play modes. But the Awake() method sometimes is not called in the edit mode. What could be the reason for this and how to fix it? To make a short story long, I've got a not so new Unity project that I believe was developed before the age of ScriptableObjects, so they used MonoBehaviour to store game settings. And they used a kind of "Singleton" pattern that was not very stable and sometimes caused artefacts, such as creating an extra instance in edit mode which could often be saved with the scene accidentally and caused some other problems. The "Singleton" was written this way private static GlobalSettings instance null public static GlobalSettings Instance get if (instance null) instance (GlobalSettings)FindObjectOfType(typeof(GlobalSettings)) if (instance null) instance (new GameObject("GlobalSettings")).AddComponent lt GlobalSettings gt () return instance to fix it I've changed the code (and added the ExecuteAlways attribute) ExecuteAlways public class GlobalSettings MonoBehaviour private static GlobalSettings instance public static GlobalSettings Instance gt instance private void Awake() if ( instance) Destroy(this) throw new GameException( "The ' nameof(GlobalSettings) ' is a singleton!") instance this as I said Awake() is not called sometimes in edit mode and the instance remains null. Another problem is that even when Awake is called it happens after the first call of OnInspectorGUI() where the game settings are needed. Any suggestions and considerations on how to make this code work stable are welcome!


Getting help on collaboration with Unity especially programmers My team and I are currently creating a 3D tower defense game with Unity and are compromised of me a few animators modelers and programmers. However as I am still fairly new to Unity I have trouble figuring out ways to collaborate with them. I know not what practices or advice I could get on the front of developing this game. I was hoping someone here might have some insight as to how best to collaborate with all team members and what one might do to get a better flow of information and help or assistance when working on this project. We are all about an hour or more away from each other so we must work remotely to collaborate. Thank you in advance.


Share a function between two passes inside CG Shader for unity3d I'm writing a shader in CG language for Unity3d. When making transparent object you need to create two similar passes in SubShader. First to render only back faces (with Cull Front) and second to render only front faces (with Cull Back). But the code for vertex and fragment function is the same. Is it possible not to double a code and declare some functions, that would be shared between passes? I want to have something like in my code example. Shader "cool shader" Properties ... SubShader CGPROGRAM need to declare vertexOutput somewhow here float4 sharedFragFoo(vertexOutput i) COLOR How to make smth like this? .... return float4(...) ENDCG pass CGPROGRAM pragma vertex vert pragma fragment frag vertexOutput vert(vertexInput v) vertexOutput o ... return o float4 frag(vertexOutput i) COLOR return sharedFragFoo(i) call the shared between passes function ENDCG pass CGPROGRAM pragma vertex vert pragma fragment frag vertexOutput vert(vertexInput v) vertexOutput o ... return o float4 frag(vertexOutput i) COLOR return sharedFragFoo(i) call the shared between passes function ENDCG


2D UI Image with 1px border randomly gets different thickness I created a test image that is 60 x 60 px, which has a 1px border. I then drop that into Unity as a UI sprite image set to the same size, however the 1px border on a few sides can appear to be thicker, and this ruins the look I am going for especially when there are multiple of them. I've tested in the editor and creating builds (testing resolutions), and the same issue in all cases. It's easier to explain this with images. The left screen shot is the actual size of the image in the game view. The zoomed in image is another case where the borders change thickness, but zoomed in to make it more clearer. I've tried various settings, always the same issue. How can I get the image to appear exactly as it should with no changes to the borders?


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?


Unity3d Rigidbodies overlap even at low speeds I have an issue that I can't solve. There are many questions relating to similar issues and they come down to "change some settings" and "object is travelling too fast". My problem doesn't seem to equate to either of these. I am running through the basic tutorial for the Breakout Game and have added some of my own tweaks to the code, my issue is that even at low speed my ball overlaps with the bricks, rather than bouncing off them. I have read various related questions but nothing seems to fix this for me. Things I've done Set Project Settings Physics2d Maximum penetration For Overlap 0.0001 Set Ball RigidBody Collision detection to "Continuous Dynamic" . Set Brick RigidBody Collision Detection to "Continuous" Forced a speed limit on the ball of 25 15. Which I think is not fast at all, as most the given solutions are talking about situations arising when the offending object is travelling at much higher speeds. Bricks are standard rigidbody cubes and ball is a standard rigidbody sphere. According to this answer I have also set the rigidbody interpolation to "interpolation" for both ball and bricks. But this seems processor expensive and doesn't solve the issue. As well as set the Project Settings Physics Solver Iteration Count to 25. This does seem to have helped somewhat (ball no longer gets "stuck" inside brick wireframes, but still overlaps). Below are some screenshots of my issue and my code. The only aspect that I can't fully account for is that I've added an acceleration function so when ball is launched it accelerates over a course of several seconds to it's max speed. It's start speed is 8 (although the force applied is actually 1000 when launched, ignore that figure), and the max speed is set to 25 15. I don't know enough to say if this is somehow "breaking" rigidbody overlap detection but it seems pretty silly if so. See line 63 below Ball Source Code using UnityEngine using System.Collections public class Ball MonoBehaviour public float initialVelocity 500f public float accelerationSpeed 5f public float MaximumSpeed 15f private Rigidbody rb private bool ballInPlay false void Awake () rb gameObject.GetComponent lt Rigidbody gt () void Update () if (Input.GetButtonDown("Fire1") amp amp ballInPlay false) transform.parent null rb.isKinematic false rb.AddForce(new Vector3(initialVelocity,initialVelocity,0)) ballInPlay true void FixedUpdate () Gradually increase ball speed if (ballInPlay true amp amp rb.velocity.magnitude lt MaximumSpeed) speedUp() Debug.Log("Ball Speed is " rb.velocity.magnitude) Clamp to maximum speed if (ballInPlay true amp amp rb.velocity.magnitude gt MaximumSpeed) rb.velocity rb.velocity.normalized MaximumSpeed rb.velocity.magnitude void speedUp() This is line 63 rb.AddForce(rb.velocity.normalized accelerationSpeed,ForceMode.Acceleration) Why are the rigidbodies not detecting and preventing overlap?


how are semantics used when declaring a struct? I don't understand how semantics are used in shaders. While reading Unity's shader tutorials, I come across this struct v2f float worldPos TEXCOORD0 half3 worldNormal TEXCOORD1 float4 pos SV POSITION and also this struct v2f float3 worldPos TEXCOORD0 half3 tspace0 TEXCOORD1 half3 tspace1 TEXCOORD2 half3 tspace2 TEXCOORD3 float2 uv TEXCOORD4 float4 pos SV POSITION Microsoft's documentation says A semantic is a string attached to a shader input or output that conveys information about the intended use of a parameter. I know there is some kind of interpolation of data because vertices and pixels aren't one to one, thus I think semantics are used for telling the graphics library what to do about the data. But here it uses TEXCOORDX for things like world position and tangent space vectors. They don't seem to have anything to do with UV coordinates. So how are these semantics actully used?


Unity ECS How do I stop an entity from spawning twice? I am implementing a flight dynamics model using Unity's built in ECS package, Entities, and I keep running into one particular issue where the aircraft I'm trying to spawn gets converted into an entity twice. Essentially, I have a singleton Monobehaviour that handles setting up the aircraft entity from a GameObject Prefab. Here's the script public class GameManager MonoBehaviour private BlobAssetStore blobAssetStore public static GameManager main public GameObject planePrefab public float zBound 0.0f public float throttleMaxBound 1.0f public float alphaMaxBound 20.0f public float bankMaxBound 20.0f public float flapMaxBound 40.0f public float throttleMinBound 0.0f public float alphaMinBound 0.0f public float bankMinBound 20.0f public float flapMinBound 0.0f public State state public Properties prop Entity planeEntityPrefab EntityManager manager private void Awake() if (main ! null amp amp main ! this) Destroy(gameObject) return main this manager World.DefaultGameObjectInjectionWorld.EntityManager blobAssetStore new BlobAssetStore() GameObjectConversionSettings settings GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore) planeEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings) SpawnEntity() private void OnDestroy() blobAssetStore.Dispose() void SpawnEntity() Entity plane manager.Instantiate(planeEntityPrefab) prop new Properties( 16.2f, 10.9f, 2.0f, 0.0889f, slope of Cl alpha curve 0.178f, intercept of Cl alpha curve 0.1f, post stall slope of Cl alpha curve 3.2f, post stall intercept of Cl alpha curve 16.0f, alpha when Cl Clmax 0.034f, parasite drag coefficient 0.77f, induced drag efficiency coefficient 1114.0f, 119310.0f, 40.0f, revolutions per second 1.905f, 1.83f, propeller efficiency coefficient 1.32f propeller efficiency coefficient ) state new State( 0.0f, time 0.0f, ODE results 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, roll angle 4.0f, pitch angle 0.0f, throttle percentage 0.0f flap deflection ) float3 position new float3(state.q1, state.q3, state.q5) manager.SetComponentData(plane, new Translation Value position ) After a little bit of commenting here and there, I was able to determine that the following two lines are responsible for creating two separate entities, though the latter is the only one I'm capable of manipulating using the system. It's also worth mentioning that these two entities are virtually identical in the Entity Debugger, except for the fact that the first entity contains the quot prefab quot tag. planeEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings) and... Entity plane manager.Instantiate(planeEntityPrefab) Is there a way to spawn this entity without both showing up in the debugger or is this unavoidable? If not, is there a way to remove the entity with the quot prefab quot tag from the world? Thanks! )


Unity reconstruct position from depth I am using Unity and I want to reconstruct position from depth and frustum corners in pixel shader. I am doing this In my App, I calculate view space corners of the far frustum plane and pass them to shader. (this is correct, I render spheres in world coordinates at corners and they are there). In Full screen Vertex shader Select corner based on corner index calculated from texcoord. This is also correct, I have rendered colors. This is passed to Pixel Shader as "ray" In Pixel shader float3 normal float depth DecodeDepthNormal(tex2D( CameraDepthNormalsTexture, i.uv), depth, normal) depth Linear01Depth (depth) position depth ray Reconstructed position is incorrect. The result I got for cube, that covers whole viewport is this But in reality, I should have this (or similar image with white, blue, pink for different handness) My output is somehow "blured" around the middle. Why ?


How to handle movements of objects in a platformer with a cylindrical map? I was wondering what would be the best approach for a game with a perspective like Resogun, where the world wraps around in a cylinder In my opinion, the easiest approach is to have a quot Center Parent quot for each moving object Offset the child object by the wanted radius Rotate the parent gt The objects will move, though this will become super limited very quickly, especially if you want to do any sort of physics. The 2nd approach is math x centerX cos(angle) radius x centerY sin(angle) radius Now i wonder if there is another way, I was thinking of another method which basically consist of changing the Forward direction of the moving objects based on their position in quot the circle quot , so basically the objects always move forward but adjust their rotation according to their position so they are always facing the right angle. My main question is that if you want to create a puzzle platformer game like Limbo for example, but in a quot cylindrical quot map like Resogun, how would you tackle it ? Thanks!


Art style for a character that has frequent visual changes during gameplay I'm creating a game with a bodybuilding fitness theme. The camera will almost always be focused on an inclined front view of a character who will be evolving very frequently during the game as the player 'levels up' the musculature of each part of the character such as arms, legs, chest, etc. I've been doing some research trying to figure out the most economical yet effective way to incorporate this visual mechanic of letting individual parts of a character independently increase in size and detail and have come up somewhat short, most likely due to my complete lack of experience when it comes to art (my experience is mostly in programming). I was thinking 2D would be best for this game, however maybe this one character should be in 3D? Would a low poly style fit these requirements, or should I look towards something akin to sprites or hand drawings? The games interactivity will be purely through menus so that doesn't need to be taken into account when dealing with the problem of this character. I would like this character to have some animations, of course, however I'm not sure if that fits the scope of this single question.


Upgrading Unity from 5.1 to 5.3.4 has broken game, specifically models made in Blender I recently decided to upgrade Unity after putting it off for some time as I have a rather sizable project started in 5.1. I knew there would be some hurdles, however, I have had very little luck in getting the game back up and running in the new version. My Blender model animations seem to be gone and many of the faces are disappearing. For example a characters arm is just missing and other similar issues across models. The warning I'm getting seems to be due, at least in part, to a shader I'm using attached to a prefab, however, when I change it to even the standard shader Im still getting the warnings and the issues persist. My question is Is there something I'm missing in the upgrade process that can make the transition easier, because right now, it would seem I need to recreate all of my Blender assets and reassign all of my materials and not be able to use some of my shaders? The process in which I upgraded was very simple. I just opened the project folder with the new version of Unity and rebuilt the project for the new version. Any help from anyone who has experience migrating projects between different versions of Unity would be appreciated.


How can the player select his weapon among many? I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https youtu.be Dn BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded? I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project. sorry for the bad english


How to organize level blocks in an Infinite runner I'm working on an Infinite Runner game. I have created many level blocks(sections) with different obstacles and pick ups for the player. They are positioned and placed manually, in such a way, to give the player a challenge. I thought that making every block a prefab and placing every obstacle and coin as a child of that prefab is going to be easier for me..because the player is going to run and these block prefabs are going to be randomly spawned in front of him and then destroyed after the player gets past them. It worked well. Then I wanted to make a change on my coins. So naturally I took the coin prefab, made the changes, and applied them hoping that the change is going to take effect on all my blocks... Well..it didn't. Then I found out that nested prefabs don't work in Unity, so now I have to reorganize everything again? How do I create organized level blocks, and then make them randomly spawn in front of the player? Is there any other option besides prefabs? Don't tell me I have to use a script for every block? Think about Banana Kong, Temple Run, Subway Surfers. The levels seem random, but it's an organized randomness with certain portions of the level repeating themselves. That's what I'm trying to do, and I don't know how to organize it...


How to move object on local space not object space in unity I am watching this (game dev, space parenting amp rotation) Sebastian Lague video and found that there are three spaces actually (not two) and these are world space, local space and object space. World space The static space (0,0,0) Object space related to the object space Local Space related to the parent of the object I am amazed that i didn't find the distinction between these two spaces(local and object) on official unity forms but actually it exists. My question is that why there is no Space.Local? I found that there are Space. Self and Space.World. Space.Self is refer to object space. I can move my object to object space using this void Update () transform.Translate(new Vector3(0,0,1) Time.deltaTime 2,Space.Self) And i can move my object to world space using this void Update () transform.Translate(new Vector3(0,0,1) Time.deltaTime 2,Space.World) but there is no support for local space that i could move the object to local space (means move the object related to its parent object). There is a fair distinction between Local and Object space but unity didn't consider it i guess or i am wrong.


How to calculate 1st, 2nd, 3rd place and draw conditions in local multiplayer game? I have a local multiplayer game with an end of round screen that pops up after each round. I'm trying to figure out the logic to calculate the 1st, 2nd, 3rd place from a maximum of 4 players. I also want draw tie conditions. It's possible for 2 or 3 players to get the same score. The score is just an int for each player. I've been struggling with this for a while... Any help appreciated, even if its just some pseudo code to point me in the right direction. Also, I'd like to avoid using Linq if possible, as I've heard it doesn't play nice with Unity. Thanks Edit Below is what I've managed to come up with for determining the draw conditions. Doesn't seem to hold up in all cases though... Surely there's a simpler approach? PlayerScore orderedScores m scores.OrderByDescending(ps gt ps.score).Take(4).ToArray() 1stPlacePlayers.Add(orderedScores 0 .playerNumber) if (orderedScores 0 .score orderedScores 1 .score) 2 player draw 1st place 1stPlacePlayers.Add(orderedScores 1 .playerNumber) if(orderedScores 0 .score orderedScores 2 .score) 3 player draw 1st place 1stPlacePlayers.Add(orderedScores 2 .playerNumber) if(orderedScores 0 .score orderedScores 3 .score) 4 player draw 1st place 1stPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 1 .score orderedScores 2 .score) 2 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 2 .playerNumber) if (orderedScores 1 .score orderedScores 3 .score) 3 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 2 .score orderedScores 3 .score) 2 player draw 3rd place 3rdPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 1 .score orderedScores 2 .score) 2 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 2 .playerNumber) if (orderedScores 1 .score orderedScores 3 .score) 3 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 2 .score orderedScores 3 .score) 2 player draw 3rd place 3rdPlacePlayers.Add(orderedScores 3 .playerNumber)


Unity detecting edge of mesh or end of mesh I'm trying to create procedurally generated tiles and I've reached a point where I need to figure out the boundaries of the mesh or the outer vertices of the mesh. RaycastHit hit if (Physics.Raycast(bound i .v2, Vector3.forward, out hit)) if (hit.distance gt 2) I've tried raycasting all the vertices, but still can't get the vertices of the edge. The mesh does have a collider. any help on how i would go about this is appreciated, Thanks.


How to load scene after a set delay? I have tried using IEnumerator and Invoke("method",delay in seconds). My first scene is just an image with my studio name on it. I have script that will load the next scene ("Main Menu") 3 seconds after the first scene is loaded. For this, I tried using IEnumerator and Invoke with 3 seconds delay before calling Application.LoadLevel. However, on the device, game is launched, unity splash screen is displayed and "Main Menu" scene appears. it looks like the image scene loads while unity splash screen is displayed and by the time unity screen is completed, the image scene has done executing. Is there any way to ensure a scene stays on screen before loading the next scene? I could add a button that player should tap to start game. But I don't want to do that.


How to select multiple frames from a sprite sheet in unity I have a sprite sheet and cannot figure out how to select multiple frames in unity 5.5 I am watching a tutorial and it doesn't say how to do it. Is there a button I have to press while clicking or is it having to change some settings?


Hierarchical "Select GameObject" Dialog or names with prefixes? I am attempting to connect a series of teleporters with entrances inside a single scene. Once the player touches a teleporter he is moved to another place. I am doing this by simply connecting two game objects as shown in the following screenshot. The particle system in the center of the upper side is used as teleporter, the red line indicates the game object where the player will be transported to. Sadly, this results in an utter mess when attempting to select a new entrance the teleporter should link to. There is no way to guess which entrance corresponds to which side and dice So the tl dr of my problem would be this The name of the object that should be selected is meaningless when isolated. It's the path to the object (or in other terms the name of some parent) that is relevant. I would see three possibilities to solve this, but sadly I haven't gotten around to find out how to do any of them. Switch the "Select GameObject" Dialog to use the same hierarchical view as used in the scene viewer. Is there a hidden option somewhere in Unity that I overlooked? Somehow prefix the names of my entrances programatically. Is there a way to include the path to a certain game object in its name? My whole approach is backwards and I am doing something in a not Unity friendly way. But what would be the "correct" way to do this?


Volumetric lighting not working when building and running game I have a volumetric lighting system implemented into Unity and when I am making the game and run it in the Unity editor the volumetric lighting shows up. When I build it and run it though it doesn't. I think this is caused because it has not exported the script with the volumetric lighting so I exported it again and it still didn't show. I dont know what is up. Any suggestions would be appreciated. In Unity with the thing working Unity built game


Coding style about collisions with geometry Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector Dot (GameObject) Sphere w Collider When I run into the sphere trigger, I can trivially say "Get me your parent and check if it's a Dot" However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent(). What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.


Gradle Build Error Unity 2019.1.6 I found out that unity has deprecated the internal build system and has defaulted to gradle. I've not built with the gradle build system before, and now after upgrading to unity 2019.1 full version, I can't build an android project. And, I installed the android module using unity hub, what can I do to fix this? Screenshot1 Screenshot2 Screenshot3 Screenshot4 Screenshot5 Screenshot6


What is the correct way to raycast on click? I am using raycast from screen point to detect if the user has clicked touched on something. The following fails 1 10 times at first I thought due to the raycast missing the subject below, but after adding in the drawline i realise that it randomly doesn't even fire layerMask declared with correct layers void FixedUpdate() if(Input.GetMouseButtonDown(0)) Debug.Log("click") Ray ray RaycastHit hit if(Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)) Debug.Log("You clicked on " hit.collider.gameObject.name,hit.collider.gameObject) If I run this in Update() function instead, it will work perfectly so FixedUpdate() seems to understandably cause the missed clicks... but i'm told I should always run the raycasts in FixedUpdate() for physics optimisation. Maybe I should split this basic action over 2 functions? A friend said i need an event handler


Calculating t value to use with Hermite interpolation I'm developing an FPS in Unity using Photon for networking. The Photon provided interpolation is very basic so I decided to roll out my own using the Hermite spline. It works good and is significantly better than the provided interpolation. However, I was wondering what's the correct way to choose the t value. In a perfect world, it should be incremented by deltaTime timeBetweenPositionUpdates. However, that doesn't work since even if the tickRate is set to 10 for example, sometimes the client sends it at 9.5, and then at 10.2 and so on and so forth. This means that we can't have a constant increment rate for the t value since it'll either lag behind or move too fast and we'll run out of buffered frames. What I decided to do is to send the time between frame updates as well and interpolate using that. But, this also isn't perfect by any stretch of the imagination and the receiving client will soon lag very much behind. What I'm doing now is using a multiplier on the t value such that if there is more frames in the buffer than we want to have then it'll speed the interpolation up, and if there's less than how many we want in the buffer then it'll slow the interpolation down. This works pretty well, but it's a hack I believe. Is there a better way, or a proper way to do this?


Collider Effeciency Question I'm creating a game where hundreds of rockets with colliders attached are shooting at a player. Should I write my script where 1 The player script reads the collision from hundreds of rocket colliders or 2 Each rocket collider updates information when colliding with the player Thanks!


Insert 3d text to the front face of a cube GameObject I want to add a text to a cube in Unity. I have a cube which has a 3d text as a child. I am using the below UnityScript to write on the 3d text var countdown int 200 function Update() GetComponent(TextMesh).text countdown.ToString() I am trying to write show the text to the front face(or very close) of the cube but I am failing. EDIT My difficulty is to make the text appear in the front side face of the cube, like it is written on it. Attaching the text or the script to any object is not an issue My last failed try was to use the below lines var tm gameObject.AddComponent(TextMesh) tm.text countdown.ToString() Any ideas?


Instantiate a new Prefab I m developing a little 3D game to improve my Unity C development. However, I am faced with a recurring error that I cannot find the solution to In fact, I always get the error Nullreferenceexception Object reference not set to an instance of an object when I want to create a new Gameobject in my scene. I wish I could spawn a bonus based on a percentage of chance when an enemy is killed. So I created a Bonus mother class and a Bonushealth daughter class. So Bonushealth inherits the Bonus methods. Here s the mother class code (Bonus) using UnityEngine public class Bonus MonoBehaviour protected int lifeTime public int LifeTime get gt lifeTime set gt lifeTime value protected void RandomDropBonus(Transform posEnemy) int chance Random.Range(1, 100) switch (chance) case int n when (n lt 100) Instantiate(Resources.Load lt GameObject gt ("bonus"), new Vector3(posEnemy.position.x, posEnemy.position.y, posEnemy.position.z), Quaternion.identity) break public void RandomBonus(Transform posEnemy) int rdn Random.Range(1, 1) Debug.Log(rdn) if(rdn 1) RandomDropBonus(posEnemy) Here's the daughter class code (BonusHealth) using UnityEngine public class BonusHealth Bonus public GameObject prefabHealth Start is called before the first frame update void Start() LifeTime 10 I call the RandomBonus() method when an enemy is killed (in the Enemy class), Here's is the code private Bonus bonus bonus.RandomBonus(this.transform) if I make Bonus bonus new Bonus() I always get this error ArgumentException The Object you want to instantiate is null. In my prefab folder is contained my bonus prefab named bonus. I added the Bonushealth script on it. I did a lot of research on the Internet but no way to find a solution Thanks in advance )


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


A collider defined as intersection of two colliders I'm working in unity and I have the following problem Suppose you have an object that's very similar to say the intersection of say the corner of a cube and a ball, and you want a nice collider for this object. First option is to simply use the mesh collider option but this is apparently not very efficient, and if for example the sphere is very smooth, there might be a lot of polygons and that could be a problem. Second, you could just fill the object with various simple colliders. However, both of the above options seem unnecessarily complicated it would seem natural to me to somehow work with both colliders the sphere collider and the cube collider. To determine if the object is touching something, the requirement is that both the cube and sphere collider are touching something, not just one of them. I don't know how the actual collision checks work, but I would expect that say in the second option I wrote above (placing a few small colliders inside the object), a collision check sees if any of the colliders is touching a collider of some other object so there is an option for "union" type of collision check (see if any of the colliders are touching something). Similarly, I would expect there would be an option of checking whether both the colliders are touching something, but I'm not aware of it. Either way, I would appreciate ideas on how to implement a good collider for this problem, and whether there's a way to implement it by the way I described, using the "intersection" of two colliders.


Why are my animated objects (from Blender) always playing at the global origin in Unity? I created and animated a sledgehammer in Blender 2.67b using an armature. The sledgehammer has one animation (created using the Action Editor) called "Idle". I parented the imported sledgehammer to an empty GameObject and set the sledgehammer's position to (0, 0, 0). I then moved the parent GameObject to where I want it in the scene. When I launch the game, the animation plays but the sledgehammer child always re positions itself to be at the global origin, no matter where I place the parent GameObject. See the image below Notice how the sledgehammer's position goes from (0, 0, 0) to ( 1087, 3, 1149). The armature has a single bone and has the sledgehammer object as a child. I've spent about 4 hours looking this up on the Internet, but it seems like parenting the animated mesh to an empty GameObject worked for everyone else except me. Anyone else experience this? I've tried both .fbx and .blend files.


Isometric ball moving in unity 3d. Ball moving in opposite direction I am making a game in unity 3d. It is a 2.5d game which mean it is in isometric. The game is quite simple. Player drags mouse and a trajectory will be shown just like in angry bird and when player release the mouse the ball will move to the direction. However I am having issue here that once mouse is released the ball moves in exact opposite direction. I am not able to understand what the real issue is. My code is as follows For Ball public class BallScript MonoBehaviour public Rigidbody2D rbg public CircleCollider2D col public Vector3 BallPos get return transform.position void Awake() rbg GetComponent lt Rigidbody2D gt () col GetComponent lt CircleCollider2D gt () public void PushBall(Vector2 force) rbg.AddForce(force,ForceMode2D.Impulse) to enable rigidbody so we can use projectile again public void ActivateRb() rbg.isKinematic false public void DeActivateRb() rbg.velocity Vector3.zero rbg.angularVelocity 0f rbg.isKinematic true The code for my game manager is as follows public class Trajectory MonoBehaviour SerializeField int dotsNumbers SerializeField GameObject dotsParent SerializeField GameObject DotsPrefab SerializeField float dotSpacing Vector2 pos float timeStamp Transform dotsList void Start() hide trajectory in the start Hide() PrepareDots() void PrepareDots() dotsList new Transform dotsNumbers for(int i 0 i lt dotsNumbers i ) dotsList i Instantiate(DotsPrefab,null).transform dotsList i .parent dotsParent.transform public void UpdateDots(Vector3 ballPos,Vector2 forceApplied) timeStamp dotSpacing for(int i 0 i lt dotsNumbers i ) pos.x (ballPos.x forceApplied.x timeStamp) pos.y (ballPos.y forceApplied.y timeStamp) (Physics2D.gravity.magnitude timeStamp timeStamp) 2f dotsList i .position pos timeStamp dotSpacing public void Show() dotsParent.SetActive(true) public void Hide() dotsParent.SetActive(false) Here is the code for gamemanager using singleton pattern Camera cam public BallScript ball public Trajectory trajectory public static GameManagerScript Instance void Awake() if(Instance null) Instance this SerializeField float pushForce 4f bool isDragging false Vector2 startPoint Vector2 endPoint Vector2 direction Vector2 force float distance void Start() cam Camera.main ball.DeActivateRb() void Update() if(Input.GetMouseButtonDown(0)) isDragging true OnDragStart() if(Input.GetMouseButtonUp(0)) isDragging false OnDragEnd() if(isDragging) OnDrag() void OnDragStart() ball.DeActivateRb() startPoint cam.ScreenToWorldPoint(Input.mousePosition) trajectory.Show() void OnDrag() endPoint cam.ScreenToWorldPoint(Input.mousePosition) distance Vector2.Distance(startPoint,endPoint) direction (endPoint startPoint).normalized force direction distance pushForce trajectory.UpdateDots(ball.BallPos,force) void OnDragEnd() ball.ActivateRb() ball.PushBall(force) trajectory.Hide() The ball moves in exact opposite direction where I wish to send it by dragging. Is it because of the isometric issue or I am missing something?P.S have applied negative force as well as in case and have also made change in direction formula rbg.AddForce( force,ForceMode2D.Impulse) direction (startPoint endPoint).normalized


How to filter list of all objects in Unity project, by their type? I want to filter the list of project objects in unity, and view all objects of specific type in the project. (by type, not by name) How can I do that?


Handheld video playback pauses when going to the home screen Put an MP4 movie in your StreamingAssets folder and play it with Handheld.PlayFullScreenMovie("MyMovie.mp4", Color.black, FullScreenMovieControlMode.CancelOnInput) Then, in the middle of the movie, go to the home screen and then go back to the game. The video is paused. You can't resume it because upon tapping the screen the video will disappear because of the CancelOnInput parameter (which I want to keep). So how can I make it so when the player returns to the game, the video resumes? I don't want to show video controls. I am using Unity Pro 5.4.2, running on an iPhone 7 with iOS 10.1.


Fail to install ML Agents (python packages) I have been trying for hours to install pytorch and mlagents with cmd, however I am getting pretty much the same error for each package I'm trying to install ERROR Could not find a version that satisfies the requirement typing extensions (from torch 1.7.0) (from versions none) ERROR No matching distribution found for typing extensions (from torch 1.7.0) I'm using python version 3.7.9, attaching a screenshot of the cmd. Also, as you can probably notice I'm getting a repeating warning every time I'm using pip and I'm not sure of it's something to avoid WARNING Retrying (Retry(total 0, connect None, read None, redirect None, status None)) after connection broken by 'ReadTimeoutError( quot HTTPSConnectionPool(host 'pypi.org', port 443) Read timed out. (read timeout 15) quot )' simple torch


Formatting Unity data for communication with a REST API I am pretty new to unity but I am not new to programming. I am building a Hololens application in Unity 2017.2 and it communicates with a REST api that I built. I am using Unity as a front end more or less and it manages my state. Coming from the web developement world, I have my server converting my models into JSON and I am sending that as a response. For the most part, it works well but since Unity works on an older version of C , I am having issues working with the JSON data, mainly if the data type is not a string, int, float, or double. For example, if my model contains a date data type I am having issues converting it back into a c model or even arrays are proving to be a pain. I don t want to rely on unity packages too much as most I have tried don t do what I need but I am open to any good ones if you know of any. My question is, what is the best way to send data from my API to Unity? Should I send xml or a csv instead? Or even a more C native approach? (If that makes sense)


How to stack sprites? I am currently working on a 2D game in Unity, I am using Animation Controllers Animators for the different slots of armor on the character. The scripts set the Animation to the player object and that seems to work out alright for the most part. However when I walk long distances without stopping it seems like the armor tends to drift away from the player object and I haven't been able to find out why. This will update the player and then update all his inventory to match his position. public void UpdateMovement() if (IsActive true) float input x Input.GetAxisRaw("Horizontal") float input y Input.GetAxisRaw("Vertical") bool playerMoved false Vector2 movement new Vector2(input x, input y) float delta Time.deltaTime if (movement ! Vector2.zero) animator.SetBool("IsWalking", true) animator.SetFloat("x", input x) animator.SetFloat("y", input y) playerMoved true else animator.SetBool("IsWalking", false) playerMoved false PlayerController.transform.position new Vector3(input x, input y, 0).normalized delta Inventory.UpdateMovement(input x, input y, delta, playerMoved, PlayerController.transform.position) This code is for each slot to update it's position. public void UpdateMovement(float x, float y, float time, bool isWalking, Vector3 pos) animator.SetBool("IsWalking", isWalking) if (isWalking true) animator.SetFloat("x", x) animator.SetFloat("y", y) animator.transform.position new Vector3(x, y, 0).normalized time animator.transform.position pos So my question is, what is the best approach for layering armor sprite animations on a player in Unity 5?


How to get good movement synchronization in a networked game (action shooter) I've spent the last two days trying to get good movement interpolation with Photon in Unity but I can't get anything that I'm happy with. I've tried several methods but none satisfied me. My understanding is that I better use some kind of interpolation (as opposed to extrapolation dead reckoning) because in my game the players can change direction fast. I've tried lerping between the current position and the last received authorized position, I've tried lerping between the old and the new authorized position, but nothing gives me the right amount of responsiveness smoothness. What can I do? Sample code public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.IsWriting) do we have authority over this object? stream.SendNext(transform.position) stream.SendNext(transform.rotation) else newNetworkTime Time.time oldPosition transform.position oldNetworkPosition networkPosition networkPosition (Vector3)stream.ReceiveNext() networkRotation (Quaternion)stream.ReceiveNext() void RemoteMovement() float t 1.0f ((newNetworkTime interpolationPeriod Time.time) interpolationPeriod) transform.position Vector3.Lerp(oldPosition, networkPosition, t) transform.rotation Quaternion.Lerp(transform.rotation, networkRotation, Time.deltaTime movementSpeed)


How can I use one method and also switch between a coroutine and the main method? Now I'm using two methods, one as StartCoroutine and one not. What I want to do is to have just one method and when I set the StartCoroutine variable to true or false when the game is running I want it to switch between the coroutine and the main. Is there a simple way to do it with one method and not two, if not, how do I achieve this? using System.Collections using System.Collections.Generic using UnityEngine public class Grid MonoBehaviour public GameObject gridBlock public int worldWidth 10 public int worldHeight 10 public bool StartCoroutine false public float spawnSpeed 0 void Start() if (StartCoroutine) StartCoroutine(GenerateGridSC()) else GenerateGrid() private void GenerateGrid() for (int x 0 x lt worldWidth x ) for (int z 0 z lt worldHeight z ) GameObject block Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject block.transform.parent transform block.transform.name "Block" block.transform.tag "Block" block.transform.localPosition new Vector3(x, 0, z) IEnumerator GenerateGridSC() for (int x 0 x lt worldWidth x ) yield return new WaitForSeconds(spawnSpeed) for (int z 0 z lt worldHeight z ) yield return new WaitForSeconds(spawnSpeed) GameObject block Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject block.transform.parent transform block.transform.name "Block" block.transform.tag "Block" block.transform.localPosition new Vector3(x, 0, z)


Detect Mouse Enter on An oval shape image in unity I have an image that is attached to a panel and I want to detect On Pointer Enter and exit. The event is working fine but currently, it is working on the full image while I want to detect this event on an inner oval shape. Actual the remaing are of the image is transparent.


Unity Small holes of light seems to go through my blender mesh So, I am currently working on a low poly terrain in Blender which will be flat shaded in Unity. It all works great, however I am working on a cave for the terrain, and I seem to be getting these small odd light artifacts I have tried to highlight them with the read circles. If you look carefully, you can see the small holes. The odd thing is, the entire mesh should be completely solid. Here's a screenshot of the cave entrance in blender (which is the floor I'm looking at in Unity) All normals of the faces seems to be facing correctly, and mesh has simply been modelled by extruding edges from existing parts of the mesh, so there shouldn't actually be any actual holes. Does anyone have any experince with this kind of problem?


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


How can I make a shader that renders only the scene's skybox? I am trying to replicate the following image There are a few ways about doing this that involve camera stacking, layers, etc. Is it possible to create a shader that will only render the skybox?


Rotation in animation not working I have a model of an SMG with arms exported from Blender and set to generic rig in unity import settings. I was creating an animation for this model in Unity Animation tab, it included changes in position and rotation of the individual parts like magazine and left arm and gun itself. Then when I was satisfied with how the animation worked (I saw it by pressing the play button IN THE ANIMATION TAB). My problem is that when I click play IN THE GAME TAB there is no rotation and some movement, only some parts move (but not rotate). Does anyone know what could be my problem? I am not sure what screenshots to post so tell me what you need to see and I'll add some. Thanks in advance.


(Unity) How to show a texture on a model at a specific Pixels Per Unit? I'd like to use flat 3D models alongside pixel art sprites, but I have no idea how to make the textures applied to these models have the same Pixels Per Units as the sprites. How can I achieve this effect in Unity? thank you


Error Cannot create FMOD Sound instance for resource sharedassets0.resource when splitting application binary in Unity I'm trying to publish an Unity app to the PlayStore. Since the size of the app is over the limit of 100MB, I need to split the binary. So I selected the option Split Application Binary in Unity. However, when I try to launch this application (either by downloading it on the Playstore or putting the .apk and the .obb directly on my device from my computer), I get the following errors on Android SDK monitor 01 24 11 38 52.442 E Unity(25004) Error Cannot create FMOD Sound instance for resource sharedassets0.resource, (File not found. ) 01 24 11 38 52.442 E Unity(25004) 01 24 11 38 52.442 E Unity(25004) (Filename Line 882) 01 24 11 38 52.442 E Unity(25004) Function SoundHandle Instance Instance() may only be called from main thread! 01 24 11 38 52.442 E Unity(25004) 01 24 11 38 52.442 E Unity(25004) (Filename Line 25) The application freezes at the "Made with Unity" splash screen. This is not happening when I don't use the Split Application Binary option and put the .apk directly on my device from my computer. I'm using Unity 5.4.0.


How can I create light shafts like Journey's in Unity? I'd like to create cartoon looking sun light shafts that look very close (or identical) to the ones in very well known and loved games like Journey and Ori How can I accomplish this?


How to handle large scene game in unity3d? I have a very very Big Huge scene to load and I can't load it at once. The one strategy i know is that I divide the scene into multiple scenes and load my scenes it into async manner as my character controller move. I am moving my character controller and accordingly loading (its near)scenes by matching its position. But it is not smooth. . . How do I load big scene smoothly? what will be the strategy? Is this right strategy which I am doing or there is any other feasible and easy to use solution available.?


Hide back button bar of android mobile while playing game I just want to hide back button bar of android mobile while playing the game. I tried to make it close by pressing back button,it getting close but its always visible. please help..


How to disable spring joint in unity 3d How can I disable Spring joint in unity 3d, since disabling feature only available in 2d mode, I am not able to find any way to disable it via script


Wrong contineous rotation to car In my 2d game, I want to rotate car face based on collision detected. But at present after 3 to 4 collision its doing continuous rotation only rather than moving straight after collision. Here is my straight movement related code myRigidbody.MovePosition (transform.position transform.up Time.deltaTime GameManager.Instance.VehicleFreeMovingSpeed) For better collision purpose, I have used Rigidbody position change approach. Here is my collision time code public void OnCollisionEnter2D (Collision2D other) if (other.gameObject.CompareTag (GameConstants.TAG BOUNDARY)) ContactPoint2D contact contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (transform.up, contact.normal) direction reflectedVelocity if (direction ! Vector3.zero amp amp pathGenerator.positionList.Count lt 0) float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg Quaternion targetRot Quaternion.AngleAxis (angle 90f, Vector3.forward) transform.rotation Quaternion.Slerp (transform.rotation, targetRot, 0.1f) if (Quaternion.Angle (transform.rotation, targetRot) lt 5f) transform.rotation targetRot direction Vector3.zero Rotation get applied within other code so that car was changing its face correctly and that method not affecting here that I have checked by placing debug statement. Share you side thought for this.


Unity 2D Bullet AddForce does not work I got the following code public ParticleSystem PS public GameObject origin public float thrust 1.0f public GameObject bullet private GameObject bullet Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButtonDown(0)) Debug.Log("Pressed left click.") PS.Play() bullet Instantiate(bullet, origin.transform.position, origin.transform.rotation) bullet.GetComponent lt Rigidbody2D gt ().AddForce(origin.transform.forward thrust) Where everything is working except the AddForce, the bullet is just dropping out of my weapon. I've made some research and my script seems to be correct. The bullet has attached a circle collider and a rigidbody2D. Update This did not change anything bullet.GetComponent lt Rigidbody2D gt ().AddForce(origin.transform.forward thrust, ForceMode2D.Impulse) And this neither bullet.GetComponent lt Rigidbody2D gt ().velocity origin.transform.forward thrust It's weird, because all of these should work actually.


My gameObject does not move, when it returns to its original scene I have a map where I have a 2d Ship as gameObject, which can be dragged with the finger to travel between islands and do the corresponding activities, when the player finishes playing on the island he returns to the map where the ship is, but when you try to drag it, you can not do it anymore. for the change of scene use collisions, as shown in the code. public string name public void OnTriggerEnter2D (Collider2D other) if (other.gameObject.tag "Player") SceneManager.LoadScene(name) Does anyone know the cause of this error? The drag code public float moveSpeed 5f private Vector3 mousePosition private Rigidbody2D rigidbody private void Awake () rigidbody GetComponent lt Rigidbody2D gt () private void Update () if (Input.GetMouseButton (0)) mousePosition Camera.main.ScreenToWorldPoint (Input.mousePosition) mousePosition.z transform.position.z Vector3 targetPosition Vector3.MoveTowards (transform.position, mousePosition, moveSpeed Time.deltaTime) rigidbody.MovePosition (targetPosition)


Accessing enum value in other scripts I am attempting to make a global MaterialAssign script that I can assign to anything and have an enum selector in the inspector to assign a material type. This would then drive hitFX and soundFX variation in other scripts. My selector script MaterialAssign.cs using System.Collections using System.Collections.Generic using UnityEngine public class MaterialAssign MonoBehaviour public enum MatSelection defaultMat, metalEnemy, metalWall, dirtWall public static MatSelection currentMat Attempt at usage in another script if (MaterialAssign.currentMat MaterialAssign.MatSelection.metalEnemy) selectedHitFX bulletMetalEnemyFX else if (MaterialAssign.currentMat MaterialAssign.MatSelection.metalWall) selectedHitFX bulletMetalWallFX I have no errors in the console BUT the enum selector doesn't show up in the inspector, so I'm assuming no value is ever passed. I read that enums can't have a static value, but not sure how to handle that. Any assistance would be most appreciated or alternate approaches welcome! I'm purposely trying to stay away from tags, but can go down that path if needed.


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


Navigating to android app settings permission from unity I am trying to rout from my unity application to android app settings permissions. till now I achieved to rout to app settings, But i want to take 1 step more to go inside permission i mean App Settings Permissions. Code try if UNITY ANDROID using (var unityClass new AndroidJavaClass("com.unity3d.player.UnityPlayer")) using (AndroidJavaObject currentActivityObject unityClass.GetStatic lt AndroidJavaObject gt ("currentActivity")) string packageName currentActivityObject.Call lt string gt ("getPackageName") using (var uriClass new AndroidJavaClass("android.net.Uri")) using (AndroidJavaObject uriObject uriClass.CallStatic lt AndroidJavaObject gt ("fromParts", "package", packageName, null)) using (var intentObject new AndroidJavaObject("android.content.Intent", "android.settings.APPLICATION DETAILS SETTINGS", uriObject)) intentObject.Call lt AndroidJavaObject gt ("addCategory", "android.intent.category.DEFAULT") intentObject.Call lt AndroidJavaObject gt ("setFlags", 0x10000000) currentActivityObject.Call("startActivity", intentObject) endif catch (System.Exception ex) Debug.LogException(ex) Help if it is possible... any help is appropriated. Thank in advance.


Why doesn't this weaponpickup script work properly? I'm making an FPS game. My guns are disabled at the start. When I use this script to pick up and hold one weapon at a time, requiring that you click J to drop it, it simply doesnt work! There are two guns using the same pickup script with different prefabs, and all the prefabs but "MyGun" and "playertransform" are the same. using System.Collections using System.Collections.Generic using UnityEngine public class weaponpickup MonoBehaviour public GameObject MyGun public GameObject WeaponOnGround public GameObject DroppedWeapon public Transform playertransform Use this for initialization void Start () MyGun.SetActive(false) Update is called once per frame void Update () if(Input.GetKeyDown(KeyCode.J)) Instantiate(DroppedWeapon, playertransform.position, playertransform.rotation) MyGun.SetActive(false) public void OnTriggerEnter(Collider other) if(other.gameObject.tag "Player" amp amp MyGun.activeInHierarchy false) MyGun.SetActive(true) WeaponOnGround.SetActive(false)


2d games unity vs Flash do people find unity better than flash for 2d games while unity is 3d engine , or Flash still better because it's made for 2d games and flash can get the job done faster ,and now flash is better for ios android 2d games . so what platform is the best for 2d games?


How can I calculate spotlight lighting in Vertex Fragment shader in Unity? I've written a vertex fragment shader for my game. It uses 3 textures and represents a floating water on the wall (so I have 1 texture for water, 1 for geometry and the last one is mask) so it looks like this But I also need a spot light attached to the camera to lit my geometry, and this is the single dynamic light source on the stage. Well, I can use a surface shader to take dynamic lighting into attention, but I want to avoid using them because it will be much larger and its execution will be much slower. Besides, I need only one dynamic light source, so I can (can I?) just calculate its lighting in the shader, and pass a position direction to the shader using material.SetVector(). It is something like float4 frag(FragmentInput i) COLOR0 float4 col i.col tex2D( Texture, i.uv) col.a tex2D( AlphaMask, i.uv).r 2 if(col.a gt 0.25f) it's water, just return the scrolled texture color float4 l1 tex2D( WaterTexture, float2(i.uv.x, i.uv.y Time.y 16)) float4 l2 tex2D( WaterTexture, float2(i.uv.x, i.uv.y Time.y 8)) return float4((l1 l2).rgb, 0.5f) else it's geometry calculate spot light lighting float lit ... calculations here ... return col lit Is it possible to do this? Will it work faster than the surface shader?


Unity camera has no preview, and is not moving I have set up a camera in 2D mode. There is only one camera named "Main Camera", and it is set to "MainCamera" (tag). In console I can see camera's transform position updating, but it isn't moving. And if I adjust field of view for perspective mode, it doesn't take effect. That is saying, when I hit "Play", the game view is always fixed. In inspector there is no camera preview neither (see image 2). The only effect I can make to camera is changing the background color. EDIT Main camera is placed right at root. And the camera is supposed to be looking at a small area EDIT Thanks for DMGreygory pointing out, I'm using default canvas settings and this won't move with camera in play mode. (btw, if not best under canvas, where exactly is suggested to apply those graphics?)


Character Movement and Collision with Ragdoll Rigidbodies Colliders? I have a player character that I'm moving with a character controller script and it is moved by applying velocity to a Ridigbody. This works when I have a rigidbody component on the player but my character also has ragdoll colliders and rigidbodies on each body parts (set up with Untiy's ragdoll wizard). What I'd like to do is remove the ridigbody and collider that are on the player and use the ragdoll colliders and rigidbodies instead for physics movement and collision. But it's not working! When I use the rigidbody from the skeleton Root and try to apply velocity the character won't move (animation plays but she keeps running on the same spot). What do I need to do to get this working? Another issue is that if I leave the player rigidbody on but remove the large capsule collider I can move the character but collision doesn't work and she runs through static objects. I already tried with convex set to true on static meshes but it doesn't make a difference. Does somebody know what causes movement and collision not to work with the ragdoll rigidbodies and colliders?


Rendering Unity across multiple monitors At the moment I am trying to get unity to run across 2 monitors. I've done some research and know that this is, strictly, possible. There is a workaround where you basically have to fluff your window size in order to get unity to render across both monitors. What I've done is create a new custom screen resolution that takes in the width of both of my monitors, as seen in the following image, its the 3840 x 1080 How ever, when I go to run my unity game exe that size isn't available. All I get is the following My custom size should be at the very bottom, but isn't. Is there something I haven't done, or missed, that will get unity to take in my custom screen size when it comes to running my game through its exe? Oddly enough, inside the unity editor, my custom screen size is picked up and I can have it set to that in my game window Is there something that I have forgotten to do when I build and run the game from the file menu? Has someone ever beaten this issue before?


Dragging text element into Text variable unity 4.6 So I was trying to make a UI element to keep score in a unity (4.6) project and I'm having trouble assigning the 'Text' element to the Text variable. So I have the text element with the script attached to it. At the moment the script is empty except from some variables being created, here it is using UnityEngine using UnityEngine.UI public class TextController MonoBehaviour public Text text public int score1, score2 Use this for initialization void Start () Update is called once per frame void Update () text.text "a" "" In the unity UI the Text variable shows but it is empty, and it will not let me drag the 'Text' object from the hierarchy into the variable box. It shows the outline like its going to accept it but remaing 'None (Text)' when I release the click. I tried importing an already working UI from another project into this but when I added it to the hierarchy it removed the text element again (just for reference the text worked perfectly in the other project). Also a screenshot of the hierarch just in case Is there a problem with the scipt or the prject or have I messed something else up? Edit Clicking the circle next to the text variable brings up the window to select the element. Mine shows up without anything in it. I expect it to show the text object I have made.


How can I make sure the rotation has finished or the transform is facing the target? void FixedUpdate() LiftProcess() MoveProcess() TiltProcess() if (hasRotate true) Vector3 targetDirection helicopterPlatform.transform.position transform.position Vector3 newDirection Vector3.RotateTowards(transform.forward, targetDirection, lookAtSpeed Time.deltaTime, 0.0f) transform.rotation Quaternion.LookRotation(newDirection) I want ot make a check IF transform.rotation has finished and the transform is facing the newDirection then change the flag hasRotate to false. What check and how should I apply ?


Agent trying to reach same position as other agents, instead start spinning in place I create units in my game and have a rally point where they should walk to when created, like Age of Empires. My problem is that since they compete for this position after a while, sometimes they end up doing this https gfycat.com decentquestionableandeancondor https gfycat.com densehonoredgalapagosalbatross As you can see one of the guys cant reach the rally point, so he starts rotating. I realize this has to do with stopping distance, but no matter how high I set the stopping distance this eventually becomes a problem when there are many enough units. And if I set it too high they dont walk to the rally point at all, since its not THAT far from the building they spawn from. Is there any way to manage this scenario? i.e just making him go as close as he can, and then stop? My AI Script using UnityEngine using UnityEngine.AI RequireComponent(typeof(NavMeshAgent)) public class BaseAi MonoBehaviour HideInInspector public NavMeshAgent agent HideInInspector public NavMeshObstacle obstacle float sampleDistance 50 Transform mTransform private void Awake() agent GetComponent lt NavMeshAgent gt () obstacle GetComponent lt NavMeshObstacle gt () mTransform transform private void Start() agent.avoidancePriority Random.Range(agent.avoidancePriority 10, agent.avoidancePriority 10) void LateUpdate() if (agent.isActiveAndEnabled amp amp agent.hasPath) var projected agent.velocity projected.y 0f if (!Mathf.Approximately(projected.sqrMagnitude, 0f)) mTransform.rotation Quaternion.LookRotation(projected) lt summary gt Returns true if the position is a valid pathfinding position. lt summary gt lt param name "position" gt The position to sample. lt param gt public bool SamplePosition(Vector3 point) NavMeshHit hit return NavMesh.SamplePosition(point, out hit, sampleDistance, NavMesh.AllAreas) public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false public void Teleport(Vector3 point) agent.Warp(point) lt summary gt Return true if agent reached its destination lt summary gt public bool ReachedDestination() if (agent.isActiveAndEnabled amp amp !agent.pathPending) if (agent.remainingDistance lt agent.stoppingDistance) if (!agent.hasPath agent.velocity.sqrMagnitude 0f) return true return false public void ToggleObstacle(bool toggleOn) agent.enabled !toggleOn obstacle.enabled toggleOn void OnDrawGizmos() if (agent null) return if (agent.path null) return Color lGUIColor Gizmos.color Gizmos.color Color.red for (int i 1 i lt agent.path.corners.Length i ) Gizmos.DrawLine(agent.path.corners i 1 , agent.path.corners i )


How to handle keyboard controls in Arkanoid game I'm making simple Arkanoid clone in Unity with both keyboard and mouse controls available. When I gave it to my colleagues to test one complain was that keyboard controls are not precise enough,. The problem is that I don't really know how to find a balance between two factors If I make paddle speed too high then it lacks precision to position it just right to make ball go to the last few blocks. If I make paddle speed too slow then it's going to be difficult to reach ball in time. I thought about it and I don't recall any version of arkanoid that solved that problem. Currently I have 3 ideas Make two (or more) keys to go in each direction. One will go faster and another slower. Instead of making multiple buttons lets allow player to change speed of paddle during the game. Probably by entering number from 0 9 on keyboard. Just leave it like it is now. Other control schemes are not intuitive enough. Does anyone have any experience with this? Which approach is the most reasonable? Edit Code I'm using Vector3 pz transform.position pz.y y pz.z 0 if (Input.GetKey(KeyCode.LeftArrow)) pz.x Time.deltaTime KEYBOARD SPEED MULTIP if (Input.GetKey(KeyCode.RightArrow)) pz.x Time.deltaTime KEYBOARD SPEED MULTIP pz.x Mathf.Clamp(pz.x, 60, 60) rb.MovePosition(pz) I simply move paddle by constant speed which includes timedelta. And then I clamp position to screen.


Why does the code still working? I was reading an Arduino code regarding counter http www.toddholoubek.com classes pcomp ?page id 58 . Since I do not own a Arduino microcontroller and would like to know the result, I test the concept of the code by using a game object in unity, the void loop() in Arduino function like the void Update in unity. The scale of game object function as if a counter and I tried generate the state 1 or 0 depend on the value of transform.position.y so I can check is it the increment of object scale happen one time only for each transition from state 0 to state 1. For the code below, it worked as intended but when if I transfer this line quot PreviousState CurrentState quot into the if statement quot if ( birdWasLaunched amp amp GetComponent().velocity.magnitude gt 0.1 amp amp transform.position.y gt 1 amp amp CurrentState ! PreviousState) quot , it still working? Been thinking for sometime couldn't see the sense why it still working. As Initially value of previous state current state 0 when transform.position.y lt 1 since the object is launch from a position.y lt 1 upward. After y gt 1 ,value of current state switch from 0 to 1, which made the equality CurrentState! PreviousState become true, then the scale gain 1 increment to its original value. Which is followed by the command line PreviousState CurrentState to made the equality of CurrentState! PreviousState become false in next frame update otherwise object scale increase according to fps. After the object drop to position. y lt 1 due to gravity, the value of CurrentState 0 and PreviousState 1 , I then launch it again upward in y axis direction until position.y gt 1 which the current state become 1 at this time the equality of PreviousState CurrentState at this moment but the scale still get one increment? This is the part where I don't understand. using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour int CurrentState 0 int PreviousState 0 Vector3 OldPosition Vector3 DistanceDifference float TotalDistance 0 Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 void start() OldPosition transform.position private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1 amp amp transform.position.y gt 1 amp amp CurrentState ! PreviousState) transform.localScale new Vector3(transform.localScale.x 1, transform.localScale.y 1, transform.localScale.z 1) PreviousState CurrentState if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1 amp amp transform.position.y gt 1) CurrentState 1 if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1 amp amp transform.position.y lt 1) CurrentState 0


Find References In Scene of scriptable object unity asset shows incorrect results I'm trying to work out why my game is loading a large sprite atlas that I don't think it should be. The snapshot view of the profiler shows that the atlas is loaded. The references pane shows that it's loaded through a scriptable asset object. That object does indeed reference the sprites in the atlas but I don't think the object is referenced in the scene at the moment. The game boots to this scene, so the atlas should not be loaded. I've replicated this profiling on both the editor and on android, so it's not an editor only thing. When I right click on the scriptable object in the project view, while the game is running, and Find References In Scene, it shows a few game objects. None of these objects seem to reference the scriptable object. None even have monobehaviours with fields for this type of scriptable object. Some are new UI button objects, that have Canvas Renderer, Image and Button scripts only. None of which could be referencing this scriptable object. Has anyone seen this behaviour before? What's going on?


How to rotate an object around one end of line till its lies on the line From the image below, I would like to rotate a game object C around a point A of a line (made using a line renderer) by an angle d to position p1 till C is on the same line joining points A and B over a given period of time. Preferably using a coroutine. Please note that the angle d is not known. How can I achieve this?


Modifying an array of quaternions I have written the following function to inter change 2 specific elements of an array of quaternions private void ChangeRotations(Quaternion rotationsArray) Quaternion bone1Rot rotationsArray (int)Bone1ID Quaternion bone2Rot rotationsArray (int)Bone2ID Quaternion temp bone1Rot bone1Rot bone2Rot bone2Rot temp But when I use Debug.Log to see if this has taken effect, I realize that the 2 array elements are unchanged. What am I doing wrong here?


SetActive doesn't work for GameObject I'm using Unity 2D for my game and I'm facing a weird problem. I have a GameObject (an image) in my scene with a button attached to it. When the player is out of the screen, the image that works as a GameOver panel appears and in case of enough coins, you can resume the game. Everything works fine but when the image appears and I click on button to resume, the image doesn't disappear while the function for decreasing number of coins still works. Here is my script in which di() is for die and but() for button using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using CodeStage.AntiCheat.ObscuredTypes using CodeStage.AntiCheat.Detectors public class UIManager2 MonoBehaviour public static ObscuredInt coin score 0 public Text coin text public Slider slider public Slider slider1 public Slider slider2 public GameObject bul public bool reverse public float timer public int delay 1 public float speed 0.5f public GameObject pause public AudioSource aud new AudioSource 3 void Start () coin score ObscuredPrefs.GetInt ("Score") StartCoroutine (elapsed ()) slider1.minValue 0 slider1.maxValue 20 bul GameObject.FindGameObjectWithTag ("Player").GetComponent lt Plane19 gt ().bullet void Update () timer Time.deltaTime if (timer gt delay amp amp reverse false) timer 0f slider2.value if (timer gt delay amp amp reverse true) timer 0f slider2.value speed coin text.text coin score.ToString () ObscuredPrefs.SetInt ("Score", coin score) if (slider2.value 10) bul.SetActive (false) reverse true if (slider2.value 0) bul.SetActive (true) reverse false public void di() pause.SetActive(true) GetComponent lt AudioSource gt ().Pause() Time.timeScale 0 aud 0 .Play() aud 1 .Pause() aud 2 .Pause() public void but() pause.SetActive(false) Time.timeScale 1 aud 0 .Pause() aud 1 .UnPause() aud 2 .UnPause() GetComponent lt AudioSource gt ().UnPause() UIManager2.coin score 2 IEnumerator elapsed () yield return new WaitForSeconds (2f) slider.value StartCoroutine (elapsed ())


Using Steering Wheel in Unity Is there any way to use a steering wheel in Unity? All I find online is people with the same problem. The numbering on the axis are not the same as with keyboard input. In some cases left is 1 and as you turn it more to the left it gradually goes down to 0 even though you are still turning left


How is this rotation done? There is a video here that shows how the camera rotates around Leon. The camera rotates around Leon in a circle, this is not difficult, but I don't understand the timing logic. Once given a short push, the camera keeps rotating for a few more milliseconds. If the camera would only be rotated during the real mouse movement, the camera would not keep rotating a bit after there is no more mouse movement. However, in this video, the camera rotates a few more milliseconds even after the last mouse movement. How could this be accomplished? Specifically, I would like to ask if somebody can tell me if the developers add some extra movement in the direction of the mouse movement which they then "smooth out", or if they "smooth out" the end of the user's mouse movement. Thank you!


How does Unity's Collider.Bounds work? From waht I understand, Collider.Bounds are the sides or bounds of the collider of the GameObject (at least for a cube with a BoxCollider). But I got a result that I wasn't expecting when I tried moving a cube continuously downwards and drawing the bounds with lines. While moving frame by frame, the collider bounds seemed to be not bounding the cube (or at least that's what my test is showing, if my test is correct). Here's 3 frames of screenshot What I did for this is create a new 3D project, add a Cube, then added a single script and then added this script to the Cube. The whole script is using UnityEngine public class NewBehaviourScript MonoBehaviour Vector3 velocity Start is called before the first frame update void Start() velocity Vector3.zero Update is called once per frame void Update() velocity.y 0.5f transform.Translate(velocity) Bounds bounds GetComponent lt Collider gt ().bounds Debug.DrawLine(new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), Color.red) Debug.DrawLine(new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), Color.red) Debug.DrawLine(new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), Color.red) Debug.DrawLine(new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), Color.red) Debug.DrawLine(bounds.min, bounds.max, Color.red) Am I not understanding something or am I doing something wrong?


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


Unity 3d auto move player forward script Trying to write a basic script to attach to the player on Unity 3D, I want them to move forward automatically. I'm guessing that will be part of the Update function and using transform, but that's about as far as I get. I'm assuming it's a Transform.translate function too, but not sure what parameters to use to move forward 1 m s automatically (for example). Also, how do I block W and S keys moving forwards and backwards, and instead use the for up and down? (My character is 'floating' and I'm looking to incorporate space harrier style controls) Thank you!


How can i detect if the player is inside an explosion radius? I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something. What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?


2.5D platformer how to darken building edges? I was wondering how I could go about creating a vignette type effect some sort of volumetric shadow for the 'cross section' parts of a 2.5D level. The effect I'm going for can be seen in 'This war of mine' where the edges of the rooms and walls floors that are facing the camera have been darkened and blurred. (see below). I thought about creating the edges in photoshop and then blurring them and putting them in, however the blur scales weirdly as I'm re scaling the sprites so it looks really fake and not like a visual effect. Is there perhaps a 2d shader I could use or make? Any help on this would be appreciated! Cheers My photoshop attempt to recreate


Calculate the starting position of a turning aircraft with inertial force to make it stop at desired position and heading Continued from the answer here, I have some problem when the aircraft in my game has inertial forces after going forward and turning itself. To illustrate, from the following image (https imgur.com a Xvqu2A7) the aircraft is moving from the point A gt B gt C' gt D. I planned to maneuver the aircraft from the point C' which is the point that would make the aircraft stop at the point D after turning with its full performance (using minimum turning radius). The question is how do I calculate the position of the point C' to make the aircraft roughly stop at the point D with the desired position and heading (It is roughly since there is also an inertial force after stopping the aircraft's engine.)? Any suggestions and answers would be appreciated.


Sort buttons in unity 2D I've a list of buttons that I create using XML stored data. To achieve it, I've created a Prefab. These buttons are created correctly, and now I want them to be sorted for the user. public List lt GameObject gt myButtons As I said, now I want to sort them. I've found out that sorting the List itself, buttons are sorted in the UI. myButtons.Sort((x, y) gt ...) The problem is, that I don't have the necessary data to sort them within them. This leaves the .Sort() method unavailable for use. I've tried to sort them adding an script to each one, which contains the data that I need to use to sort them. However, it doesn't work correctly and I seem unable to find out why, so I'm wondering about other more direct methods to sort them. Notice that I'm referring to simple buttons in a 2D game, and that they're all inside the same parent gameobject. Technical Details Let's start by the basics I want to order the buttons taking into account if the user has reached a point in which the item it represents should be available. This is stored in an instance of a class that represents the items related to the buttons of the question. public class myItemClass Here there are other properties public bool available Therefore, we've a correspondence between two lists public List lt myItemClass gt myItems public List lt GameObject gt myButtons Where myItems 0 is related represented by myButtons 0 ... NOTICE that this relation exist at the initialization of the game, so i need to keep it at any moment (meaning, having to sort both lists). What I tried To be able to order my buttons depending on if the items are available or not, what I've done is Creating an script myItemScript, which has a reference to my original items from the other list. Sorted the items using Sort function over them. public class myItemScript MonoBehaviour public OtherClass.myItemClass dataObject And then sorting them like myButtons.Sort((x, y) gt y.GetComponent lt myItemScript gt ().dataObject.available.CompareTo(x.GetComponent lt myItemScript gt ().dataObject.available)) As I said before, both list need to be following the same order, so just after it, I order the item list as well myItems.Sort((x, y) gt y.available.CompareTo(x.available)) Checking Debug As result, I found that items were in fact sorting different. However Items inside myItems List were sorted as expected. Buttons in UI (and hence, myButtons List were not sorted as expected. Mixed items (available true false) were mixed and not ordered in two blocks, one first and then the other one. This was checked using breakpoints within VS2017 and pausing the game in Unity interface.


How to create a 2D Polygon Sprite from prefab at runtime? At start of my 2D unity game I want to create a new quot building quot (at random). So I created a prefab named quot Building quot from a polygon sprite. Then I created a quot Empty Game Object quot named quot GameManager quot with a script named quot GameManager quot attached to it. The script looks like this public class GameManager MonoBehaviour public GameObject Building Start is called before the first frame update void Start() var createdBuilding Instantiate(Building, new Vector3(0, 0, 0), Quaternion.identity) var sprite createdBuilding.GetComponent lt SpriteRenderer gt ().sprite Vector2 geometry new Vector2 6 geometry 0 new Vector2(0,0) geometry 1 new Vector2(0,20) geometry 2 new Vector2(20,20) geometry 3 new Vector2(27,20) geometry 4 new Vector2(29,29) geometry 5 new Vector2(16,0) sprite.OverrideGeometry(geometry, sprite.triangles) The hardcoded position values are just for testing purporses. The plan is to create multible buildings but first I have to get unity to show at least one of them. Afterwards I attached the prefab quot Building quot to the variable quot Building quot via the inspector. But when I ran the game the sprite is shown as a Pentagon, regardless what I write into the quot geometry quot Array. So why I cant change the geometry? And is this even the right way to create buildings at startup?


Unity UI InputField does not consume the keyboard input Unity UI I have an input field in which I can type. Unfortunately, when I hit any of the movement keys, such as the space bar, I move while I'm typing which is not the effect I want. Is there a way to force the input field to consume the keyboard input so it doesn't also get picked up by the game? Or do I have to write the code in my game to do that for me. (Seems like it should be configurable at least).


Sprite editor "minimum size" feature alternative in Unity 5 As you know , unity has been removed its minimum size feature in sprite editor multiple auto slice mode. In some pics Unity discovers a lot of tiny rubbish sprites for example as 4x3 or 10x5 pixels. Is there anyway to set minimum size for good auto slicing in Unity 5?


Hardcode per instance properties into the shader in unity I am using one of the packages from the asset store and using its Polyline feature for wire rendering. There are thousands of wires and its taking much fps Batch counts. The reason of the lack of support for static batching. Now there is a workaround suggested by the author of the package. if you don't use polylines for anything other than that, and all your shaders use the same properties, you could hardcode all per instance properties into the shader Due to a lack of shader knowledge(I am developing the knowledge currently and it will take time) I am unable to hard code the above properties I tried and here is the current scenario define int ScaleMode 1 define half4 Color (0,0,0,0) define float4 PointStart (0,0,0,0) define float4 PointEnd (0,0,0,0) define half Thickness 0.5 define int ThicknessSpace 1 define half DashSize 1 define half DashOffset 1 define int Alignment 1 HOw do i correctly hard code above values?


Ray is not shooting forward This is the code for Raycast RaycastHit hit Vector3 direction transform.forward Debug.DrawRay(transform.position, direction 200f, Color.red, 0.1f) if(Physics.Raycast(transform.position, direction 200f, out hit, 200f)) if(hit.transform.tag "Enemy") do something with enemy I'm shooting the ray to in front of the object, but it's not quite working to me. These are the screenshots As you can see above second picture, shot the ray to forward, but actual ray wasn't forwarded. I also rotated the ray z axis 90 or 90 degree, but stil not working. (Actually I tried to rotate each axis 90 and 90, but nothing seems work) Vector3 direction Quaternion.Euler(0, 0, 90) transform.forward Doesn't work Vector3 direction Quaternion.Euler(0, 0, 90) transform.forward Doesn't work either What am I missing?


How to detect a swipe and make the player GO rotate towards the end of the touch Android Unity I am making a game where the user can swipe on the screen and the player gameobject will turn towards the end of the swipe. I am using the following to detect the end of the swipe if (touch.phase TouchPhase.Ended) swipeEndPos touch.position swipeDistance (swipeEndPos swipeStartPos).magnitude if (swipeDistance gt minSwipeDistance) Vector3 swipeEndPoint mainCamera.ScreenToWorldPoint (swipeEndPos) player.Turn (swipeEndPos) And the following to make the player turn towards the end position public void Turn(Vector3 direction) transform.Rotate (new Vector3(0,direction.y,0), Space.Self) Can someone please explain what I am doing wrong? Thank you.


How can I create a custom MeshCollider for my object, or fix my collision problem? I have a problem with collisions in Unity and I am unsure how to fix it. I have an octree with a depth of 2, and each node in the tree has a Bounds object attached to it for collisions. I am trying to see which nodes have been intersected by a specific object however it is giving me unexpected results. The colliding object is a flat triangle that I have constructed myself which is acting as a cutting plane and I have attached a MeshCollider component to the GameObject. When there is an intersection with a leaf node in the octree, the node is outlined in yellow and if there is no intersection, it is outlined in purple. Before rotation After rotation In this image I rotated the triangle a small amount on the Y axis and apparently Unity found a collision even though the objects are not even touching at all. I am drawing the octree nodes using Gizmos.DrawWireCube, providing the center and size of the cube which are used to create the Bounds object of the node. Due to this it seems that the Bounds object for the nodes are correct, however the collider for the triangle may be incorrect. When I test this with another 3D object such as a cube, it works perfectly, however not with the object I need it to work with. How can I fix this issue? Collision checking code public bool intersects(Bounds otherBounds) bounds refers to the node's Bounds object otherBounds is the one I'm checking against, in this case the triangle's bounds from the MeshCollider if (otherBounds.Intersects(bounds)) return true return false Octree traversal if (node.intersects(triangleCollider.bounds)) if (node.isLeaf()) node.colour Color.yellow if (node.hasChildren) for (int i 0 i lt node.children.Length i ) findIntersections(node.children i ) It seems that perhaps a quad is being wrapped around the triangle as can be seen in the image below. This image has a triangle which is intersecting the top half of the octree, however the top left octant should have no collision. How can I create a custom MeshCollider which I can specify the vertices manually? See accepted answer for solution int cutterMask 1 lt lt 9 Collider intersectedColliders Physics.OverlapBox(node.bounds.center, node.bounds.extents, Quaternion.identity, cutterMask, QueryTriggerInteraction.UseGlobal)


Focus object with specific Rotation in unity C I have different kind of objects with variable dimensions and placed at different position in a scene. I want to focus display each object with the camera with a hard code rotation (north rotation). Like with specific camera rotation I want to focus the object that it completely show to the camera and center of the screen. For this reason, I have write this code snippet that 1 Get the position behind the specific focus object using TransformPoint Provide the elevation using the largest extent of the bound so that it display maximum area of the object. Assign the position and the fixed rotation Vector3 dest destination.transform.TransformPoint(0, 0, behindPositionDistance) GetBehindPosition(destination.transform, behindPositionDistance, elevation) Debug.Log(dest) float eleveMax Mathf.Max(destination.GetComponent lt MeshRenderer gt ().bounds.extents.x, destination.GetComponent lt MeshRenderer gt ().bounds.extents.z) dest new Vector3(dest.x, eleveMax, dest.z) camera.transform.position dest camera.transform.rotation lookNorth But the problem is, it is not accurately working with all objects as every object is at different position and dimension. I want to focus the full object using the camera but without changing the rotation.


Unity gizmos with custom renderer Im working on a small project to learn the basics of post processing, shaders and other effects in Unity. My project is in 2D, so I followed this Brackey's tutorial and this tutorial. The bloom effect did not work for me with the expiremental 2D renderer, so I used a forward renderer instead. Problem is, now all of my gizmos (including the camera's gizmos) are gone! Anyone knows what could be the problem? Do I need to set something in the renderer so it will show?


C Script file is not showing in Onclick Event in Unity 5.0.4f1? I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me? C code using UnityEngine using System.Collections public class LevelLoader MonoBehaviour Use this for initialization void Start () Update is called once per frame public void LoadLevel(int a) Application.LoadLevel(a) public void Quit() Application.Quit() Correct me where I am wrong. I am following this racing car game tutorial. At 7 58 he added this event. Please help me!!!


How to Instantiate enemies (triangles) in the shape of an n sided polygon I am trying to instantiate a cluster of triangles (enemies) in the shape of a polygon and am unsure how to angle them correctly to all be facing away from the center. Thanks to another question, I got the positions roughly right for (int i 0 i lt formation.Count i ) Vector3 pos new Vector3(Mathf.Sin((float)i formation.Count 2 Mathf.PI), Mathf.Cos((float)i formation.Count 2 Mathf.PI)) GameObject tri Instantiate(gameObj, pos, Quaternion.Euler(0, 0, z) , parent) as GameObject Now I just need to get the angles such that all triangles face away from the center.


How do I reduce overdraw in a forest scene with lots of foliage? Unity comes with an overdraw view that looks something like this We've probably all seen it, and have probably been advised to check for overdraw. How do you go about actually doing anything about it? My specific case I'm currently seeing a lot of overdraw from my terrain grass and trees as they do not respect occlusion culling. This seems to be a limitation in Unity. Is there anything I could do about it to reduce overdraw without losing the lush environment? For reference, here is the foilage responsible for most of the overdraw and I'm exploring options other than to simply reduce the amount of foliage in the scene and lose the aesthetics


(Unity) Is there a way to automatically create a material for each texture and assign the texture to it? I have imported hundreds of textures in my Unity project, and I'd like to create a material for each of them. This would obviously take a lot of time, so how would I go about doing this automatically? These are just basic textures that I want to assign to albedo on the standard Unity 5 shader. No need for normal maps.