Multi Screen Rendering in Unity My experience with Unity in not that in depth. But I am wondering if it possible in unity to split what is being rendered across multiple screens. It's hard to explain, so here is an image So while the middle screen is fine to render, I want to spread the image all around the player. That is both to the side and, the bottom and top of the player. Is such a thing possible? Has anyone ever done something similar?


Efficient way to load chunks of a 2d level to prevent game from loading stutters I am building a 2D sidescroller game in Unity3D. It's tile based. To get better performance I divided the level into chunks. I activate these chunks when the player enters 2D Triggers and deactivate it again when he exits the 2d trigger. So I normally only have a max of 2 chunks loaded. This works good BUT I do have some loading stutters of a few frames when I load a new chunk. How can I prevent that from happening? Thank you!


How to serialize animation state? In Unity, I have an Animator on a character. Upon saving loading the game, I want to preserve the pose and animation state the character is in. However, I can see no way to read write all the data from the Animator Animation Controller in such a way that I can store it in and retrieve it from a binary file. Is there a non obvious way to achieve this?


Invoking a common method after a button press I want to implement a common method that handles several numeric values and performs and action based on those values. So I have buttons with specific methods to change this values without affecting the rest. However I want to link them all to a final method that runs right after the press of a button, so this way the game will change only when the player chooses to change it and changes according to the players decisions. How can I implement this in my script? Most of my methods are like this public void "ButtonIDGoesHere" (int "SpecificVariable") Add, Sub, Multiply, etc. What can I add so that it goes to a common method right after it executes its instructions?


How to get plane geometry associated with primitive 3d plane in unity3d I assume there should be a plane (struct) associated with a primitive 3d plane in unity3d, how to get that? Or if not associated, can we build plane struct object somehow using corner vertices of 3d plane. Can somebody help me how to get cornor vertices of 3d plane mesh. Update What I am trying to achieve is to use Plane.Raycast on a 3d Plane, but I am not certain whether there is any plane geometry component associated with it, or Is there any way to build a plane geometry which should be going through all the corners of the 3d plane, so that I'll be able to use Plane.Raycast from the normal direction of 3d plane towards itself.


Get world position of touch on objects In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it. How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly? OK one cannot answer the question with the information I provided. In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).


SteamWorks.Net for unity and inviting a friend to a multiplayer game I'm trying to send an invitation to a steam friend and have it that when he accepts I create a PUN 2 room for both players and they can start their match. So far I've done this protected Steamworks.Callback lt GameRichPresenceJoinRequested t gt m GameRichPresenceJoinRequested private void OnEnable() m GameRichPresenceJoinRequested Callback lt GameRichPresenceJoinRequested t gt .Create(OnGameRichPresenceJoinRequested) public void InviteFriend() SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "") private void OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested t pCallback) Debug.Log(pCallback.m rgchConnect) Debug.Log(" lt color green gt Friend accepted the invite lt color gt ") The invite is being sent to the correct friend and when he accepts it launches the game but I get no callback from that and thus have no way to place them in a room. What am I doing wrong ?


How to stop camera from rotating in 2.5d platformer I'm stuck with a problem I can not make my camera stop rotating after character. What I already have tried using empty game object with rigid body and locked rotation and make it parent of camera, while player being the parent of object. Also, I've tried using few scripts from web, that did not help. Right now I'm bad with using JS in Unity (can handle JS on website, but I dont know how to integrate it for now) and practicing the basics, making easy 2.5d platformer with basic features, so I can not write code for now.


Unity2D force of an impact I don't know how to name what I am searching for... Force, Impact? It's easier to explain with an image for me. We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360 movement possibilities). First case (left) A go to the right at a speed of 2, B to the left at a speed of 1 and they collide. How to calculate that A take 1 damage (from the speed of B in its direction) and B take 2. Second case A go to the right at speed of 2 and B to the right at speed of 1. A take 0 damage and B take 1. I am using Collision2D which doesn't have "impulse" property. I have no idea how to calculate thing like this manually.


What is Unity Quaternion range? I've read somewhere that a Quaternion in Unity ranges between 1,1 values. I mean the individual XYZW values. Ex new Quaternion(.1f,.2f, .3f, .4f) Is this true? More clearly I know they take float values therefore the theoretical limit is floating point value limitations, I'm asking the real rotation results. For instance when I look up Quaternion values while rotating a GameObject it is usually in the 1,1 limits. But I'm not sure if that's my case or not.


How can I stop this fixed update from executing so I want this FixedUpdate() Method to stop executing when the Method OnMouseDown() is executed. A bool doesn't work a if() statement also doesn't work Please use my whole code Please help ) Thanks, private void FixedUpdate() int random Random.Range(1, 4) if (random 1) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.green if (random 2) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.blue if (random 3) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.yellow private void OnMouseDown() shouldexecute false


Still i can't make the cross hair to be in the middle of the screen, What am i missing? In the editor i did GameObject UI Image On the Canvas i changed the Render Mode to Screen Space Camera. It created a Canvas and a child Image in the Hierarchy. Then i changed the Image source to UISprite changed the color to red also added to it a material in red. I can't changed the Canvas anchors not sure why. The Image rect transform anchors is set to the center. I don't have a Main Camera the only camera i have is on the FirstPersonController (The FirstPersonController is a child of a FPSController). But still the red dot circle is a bit to the left not in center. Screenshot of the Canvas And two screenshots of the Image And


Allocator error in Unity Suddenly, a wierd error started to come up in my console saying More than 2048 allocators are registered. Reduce the allocator count. This error leads to freezing of editor.


Subsurface Scattering Transmittance I have a question related to SSS and especially transmittance. I've looked at several papers about that topic, most of them from Jorge Jimenez, which are very interesting and, I admit, a bit hard for me. Here is one of the papers http www.iryoku.com translucency I have some difficulties to understand the way it works and the way it calculates the distance the light traveled through the object. I think that I understand the very big lines but I am also a bit confused as I am trying to integrate this into the Unity engine and I have some difficulties to match Unity engine available values such as the shadows maps, the shadows coords, etc... to make them fit the way they are used in the paper. So here it is, I am a bit lost in the "in between" and I hope that somebody might be able to help me. Thanks a lot. EDIT added the shader code from referenced paper float distance(float3 posW, float3 normalW, int i) Shrink the position to avoid artifacts on the silhouette posW posW 0.005 normalW Transform to light space float4 posL mul(float4(posW, 1.0), lights i .viewproj) Fetch depth from the shadow map (Depth from shadow maps is expected to be linear) float d1 shwmaps i .Sample(sampler, posL.xy posL.w) float d2 posL.z Calculate the difference return abs(d1 d2) This function can be precomputed for efficiency float3 T(float s) return float3(0.233, 0.455, 0.649) exp( s s 0.0064) float3(0.1, 0.336, 0.344) exp( s s 0.0484) float3(0.118, 0.198, 0.0) exp( s s 0.187) float3(0.113, 0.007, 0.007) exp( s s 0.567) float3(0.358, 0.004, 0.0) exp( s s 1.99) float3(0.078, 0.0, 0.0) exp( s s 7.41) The following is done for each light 'i'. Calculate the distance traveled by the light inside of the object ('strength' modulates the strength of the effect 'normalW' is the vertex normal) float s distance(posW, normalW, i) strength Estimate the irradiance on the back ('lightW' is the regular light vector) float irradiance max(0.3 dot( normalW, lightW), 0.0) Calculate transmitted light ('attenuation' and 'spot' are the usual spot light factors, as in regular reflected light) float3 transmittance T(s) lights i .color attenuation spot albedo.rgb irradiance Add the contribution of this light color transmittance reflectance


Changing AnimationOverrideController "sometimes" fails Unity 5.2.1 I have the following code, in a menu where you can chose the armor and weapon of a character private List lt string gt armors new List lt string gt "armor1", "armor2", "armor2" private List lt string gt weapons new List lt string gt "weapon1", "weapon2", "weapon3", "weapon4", "weapon5", "weapon6", "weapon7", "weapon8", "weapon9" private int armor index 0 private int weapon index 0 public GameObject avatar body public GameObject avatar weapon void Update() if (Input.GetKeyDown(KeyCode.RightArrow)) nextArmor() else if (Input.GetKeyDown(KeyCode.LeftArrow)) previousArmor() else if (Input.GetKeyDown(KeyCode.DownArrow)) nextWeapon() else if (Input.GetKeyDown(KeyCode.UpArrow)) previousWeapon() else if (Input.GetKeyDown(KeyCode.Return)) loadLevel() void nextArmor() if (armor index lt armors.Count 1) armor index 1 else armor index 0 setArmor() setWeapon() void previousArmor() if (armor index gt 0) armor index 1 else armor index armors.Count 1 setArmor() setWeapon() void nextWeapon() if (weapon index lt weapons.Count 1) weapon index 1 else weapon index 0 setWeapon() void previousWeapon() if (weapon index gt 0) weapon index 1 else weapon index weapons.Count 1 setWeapon() void setArmor() avatar body.GetComponent lt Animator gt ().runtimeAnimatorController Resources.Load("AnimationControllers player " armors armor index " body" ) as AnimatorOverrideController void setWeapon() avatar weapon.GetComponent lt Animator gt ().runtimeAnimatorController Resources.Load("AnimationControllers player " armors armor index " " weapons weapon index ) as AnimatorOverrideController The problem is when I start switching between the weapons, sometimes the sprite showing does not update. Inspecting the GameObject, it is weird, because the Animator Component has successfully updated, but the Sprite Renderer still shows a fixed sprite from the last Animator. Here are 2 examples Here we see that the animator is set for the weapon Gladius, and that the Sprite renderer is looping through all the frames of that animation Here we can see that even though we have moved to the Flanged mace animator, the Sprite Renderer is still stuck on a sprite of Gladius The problem is hard to recreate, because it happens just SOMETIMES. If I were to switch back to gladius and then once again back to flanged mace... Now it works... but I didn't change anything. What is going wrong??


How to add the sound effect of a ball rolling, based on his velocity? I have a ball which roll (like all ball does ) ) ... My ball can roll on different type of surfaces (2 or 3) and at different velocity. I don't know how to approach to reproduce in my game the sound effect. I can assume to do Get an Sfx of a rolling ball Run in loop if my ball is moving then ? Well.. i need some help. Thanks


How do I know when the app is launched, loses focus and gets focus again on mobile? I searched in Unity Documentation but there are no information. I'd like to know which methods is called and what it returns in the following scenarios on Android App initially starts App goes in the background App is brought forward after being in the background As for IOs I know that the scenarios should be the following App initially starts OnApplicationFocus(true) is called App goes in the background OnApplicationFocus(false) is called OnApplicationPause(true) is called App is brought forward after being in the background OnApplicationPause(false) is called OnApplicationFocus(true) is called


Where does Unity save Inspector properties for objects in a scene? If I add a collection of objects to my scene and configure Inspector properties on those objects (like name, layer, tag, transform parameters, attached Components and their parameters), where does the information about those Inspector properties get saved within my project? Is it all saved within the scene's .unity file or are there other files I should look at?


Data structure for objects in a galaxy of star systems I'm having some difficulty coming up with the appropriate data structure to use for a game. I'm aiming for a galaxy view with tens of thousands of visitable star systems. Structure Hierarchically, each star system can contain one or more of the following Planets and their moons Asteroid Belts Megastructures and their moons sub structures All of the above can have quot points of interest quot POI eg a station in low orbit, a surface resource node, a docking bay. Usage I don't particularly care about physical location within a system beyond knowing its order in the hierarchy (I'll be showing a list of locations, rather than trying to render them in 3D space). So I can treat all objects within a system as located at the star for the pursposes of calculation. I do, however, need a way to specify routes from any Planet AsteroidBelt Moon Megastructure POI to any other. I also need to be able to search for other locations meeting certain criteria both to offer as destinations in the UI and to handle rendering . Each type of location will have some unique properties (Asteroid belts have resource distributions, for example whereas planets ave atmospheres) but they also have lots of common properties (inventory, owner, comms network node id, etc). Ideas so far Obviously, with the numbers I'm considering I need to take a sparse lazy generated approach. Currently the galaxy is built entirely in the GPU and stars are only presented to the CPU when the user first clicks on them. That lends itself nicely to a hierarchical data structure with a load on first access approach. Click on a star and it's added to the list, so the name is saved. Scan visit it and I'll generate the system contents. Unfortunately, I also need to be able to search across all generated locations efficiently (given an ID, find the star system coordinates, find planets with an atmosphere like X, find any location with X in its inventory) in a potentially huge search space. That doesn't align with recursively walking up down trees. I considered using a heirarchy and manually maintaining a number of separate indices to speed up searching. It's doable but a pain and error prone. It also feels like one of those solutions where I'm going to keep finding one more type of query I need to support and before long I'm trying to implement a minimal database. Speaking of which I also need to persist this data at some point. Currently I'm serializing to a densely packed binary blob. So... I took a step back and wondered whether I should actually use a database. I can see the benefits of using something like SQLite which I could bundle with the game and would handle persistence, indices, and the rest. Db? After spending a couple of days implementing the basics, I can see this is going to be quite a long and involved process. None of the friendly tooling works well in Unity, so I can't take advantage of entity framework w code first, nor nice Linq To Sqlite predicate handling. Even worse, most of the libraries to work with EF are tightly coupled to windows. EF Core seems like an option but I haven't been able to get it working in Unity (I need to do some assembly version mapping but as Unity overwrites the project file regularly and doesn't seem to support this itself, I think it's a losing battle). So I've headed down the route of implementing a data layer that generates SQL as needed. I can do that, but it opens up a huge can of worms in terms of manually maintaining the DB schema. I'm going to have to start tracking a DB version and bundling migration scripts with any update patch. It's a whole new maintenance burden. Question So... What am I missing? What's the elegant way to store a sparse hierarchy of data whilst still supporting flexible search across disparate object types that just happen to have a lot of common properties?


Unity Ajax and json data sending once again i need your help! with help from here i managed to make a function that sends a formated json text to a subscription service.the format is this quot profiles quot quot email quot quot example example.com quot that works fine and great from my pc but once i upload the game it gets blocked by cors. Now i have cors enabled so i contacted klaviyo which handles the data and they told me their api does not accept data from the front end and i could use ajax to make it happer, an example of which is this var settings quot async quot true, quot crossDomain quot true, quot url quot quot https manage.kmail lists.com ajax subscriptions subscribe quot , quot method quot quot POST quot , quot headers quot quot content type quot quot application x www form urlencoded quot , quot cache control quot quot no cache quot , quot data quot quot g quot quot LIST ID quot , quot email quot quot email address.com quot , pass in additional fields (optional) quot fields quot quot source, first name, last name quot , quot source quot quot Account Creation quot , quot first name quot firstname, quot last name quot lastname .ajax(settings).done(function(response) console.log(response) ) now my code which is working from my pc is this public class testing MonoBehaviour public InputField field private string URL quot https a.klaviyo.com api v2 list YeXzKp members?api key pk ec448e1bdab7504c143466ca5eeabc5e95 amp profiles quot public void SaveData() string data JsonUtility.ToJson( new EmailApiData() profiles new EmailApiProfileData new EmailApiProfileData() email field.text ) StartCoroutine(SaveIntoJson(URL , data)) IEnumerator SaveIntoJson(string url, string data) var request new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST) request.SetRequestHeader( quot Content Type quot , quot application json quot ) request.SetRequestHeader( quot Access Control Allow Origin quot , quot quot ) request.SetRequestHeader( quot Access Control Allow Credentials quot , quot true quot ) var jsonBytes Encoding.UTF8.GetBytes(data) request.uploadHandler new UploadHandlerRaw(jsonBytes) request.downloadHandler new DownloadHandlerBuffer() yield return request.SendWebRequest() if (request.isNetworkError request.isHttpError) Debug.Log(request.error) Debug.Log(request.downloadHandler.text) else Debug.Log( quot Form upload complete! quot ) Debug.Log(data) Serializable public class EmailApiProfileData public string email Serializable public class EmailApiData public EmailApiProfileData profiles how can i put those two together?? i know im way out of my waters here but i want to learn it!Thank you once more!


Emissive material from white texture I have texture with black and white shapes. I would like that white parts are emissive and black parts are transparent glass. How to make such material ?


Play two different audio sources depended on code behind How can I play two different audio clips in Unity depended on the code behind? Into my object I've added two audio sources namely 'Player GunShot' and 'outOfAmmo'. Into the same object I've also added a C script whit this code public currentBullets 1 private AudioSource gunAudio private AudioSource outOfAmmo void Awake() gunAudio GetComponent lt AudioSource gt () outOfAmmo GetComponent lt AudioSource gt () void Update() if (currentBullets 0) outOfAmmo.Play() else gunAudio.Play() Can this code give any problems because in the Awake methode? I've not defined with audio source the variable must be. So which source go he take to play?


How do I cover a plane in a bumpy foam material effect? I need to fill a weapon bag with foam material. This is what it should look lik The material in the upper part of the bag looks like this I'm using HDRP. How could I do this? Thank you! Edit I have played around with Parallax Occlusion mapping, and I got this result. Edit2 I am not sure if I use the Pixel Displacement as it has been suggested to me. Also, I'm not sure if I use it the correct way I have created a Height map and put it into the Height map slot. This doesn't create any effect. I have to put the same map into the Base map slot in order to see the effect. If I put a black image into the Base map slot or if I choose Black as the Base color, no effect is visible. I don't understand why this is so. I think even if my Base map is black, the Shader has pixels that it can move. This is my height map Edit 3 It was suggested that I should use a normal map. This doesn't look at all what I expected. The normal map was created from the Height map using an online tool By Philipp's answer I found out that the normal map alone is not enough.


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


Build displays black screen with static Something really odd happens when I'm trying to load a scene. It is supposed to look like this (it also has to show the next scene after loading) What is going on?


How to convert game object world position to hex grid cell coordinates? I have a hex grid and a game object, let's say it's the player. What I want to do is know on which cell the player is on based on his world position, this would be easy on a simple grid but on a hex grid it's giving me a headache.


Why does Unity ignore normals when calculating backfaces? Here's some code to generate a square mesh. Vector3 vertices new Vector3 new Vector3(x1, y1, z), new Vector3(x2, y1, z), new Vector3(x2, y2, z), new Vector3(x1, y2, z) int triangles new int vertexIndex, vertexIndex 1, vertexIndex 2, vertexIndex, vertexIndex 2, vertexIndex 3 Vector3 normals new Vector3 this.normal, this.normal, this.normal, this.normal The resulting mesh looks like this The normals have been set to (0, 0, 1), making the square face in the positive Z direction. I would like them to face in the negative Z direction, so the intuitive solution would be to set the normals to (0, 0, 1), but the result looks like this Despite the normals facing the opposite direction, the face's front is still in the positive Z direction. When viewed from the negative Z direction, the square is invisible due to backside culling. Why do my normals not affect the directionality of the faces?


Editor throwing NullReferenceException I have the following exception being thrown at compile time NullReferenceException Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Edge.cs 114) UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List 1 T inEdges, System.Collections.Generic.List 1 T ok, System.Collections.Generic.List 1 T error, System.Boolean inEdgesUsedToBeValid) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 387) UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 286) UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 272) UnityEditor.Graphs.Graph.WakeUp () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 250) UnityEditor.Graphs.Graph.OnEnable () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 245) I know well enough what a NullReferenceException is and what causes one, but the stack trace above implies that it's being thrown by the editor or some other internal thing. Does anyone have any advice on how to debug this?


If a 3d surface is occluded by another 3d surface, does this have any effect on the performance and rendering speed? We have a 3D character who is wearing a gauntlet on his forearm and visibility of which can be turned on and off. Would it be better to create two versions of arm, one without extra triangles that are hidden beneath the gauntlet? Or we can just one model with gauntlet as separate object which can be turned on and off ? Does the hidden triangles have any effect on rendering or are they completely ignored by engine? We are using Unity 3D.


How to calculate IsGrounded more effective? if (SimpleInput.GetButtonDown(jumpButton) amp amp IsGrounded()) rb.AddForce(0f, 8f, 0f, ForceMode.Impulse) bool IsGrounded() return Physics.CheckCapsule(Char Collider.bounds.center, new Vector3(Char Collider.bounds.center.x, Char Collider.bounds.min.y, Char Collider.bounds.center.z), Char Collider.radius 0.27f, GroundLayers) I've multiplied Char Collider.radius with 0.27f 'cause in the tutorial that guy said You need to multiply this with 90 of your character's actual size That might be the problem because i don't actually know my character's size, i've made it in blender and scaled it down at the unity. So if you look at the inspector panel you'll see it's 0.1 0.1 0.1 but it's actually not. I tried to spawn a cube and match them together roughly, cube's size was 0.3 1.2 0.3, that's way the number is 0.27f 'cause i just simply calculated it with the 0.3. And finally my problem is I get return values from IsGrounded delayed, sometimes doesn't even get a value. Like example when i jump, sometimes it returns the value of IsGrounded False when i'm just about the hit the ground, and sometimes it doesn't returns the value of IsGrounded False. Because of this i can't make jump animation properly. This is my HandleAnimation() method (I call that from FixedUpdate()) void HandleAnimation() if (!IsGrounded()) anim.SetBool("Jumping", true) else anim.SetBool("Jumping", false) And this is my animator I am also adding those because sometimes when IsGrounded() returns false, animation doesn't works.


Animation Change Delay When Landing On Ground I am working on a 2d platformer like game in Unity. My problem is that when my player character jumps and lands back on the ground, there is a slight delay at times when transitioning to the player idle animation. This is not due to exit time. Instead, upon researching this topic, I found that my real problem lies in the Unity physics loop(FixedUpdate). FixedUpdate, as the name implies, is called a fixed amount of times, not every frame. My animator relies on a Jumping boolean to tell it whether or not to be in the jumping animation. In my code, the Jumping boolean is set to false when the player lands on the ground. This is handled by OnCollisionEnter2D, which runs on FixedUpdate. This is were I think my problem lies private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Ground")) isOnGround true animator.SetBool("Jumping", false) I need to know whether or not the player is colliding with the ground, So I setup a tag. I need to find a way to constantly check whether or not I am colliding with the ground, So that I do not see an animation transition delay. Any Ideas of how I could accomplish this?


Changing distance after some time on OnGUI Unity Though I am using IEnumerator to calculate the distance travelled value, the distance is updated very frequently, how can I change that? and why exactly increasing the time in WaitForSeconds function not changing the behaviour? void OnGUI () GUI.contentColor Color.black GUI.Label (new Rect (40, 40, 140, 40), "Speed " speed, "color") StartCoroutine (distancetravelled ()) GUI.Label (new Rect (40, 100, 100, 140), "Dist " Mathf.RoundToInt (distance 1000) " Kms", "color") IEnumerator distancetravelled () timeInHours (Time.smoothDeltaTime 60) 60 if(PlayerControl.collision ! true) distance speed timeInHours yield return new WaitForSeconds (60)


NullReferenceException in StartCoroutine method Maybe it's a repeated subject in the community but other answers didn't solved my question... I tried as the tutorial http answers.unity3d.com questions 11021 how can i send and receive data to and from a url.html and worked fine in start method but when I try public Class A ...CODE... new B().JSONRequest(jsonString) public Class B public void JSONRequest(string json) string url URL.LOCAL.url Hashtable postHeader new Hashtable() postHeader.Add("Content Type", "application json") UTF8Encoding encoding new System.Text.UTF8Encoding() WWW request new WWW(url, encoding.GetBytes(requisicaoJSON.ToCharArray()), HashtableToDictionary lt string, string gt (postHeader)) print("Request " request) StartCoroutine(WaitForRequest(request)) IEnumerator WaitForRequest(WWW www) yield return www check for errors if (www.error null) Debug.Log("WWW Ok! " www.data) else Debug.Log("WWW Error " www.error) It gives me in the StartRoutine line NullReferenceException UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) (at C buildslave unity build artifacts generated common runtime UnityEngineMonoBehaviourBindings.gen.cs 61 Console prints Request UnityEngine.WWW so it does not appear to be null.


Applying movement to a Rigid Body Isometric in Unity 3D I'm making an isometric dungeon crawler. I initially used transform to get isometric movement and things worked well, but I couldn't use collision which meant it was unsuitable. So I'm now trying to use Rigidbody and I'm having some weird issues. First of all, this is the code I currently have public class CharControllerRigid MonoBehaviour SerializeField private Rigidbody characterRigid private Vector3 inputVector void Start() characterRigid GetComponent lt Rigidbody gt () void Update() inputVector new Vector3(Input.GetAxis("Horizontal") 10f, characterRigid.velocity.y, Input.GetAxisRaw("Vertical")) transform.LookAt(transform.position new Vector3(inputVector.x, 0, inputVector.z)) private void FixedUpdate() characterRigid.velocity inputVector I have two issues First, how do I get the movement to work on an isometric plain? Second, how do I get the movement to work in all directions? Current when I move left and right the movement is good, but up and down are really slow in comparison.


Periodic updates of an object in Unity I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error Update() cannot be a coroutine.) How would I fix this? Would I need a timer system to toggle the collider? var waitTime float 1 var trigger boolean false function Update () if(!trigger) collider.enabled false yield WaitForSeconds(waitTime) if(trigger) collider.enabled true yield WaitForSeconds(waitTime)


How to know the size of object in Unity in world units? Suppose I have some external package with objects. Suppose I place some of these object to the scene. Now how to know actual size of object in world units? I found no any rulers or something in Unity. The I thought I can place primitive cube and compare it, but then I realized that I don't know the size of cube too. Is is possible to "measure" arbitrary object in Unity somehow?


Network Message Registering message handler Problem I have a confusion about when and where to use NetworkServer.RegisterHandler() and NetworkManager.singleton.client.RegisterHandler()? And also I am getting Unknown message ID 1002 error. I have a message class public class NetworkMsgHandler NetworkBehaviour public const short movement msg 1002 public class BulletMovementMsg MessageBase public string objectName public Vector3 objectPosition public Quaternion objectRotation public float time I have ServerRelay which has ServerOnly authority has Script ServerRelay for registering Message Handler on Server. public class NetworkServerRelay NetworkMsgHandler private void Start() if(isServer) RegisterNetworkMessages() private void RegisterNetworkMessages() NetworkServer.RegisterHandler(movement msg, OnReceivePlayerMovementMessage) private void OnReceivePlayerMovementMessage(NetworkMessage message) BulletMovementMsg msg message.ReadMessage lt BulletMovementMsg gt () NetworkServer.SendToAll(movement msg, msg) Then I have Bullet GameObject it has script Projectile which is sending movement message this class is derived from NetworkMsgHandler. public class NetworkProjectile NetworkMsgHandler private void Start() if (localPlayerAuthority) canSendNetworkMovement false RegisterNetworkMsg() else isLerpingPosition false isLerpingRotation false realPosition transform.position realRotation transform.rotation private void RegisterNetworkMsg() NetworkManager.singleton.client.RegisterHandler(movement msg, OnReceiveMovementMsg) private void OnReceiveMovementMsg(NetworkMessage networkMessage) Debug.Log("Message received") BulletMovementMsg msg networkMessage.ReadMessage lt BulletMovementMsg gt () if(msg.objectName ! transform.name) ProjectileManager.Instance.SpawnedBullets msg.objectName .GetComponent lt NetworkProjectile gt ().ReceiveMovementMsg(msg.objectPosition, msg.objectRotation, msg.time) public void ReceiveMovementMsg(Vector3 position, Quaternion rotation, float timeToLerp) lerping between position private void Update() if(!canSendNetworkMovement) canSendNetworkMovement true StartCoroutine(StartNetworkSendCoolDown()) private IEnumerator StartNetworkSendCoolDown() timeBetweenMovementStart Time.time yield return new WaitForSeconds((1 networkSendRate)) SendNetworkMovement() public void SendNetworkMovement() timeBetweenMovementEnd Time.time SendMovementMsg(bulletID, transform.position,transform.rotation, (timeBetweenMovementEnd timeBetweenMovementStart)) canSendNetworkMovement false public void SendMovementMsg(string bulletID, Vector3 position, Quaternion rotation, float timeToLerp) BulletMovementMsg msg new BulletMovementMsg() objectRotation rotation, objectPosition position, objectName bulletID, time timeToLerp NetworkManager.singleton.client.Send(movement msg, msg) So whenever a bullet spawns it generates an error on client side saying Unknown message ID 1002 connId 1 UnityEngine.Networking.NetworkIdentity UNetStaticUpdate()


strategies for detecting regressions I know writing tests would be a good way to catch regressions. But what are some other strategies? TDD and game dev don't suit, but catching regressions is obviously something desirable. I would love to find some cheap and easier ways to catch regressions without having to invest a lot of effort or writing tests after the fact. Strategies suggested don't have to be perfect, if they can give rough ideas or things to playtest rapidly then that would also be beneficial. Please advise.


Effects of collisons broken glass, damaged cars, how are they created? My question is related in particular to achieving the effects of collision in game engine, how is this done? I have searched a bit, read from the internet and went through a few tutorials, and saw that one way to create one of the effects, explosion, or something breaking is to create the model in pieces, and apply force (in a game engine such as Unity 3D) to make the pieces fly off. It seems to be a solution, but it doesn't address the problem of items that are vaporized in a big explosion, with so many pieces. How is this done? Basic methods and tricks etc would be helpful. Secondly, the problem of things bending and getting damaged on impact, such as a car's front end destroyed when it hits a wall? How is this done? One thing that comes into my mind is to create each component of a car in a different state as an animation in 3Ds Max or Maya, and then in the engine, according to the collision, switch the model state in the time bar. Is this how it is done? Finally, what about materials, such as net of a basketball net, or a soccer goal net for example? Effects of ball hitting it can be calculated and applied in a script, but how to make the net bend and stretch with it? Is it done through models or materials? Also what about a flag fluttering in the wind? My questions are specific to game engines, particularly Unity3D. Some good links on the subject would also be helpful.


Making a zoom out in space map in Unity I'm new to unity, I was wondering how would one go into implementing a dynamic 2d space map. Let me give you an example what i mean. You see our solar system on the map, if you zoom out at a treshold value this solar system would just be represented by a name and our sun and around it you see adjacent solar systems. How would I do this in unity?


OnTriggerEnter With First Person Controller I'm working on an FPS for my first time. I'm creating a simple terrain and instatiating 15 cubes on my terrain. (This works fine). Each cube is named "cube" and has a static trigger collider. Here's what my scene looks like When my first person controller collides with my cube (instantiated object) then I want the cube to deactivate and add 1 to my score, but nothing happens. Code I added this code in FirstPersonController.cs void OnTriggerEnter(Collider other) if (other.gameObject.name "cube") other.gameObject.SetActive(false) when the player touches my spawned object then I want to deactivate my cube, but nothing happens Debug.Log("collidedwith " other.gameObject.name) score 1 scoreText.text score.ToString()


Write Data From List To CSV File I am trying to write to a CSV file the values that I put in lists from a key press in the keyboard. It does work somehow but in my csv file I get the values 2 times. Also, when I put values to only one of the lists, I don't get any data to CSV file. How can I save the values from the lists to my csv file but to be independent from each other? This is my code using UnityEngine using System.Collections using System.Collections.Generic using System.Text using System.IO using System public class record MonoBehaviour public List lt string gt inventory new List lt string gt () public List lt string gt OnlyX new List lt string gt () void Update() if (Input.GetKeyDown(KeyCode.F)) inventory.Add("F") if (Input.GetKeyDown(KeyCode.J)) inventory.Add("J") if (Input.GetKeyDown(KeyCode.X)) OnlyX.Add("X") string filePath getPath() StreamWriter writer new StreamWriter(filePath) writer.WriteLine("Inventory,OnlyX") for (int i 0 i lt inventory.Count i) for (int j 0 j lt OnlyX.Count j) writer.WriteLine(inventory i "," OnlyX j ) writer.Flush() writer.Close() private string getPath() if UNITY EDITOR return Application.dataPath " Data " "Saved Inventory.csv" elif UNITY ANDROID return Application.persistentDataPath "Saved Inventory.csv" elif UNITY IPHONE return Application.persistentDataPath " " "Saved Inventory.csv" else return Application.dataPath " " "Saved Inventory.csv" endif


When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0))


What are some strategies for handling a zoomed out grid of sprites? I'm writing a grid based 2D game in Unity3D that would ideally use grid sizes of around 200x200 or so, with multiple zoom levels, including all the way out. When I tried render a 200x200 grid at the most zoomed out level where everything is visible, Unity crapped out saying that there were too many vertices to attempt to draw. This makes sense, as it's trying to render 40,000 sprites. I was wondering, how do games like Dwarf Fortress and OpenTTD manage so many sprites at once on the screen when the map is zoomed out all the way? Are there any general strategies for handling the rendering of a large number of sprites such as this?


Unity URP Batching GPU instanced objects with same material mesh not working I have 100 units (exact same prefab) on screen. The material is a URP Lit using a texture with GPU instancing enabled. Why is it not batching? Am I missing something? I also noticed it requires 3 4 batches per model, why is this? See screenshots for stats and info.


Video play in unity3d skybox I want to play 360 video in skybox. Is there any direct way avaiable to do this task. One long, boring, inefficient procedure which seems that Convert 360 to frames Convert frames into cubmap Use that cubeMap in skybox and Programatically change it's textures(Frame) quickly so that video effects shown This is the long task which seems to me possible but is there any other way available?


Unity Exporting Game creates Texture Glitches In the editor the textures are fine, however upon exporting I'm constantly faced with glitches like these I mainly use the Built in Standard Specular Shader and the texture that gets glitched is always the Detail Texture. When re exporting the game multiple times the texture gets glitched exactly the same way in the same spots. Meshes are always below 65536 polygons. In game size is usually around 2x2 kilometres. The smallest Terrainmesh is 500x300metres and the origins are usually close to the terrain, always at 0,0,0. Scale and Rotation are always reset. This has happened in pretty much every scene so far. Screenshot of UV coordinates


Character permanently disappears when camera zooms in I am using ThirdPersonController and FreeLookCameraRig, both from the standard assets package. The camera generally follows the player fine but there is an issue when I move the camera very close to the player. When I do this, the character disappears, though it still behaves as though it is in the scene. For example, the xyz coords still show it as being in the scene and when it jumps, the camera still follows it. Here's a visual explanation. Notice how the character disappears after about 5 10 seconds and doesn't come back. (Note the gif is too large to display here, so please see it on imgur. http i.imgur.com PbMDlXD.gifv). The ThirdPersonController has Transform, Animator, CapsuleCollider, Third Person User Controller, and Third Person Character The FreeLookCameraRig has Transform, Free Look Cam, and Protect Camera From Wall. I have tried messing with many of these settings, but nothing has worked. By the way, some of the course was created in Sketchup.


How can I play an audio source while a key is being held down? if (Input.GetKey(KeyCode.A)) audioSource.Play() Except this only functions once as the key is held down. Same goes with GetKeyDown. Is there any way I can get this to loop as long as they key is being held down? (Is in Update)


How can I set a property for the upper limit for another property's range I have two properties, I would like to set one property as the upper limit of another property, hence making the upper rely on a property. As below public int fullLength Range(0, fullLength) public int segmentLength Is there a way to do this, possibly with a custom editor? If yes, how can it be done?


Debug.Assert Behavior in Unity Is this normal behaviour that Unity continues to run after a condition in a Debug.Assert statement was NOT met when I launch the game within the Editor? I can see the assertion in the console output, but still would expect it to stop the game. Development build and Script Debugging are turned on in my player settings.


Accelerometer bike game rotation help Hi I've been making a game for the last few months and not sure what to do. It's a 2d bike game and I want the rotation done with accelerometer, at the moment To test on computer I've set the rotation up as if left is hit transform.rotate to the left but because gravity my bike will not stay doing a wheelie. Is there another way to do this can I just set up that the rotation of the bike is equal to the screen rotation? Or do I need the bike to stay in the air first and then when rotated right it goes right ect? Really not sure and have been stuck on this for a month noob to unity too thanks


Is a final yield return 0 required in corutines? I have the following code run in a coroutine. I would like to know if the last yield return 0 is necessary and why. Thank you! private IEnumerator pChangeFoV() float duration 0.7f float zValue 5f for (float t 0f t lt duration t Time.deltaTime) float fNew Mathf.Lerp( camera.fieldOfView, zValue, t duration) camera.fieldOfView fNew yield return 0 camera.fieldOfView zValue make sure we're really where we want to be now do everything that should be done after we're done with this coroutine pEnableSomeScripts() yield return 0 is this final yield return 0 required???


Unity AI issue with recalculating NavMesh at runtime I am using Unity NavMesh to control my units. I am running into an Issue when updating Navmesh at runtime, It seems agents re calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an IndexOutOfBounds error agent.steeringTarget agent.path.corners agent.path.corners.Length 1 I guess something is happening while re calculating path that might mess with this for 1 frame. I solved this by putting a try catch around it, but is there some better way I can manage this so I don't get the error at all?


How to Get VR Controller's Velocity in Unity with SteamVR? Back when I used Unity 2017 and controller bindings weren't a thing, I simply attached a rigidbody to my Vive controller and read out the velocity of the rigidbody to know how fast the player was swinging the controller. Now, I've updated to Unity 2021.2.0a14, I went through all the effort of modifying my code to work with bindings, and it doesn't seem like I can get velocity anymore. The rigidbody always reports zero velocity. I can see the World Center of Mass vector changing so I know it registers motion, but it's just not reporting the velocity anymore. Is there a new setting in Unity I need to turn on to measure things that it doesn't personally control? Or do the new bindings options have a way to get velocity as an input? Am I forced to calculate it myself now? Thanks! Edit Base assumption was wrong, I did not get velocity from the rigidbody attached to the hand controller like I thought I did. I got it directly from SteamVR Controller. So Unity is probably acting like it ever did.


SteamWorks.Net for unity and inviting a friend to a multiplayer game I'm trying to send an invitation to a steam friend and have it that when he accepts I create a PUN 2 room for both players and they can start their match. So far I've done this protected Steamworks.Callback lt GameRichPresenceJoinRequested t gt m GameRichPresenceJoinRequested private void OnEnable() m GameRichPresenceJoinRequested Callback lt GameRichPresenceJoinRequested t gt .Create(OnGameRichPresenceJoinRequested) public void InviteFriend() SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "") private void OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested t pCallback) Debug.Log(pCallback.m rgchConnect) Debug.Log(" lt color green gt Friend accepted the invite lt color gt ") The invite is being sent to the correct friend and when he accepts it launches the game but I get no callback from that and thus have no way to place them in a room. What am I doing wrong ?


Why do I get this error with FB.LogInWithPublishPermissions? I don't know what's wrong. I know that FB.Login is already deprecated. I don't know what syntax to use. public class FBholder MonoBehaviour void Awake() FB.Init (SetInit, OnHideUnity) private void SetInit() Debug.Log ("FB Init Done") if (FB.IsLoggedIn) Debug.Log ("FB Logged in") else FBlogin () private void OnHideUnity(bool isGameShown) if (!isGameShown) Time.timeScale 0 else Time.timeScale 1 void FBlogin() FB.LogInWithPublishPermissions ("user about me, user birthday", AuthCallback) void AuthCallback(ILoginResult result) if (FB.IsLoggedIn) Debug.Log ("FB Logged in worked") else Debug.Log ("FB Logged in failed") and I'm getting this error Assets FBholder.cs(40,6) error CS1502 The best overloaded method match for Facebook.Unity.FB.LogInWithPublishPermissions(System.Collections.Generic.IEnumerable, Facebook.Unity.FacebookDelegate)' has some invalid arguments and this Assets FBholder.cs(40,35) error CS1503 Argument 1' cannot convertstring' expression to type System.Collections.Generic.IEnumerable'


Adding Animation to Object Unexpected Behavior I've been following the Unity 2D roguelike tutorial and I'm a bit confused about something. When he drags a series of sprites to his player object, a dialog box appears that prompts him to name and choose a location for his animation. I have seen this behavior in a couple video tutorials now. When I do this, it simply creates the animation and animation controller in the sprite folder and nothing more. This becomes a bit tedious after a while and I'm not sure these animations are being associated with the object correctly. What am I doing wrong?


How do I add a "pointer" to my UI menu? I'm sure there has to be a simple answer to this, but frankly I cannot find anything about it anywhere on the internet, so I'm asking here. How do I add a pointer like this hand to the side of the currently selected UI button in my game? I tried using Unity's built in UI system to do this, using the "sprite swap" feature that changes sprites based on whether or not the button is currently selected. I made an image for my "Play" button, and then an image for when the play button was selected that included a pointer as part of the image, but the image would either resize when the button was selected, or the image was moved to the right to accommodate Unity's centering mechanic on the UI. Perhaps this wasn't so wrong, and I'm just not using the UI system correctly. Does a feature like this have to be hard coded into the UI design?


Unity animation tool doesn't save changes I'm trying to create an animation inside Unity using the animator tool, however the record tool isn't recording my changes and I'm struggling to get this to create animations. I have created an example here https i.gyazo.com 91f88b3531b4fb3ffd4100d40f06bdcf.mp4 I have tried recreating the animation file, but no matter what I do it refuses to record the element? Any information would be appreciated, as it appears unity may be bugged. When applying an update between tweened keypoints the fields for X Y Z are red and do not apply changes


How can I debug a black screen when testing on a device? I have made an Android game with Unity. But, when I opened my game, I see a black screen and a closed game. It works on a tablet but does not work on mobile phones. I tested it on 2 mobile phones. On the first phone I installed it on, I see nothing but a black screen and closed game. On the second one, it installed once and worked, but when I uninstalled it and tried to install it again, I get the black screen and closed game. What can I do to help me find out what is going on?


Unity3D Change Background Image on a GUI Skin So I'm testing with GUI Skins and trying to make something cool, and I want to change the background image of the application background. This is what I mean In the screenshot above, the background is just blue, i'd like to change that to an image so it looks a lot better. Anyone know how to do this?


How to design prefabs in Entity Component Systems In Unity (and I presume other game engines) you can create "prefabs" which are blueprints for game objects. They contain a list of components, and default values for those components. Prefabs can be instantiated many times, which is an efficient way of creating many objects of the same kind. One feature in particular of prefabs is that you can modify an attribute on a single instance of a prefab, without modifying the prefab itself. Similarly, you can modify the prefab, which will propagate the change to all instances. I've been working on an implementation of the Entity Component System (for a high level description of ECS see this question How to implement n body in an Entity Component System), and I got stuck on how to implement prefabs efficiently in ECS. I think it's a powerful capability of EC design, and implementing this on native ECS would be awesome. I can come up with a few approaches Create archetypes, which are predefined lists of components (Unity approach). This does not let me set initial values for the components, nor override them (there is nothing to override). Easy to implement, but doesn't really do what I want it to do. Create a "prototype" entity from which other entities are cloned, including component values. With this design I can override individual attributes, but when I update the prototype, the clones don't get updated. Create entities with a reference to a "base" entity. When getting a component from an entity, first look in its component list, then try the base entity. This way when I update a base component, base instances change as well. To override a base component I can simply add it to the instance entity. Of these three approaches the third approach comes closest, but I don't see a straightforward way to extend it so I can override a single attribute. How can I make this work?


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


How to Clamp rotation of a turret I'm going mad to clamp rotation of an object. I've tested using Inspector that correctly rotation range is Z 15 and Z lt 30. I've written this code but it isn't working properly ! if (rb.transform.rotation.eulerAngles.z gt 30) rb.transform.Rotate ( Vector3.forward speedTurretMovement , Space.Self) if (rb.transform.rotation.eulerAngles.z lt 15 ) rb.transform.Rotate (Vector3.forward speedTurretMovement , Space.Self) Thanks


How to fuse 2 sprites as they approach each other in Unity2D? Hi i seen this video by Sebastian Lague on ray marching. Link https www.youtube.com watch?v Cp5WWtMoeKg amp t 204s At 3 19 mins. I want this merging effect but for 2D sprites. Please can someone instruct me on how it can be made or the steps to make it.


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


Monster Spawner Reference Issue I have a monster spawner that spawns the quot enemy quot kid which is red, and it has a line in the script where it references the quot player quot gameobject's transform. Before I made the spawner, I had the enemies put by hand and I could reference the player object without issue. Now they're not handplaced, they are spawned from the prefab folder by the spawner. When they spawn the game gives the null reference exception error and stops. I look up to the enemies that are spawned and none of them have the player gameobject referenced. Also when I click on to the enemy prefab to reference the player object, it just doesnt allow me to. How can I resolve this issue?


Movement appears to be frame rate dependent, despite use of Time.deltaTime I have the following code to calculate the translation required to move a game object in Unity, which is called in LateUpdate. From what I understand, my use of Time.deltaTime should make the final translation frame rate independent (please note CollisionDetection.Move() is just performing raycasts). public IMovementModel Move(IMovementModel model) this.model model targetSpeed (model.HorizontalInput model.VerticalInput) model.Speed model.CurrentSpeed accelerateSpeed(model.CurrentSpeed, targetSpeed, model.Accel) if (model.IsJumping) model.AmountToMove new Vector3(model.AmountToMove.x, model.AmountToMove.y) else if (CollisionDetection.OnGround) model.AmountToMove new Vector3(model.AmountToMove.x, 0) model.FlipAnim flipAnimation(targetSpeed) If we're ignoring gravity, then just use the vertical input. if it's 0, then we'll just float. gravity model.IgnoreGravity ? model.VerticalInput 40f model.AmountToMove new Vector3(model.CurrentSpeed, model.AmountToMove.y gravity Time.deltaTime) model.FinalTransform CollisionDetection.Move(model.AmountToMove Time.deltaTime, model.BoxCollider.gameObject, model.IgnorePlayerLayer) Prevent the entity from moving too fast on the y axis. model.FinalTransform new Vector3(model.FinalTransform.x, Mathf.Clamp(model.FinalTransform.y, 1.0f, 1.0f), model.FinalTransform.z) return model private float accelerateSpeed(float currSpeed, float target, float accel) if (currSpeed target) return currSpeed Must currSpeed be increased or decreased to get closer to target float dir Mathf.Sign(target currSpeed) currSpeed accel Time.deltaTime dir If currSpeed has now passed Target then return Target, otherwise return currSpeed return (dir Mathf.Sign(target currSpeed)) ? currSpeed target private void OnMovementCalculated(IMovementModel model) transform.Translate(model.FinalTransform) If I lock the game's framerate to 60FPS, my objects move as expected. However, if I unlock it (Application.targetFrameRate 1 ), some objects will move at a much slower rate then I would expect when achieving 200FPS on a 144hz monitor. This only seems to happen in a standalone build, and not within the Unity editor. GIF of object movement within the editor, unlocked FPS http gfycat.com SmugAnnualFugu GIF of object movement within the standalone build, unlocked FPS http gfycat.com OldAmpleJuliabutterfly


Make one object rotate to face another object in 2D In my 2D project, I have an object that is sometimes above or below another object. Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object. (Here, following Unity's default setup, the z axis is the axis pointing into the screen)


How big can a background file in Unity be? I want to start a new 2D top down project in Unity and want to figure out how to organize my background (one big file or a lot of files joined together). So how big can a background file get in Unity? The target platform is Windows.


Inserting into the first available inventory slot Hello my inventory system picks up one item but does not pickup any more to fill the other two slots. It is saying the whole inventory is full when it should be one slot is full. Here is my code for the inventory and this is attached to the player. public class MedInventory MonoBehaviour public bool isFull public GameObject MedkitSlot public GameObject BandageSlot public GameObject CoffeeSlot This next script is attached to the items you pickup. public class MedPickup MonoBehaviour private MedInventory medInv public GameObject itemButton private void Start() medInv GameObject.FindGameObjectWithTag( quot Player quot ).GetComponent lt MedInventory gt () itemButton.SetActive(false) void OnTriggerStay2D(Collider2D other) if (other.CompareTag( quot Player quot )) GameObject targetSlot new GameObject 0 bool validItem true switch (gameObject.tag) case quot medkit quot targetSlot medInv.MedkitSlot break case quot bandage quot targetSlot medInv.BandageSlot break case quot coffee quot targetSlot medInv.CoffeeSlot break default validItem false break if (validItem) for (int i 0 i lt targetSlot.Length i) if (!medInv.isFull i ) medInv.isFull i true itemButton.SetActive(true) Instantiate(itemButton, targetSlot i .transform, false) Destroy(gameObject) break


Best way to do multiple choice in Unity 2D? So I'm about to start development on a game in unity that is going to require multiple choice each choice having a some what unique function. I've thought of 2 ways of doing this but I'm unsure if there is an easier way as I've never really worked with unity. So the first way I was thinking about doing this and I think better then the second would be to make a class for each choice with all the functions that belong to that choice in there and then just calling it when its needed. However, I don't know if this will scale very well as I will have over 100 different events with their own choices... The second way I was thinking was to do it via JSON and then just code each function to parse that. So for example addmoney, dothis, dothat etc... However this seems like a lot more work then it would be worth so I'm not 100 sure... So I'm wondering what option would be better and if anyone else has any suggestions I'd love to hear!


Object Composition in the Unity Editor I'm trying to learn how to use Unity for my class composition, and I was wondering if you could help me. I'm trying to create a simple game where the player is trying to pop a bunch of balloons. However, any given balloon can only be popped if all of its conditions are met. Example conditions are The player color must match the balloon color The balloon must be popped in sequence (balloon A must be popped before balloon C) The balloon is only pop able during a certain time window And I'm sure you could think of more. Balloons can have 0 to many conditions associated with them, but they follow the 80 20 principle where 80 will fall into a specific category (e.g. color match only, or color and sequence only). My Initial Solution I created a "Balloon" class that contains a list of "ICondition" interfaces. When a collision occurs, the balloon loops through each condition to determine whether the balloon is pop able or not. I populate this list within a "BalloonFactory" class. For 80 scenarios I can just pass in the name of the balloon type I want. For 20 scenarios I can pass a list of conditions. This solution works, except for each new combination I need to change the factory code to include the new condition. What I'd Like to Do Instead of storing the balloon definitions in code, I'd prefer to create prefabs in Unity and use the editor to assign condition implementations to each balloon. My problem so far is that the Unity editor doesn't seem to like displaying a list of interfaces or abstract classes. Is there some way to do what I'm trying to do here? Or is there a third option which you would recommend?


How can I make Maya or Blender model work with mecanim? I'm working on a simple game project, where I need a stick figure. Due to being stubborn and the desire to learn a new skill, I want to make the stick figure myself! I have followed several tutorials in both Maya and blender. For Maya, I'm using the student version. I have my stick figure rigged within Maya and blender, both utilizing their respective bone tools. I can manipulate their limbs well, enough. However, I can't seem to get the models to work with Mecanim. I have the Kinect adapter for the PC and would like to be able to use it to create the animations utilizing a tool such as the Kinect v2 mocap animator. How I can get my model to work with Kinect based mocap?


Why doesn't Unity keep keydown states between scenes, and how can I change that? So basically, when my scene in Unity changes and I'm holding down, say, Right or Left, when the scene resets, my player (and Unity) doesn't even recognize that I'm still holding that button, until I lift my finger and put it back. Any thoughts? Sorry for any broken English or anything, I'm running off two hours of sleep.


Trees swaying in the wind using Tilemap I am working on a top down, tile based game (think 2D RPG). However, I would like to have trees that sway in the wind and shake a little if the player bumps into them! How should I approach this? Is it achievable with trees that are composed of tiles and part of a tilemap? Or should I exclude my trees from the tilemap and turn them into game objects instead? If I were to turn them into separate game objects, would I then manually tweak their rotation position to achieve the sway and shake, or is there some form of shader I can use?


Unity Help solving Uncaught Abort on HTML5 Build For some reason there is a Invoke that is triggered when a button is clicked that causes my game to crash. Any idea how I can sort this out? I have plenty other Invokes and none has given problems. I have the Enable Exceptions option set to None and game works fine inside Unity. I can give more info on the error if you can point to me to what's relevant. Thanks so much! Invoking error handler due to Uncaught abort(145) at Error at jsStackTrace (ed63bf36d25f876fa57fb81632b59202.unityweb 8 22380) at stackTrace Object.stackTrace (ed63bf36d25f876fa57fb81632b59202.unityweb 8 22551) at Object.onAbort (https v6p9d9t4.ssl.hwcdn.net html 1680115 PowerTheGrid Level3 v7.2 HTML5 Build 3998187b7e8feaa618a93b293c0e6812.js 4 11065) EDIT Here is the code generating the error public void OnClick() if (buyCoal.interactable true) trainObject.trainMovementStart() if (SceneManager.GetActiveScene().name "Level1" SceneManager.GetActiveScene().name "Level2") Invoke("coal refill", 6f) if (SceneManager.GetActiveScene().name "Level3") Invoke("coal refill", 12f) Money.UseMoney(coalcost) buyCoalAudio.Play() countdown 1 agora count up tipCoalReady 2 buyCoalButtonIndex 0 DISABLE COAL Buy Button coal stock countdown.text countdown.ToString() coaltipCounter 1 void coal refill() ThermoElectric.quota 17.5m Invoke("reactivateBuyCoalButton", 5f) void reactivateBuyCoalButton() buyCoalButtonIndex 1


RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.


Keep gravity velocity the same all the time I have 2D rigidbodies that fall to the ground, however they speed up while falling. Also, when they freeze in the air and then unfreeze, the velocity is set to 0 and they gradually start speeding up again. How can I keep the velocity constant at all times, until they hit the ground?


Is this Code saving performance ? It is kind of a Occlusion Culling I wanted to do Occlusion Culling on my Scene but I just get a bunch of Errors like "Couldn't load geometry..." etc. I tried to do like another way but the same thing, the Occlusion Culling just disables the Objects the Camera dont see. I tried it with OnTriggerEnter and Exit. I have 2 Areas one is on the left and one on the right, when the Player is walking in the first Area the Box Collider checks it and disables the Objects in Area2 but when Player is walking into Area2, Objects in Area1 disables and Different. Got the Script on both Areas that it disables a list of arrays as GameObjects. My Question is, does this save performance ? public GameObject deactivatingModels bool playerEntered false void OnTriggerEnter (Collider other) foreach(GameObject envis in deactivatingModels) if(other.gameObject.tag "OcclusionCuller") envis.SetActive(false) Debug.Log ("Player has entered Occuling Zone") void OnTriggerExit(Collider other) foreach(GameObject envis in deactivatingModels) if(other.gameObject.tag "OcclusionCuller") envis.SetActive(true) Debug.Log ("Player has left Occuling Zone")


Unity Android build fails, error Could not find com.android.tools.build gradle x.x.x Can't build for Android, error log CommandInvokationFailure Gradle build failed, And this is in it's description Could not find com.android.tools.build gradle 3.2.0.


Get the XZ to the right of a rotated point? I need to do this entirely with math, take a look at this picture What I'm doing is building a path finder algorithm that basically looks 30 units ahead, raycasts a few times perpendicular to the future point, finds the midpoint between the min max vectors that found the dirt road, and puts a green cube in the middle. I thought this would be rather simple, yet here I am trying to figure out how to plot the exact geometry of a rotated left right projection. I hope I explained this well enough! I'm also open to suggestions on how to do this if my approach is silly. Eventually this path will split and the algorithm has to detect the split and have the user decide which direction to go. EDIT After applying the math below (I opted to use the trig version) I go this result on my algorithm. THANK YOU!!!


Reading from Streaming Assets in WebGL I'm trying to set up my Unity game for WebGL, but I quickly found out that you can't access your streaming assets as you would in a standalone build. For example, I have a code snippet below of how I load in all of my game's text for localization (i.e. get english translations of all text in my UI). public void LoadLocalizedText(string fileName) localizedText new Dictionary lt string, string gt () StreamingAssetsPath will always be known to unity, regardless of hardware string filePath Path.Combine(Application.streamingAssetsPath, fileName) if (File.Exists(filePath)) string dataAsJson File.ReadAllText(filePath) deserialize text from text to a LocalizationData object LocalizationData loadedData JsonUtility.FromJson lt LocalizationData gt (dataAsJson) for(int i 0 i lt loadedData.texts.Length i ) localizedText.Add(loadedData.texts i .key, loadedData.texts i .value) else ideally would handle this more gracefully, than just throwing an error (e.g. a pop up) Debug.LogError( quot Cannot find file quot ) isReady true I've been looking at online examples, and there's a lot of obsolete examples regarding the use of unity's WWW class and php. From what I understand the UnityWebRequest is now the way to go, but I'm confused how to use it with regards to the example above. I'm also trying to figure out how to connect to my SQLite database which is also stored in streamingAssets. public SqliteHelper(string databaseFileName) if (Application.platform RuntimePlatform.WebGLPlayer) ???????? else tag databaseFileName quot t quot string dbPath Path.Combine(Application.streamingAssetsPath, databaseFileName) if (System.IO.File.Exists(dbPath)) dbConnectionString quot URI file quot dbPath else Debug.Log ( quot ERROR the file DB named quot databaseFileName quot doesn't exist anywhere quot ) Now that I can't just open an SqliteConnection, I have no idea if there's a c only solution, or if I have to learn php as suggested from tutorials such as this one. If someone could walk me through how to solve either of these problems I would greatly appreciate it.


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


How to get smoother transition between the surface normals rotation of player in Unity I kinda have a problem that my player is snapping onto the other surface while I wanna move a ramp up. I want to have it rotate smooth to the normals of the ramp. How can I change the code below to a smoother rotation function of the player? Code void NormalsOfGround() RAYCASTS THE NORMALS ON THE GROUND THAT THE PLAYER MOVES ALONG SURFACE Debug.DrawRay(rayCastNormal.transform.position, transform.up, Color.blue, 2.5f) Ray ray new Ray (transform.position, transform.up) RaycastHit hit if(Physics.Raycast(ray, out hit, 2.5f, GroundLayer) true) transform.rotation Quaternion.FromToRotation (transform.up, hit.normal) transform.rotation


Unity2d orthographic camera and z axis? I wonder if anyone can help with an explanation of the z axis and using unity with 2D with an orthographic camera. Up until now i have only been modifying the x and y values of game objects, thinking this is the correct way. i thought the Z axis didn't exist in 2D space (i.e. unity 2d with orthographic camera) but I do notice that the orthographic camera is placed at 10 on the z axis, if i change this value then the camera disappears. I sort of began to accept that. Now I cam to a point where I wanted to rotate something, and I notice that rotating eithe on the z or x axis, doesn't seem to do anything, only on the z axis, there is that z axis again ! Can anyone tell me when i should be worrying about the z axis in unity using 2D games. It seems now that it is more important than I once thought ) Thanks in advance.


Nav Mesh Agents are not moving along the mesh I'm fairly new to unity.I've been playing with Nav Mesh Agents lately.I have encountered this problem twice.The first time I didn't bother redoing my project all over again.But now its bothering me too much. I initially had a NavMesh baked along the road in my game.But later I had to change the layout of the roads, hence I had to rebake the Nav Mesh. But now I'm having the problem where the agents are not moving along the Nav Mesh to Reach the destination, but instead they quot try quot to move along the shortest path.As a result of this all agents gather to a point rather than moving along the track.I've shown below a picture to better illustrate my problem. They try to move along the red line instead of going along the road and then getting to the destination. I'm pretty confident that nothing's wrong with my code because it worked earlier and works well in other scenes.Is there anything I missed when re baking the Nav Mesh?Any help to get the agents to move along the road is much appreciated? Thanks in advance.


How can I make natural rain drops on screen? I'm trying to make rain effect drop with metaballs and trail on screen.I find a clue in shadertoy but I didn't understand how implemented https www.shadertoy.com view ltffzl unfortunately it have many math calculations and i can't use it in unity because it produces a lag.obviously I should use textures but how can I have trail effect?! my idea is using a texture and trail renderer for droping but how can I have metaballs effect? Update I could Implement Metaballs by This Article https github.com smkplus RainFX tree master but I haven't Idea about trail


How can I play user provided music stored on the phone inside my game? I am creating a car game. Is any way to play the music stored on the phone inside the game? I'd like the player to choose files that are already on their device and hear them played in the game. For example, in GTA Vice City game there was a folder named Music, and if we placed songs in there they would play on the car radio while we're driving around inside the game. If we want to switch the songs around, we can do so. how can I do the same in Android and iOS? I am using unity 5.2, C .


Unity Exposing a function to the inspector I wish to expose a script's function to the inspector, but I have no clue how to. I found something about Invoke() which was a start, but it isn't clear how to finish. My code for the class System.Serializable class MoveAction UnityEvent lt MonoBehaviour gt , IUIAnimationEvent region Move public MoveAction() to ensure only one mover coroutine can be active. IEnumerator moveRoutine null region Solution 2 using fields and not parameters Transform from Transform to float overTime public delegate void UIchain(MonoBehaviour mono) public event UIchain NEXT FUNCTION public MoveAction(Transform from, Transform to, float overTime, IUIAnimationEvent chain) this.from from this.to to this.overTime overTime public void Move(MonoBehaviour mono) if (moveRoutine ! null) mono.StopCoroutine(moveRoutine) moveRoutine Move(from, to, overTime, mono) mono.StartCoroutine(moveRoutine) Invoke(mono) IEnumerator Move(Transform from, Transform to, float overTime, MonoBehaviour mono) Vector2 original from.position float timer 0.0f while (timer lt overTime) float step Vector2.Distance(original, to.position) (Time.deltaTime overTime) from.position Vector2.MoveTowards(from.position, to.position, step) timer Time.deltaTime yield return null if(NEXT FUNCTION ! null) NEXT FUNCTION(mono) This is a lot of code, but the interesting part is the Move(MonoBehaviour mono) function. I want to expose that to the editor. How? EDIT Something like this would be preferable


Unity error "must have a body because it is not marked abstract, extern, or partial" I'm trying to setup a system where I pickup an object drop it into a zone, and then the object is destroyed. So far I have using UnityEngine using System.Collections using UnityEngine.UI public class TriggerZone2 MonoBehaviour public Text MyText private int score public bool CompareTag(string Player) Use this for initialization void Start () MyText.text "" Update is called once per frame void Update () MyText.text " " score void OnTriggerEnter(Collider coll) score score 1 if (other.CompareTag ("Player")) Destroy (other.gameObject) Everything works up until I try to destroy the game object. The console keeps saying Assets Scripts TriggerZone2.cs(11,21) error CS0501 TriggerZone2.CompareTag(string)' must have a body because it is not marked abstract, extern, or partial. I've looked up quite a few threads, but I'm still not sure what it wants me to do with it. How do I fix this?


Why is an empty Unity Iphone Build over 700 Megs? Is this Normal? So after 2 weeks of slaving over my first game I was finally done! I was entirely ecstatic....until I saw its file size. 770 Megabytes For a simple numbers game, that was way too much and I created an empty unity project as a test and that was also over 700 megs Why is an empty Iphone project this large?


Architecture for extremely modular game? I'm developing a modular game in Unity 5.6. Each module has very little overlap in assets with the others. I'm concerned about having a bloated repository after a few months of development, and since I'm using Bitbucket (a free account) I'm limited in my repo size, but not in my number of repos. So instead of having one huge folder for my game I'm considering having a launcher project and scene that loads builds from a folder in Assets. Each module would be its own project, and I would just drop its build into the launcher's folder. My question is, is this a reasonable approach to building a highly modular game? Hopefully I'll be continuing development for quite a while, and I want to make sure the project is as lightweight and extendable as possible. Or am I overthinking this, and should I just use one big repo?


To extract Grabpass image as texture2d via script We applied it to the plane object using Grabpass. I want to import the image shown in plane through script. I want to make the imported image in texture2d format. Is there a way? Below is the relevant code.


How to make tank track rig? On unity How to rig an unity tank track? Does it use animation or it use some another ways. Can anyone explain how to do this. thanks


How to remember a non consumable Unity IAP the right way I have implemented Unity 5's IAP system through Google Play. I read a few guides that mention not to store completed purchases in PlayerPrefs because it is clear text and easy to hack, but none mention the correct way to "remember" purchases. For example, when re installing an Anroid app, purchases are restored the first time the app runs by individual calls to this method defined in the Unity IAP API. public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs e) my Playerpref save that I want to avoid is here. return PurchaseProcessingResult.Complete On subsuqent app runs, this method is not called again. Is there a way to query past purchases other than saving them in PlayerPrefs?


Delay for seconds when key is held down? Hello I am very new to Unity and am trying to make a shooting game in which when the space key is pressed down the gun charges then shoots. I want it to wait for 0.3 seconds before the gun fires off because I want an effect to happen with a particle system(I confused animation with effect in the first post). Also the problem the script has is that the bullet would not fire at all when the space is pressed. Here is the scripts I wrote void Start() StartCoroutine("Shoot",0.3f) IEnumerator Shoot() yield return new WaitForSeconds (0.3f) Bam () void Bam() transform.Translate (0, 0, 12) void Update () if (Input.GetKey (KeyCode.Space)) Shoot()


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


Why are there weird texture artifacts in baked light which don't appear with realtime light? This is the comparison of the same scene, realtime light vs baked light. What's am I wrong ? EDIT In particular, also texture are low quality (see image 2). Why ?


Using IPAD's as controllers for a Unity game We are making a Multiplayer game using Unity. The actual game would be run from a PC projected on a screen and the players would be using their respective Ipad as a controller to play the game. I am not sure how difficult this would be to achieve inside Unity but I am assuming that all the game data inside Unity would need to be fed and retrieved from some kind of a server. How would this be possible with Unity because each Ipad would have a separate Unity build and also a separate build for the PC from where the actual game would be running.


How are writing shaders different in Unity's scriptable render pipeline vs the standard pipeline? So I want to start learning how to write shaders because the shadergraph seems very limited at the moment. I've done some research and it seems that I should learn the HLSL language which is used by Unity. I'm becoming confused though how this will carry over between pipelines. I read that standard pipeline shaders aren't supported in URP so I'm confused how the shader language is different in URP if they both use the HLSL language. I was wondering if someone with a better grasp on this could explain the difference between them and if the skills carry over, as most tutorials online seem to be for writing shaders in the standard pipeline. Thanks.


How do I use trigger colliders in Unity? I am trying to create a "Fruit Ninja" style game in Unity in VR. I have a BoxCollider on my sword set to "Trigger" and I have some "fruit" objects coming towards it. I then have this function void OnTriggerEnter(Collider other) Destroy(gameObject) Destroy(other.gameObject) I've tried applying this script to the sword and to the objects, but nothing is destroyed. In the documentation, there is also a note of "Trigger events are only sent if one of the Colliders also has a Rigidbody attached", but I've attached a Rigidbody to the objects.


How can I move my box collider temporarily? I'm very new to game development, I mostly program other things. I'm trying to write a basic whack a mole type of game. I've gone ahead and created a hammer with a swinging animatio in the FBX. I've also attatched a box collider to the head of the hammer. The issue is that when I play the hammer swing animation (and the hammer moves down), the box collider does not follow. I understand that this is because the animation is only for the object, but in this case it presents a problem since I need the collider to be at the hammer's lowest point once the animation gets there. What is the right way to approach this problem? I've thought of a couple solutions on my own, are any of these valid? 1) Move the Collider with the animation. I've got no clue on how to do this. 2) Store the time when I start the animation, check if enough time has ellapsed for completed animation. Then manually move collider to the contact point. Wait a few milliseconds, then move it back. I tried this, the issue with this is that it moves the entire object with the collider. void Update() if (Input.GetMouseButtonDown(0)) animator.SetTrigger("hammer") animationStartTime Time.time toAnimate true if(Time.time animationStartTime gt 0.38 amp amp toAnimate true) toAnimate false bc attatched box collider bc.transform.position new Vector3(0, 0, 0) move to target point (won't be 0,0,0 for real, just a test point) if(Time.time animationStartTime gt 0.50) bc.transform.position transform.position bcOffset reset to original position 3) Do what I did in step 2, but create a collider not attatched to a parent object so that the parent object isn't moved. I don't know how to create a collider on its own however. BoxCollider bc new BoxCollider() I then use bc.size and bc.position and set them but it does not show up on my scene view so I don't think this works. NOTES This script is attatched to hammer object. The hammer is moved with this code hPos Input.GetAxis("Mouse X") 0.7f fPos Input.GetAxis("Mouse Y") 0.7f transform.position new Vector3(fPos, transform.position.y, hPos) Edit is it possible for me to apply the animation to the collider? This would probably be the easiest way.


unity webgl scale page on different sizes of internet browsers on pc or phone unity only has a fixed resolution for building webgl. how can I make it changebale on users browser size change. there are some tutorials on the internet that doesn't match. there is only index.html unityloader.js gamename.json gamename.data.unityweb gamename.asm.memory.unityweb gamename.framework.unityweb gamename.asm.code.unityweb how can I make multi res webgl output happen for unity?


Calling method with enum parameters from buttons I have the following enum public enum WeaponType Sword, Spear, Blunt, Ranged And I have the following public methods on a component public void MyMethod1(int myparam) ... public void MyMethod2(WeaponType myparam) ... Why is it that when I try to call my methods from a Button component, I can not see the ones that use enumerations as parameters?


AudioSource not working. Empty Exception I'm trying to load and play an wav file that exists in my Application.dataPath but when the game gets to the line GoAudioSource.PlayOneShot(audioLoader.audioClip) It justs throws a empty exception and no sound is played. I've already checked if the path is correct and it is. I've also tried uploading this wav file to an FTP and loading it via HTTP instead of File but nothing changes. This is my full code private IEnumerator WriteResponseAudio(ResponseModel res) File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME RESPONSE), Convert.FromBase64String(res.intent.audio.content)) string path "file " Application.dataPath " " FILENAME RESPONSE WWW audioLoader new WWW(path) yield return audioLoader try GoAudioSource.PlayOneShot(audioLoader.audioClip) catch (Exception ex) Debug.LogError("Erro " ex.Message) This is the version with HTTP request private IEnumerator WriteResponseAudio(ResponseModel res) File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME RESPONSE), Convert.FromBase64String(res.intent.audio.content)) string path "http www.raphaelrosa.com response.wav" WWW audioLoader new WWW(path) yield return audioLoader try GoAudioSource.PlayOneShot(audioLoader.audioClip) catch (Exception ex) Debug.LogError("Erro " ex.Message) This is the console


How do I change the size and specific height values of Unity generated terrain? I'm having problems with terrain scripting while trying to do a infinite world with Unity's terrain generation. How do I change the terrain height at specific points? And how do I set the amount of terrain generated? Edit What I'm having problem with is doing that from a script, from the editor is plain easy.


Unity Anti Cheat solutions I'm currently working for a websites client development team and need guidance on where to go for anti cheat with unity. We have scripting, where a user can code in their own features via a editor we have made in lua, with a scripting api that allows them to interact with parts of the game via said scripting, others can exploit this with tools and execute scripts on games that didnt have said scripts, via "hacking". I'm trying to stop script execution exploit(eg scripts being executed that weren't put there by the author) and general hacks such as speedhacks, assembly injection, etc. We have tried the anti cheat toolkit but it hasn't worked well for us. In terms of execution we have the lua5.2 library in a dll, of course they can hook this library and execute anything via luas execution functions built in, statistcally linking the library would help defend againist this but that is not a option that is easily done in unity, so anyone could just hook it and execute any script lua they want. we have server side scripts(executed on server) and client local side scripts(executed on client locally), we've done our best to secure these but we're looking into more ways to help protect us, such as anti cheat. We have plans to possible invest into paid anti cheats in the future such as battleeye, easyanticheat, etc. we currently don't make a lot of capital and i have no experience making any type of anti cheat nor anti cheat in unity, where do i start and what do i do?


how to reference a variable in an anothere script i have a object which sets pickedup true on collision public class IDCARD MonoBehaviour private bool pickedup false Start is called before the first frame update void Start() Update is called once per frame void Update() private void OnCollisionEnter(Collision collision) print( quot k quot ) pickedup true Destroy(gameObject) now i want exit script in an another object to check if pickedup true on collison now what can i do pls give a brief explanation with a names i have given i have written your code. but i think there is some issues