NullReferenceException Object reference not set to an instance of an object on boolean variable from separate class I'm trying to develop game scenario that able to trigger the alarm with alarm light and siren audio to play. For the testing purpose I set it that to boolean value as "alarmOn" in AlarmLight class. AlarmLight.cs public class AlarmLight MonoBehaviour public float fadeSpeed 2f public float highIntensity 2f public float lowIntensity 0.5f public float changeMargin 0.2f public bool alarmOn false private float targetIntensity public Light light add alarm lights tag as siren void Awake() light.intensity 0f targetIntensity highIntensity void Update() if (alarmOn true) light.intensity Mathf.Lerp(light.intensity, targetIntensity,fadeSpeed Time.deltaTime) ChecktargetIntensity() else light.intensity Mathf.Lerp(light.intensity, 0f, fadeSpeed Time.deltaTime) void ChecktargetIntensity() if (Mathf.Abs(targetIntensity light.intensity) lt changeMargin) if (targetIntensity highIntensity) targetIntensity lowIntensity else targetIntensity highIntensity Then I tried to access that value with LastPlayerSight class and for the testing purpose i was trying to return false as below. alarm.alarmOn (playerPosition ! resetPlayerPosition) Then I tried to play my scene, and I got the error which is the problem with above line of code. This is my LastPlayerSight.cs class public class LastPlayerSight MonoBehaviour public Vector3 playerPosition new Vector3(1000f, 1000f, 1000f) public Vector3 resetPlayerPosition new Vector3(1000f, 1000f, 1000f) public float lightHighIntensity 0.25f public float lightLowIntensity 0f public float fadeSpeed 7f public float musicFadeSpeed 1f directional alarmlight ref private AlarmLight alarm main directional light ref private Light mainLight private AudioSource panicAudio siren audio private AudioSource sirens void Awake() alarm GameObject.FindGameObjectWithTag(Tags.alarms).GetComponent lt AlarmLight gt () mainLight GameObject.FindGameObjectWithTag(Tags.mainLight).GetComponent lt Light gt () GameObject sirenAttachedGameObjects GameObject.FindGameObjectsWithTag(Tags.siren) sirens new AudioSource sirenAttachedGameObjects.Length for(int i 0 i lt sirens.Length i ) sirens i sirenAttachedGameObjects i .GetComponent lt AudioSource gt () void Update() SwitchAlarms() MusicFading() void SwitchAlarms() alarm.alarmOn (playerPosition ! resetPlayerPosition) float newIntensity if(playerPosition ! resetPlayerPosition) newIntensity lightLowIntensity else newIntensity lightHighIntensity mainLight.intensity Mathf.Lerp(mainLight.intensity, newIntensity,fadeSpeed Time.deltaTime) for (int i 0 i lt sirens.Length i ) if (playerPosition ! resetPlayerPosition) sirens i .Play() else sirens i .Stop() void MusicFading() AudioSource audioTemp audio.GetComponent lt AudioSource gt () if (playerPosition ! resetPlayerPosition) audio.GetComponent lt AudioSource gt ().volume Mathf.Lerp(audio.volume, 0f, musicFadeSpeed Time.deltaTime) panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.8f, musicFadeSpeed Time.deltaTime) else panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.0f, musicFadeSpeed Time.deltaTime) I'm beginner of developing such things and can anyone guide me to correct the problem?


How to import a texture to be used as occlusion map? The same way normal maps need to be imported as "Normal map" in the import settings, how should I setup an Ambient Occlusion texture to correctly work? I've been searching around in the manual and the web but still not sure if AO maps should be imported as Lightmaps.


Loop around a 2D Tile Map I have made an algorithm for procedurally generating a 2D tile map in Unity. The player can use the mouse to pan the view and look at the map. My intention was that when the player reaches one of the sides of the map, he would simply see the other side as if he was going around the Earth so to speak. The only way I have achieved this is by simply instantly setting the camera's position to the other side of the map when the player crosses one of the edges. The problem with this is that the player never actually sees the "border" connection continuously and that bothers me since I took the care to generate the map in such a way that connecting the east west edges makes sense. How can I achieve the desired effect?


Mobu Motion Files Naming Scheme for Unity When exporting takes as several fbx files in Motionbuilder 2014 with File gt Motion File Export..., the files are named like so file Take1.fbx file Take2.fbx file Take3.fbx In order for the motion files to be loaded into Unity correctly, I have to rename them to file Take1.fbx file Take2.fbx file Take3.fbx Having to replace underscores with ' ' is fine for small projects but can become time consuming when working with many takes in large projects. Is there a way to change the default naming scheme in Motionbuilder, through preferences or python scripting, so that the default underscore is replaced with an ' '?


How can I call Schedule() on interface that inherits from IJob So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual) public interface IMesherJob IJob VoxelDataVolume lt byte gt VoxelData get set NativeArray lt MeshingVertexData gt OutputVertices get set NativeArray lt ushort gt OutputTriangles get set One example of a meshing job is marching cubes, which looks like this public struct MarchingCubesJob IMesherJob So here's my question If I have a reference to an IMesherJob, can I somehow call Schedule on it? If I have a reference to MarchingCubesJob, I can call Schedule on it This works MarchingCubesJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) But this does not work IMesherJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) I noticed that Schedule() is an extension method for T where T struct, IJob so that might be interfering with it, but it should still work because IMesherJob inherits from IJob


How to create a "border" effect in Unity? Okay let me start off by saying I have searched for several days on this topic, and it seems that either nobody posted anything about it, or it is on the internet, but too far buried under piles of useless information for me to find. I have created a custom terrain algorithm in Unity and have built a parser to read provinces onto the map. The short version description of the parser is that it goes into the assets folder, finds "map provinces.png", reads the borders of the provinces as vertices, reads "map height.png" to determine the height of the visual terrain, and reads "map terrain.png" to determine how much of each province is of each terrain (for example, Paris can be 95 urban, and 5 forest in my setup). I want to make each and every one of the 500 european provinces start with a player. The idea is that the players will fight small scale wars for 30 40 turns, by which point most or all small players will be absorbed into the most successful players country. These will then fight for 60 80 turns for dominance, with alliances being forged and broken and countries being destroyed. The problem is described below Each player has his own unique color. Many of the players will obviously have similar colors, and I do not want 2 dark red countries bordering eachother without some easy way to see the border. I want to basically draw a line in between any two provinces that belong to different players and border each other. I am having trouble finding a way to easily do this, as my current solution tests all provinces if they border foreign provinces, and runs a rather expensive test on each of the bordering provinces vertices to see if they border eachother, then stores those vertices as vectors and draws a line from each vertex to its others. I have considered using a shader to accomplish this, but was unsure if that was the right approach and whether or not that would (or could?) be more efficient.


How do I differentiate between the two Vive motion controllers? I am working with a Vive Pre (devkit) and I have most everything working the way I want it to. However I am wondering how do I refer to or even know which motion controller is which? From what I can tell the headset is ALWAYS assigned first into a list, and the others are seemingly randomly assigned. So how do I differentiate between the two or refer to one separately?


Animated textures for models How to write a shader? Was watching some Rocket League and notice there was animated decals and wheels. . I would like to implement something similar to the effects in the image above. How would I go about writing a Unity Shader to do the wheel effect? I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect?


How to create a repeating gif style imagery for a game tutorial dialog I want to create a gif style video that shows up in a tutorial window using Unity. How can I make this? Do I record the thing I want to show and then put it in a texture? Example


What's the difference between Mathf.Lerp and Mathf.SmoothDamp I want to smoothly go from one value to a new one (moving a slider or changing color). I tried using both functions and they all basically give the same result. What is the difference between them and which one should I use? How I used SmoothDamp Show the HUD private IEnumerator ShowHUD() var HUDCanvasGroup GameObject.FindWithTag("HUD").GetComponent lt CanvasGroup gt () var alphaValue 1f var velocity 0f var time 0.30f yield return new WaitForSeconds(1.5f) Gradually fade in the canvas while (!Mathf.Approximately(HUDCanvasGroup.alpha, alphaValue)) HUDCanvasGroup.alpha Mathf.SmoothDamp(HUDCanvasGroup.alpha, alphaValue, ref velocity, time) yield return null HUDCanvasGroup.alpha 1 Since float is not accurate, manually set the alpha to 1 after HUDCanvasGroup.interactable true var blur GameObject.FindWithTag("BlurryCamera").GetComponent lt BlurOptimized gt () blur.enabled true How I used Lerp public static IEnumerator Dim() while (t lt 1) t Time.deltaTime 0.4f dimRend.material.color Color.Lerp(undimColor, dimColor, t) yield return null


OnTriggerEnter error The message parameter has to be of type Collider I have a crate and I want to make it so if you are in the trigger of the crate a UI appears and says quot Click E to loot quot . I have the UI setup but the script is not working. Here is my script and after it are the errors. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class UI Appear MonoBehaviour SerializeField private Image image void OnTriggerEnter(Collider2D other) if (other.CompareTag( quot Player quot )) image.enabled true void OnTriggerExit(Collider2D other) if (other.CompareTag( quot Player quot )) image.enabled false The errors say Script Error OnTriggerEnter The message parameter has to be of type Collider Script Error OnTriggerExit The message parameter has to be of type Collider


How to add Facebook Data Storage to Mobile Game? I was wondering how I would add the option for players to sign into their Facebook profiles on my mobile game and then have Facebook store their game save data, so they can recover it on any device when they sign into Facebook. Other Facebook features would include seeing their friends on the Facebook leaderboards, inviting their friends to the game and challenging their friends to beat their scores. I would hate for the Player's data to be lost, so the Facebook data save part is very important. A good reference to this feature is the Hungry Shark mobile game. I wasn't sure how this works. My programming friend and I are creating the game together, but he doesn't know how to do this and I don't know how to program. Once I figure out exactly what has to be done, I would like to hire a programmer who knows how to add this feature. Thank you!


Changing alpha of Sprite I'm using OnGUI to draw a rect when I "box select" or "drag select". The texture that gets drawn is a PNG file made in Paint.Net with the opacity alpha channel set quite low. In Unity however, when I go to box select, the texture is completely opaque. How do I get Unity to honor the alpha set in Paint.Net? I also wouldn't mind using Unity itself to adjust the opacity, but I haven't found such an option in the import texture part of the inspector.


How to fix double click problem in this code? Please see the gif below to better understand what's going on. On first click they all work normally but after first click I have to double click them to select them. I'm not a advanced developer so I've been trying to figure this out for straight 2 hours and last choice I wanted to ask you guys. I declared select effect here. (White circle) And added an Array to get all select effects. public GameObject selectEffect private bool isSelected false public GameObject selectEffectArray I put them inside the Array. private void Awake() selectEffectArray GameObject.FindGameObjectsWithTag("planetSelected") selectEffect transform.Find("selectEffect").gameObject I deactivate all select effects on start. void Start() Deactivate() Here's Deactivate code. void Deactivate() foreach (GameObject effect in selectEffectArray) effect.SetActive(false) When I click one of the planets these happens. (I'm a little confused so I hope you can understand it.) void OnMouseUp() if (isSelected) selectEffect.SetActive(false) travelbutton.SetActive(false) isSelected false else Deactivate() planetName text.text planet.name requiredFuel text.text planet.requiredFuel.ToString() travelbutton.SetActive(true) selectEffect.SetActive(true) isSelected true I don't want to double click a planet to select it.


How to code camera for layered map in unity For a current unity project I need a layered map like in Dwarf Fortress. The game will take place in a 3D city enviroment and the camera should be 'snapped' to layers. So there will be (for example) a cave layer, ground layer and floor 1 3 layer. The player should be able to navigate the camera up and down with a keypress. So if the player is looking currently at the ground layer and press the camera should snip to floor 1 layer. All layers below the current level will be blurred and all levels above wont be visible (or at least faded out very strong) My question now is Is the layer system of unity useful for such a scenario, or is it better to implement an own data structure? I know about the ability of ignoring layers for rendering and raycasting but can the system be extended to support the features described above?


Unity C Rotate smoothly an object towards the direction given by input I am trying to rotate an object towards the direction given by de direction of the input. For example, if I am pressing 'up' of the directional pad, the player should rotate pointing that direction. I've tried using Euler angles, and when I press the direction, I call a coroutine that sums the eulerAngle.y of the object till it gets the angle of the direction, but it doesn't work. I don't know if there is another approach to use. Here is the code for the coroutine. It starts if a certain key is pressed and if a flag is not activated IEnumerator rotateTowards(float angle) rotating true Debug.Log("Rotating the mono...") Debug.Log("Your angle " transform.eulerAngles.y) float turningTime 0.8f float thisAngle this.transform.eulerAngles.y Vector3 thisAngle this.transform.eulerAngles if(thisAngle.y lt angle) while(thisAngle.y lt angle) thisAngle.y turningTime Time.deltaTime this.transform.eulerAngles thisAngle if(thisAngle.y gt angle) while(thisAngle.y gt angle) thisAngle.y turningTime Time.deltaTime this.transform.eulerAngles thisAngle this.transform.eulerAngles thisAngle rotating false yield return null Thanks in advance.


Parenting a child object to parent in Unity I am making an 3d Tennis game in Unity 5.0. I have made 3d model of the Tennis player in Makehuman and have successfully imported it to Blender and Unity. I want to add an tennis racket in the hand on my Makehuman model. So what should the strategy be? Should I add the tennis racket to the Makehuman character in Blender as the child of the Makehuman model and then animating it or is there a simple way to do that in Unity in the game.


How to slow down a Sphere smoothly in a world controlled by force and stop it (Unity 5)? I am a beginner and I started to use Unity 5. I play with tutorials on the site and documentation. I was basically testing springs, physics materials etc. I have a problem understanding probably a very basic thing I have a Sphere (Collider Rigidbody) and a Ground (Mesh Collider). I add force to Sphere on FixedUpdate with GetAxis method. I added Physics material to both sphere and the ground to create a friction. Ball slows down when I do not touch the keys (no new forces) but it never stops while moving on the ground. I know that as only 1 point is touching the gorund friction may not be good enough, but it almost does not affect the ball after a certain period. (I print the speed of the ball (Sphere) on a GUIText so I can numerically check it there too.) I am aware of default Sleep treshold value but it will effect everything as it is a global variable, so I can't use that. So, ball never sleeps. I am aware of drag and angular drag (like the friction of Air) of Rigidbody component and they for sure work, BUT it feels like the ground is sticky and ball stops very quickly. It doesn't look smooth and natural. Is there something that I am missing? The only way to do this is checking the speed of the ball and making it sleep manually when it's speed is low? Isn't there any other method? I don't want to do this as the world itself must live itself I don't want to check movement of every single object.. This is probably one of the most basic things, but I cannot understand why it doesn't work..


How to get crash reports from game Unity3d I am working on a project and I am in need of to gather CrashReports, email crash log, along with allowing the user to describe how the crash happened. I cannot find anything on how to do this, anyone has any ideas? Thanks! Learning Unity User


How to remove an element from the scene while keeping it in array? I combined cube meshes to make a big one. I stored the info of every cube in an array within a list of chunk. Now i want to delete the cubes in the scene to only keep the combined result, but without deleting the elements in the array. After combining meshes, i want to be able do destroy cube from it. So i want to keep the info so when i click the mesh, i get the position of the cube that would be there and check if it matches wit ha cube from the array. If it does, i want to remove it from the array and regenerate the mesh without that deleted cube. How would I do that ?


When would a mesh collider be better than primitive colliders I have been reading through the Unity Manual and have come across some interesting information about mesh colliders and primitive colliders. It got me wondering if using many primitive colliders would be better than using a mesh collider for say a character object? I was also wondering if there was any information on exactly how inefficient a mesh collider is to say having 20 box or cylinder colliders on a character mesh. I am guessing that the number of polygons on the mesh would be a factor but it would be interesting to see some raw comparisons between how this efficiency scales per polygon (or per 100 polys or some unit of measurement)


Change axis to view world from above in Unity Developing a 2d game where you view the "table" from above (think of a card game being played on a table). I have a candlestick on the table, but I must have something wrong because when I run it, it thinks it's on a wall versus a table because the flame goes up to the top versus "at" the camera from above. Here's the code of that "LookAt" script public class CameraFacing MonoBehaviour public Camera cameraToLookAt void Awake() cameraToLookAt Camera.main void Update() Vector3 v cameraToLookAt.transform.position transform.position v.x v.z 0.0f transform.LookAt(cameraToLookAt.transform.position v)


How can I rotate cubemap in shadergraph? I know how to rotate cube map with legacy surface shader Shader Rotation Matrix uniform float4x4 Rotation o.Emission texCUBE ( Cube, mul( Rotation, float4(IN.worldRefl,0))).rgb RotateCubeMap using UnityEngine public class RotateCubeMap MonoBehaviour public float speed 20 private MeshRenderer meshRenderer private void Awake() meshRenderer GetComponent lt MeshRenderer gt () public void Update() var rot Quaternion.Euler (0, Time.time speed, 0) var m new Matrix4x4 () m.SetTRS(Vector3.zero, rot,new Vector3(1,1,1) ) meshRenderer.material.SetMatrix (" Rotation", m) I tried to recreate it by shadergraph but it didn't work! I need a result like this


Smooth Lighting Falloff So, I'm having some issues with lighting in my Unity game. I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow". The reflected and refracted light ends up having two issues the light abruptly ends at the edge of floor tiles, and depending on the position, the light sometimes goes from it's blue color to a reddish color. I have a short (11 second) video here http www.labyrintheer.com wp content uploads 2016 11 Nov 17 2016 21 07 57.mp4 so that you can see what I'm talking about. I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue. Still images for anyone hesitant to click the video link Hard falloff Reddish color Using a single point light inside the cube, instead You can see it on the wall in the upper right and the floor at the top a bit. The upload seems to have lowered the quality a bit, but you can still see it. The single light makes it a little bit better, but there's still complete falloff.


Switching between meshes vs Loading only specific mesh I am currently developing an online multiplayer game on Unity. In the game, the character of each player will be assigned its mesh after the game receives parameters (their meshes' names) for each character from the server. Assigning each character's mesh can happen after the main scene is loaded. I am wondering whether I should make each character's object the same by having every mesh possible loaded into it and only activate the corresponding mesh for that player. I should create a class that holds every mesh possible (like, mesh manager) and tell each character to use its mesh from that class. I should delay the characters' meshes loading to wait for the parameter from the server first. Then, load the mesh after the scene has been loaded. I am not sure if specific assets can be loaded outside of its scene in Unity. If anyone has any different solutions, feel free to suggest. Thanks in advance.


Is it possible to measure Used vs Unused time in a 60hz frame in Unity? In custom engines I've often made a frame rate meter that shows how much of the each frame was actually used. In other words if the game is locked to 60fps using vblank I show a graph of how much of each frame was used for processing and how much was just waiting for the next vblank. This gives a visual indication of how much more can be added to a scene without hitting my frame rate budget. Is this possible to do in Unity? What I tried I made a script that creates a System.Diagnostics.StopWatch and starts it. I set that script's Script Execution Order to be the very first script. In the script's Update I record the ElapsedTicks from the stopwatch as startTicks. In the scripts's OnGUI I compute a deltaTicks as in long deltaTicks m stopWatch.ElapsedTicks startTicks I can then compute how much of a 60fps frame was taken with long ticksPerFrame System.Diagnostics.Stopwatch.Frequency 60 float amountOfFrameUsed (float)((double)deltaTicks ticksPerFrame) Note I get that OnGUI is called multiple times per frame but the way I end up storing amountOfFrameUsed I only end up recording the time from the last time OnGUI is called that frame. Anyway, this does give me a graph to look at but I have no idea if what it's slowing me is correct for Unity. In my own engine I'd record the time at VBlank and then in my code, when all processing was done I'd compute the elapsed time since vblank. Is what I'm doing correct? Is there a better or another way I should be doing this? (note I have not used the profiler because I wanted to see this FPS meter in a production app, not in the Editor where there is tons of overhead).


Visualizing NavMesh to Camera When Unity builds a NavMesh, you can see it in the scene view if you have the Navigation window open and select "Show NavMesh" in the Navmesh Display box. I'd like to use the exact same overlay in a camera view. Is this accessible in any way? Can it be rebuilt during runtime? Since the navMesh isn't an actual mesh, I can't seem to find a way to make this happen. EDIT This is what I'm trying to work with right now public class NavMeshToCamera MonoBehaviour NavMeshTriangulation triangles Mesh mesh void Awake () triangles NavMesh.CalculateTriangulation() mesh new Mesh() mesh.vertices triangles.vertices mesh.triangles triangles.indices I have this script attached to a secondary camera that will be enabled while holding down a button to see an overlay of a minimap of the current dungeon. I'm not quite sure what to do with the mesh data to provide a mesh visible to the camera. Since no mesh exists initially, I suppose I'd have to take the new mesh, apply a layer to it, and have only that layer visible to the camera. But I'm having some difficulties with this.


How to make an object track another object's exact movements This script below helps me to to tell the follower object to copy exact movements of the leader object, I found this script in Unity forums and it works pretty well. My question is how can I add some kind speed variable to it how can I tell the follower object to move at lower speed? public class delayTracker MonoBehaviour float progress const int MAX FPS 60 public Transform leader public float lagSeconds 0.5f Vector3 positionBuffer float timeBuffer int oldestIndex int newestIndex Use this for initialization void Start() int bufferLength Mathf.CeilToInt(lagSeconds MAX FPS) positionBuffer new Vector3 bufferLength timeBuffer new float bufferLength positionBuffer 0 positionBuffer 1 leader.position timeBuffer 0 timeBuffer 1 Time.time oldestIndex 0 newestIndex 1 void LateUpdate() Insert newest position into our cache. If the cache is full, overwrite the latest sample. int newIndex ( newestIndex 1) positionBuffer.Length if (newIndex ! oldestIndex) newestIndex newIndex positionBuffer newestIndex leader.position timeBuffer newestIndex Time.time Skip ahead in the buffer to the segment containing our target time. float targetTime Time.time lagSeconds int nextIndex while ( timeBuffer nextIndex ( oldestIndex 1) timeBuffer.Length lt targetTime) oldestIndex nextIndex Interpolate between the two samples on either side of our target time. float span timeBuffer nextIndex timeBuffer oldestIndex float progress 0f if (span gt 0f) progress (targetTime timeBuffer oldestIndex ) span transform.position Vector3.Lerp( positionBuffer oldestIndex , positionBuffer nextIndex , progress ) void OnDrawGizmos() if ( positionBuffer null positionBuffer.Length 0) return Gizmos.color Color.grey Vector3 oldPosition positionBuffer oldestIndex int next for (int i oldestIndex i ! newestIndex i next) next (i 1) positionBuffer.Length Vector3 newPosition positionBuffer next Gizmos.DrawLine(oldPosition, newPosition) oldPosition newPosition


WorldToGUIPoint seems always off by about 2 pixels I'm trying to draw small boxes at each vertex of a mesh, in the editor. My OnSceneGUI code looks like this foreach (Vector3 vertex in mesh.vertices) Vector3 worldVertex meshTransform.localToWorldMatrix.MultiplyPoint3x4(vertex) Vector2 guiPoint HandleUtility.WorldToGUIPoint(worldVertex) var rect new Rect(guiPoint, Vector2.one BOX SIZE) EditorGUI.DrawRect(rect, Color.red) I want the upper left corner of each box to align with the mesh vertices. With the above code, the boxes are drawn at the wrong location, as you can see in the picture below. If I apply an offset of (2, 2) in GUI coordinates, however, the boxes are drawn at the correct location. I'd like to avoid having to hard code this (2, 2) offset into each draw call. Why is Unity off by a few pixels here? I also tried using GUI.Box to do the drawing, but it was off by the same amount. What is going on? Incorrect Correct. With constant (2, 2) offset Update I have an untested hypothesis as to why this is happening. I am rendering a GUI rect with the default GUIStyle. The default GUIStyle has the padding and margin values set. I bet that if I created a custom GUIStyle with zero padding and margin the rects would draw where I want them to.


How to create a walkable crate box? I have a 2D platformer with each platform having a PlatformEffector2D component. I want to create a crate that can be pushed. When I jump into the edge of the crate, my player gets stuck, so I added PlatformEffector2D to the crate. But when the crate has a PlatformEffector2D component it falls below the platform. I can remove the component and add a Physics2D Material with zero friction to prevent the player from getting stuck in the crate's edge, but I can't walk above the crate (because the zero friction). The images below illustrate it. Player getting stuck in the edge of the crate that don't have PlatformEffector2D. If it has a PlatformEffector2D it will fall below the platform. My objects have the following components (when the player gets stuck at the edge of a crate) Player (BoxCollider2D, Rigidbody2D) Crate (BoxCollider2D, Rigidbody2D) Platform (EdgeCollider2D, PlatformEffector2D) What should I do so my player can push the crate and walk above the crate? Would anyone happen to have a sample script? FYI I use Physics2D.OverlapCircle to detect the ground. (Unity 5.4.0)


Is it possible to debug a Unity Android game directly on a device? I'm working on my game and every time I make changes to it I send the game to my mobile device to debug it. I want to know how I can directly debug my game using an Android device instead of the MonoDevelop editor?


How can I make the overlapping object's outlines merge and not display on top of other objects that have the outline shader? This is what I am trying to achieve. I was following https www.youtube.com watch?v SlTkBe4YNbo but the outlines show on top of other if the objects overlap. I tried looking through various outline shaders but couldn't find much. I found that it has something to do with Z Depth but I am not sure how. My reason for doing this was to replicate the Unity Editor's object selection in the project. I somehow got the gizmo partially working(using a 2nd camera) and am now stuck on object highlighting on selection.


Stop Camera up movement I am developing 3D game , the main camera is child of player. When player jumps camera too gets move up with player as its child of player.Is there anyway to stop this behavior? The only thing I can guess is to make camera separate gameobject and let it follow player EDIT After applying Everless Drop 41's script, here is what main problem arises


1 bit game How to change the palette for the entire game at runtime? So I'm making a 1 bit color game, and would like to have an option in the menu to change what those two colors are so the player can adjust it to their liking. What is the simplest and or best method to go about this? This would apply to the entire screen, not individual sprites meshes, as I want to preserve the 1 bit color look. Most of my assets are sprites, with a few flat meshes that are rendered without anti aliasing so that they blend in with the sprites. They're all exported with the two standard colors I'm using (a yellow ish off white and a dark grey ish blue), but I can go back and re export them in black and white if that is necessary for the suggested method. My eventual plan is to support the basic black and white, a few monochrome monitor color schemes, and some color combinations that you'd see on 8 bit computers (C64, Apple, etc.).


How can I separate gameview from UI most efficiently in Unity? Let me provide an image to illustrate what I mean. It is from a game called Runescape.


In Unity, how do you check if a camera is rendering anything? (Unity 2018.3) I'm trying to have a camera automatically disable if it's not rendering anything. Is there a simple way to check if a camera is blank empty? Edit Alternatively, is there a way to prevent a camera from rendering if there is nothing in it's view? For example, I do not want MSAA applied to a blank camera. (I'd hope it would attempt AA, but effectively do zero work)


How can I "amplify" current motion ? I've two objects A and B. A impact B causing B movement. I want programmatically "amplify" B movement mantaining B resulting direction. I've try adding a script like this void OnCollisionEnter(Collision col) Controllo se un tag if ( forceAlreadyApplied false) rb.AddForce ( forcePower transform.forward, ForceType) forceAlreadyApplied true The problem is that transform.forward obviously change B direction. Maybe this is a wrong approach. My question is how to "amplify" current speed ? Thanks


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


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


How to set parent for prefab in Unity I have a prefab of a button (btn) that I need to set parent ( canvos) for it after it spawned (online)... I have try this code public Transform btn public Transform mkn public Image canvos public void test () Transform InTank Network.Instantiate (btn, mkn.transform.position, Quaternion.identity, 0)as Transform btn.SetParent( canvos) But it doesn't work. error MissingReferenceException The object of type 'Object' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. what's the problem??


How do I get a popup menu to block clicks from hitting UI elements beneath it? You can see in the picture that I have a Canvas with a popup menu in it. I just enable this, and it covers the main menu stuff. Clicks go through it and hit stuff in the main menu. I've tried adding an EventTrigger to the PopupRoot object, and adding an event to listen for PointerClick events, but it doesn't fire. EventTrigger trigger m popUpRoot.GetComponentInChildren lt EventTrigger gt () EventTrigger.Entry entry new EventTrigger.Entry() entry.eventID EventTriggerType.PointerClick entry.callback.AddListener((eventData) gt PopupClickBlocker((PointerEventData)eventData) ) trigger.triggers.Add(entry) I'm open to other suggestions. My current system is horrible button click events query the Popup to see if it's enabled or not, then return doing nothing if it is. This doesn't work for sliders very well, so I want to do this the right way.


Create an atlas texture in photoshop to use in unity To create a button in NGUI looks like we need to create something called Atlas that is a material that contains a lot of little images called Sprites. I created a set of 40 sprites (for 20 buttons needed in game, normal state and clicked state) in photoshop in a 2048x2048 image file. When i tried to use NGUI atlas maker i realized that atlas maker requires each sprite in a separate file and wants to merge them in the atlas itself! Well, i already have them in one file, should i slice all these buttons and save them in 40 other separate files and let the atlas maker merge them again for me? (Sounds very stupid!) Isn't there any way to give the merged 2048x2048 file to atlas maker (or any other equivalent plugin software) and then tell the software "Hey! I have 40 sprites in this image, let me tell you where they are! The first one is in (3,3) with size of (150px, 150px), The second one is..."? UPDATE I found a part of solution, unity could identify my 40 sprites in texture using sprite editor tool, but NGUI cannot still find them. I created a material using "Unlit Transparent Colored" shader and referencing the atlas to it, then i created a new empty game object, added UI Atlas component to it and referenced the material in it, but it says there are no sprites. If i make a prefab out of this game object then NGUI can use it as an atlas and my problem will be solved


Admob for Unity clarification on use needed I'm following this documentation by Google on how to integrate Admob ads into my game and I'm confused because of the following This documentation says I build by game and then I mess around with ads. (Section Unity plugin API tells me how to add ads and that's after the build instruction). Shouldn't it be vice versa? That I place those ads and build last? Or, if I really do build first, where do I add those ads?


Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D


Unity OnGUI streamlining So like most games, I have inventory screens, equip screens, shop screens, and all that. I've previously been making each "screen" controlled by its own script (which is normal I think), and I draw the screens using GUI. However, I'm worried about having multiple OnGUI functions in my game (one OnGUI for each "thing" I draw eg Inventory or Shop ) since OnGUI really isn't that best for performance. How should I solve this problem? I thought about making each screen its own scene in the game but I wasn't sure if that would help things much.


How do I make an object's y axis align with a Vector3? I have a golf ball on the ground, and from a raycast, I have the normal which gives me the slope of the ground by the ball. I have an object which is rendered on the HUD to show that slope to the player. I have a parent object rotated 90 degrees around X, so that the indicator's Z axis points up. This way I can do this Quaternion yRot Quaternion.Euler(0, CameraController.Instance.CachedTransform.eulerAngles.y, 0) Vector3 displayGroundNormal yRot groundNormal lieIndicator3DParentCachedTransform.rotation Quaternion.LookRotation(displayGroundNormal) This, as far as I can tell, takes the ground normal, rotates it around the y axis so that it shows the proper perspective given the camera's facing. Then it tells that parent object to look in that direction, which aligns its z axis with the rotated ground normal. This works, except the object I have also rotates around the y axis depending on the orientation of the camera. I thought that I was throwing that information away in the second step by keeping only a Vector3 aligned with the ground normal rotated for the camera position. So I want this Not this


Unity3D AI follow player script for prefab enemy? So I am having an issue, I have an enemy prefab that is created when the new wave happens(think of Nazi Zombies from Call of Duty, same system) but every script I have found that deals with ai following player always involves a public transform variable. The issue is that the object I put in that variable in the inspector does not save with the prefab, rendering the script useless. Is there anyway I can get the enemy prefab when the enemy spawns to follow the player? He is a script I tried and failed due to the issue The target player public Transform player In what time will the enemy complete the journey between its position and the players position public float smoothTime 10.0f Vector3 used to store the velocity of the enemy private Vector3 smoothVelocity Vector3.zero private void Start() Call every frame void Update() Look at the player transform.LookAt(player) Move the enemy towards the player with smoothdamp transform.position Vector3.SmoothDamp(transform.position, player.position, ref smoothVelocity, smoothTime) Time.deltaTime


Passing Gameobject to another script in unity 3d I'm trying to pass a gameobject from one script to another runtime attached script. My fisrt script is attached to the FirstPlayerController and the gameobject is not dragged in the editor, but is picked up and carried in the script. All i want is to pass the gameobject to the CameraController class to as make the second camera follow that object. Below is what i've tried so far. I dont want to access the gameobject with the tag, because there are more gameobjects that can be picked up. I want to access the carried object to the cameracontroller class. Thanks! Pickupobject.cs using System using System.Collections using System.Collections.Generic using UnityEngine public class pickupobject MonoBehaviour GameObject mainCamera bool carrying public GameObject carriedObject public float distances public float smooth float speed 1000f new Camera camera Use this for initialization void Start() mainCamera GameObject.FindWithTag("MainCamera") camera GameObject.FindWithTag("secondCamera").GetComponent lt Camera gt () camera.enabled false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.T) amp amp carrying) carrying !carrying ThrowBall() if (carrying) carry(carriedObject) else pickup() private void pickup() if (Input.GetKeyDown(KeyCode.E)) int x Screen.width 2 int y Screen.height 2 Ray ray mainCamera.GetComponent lt Camera gt ().ScreenPointToRay(new Vector3(x, y)) RaycastHit hit if (Physics.Raycast(ray, out hit)) pickupable p hit.collider.GetComponent lt pickupable gt () if (p ! null) carrying true carriedObject p.gameObject camera.enabled true camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () void carry(GameObject o) o.GetComponent lt Rigidbody gt ().isKinematic true o.transform.position mainCamera.transform.position mainCamera.transform.forward distances void CheckDrop() if (Input.GetKeyDown(KeyCode.U)) Drop() void Drop() ThrowBall() void ThrowBall() mainCamera.SetActive(false) camera.enabled true carriedObject.AddComponent lt CameraController gt () camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () carriedObject.GetComponent lt Rigidbody gt ().isKinematic false carriedObject.GetComponent lt Rigidbody gt ().AddForce(0f, 0f, speed) CameraController.cs using System.Collections using System.Collections.Generic using UnityEngine public class CameraController MonoBehaviour public GameObject icosphere public GameObject abc Vector3 offset Use this for initialization void Start () icosphere GameObject.FindWithTag("purpleball") offset transform.position icosphere.transform.position Update is called once per frame void Update () transform.position icosphere.transform.position offset


Photon2 Unity2D How to send float with RPC I have big problem in my code .. I want to spawn obstacle exactly on the same position as on the server is spawned so I made rpc Method and tried to pass random variable of float , but when i run the game obstacles are spawned on the diffrent position. I am loosing a lot of time to get it done but I still can not find solution. Here is the code PunRPC void RPC SpawnColumn(Vector3 position) Instantiate(prefab, position, Quaternion.identity) Debug.Log("THIS IS SPAWNYPOSITION" spawnYPosition) Instantiate(prefab, new Vector2(9, spawnYPosition), Quaternion.identity) private void OnTriggerEnter2D(Collider2D collision) print("Are we here") if (collision.GetComponent lt ColumnsMultiplayer gt () ! null) print("Or are we here") if (SpawnOnce) spawnYPosition Random.Range( 3.36f, 2.98f) photonView.RPC("RPC SpawnColumn", RpcTarget.Others,new Vector3(9, spawnYPosition)) this is SpawnColumn() SpawnOnce false Thank you so much for reading post. Edit I need to send spawnYPosition from method two to method one and spawn it with same position of spawnYPosition in the second method.


How to rotate an object to a specific transform? I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels?


How can I cut a doorway through my wall at runtime? I am working on a Unity project where I have 3 models a stacked, rounded wall (think logs), a flat wall (think bricks), and a door. The door has an animation to open close itself, and when it's attached to a wall, there's one major problem when the door swings in, it reveals not the empty space one would expect, but the segment of wall it's layered on top of! Since all 3 models are part of dynamic mesh structures, I can't "pre calculate" what the model should look like to account for the empty space of the door what if the player puts the door on the next segment of wall instead? I considered expanding the "door" model to a "door wall segment" model (replacing that wall segment entirely), but because I already have two separate shapes of wall, it quickly becomes a combinatorics problem 2 models for each door, per door shape (not to mention windows, or a 3rd or fourth! wall shape!). In short, this doesn't seem like a tenable solution. What would work most cleanly is if I could remove a "Door shaped" segment of my Wall segment mesh, leaving a clear hole that the Door model could snugly fit. In an equation Final Mesh A Mesh A Volume (Mesh A Volume Mesh B Volume) Is an operation like that feasible? My gut tells me that polyhedron intersection is hard, and there might be a better way to do this. I'm also equally interested if someone has a better suggestion on how to solve the initial problem of doors intersecting with wall segments.


How to rotate a local position offset based on a direction vector? I'm trying to fire three raycasts in the direction of movement, from offset starting points. I'm having trouble calculating the start positions of the rays based on the direction. As you can see in the animation, the three parallel lines in the middle overlap when moving upwards using the code below, but I want them to remain evenly spaced. I cannot use transform.right (up etc) etc because the transform is always facing the same direction by design. Instead I am using the currentDirection which is the normalized last movement velocity. I want the lines to always be evenly spaced based on the direction the object is moving without rotating the actual transform the problem is I don't know the math behind it and have spent last several hours trying to figure it out. Current code Debug.DrawRay(this.transform.position, currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.magenta, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) I've tried to get the position based on direction by using var drawRayTopPos currentDirection localpos position


Unity scaling and animations In my Unity project I have a script that programmatically changes the scaling of an object during the game. Recently I wanted to add a spawning animation clip to my object, which modifies the object's scaling (but only during a short delay). So I added an animation controller to the object, containing the spawning animation clip. I can now successfully run the spawning animation but the in game programmatic scaling changes don't work anymore, even when my animation is not running. Any idea?


How to access arrays of prefabs and other properties through the inspector in a given hierarchy The script below is added to an empty game object WeaponGroup, which can be populated using the editor. I have made a new game object WeaponGroups which should have a script SetupWeaponGroupsScript. How can I transfer the properties below so that each WeaponGroup (SetupWeaponGroupsScript will have an array of WeaponGroup objects) is setup in a way similar to what is done below, so that I make the SetupWeaponsScript properties hidden to the inspector and populate them through SetupWeaponGroupsScript? public class SetupWeaponsScript Here's our tuple combining a weapon prefab and a direction. System.Serializable public struct DirectedWeapon public WeaponScript weapon public WeaponScript.Direction direction The prefabs array is now this tuple type. public DirectedWeapon weaponPrefabs public WeaponScript weapons void Start () weapons new WeaponScript weaponPrefabs.Length for (int i 0 i lt weaponPrefabs.Length i ) Using typed Instantiate to save a GetComponent call. weapons i Instantiate lt WeaponScript gt (weaponPrefabs i .weapon) weapons i .weaponDir weaponPrefabs i .direction In other words I'd like to have the following hierarchy in the editor


Moving the rendered object the projection perspectives based on an AR marker I saw this video and now I am trying to making it. I have used Vuforia AR Camera Pulgin, and so far tracked the image on a marker but the problem is getting the four projections of the 3D object on a screen. Here is an example of what it looks like. I have used Viewport Rect method with four cameras but that does not seem to change the projections as I move the marker.


How do I prevent falling tiles from bouncing on each other in my match 3 game? I am working on a match 3 game in Unity. The tiles have a RigidBody2D in dynamic mode and a BoxCollider2D. When a match occurs and the tiles are removed, the tiles above (including spawned replacement tiles) fall until they land on another tile or the tile catcher at the bottom of the board. There is a routine which checks when everything is settled (all tile rigidbodies are asleep) and then processes any new matches. However, the tiles push each other down on impact, causing a rebound and a very slow process of "settling" to their final position. The physics material for the tiles has no bounciness, so I believe this is being caused by the cumulative force of the tiles landing on each other in the physics simulation. What I'm hoping to do is have the tiles drop the way they do (the gravity simulation is just right!) but essentially stop when they collide with another tile (i.e. not transfer any force at the point of collision). This way, they shouldn't rebound visually and also should sleep more rapidly, so matches from falling can process more immediately. So far, the suggestions I've seen are Set the velocity to 0. This doesn't work, and I assume it's because there is still being force applied. Detect the tile collision and set the tile to kinematic, then set it back to dynamic. I haven't been able to get this to work, as they won't turn back to dynamic. I even tried to disable the colliders until they turn back in case the collision detection keeps happening and is just overwriting it too rapidly. At any rate, this feels like a dead end. Scrap the rigidbodies and essentially write my own, scripted gravity simulation. I'm simply hoping to avoid this because the rest of the simulation is working great. Create a kinematic rigidbody on a child object, set the dynamic parent and kinematic child to ignore collisions with each other, make the kinematic collider slightly (0.1) larger so it collides first. I gather the idea here is to have the physics simulation pull down the dynamic body, while the kinematic child will stop on collision. At any rate, this also did not work, and also sounds like a bad idea. I've considered trying to calculate the impact force and apply an equal opposing force, but I haven't figured that out yet, and I imagine at that point I should just write my own gravity simulation, per above. I've recorded a video for visual reference on the "bounciness" https youtu.be aSCEJX4nzoI


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


combining multiple materials into one material (Unity) I am confused with how should I texture my character. I am using blender for modelling. And while my model is too complex I dont want to use uv map techniuqe. I can get what I need with using seperate materials. Therefore I assign different materials to different meshes in Blender then import it to Unity. Therefore I have lots of different material in one model and I think it increases draw call. What can I do to combine these material into just one. I thought baking would be sollution but while my character is dynamic I can not get a good result.


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.


Unity3d Android Fixed Resolution How can i set a fixed 720p resolution on any devices using unity3d android? unity3d version 2018.4.5f1


Sending a shot left right up down based on directional key press I am trying to make a top down shooter game with similar combat to the Binding of Isaac when I press the up key the shot goes up when I press the right key the shot goes to the right I have all the rest of the code such as the point where the projectile is instantiating and the if statement to check for the button press I just want to know where I should put the vector 2 to allow me to set the direction and what to write into the vector 2 private void Update() if (Input.GetKeyDown("up")) if (Time.time gt shotTime) Instantiate(projectile, shotPoint) shotTime Time.time timeBetweenShots This is my Projectile script (at least the parts that I think would be useful) void Update() transform.Translate(Vector2.up speed Time.deltaTime) I realized that if I change the Vector2.up to make it say Vector2.down it would now shoot down But I need that to be able to change depending on which direction I am shooting.


How do I make my character change his ability's when his sprite changes I am making a platformer and am currently trying to have it so that my character will have different powers based on his emotions, and his sprite will change to match those emotions. I have got it so that his sprite will change but I don't know how to get his powers to change as well. Note that I haven't even made his other powers yet, but even if I did I don't know how to change his ability's with his sprites as I am still very new to this whole coding thing. Can anyone please help me? Here is my code for changing his sprites, if that would help. using UnityEngine using System.Collections public class MoodManager MonoBehaviour public Sprite sprite1 happy public Sprite sprite2 angry public Sprite sprite3 sad public Sprite sprite4 default private SpriteRenderer spriteRenderer void Start () spriteRenderer GetComponent lt SpriteRenderer gt () we are accessing the SpriteRenderer that is attached to the Gameobject if (spriteRenderer.sprite null) if the sprite on spriteRenderer is null then spriteRenderer.sprite sprite1 set the sprite to sprite1 void Update () if (Input.GetKeyDown (KeyCode.Alpha1)) If the space bar is pushed down ChangeMoodHappy () call method to change sprite if (Input.GetKeyDown (KeyCode.Alpha2)) ChangeMoodAngry () if (Input.GetKeyDown (KeyCode.Alpha3)) ChangeMoodSad () void ChangeMoodHappy () if (spriteRenderer.sprite sprite1) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite1 otherwise change it back to sprite1 void ChangeMoodAngry () if (spriteRenderer.sprite sprite2) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite2 otherwise change it back to sprite1 void ChangeMoodSad () if (spriteRenderer.sprite sprite3) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite3 otherwise change it back to sprite1


Unity 3d Forge Networking Transfer object ownership I have a simple chess game setup to play around with the Forge Networking asset. I am having an issue where only the server is able to click and drag pieces around the board. If a client attempts to move a piece, it gets snapped back to its original position. I assume this issue is because the server is the actual owner of the NetworkedMonoBehaviour components on my chess pieces. Is it possible to transfer ownership of a NetworkedMonoBehaviour in code? It seems that all of the owner properties have protected set methods so I am unable to access any of them.


3D Studio Max biped restrictions? I have a stock biped character in 3D studio max which has a jump animation. The problem I have with the jump animation is that there is actual y offset happening inside it which makes it awkward to play while the character is jumping since it's not only jumping in the game world but the jump animation is adding its own height offset. I'm tryuing to remove the jump animations height offset, so far I've found the root node and deleted all its key frames which has helped a bit. The problem I'm having now is that the character still has some height offset and if I try to lower it it has a fake 'ground' that isn't at 0 and the limbs sort of bend on the imaginary floor, si there a way to remove this restriction just for the jump animation? Here's what I mean http i.imgur.com qoWIR.png Any idea for a fix? I'm using Unity 3D if that opens any other possibilities...


What is the "Unity" way to approach tech design for a 2D game like this? So I come from C land where I've always done every little thing myself. Now I'm getting into Unity and C and I'm ironically overwhelmed with the domain. I'm starting off with this simple little 2D game and I'm wondering... if someone can point me to the correct tools that would lead to a successful implementation of this game. Here is a quick mock up I did in paint These are the parts of Unity I've investigated Tilemap Canvas GridLayout Prefabs GameObjects (these seem fundamental to Unity, heh). After researching these topics, and playing around a bit, here are my initial questions How do you approach Canvases in Unity? I could see this being split into 5 separate Canvases, one for each local body of UI. Or 1 Canvas for the game board, and 1 canvas that contains a single overlay with all of the other UI components. But then how do those components typically get positioned? Is it common practice to place by absolute coordinates? I guess I'm getting hung up on.. how do I place my canvas for the game board in that position relative to all the other UI elements? I'm a C application developer so if I'm doing UI at all I'm used to layout systems. I'm not sure how common that is in this ecosystem. Should I even use TileMap for this? It doesn't seem like I need that kind of power. My grid is finite and fits on screen. My gut reaction is that I should just instantiate a bunch of colored squares at first. But I'm not really sure the best approach to that either. GridLayout on a canvas? Absolute coords? TileMap? What other tools should I be looking at? By tools I mean Unity concepts I didn't mention above. My initial thought is to just have a backing data structure that holds all the data for the grid, and then I just render... prefabs? based on that data? Maybe I just want someone to tell me I'm on the right track or quot no you're doing it totally wrong use this other thing quot , heh.


An error comes up in console when trying to enter play mode in unity Hay folks, i pray for everyone's wellbeing. I want to ask a question that whenever i enter playmode in unity, error message is displayed even though there is nothing in the console. This doesn't get fixed even after restarting unity. Any help would be great.


Unity 3D C How to properly reset a scene I have a problem when I try to reset a scene. It doesn't seem to run, I have a script (of all scripts that have Awake and Start methods on that scene) that on the Awake method starts a coroutine, but when reseting the scene it doesn't even run it. I've read that it may be a problem of using the DontDestroyOnLoad method, but that doesn't seem to solve the problem since that script on the start takes a lot of references of objects that are only on the scene that I want to restart. I don't use any static variables on any script. I made an unitary test trying to restart a scene with just one object and one script attached, on its Start method it also starts a coroutine but even in that test it doesn't even run the coroutine. Here's the script of the unitary test using UnityEngine using System.Collections using UnityEngine.SceneManagement public class LoadingSceneController MonoBehaviour void Awake() DontDestroyOnLoad(this.gameObject) Scene scene Use this for initialization void Start() scene SceneManager.GetActiveScene() DontDestroyOnLoad(this.gameObject) useStartCoroutine() void useStartCoroutine() StartCoroutine(loadScene()) IEnumerator loadScene() yield return new WaitForSeconds(3) SceneManager.LoadScene("gameplayScene 1") SceneManager.LoadSceneAsync("gameplayScene 1")


Display musical symbol (unicode) in Text component not working? I downloaded and specified to use a unicode font that supports musical symbols (Musica), but when I set the text value of the Text component to quot quot nothing is displayed? I tried using the unicode code point with U as well. What is going wrong? (I could not get TextMesh Pro working either with that symbol.)


unity read from text file to instantiate objects I'm trying to use the following code to read a text file stored in the Resources folder or in a file on my computer, and instantiate objects in a Unity 3D scene accordingly. I'm having trouble getting it to work. I've tried attaching the script to either the main camera or an empty gameobject. Neither work so far... I either end up with an error saying the path does not exist (when I put the text file into the project folder on my desktop), or a null exception, or that the path contains invalid characters. Where am I going wrong? I'm trying to use a jagged array because I'll need users to eventually be able to change the text file on the go to create a level. The text file contains the following data S 0 0 0 1 0 0 1 0 2 2 0 0 2 1 My script currently reads using System.Collections using System.Collections.Generic using System.Text.RegularExpressions using UnityEngine using System.Linq using System.IO using UnityEngine.UI public class GenerateLevel MonoBehaviour public Transform player public Transform ground public Transform floor valid public Transform floor obstacle public Transform floor checkpoint public const string sfloor valid "0" public const string sfloor obstacle "0" public const string sfloor checkpoint "2" public const string sstart "S" public string textFile "maze" string textContents Use this for initialization void Start () Instantiate(ground) TextAsset textAssets (TextAsset)Resources.Load(textFile) textContents textAssets.text string lines System.IO.File.ReadAllLines(" maze.txt") string textFile textFile Resources.Load("assets resources maze").ToString() string jagged ReadFile(textContents) for (int y 0 y lt jagged.Length y ) for (int x 0 x lt jagged 0 .Length x ) switch (jagged y x ) case sstart Instantiate(floor valid, new Vector3(x, 0, y), Quaternion.identity) Instantiate(player, new Vector3(0, 0.5f, 0), Quaternion.identity) break case sfloor valid Instantiate(floor valid, new Vector3(x, 0, y), Quaternion.identity) break case sfloor obstacle Instantiate(floor obstacle, new Vector3(x, 0, y), Quaternion.identity) break case sfloor checkpoint Instantiate(floor checkpoint, new Vector3(x, 0, y), Quaternion.identity) break Update is called once per frame void Update () string ReadFile(string file) string text System.IO.File.ReadAllText(file) string lines Regex.Split(text, " r n") int rows lines.Length string levelBase new string rows for (int i 0 i lt lines.Length i ) string stringsOfLine Regex.Split(lines i , " ") levelBase i stringsOfLine return levelBase


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?


Platformer Crouching problems I'm trying to implement a crouching system to my 2D platformer. The problem is, I don't want the character to be able to do anything else except jumping when it's crouching. I have many functions but I think posting the movement function here would be enough. When I gain velocity and then press crouch, I skid across the platform, and stop. First, my crouch function private enum State idle, running, jumping, falling, crouching void Update() crouch if(Input.GetButton( quot Crouch quot )) animator.SetInteger( quot state quot , 4) Crouch() else boxCol.size new Vector2(0.5454721f, 1.8065f) void Crouch() boxCol.size new Vector2 (0.6933689f,1.44953f) And here is my movement function. I tried to fix it by adding the if condition on top of it, but when I run and crouch, it slides a lot before stopping. What can I do to fix that? The character already has a physics material with zero friction. I know I can make the velocity zero if the player is crouching but that would just kill the gameplay. I need to add a smooth stopper. I'm not sure how to make a decelerating script and use it in my case. public void Move() if(animator.GetInteger( quot state quot ) ! 4) float x Input.GetAxis( quot Horizontal quot ) float moveBy x speed rb.velocity new Vector2(moveBy, rb.velocity.y) if (x gt 0f) transform.localScale new Vector2(1, 1) isRight 1 isLeft 0 else if (x lt 0f) transform.localScale new Vector2( 1, 1) isLeft 1 isRight 0


Alternatives to raycasts in unity? I have an ai car script. The car needs to be able to slow down and or stop if it gets too close to another car. Right now I'm using 3 raycasts like so if (Physics.Raycast(lRay, out lHit, rs.forwardCollisionRayLength, rs.rayLayerMask) Physics.Raycast(rRay, out rHit, rs.forwardCollisionRayLength, rs.rayLayerMask) (Physics.Raycast(mRay, out mHit, rs.forwardCollisionRayLength, rs.rayLayerMask))) some code... However this is really long and inconvenient because it's a pain to figure out which raycast actually had the hit. And then there's other cases where multiple raycasts hit the same car, which point do I use, or if different raycasts hit different cars...Anyway, you can see that this is not ideal. Also, depending on the size of an object, it could go between the raycasts. In the image below, the blue box is ok because its wider than the width between the raycasts, thus two of the raycasts find it. But on the other side, the green pole is too small, so the car can't see it and drives on. I also need to get the distance between the hit.point and the car so that I know how much the car needs to slow down so that there's a reasonable distance between the two cars at all times. I could use something like Physics.OverlapBox or Physics.CheckBox but then I can't get the distance between the closest point of the car, only the center of it. This is bad because some cars are longer than others I need the distance between the nearest point of the car. Also, keep performance in mind, I could solve the problem of objects going in between raycasts by adding more, but that will drain performance hugely, mainly because I have up to about 40 cars running at a time. TL DR What are some alternatives for a raycast that can also give me the distance to the closest point?


Animate moving object I have a sphere shot out of a cannon which i need to get lined up with another sphere when and if the two spheres collide. Considering that both spheres are moving (one in X and the other is shot at the first one) how would i animate the cannon sphere to line up if the collision occurs? I can use a bool to check if collision but how do i animate the projectile in the animation tab so that the projectile takes into consideration the always changing position of the X moving sphere ?


Load Material from file path or parse .mat file to Material Unity Is it possible to load a material from a file path? Or, otherwise parse a .mat file saved on disk to a Material usable at runtime? I had naively thought it would be possible to assign the bytes from a .mat file, as read by File.ReadAllBytes to a Material object, but that does not seem to work.


How I start a over a new game using a ui button logic code? My Hierarchy have 3 main GameObjects Game Data where all the gameplay objects are stored as childs of the Game Data GameObject. Main Menu and all objects of the main menu stored as childs under the Main Menu GameObject. Game Manager GameObject that have a script that control the game like pausing the game or go to the main menu. By default the Game Data is disabled and all the gameplay objects childs disabled too. Then when starting the game with the main menu when clicking the button to start a new game I'm just activating the Game Data object This script is attached to the Main Menu using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class MainMenu MonoBehaviour public GameObject gameData public void StartNewGame() gameData.SetActive(true) public void ResumeGame() public void QuitGame() Application.Quit() This is working for first time starting a new game. And this script is attached to the Game Manager GameObject using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class GameController MonoBehaviour public static bool gamepaused false public GameObject gameData public GameObject mainMenu private void Update() if (Input.GetKeyDown(KeyCode.P)) gamepaused !gamepaused if (gamepaused) Time.timeScale 0f else Time.timeScale 1f if (Input.GetKeyDown(KeyCode.Escape)) gameData.SetActive(false) mainMenu.SetActive(true) Time.timeScale 0f This script is working. When pressing the P button the game pause continue. When pressing the ESCAPE key the game also pause but also back to the main menu by switching the gameobjects disable enable. Now let's say I pressed the escape key while playing the game and I'm back to the main menu now I want to start a new complete game but clicking the StartNewGame ui button. The problem is that this time I don't want to just active the Game Data like I did before gameData.SetActive(true) This time at least in my logic I want to destroy the existing Game Data and instantiate a new Game Data using a prefab I already have of the Game Data. This is my logic but I'm not sure how to do it. Or something like that. The main goal is to be able to start over a new game each time clicking the StartNewGame ui button.


Display Rich Text in a TextMeshProUGUI component I am rading a text to be displayed in a Text UI from an asset using the standard commands Resources.Load lt TextAsset gt ("nameOfMyTextAsset") The text is a .txt. The text contains richtext tags to format the text in bold or italics. The richtext tags are displayed as such. I am using TextMesh Pro and insert the text via the following cmd public TextAsset MainText MainText Resources.Load lt TextAsset gt ("nameOfMyTextAsset") this.GetComponentInChildren lt TextMeshProUGUI gt ().text MainText.text The text is displayed like this How can I read text with richtext tags from a text asset?


Unity, Player isnt following along the waypoints I have a player with a Rigidbody, I want it to follow along the Waypoints, I have a script for it I tested it first on a Cube, everything worked fine, but on my character it just moves Towards the first waypoint then stays on the first waypoint instead of going ahead. Even if I comment out the LookAt Code section its not working. It could maybe cause the Y position of the waypoints that my player is stuttering, I changed it now. It is now moving along but stuttering much. Here is a picture of the problem Here is my code public GameObject waypoints public float grindSpeed public float turnSpeed public int currentWaypoint private Animator anim private Rigidbody rb public bool isGrinding false void Start() anim GetComponent lt Animator gt () rb GetComponent lt Rigidbody gt () void Update() MoveAlongWaypoints() if(isGrinding) anim.SetBool ("isOnGrinding", true) else if(!isGrinding) anim.SetBool("isOnGrinding", false) void MoveAlongWaypoints() if(isGrinding) TRANSLATE transform.position Vector3.MoveTowards(transform.position, waypoints currentWaypoint .transform.position, grindSpeed Time.deltaTime) ROTATE var rotation Quaternion.LookRotation(waypoints currentWaypoint .transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, rotation, turnSpeed Time.deltaTime) if(transform.position waypoints currentWaypoint .transform.position) currentWaypoint void OnTriggerEnter(Collider other) if(other.gameObject.tag "GrindWayPoint") Debug.Log ("Waypoint!!") isGrinding true


Is it possible to customize the Scriptableobject inspector for Simple level data, without the use of PropertyDrawers? I've invented an innovative, new game mechanic for Bricker Breaker Quest and want to create a quick prototype to recruit a game development team. After wasting a week researching the best way to easily represent the simple level data, I reluctantly started using Scriptableobjects. Each level is defined as a List lt Block gt , where public class Block MonoBehaviour, IComparer lt Block gt public int x public int y public int lives 0 private int pastLife 0 private SpriteRenderer spriteRenderer private TextMeshPro text private void OnCollisionEnter2D(Collision2D collision) lives if (lives gt 0) UpdateVisualState() else gameObject.SetActive(false) private void Awake()... public void AddLives(int life)... How do I properly serialize the Block object so that I can enter the X, Y, and Lives integers directly in the Inspector? As a quick hack, I created a List lt Vector3Int gt instead of the Block List and use the Z input field to enter the lives. Seems like overkill to create a PropertyDrawer just to relabel one field. Any other advice is appreciated.


Suggestions on how to achieve circular "hole" in environment I'm working on a 2D Sidescroller and I'm wanting to achieve a object that when activated it creates a port hole to the sprites underneath, giving the appearance of the object "cleansing" the area. Edited image showing the desired effect At this point I have no idea how to achieve this and am after suggestions, thanks!


How do I run code for a period of time and then return to normal behavior? i wanna run a code for my special power for five seconds only and then return to my normal working. when that power activates i am changing my player's material and i wanna return to my old material after those five secs are over. this is the code i tried void Start () transform.GetComponent lt Renderer gt ().material.mainTexture texts 0 void Update () if (condition) for (int t1 0 t1 lt 5 t1 (int)Time.deltaTime) transform.GetComponent lt Renderer gt ().material mats 0 transform.GetComponent lt Renderer gt ().material.mainTexture texts 0 this code breaks the game i think because unity is freezing when the condition is being met.


why contacts length could be 0 when collision2D happens in Unity3D? I made a ball with RigidBody2d and CircleCollider2D to collide with other balls with the same component, and I simply use the following snippet to check the contacts of the collision public void OnCollisionEnter2D(Collision2D collision) if(collision.contacts.Length 0) Debug.LogWarning(" collision contacts length is 0 ") return futher more code to deal with situation when contacts exists And I found sometimes the collision could happen without contacts I mean the contacts array could contain 0 points. Why does that happen? Cause it's very important for me to find the normal direction of the collision, but without a contact point, I could find that.


Unintended sliding blocks Unity (5) physics A game I'm working on right now relies on the Unity physics system for collisions, gravity etc. This all works well except for one strange thing. When an explosive is placed on a stone cube, it'll slide right off. A video displaying the sliding behavior https www.dropbox.com s lr6lhnn30x61tvf Unity 202015 02 19 2013 41 39 54.avi?dl 0 The stone gameobject settings http puu.sh g3BFn c15483b8ea.jpg The explosive has the same settings except for that the Mass is 1. What could cause this weird sliding and how can it be fixed?


ERROR Destroying assets is not permitted to avoid data loss I want my gameObject named lvl 01 to destroy when I click left or right arrow key but it's keep showing this error "Destroying assets is not permitted to avoid data loss" instead of destroying that gameObject, Can anybody please tell me what is going wrong around here. using UnityEngine using System.Collections public class Level 01Text MonoBehaviour public GameObject lvl 01 Use this for initialization void Start () Instantiate (lvl 01) Update is called once per frame void Update () if((Input.GetKey(KeyCode.RightArrow)) (Input.GetKey(KeyCode.LeftArrow))) Destroy (lvl 01) Debug.Log ("Something is seriously going wrong around here")


Why isn't my BoxCollider2D doing anything? I'm trying to make a speech bubble appear when you approach the tutorial board. The bubble is there and it has its animation states "Appear" and "Disappear" Appear is called OnTriggerEnter2D Disappear is called OnTriggerExit2D The collider is on the parent, tutorial board The animator and script are on the bubble itself. This is the script I have attached to the bubble, the conditions script. using System.Collections using System.Collections.Generic using UnityEngine public class Conditions MonoBehaviour private Animator bubblecondition private BoxCollider2D boxCollider Start is called before the first frame update private void Awake() bubblecondition this.GetComponent lt Animator gt () bubblecondition.Play("Disappear", 0, 1f) void Start() bubblecondition.SetBool("Here", false) boxCollider this.GetComponentInParent lt BoxCollider2D gt () Update is called once per frame void Update() public void OnTriggerEnter2D(Collider2D other) if (other.tag "Player") bubblecondition.Play("Appear", 0, 0f) else return public void OnTriggerExit2D(Collider2D other) if (other.tag "Player") bubblecondition.Play("Disappear", 0, 0f) else return What am I doing wrong? I spent an hour trying to know why. I even tried to have the console write a message on collision but it's just dead. Not only that, but I also tried to make it public and referenced it, still nothing. Help me see my mistake )


Unable to wire UI Text object to C Script I have created UI text object And then created Text field in behavior class using UnityEngine.UI public class Explorer MonoBehaviour public Material mat public Text text ... void FixedUpdate () ... text.text string.Format( quot x 0 quot , scale) If I just run it, it says Object reference not set to an instance of an object at runtime. If I try to drag ZoomText to Text slot, it doesn't allow me If I first drag ZoomText from Hierarchy to Project then it allows me to set Text slot, but still gives Object reference not set to an instance of an object at runtime. If I am trying to set text field by Find private void Start() text (Text) GameObject.Find( quot ZoomText quot ) it gives me Cannot convert type 'UnityEngine.GameObject' to 'UnityEngine.UI.Text' What I am doing wrong? Suspect may be incorrect types, but how to know correct ones?


LookAt different object smoothly in unity3d As picture depicted my camera moving on path i want to lookAt bath different object smoothly. Currently have tried trasnform.LooAt(activePath.gameObject.transform) but it producing jerky result. object suddenly lookAt to next object how to avoid it. I searched and found this sloution but it also not working var targetRotation Quaternion.LookRotation(activePath.gameObject.transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime)


Unity Toolbox pattern is not safe When I create a toolbox such is in this tutorial. How do I defend against breaking the pattern with multiple instances like this gameObject.AddComponent lt Toolbox gt () gameObject.AddComponent lt Toolbox gt () I when calling Toolbox.Instance I get following message Singleton Something went really wrong there should never be more than 1 singleton! Reopening the scene might fix it. Is there a way to defend against it ?


Combining cubes Issue in Marching Cubes I was trying to implement the marching cubes and combine every little cube this way I get a cube of vertices depending on their surfaceLevel I look for the ones that are below the surfaceLevel and get the edges that relates to them get a vertice out of the edge using the formula on http paulbourke.net geometry polygonise I put every vertex i created based on the edges on mesh.vertices I make the order on mesh.triangles based of the edge number on triTable i combine everything but i get this Here's my code https pastebin.com jqetCk8r. My guess was that the combine order of every marched little cube is not good. I've got no idea know how to solve this. ps the triTable doesn't show in the pastebin, i copied it from the same link above.


Player Flying after colliding Unity I have a Player with a capsule collider on him and i have various objects in the scene. Most of the objects have either mesh collider or box collider enabled. When i move my player and the player collides with any object, my player just starts flying into space, literally. Any way to fix this? Thanks in Advance. The code i have on my player is this using UnityEngine using System.Collections public class Controller MonoBehaviour Animator anim Rigidbody rbody float inputH float inputV int Life 20 bool Dead false public float sensitivity 10f void Start () anim GetComponent lt Animator gt () rbody GetComponent lt Rigidbody gt () void Update () if (Dead false) inputH Input.GetAxis ("Horizontal") 50f inputV Input.GetAxis ("Vertical") 20f anim.SetFloat ("inputH", inputH) anim.SetFloat ("inputV", inputV) float moveX inputV Time.deltaTime float moveZ inputH 0.5f Time.deltaTime this.transform.position this.transform.forward moveX this.transform.position this.transform.right moveZ transform.Rotate(0, Input.GetAxis("Mouse X") sensitivity, 0) if (Input.GetKey (KeyCode.Z)) Life if (Life 0) Dead true anim.SetBool("Dead",Dead)


Unity Animation makes object spawn at x0 y0 z0 I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at x0 y0 z0 and is doing the animation there. Then I realized that it was the animation, that increases and decreases y position and y rotation, starting at 0. So, I need to make the animation, that increases and decreases position y and rotation y, without affecting the actual position, because it will be different the position of the coins each time. In a while I will upload a screenshot for describing better the problem. Any clue?


Unity multiple servers for rooms I have an FPS game that I'd like to make multiplayer. It would need to support multiple matches at once with about 10 players in each. However I want physics to be server authoritative so that means running a Unity instance. How do I have multiple Unity processes running on a server, creating destroy them as needed, having players connect to the instance they need, and so on? How does this vary between uNet Sockets LLAPI Photon Bolt etc? There just seems to be an atrocious lack of information on Unity networking and when people ask online there's almost never any answer, or it's too vague to be useful.


Using Burst Compile attribute on methods Can we use BurstCompile attribute without using any Jobs or ECS System in Unity? does adding BurstCompile attribute before methods bring us any benefits?


How do I make a slot car game? I new to game development with Unity and my first project is a slot car racer. For a realistic slot car like driving experience, I first build a track with a channel in the track and a pin on the car. This kind of works, but it does not look like a slot car, its more like a car with a pin and sometimes the physics just go crazy and kick me out of the channel. I next tried making a spline with a simple game object following the track. I attached my car to my "follower" with a fixed joint. This didn't work so well My car was tumbling and pulled sideway but I never archived that my car gets pulled down the track. How should I be approaching this? I'd like the car to accelerate and decelerate quickly, with that acceleration and deceleration controllable by the user.


How to add scene after build and deployed in Unity? I want to be able to make new levels after build. I could use a map tool and script but I rather just add scene with all the resource packed with it. But what is the best practice forward?


How can I use one keycode key as toggle switch for two cameras? using System using UnityEngine using UnityEngine.UI using Cinemachine public class CameraSwitch MonoBehaviour public CinemachineVirtualCamera vcam public CinemachineFreeLook fcam private void Update() if(Input.GetKeyDown(KeyCode.V)) fcam.enabled false vcam.enabled true When pressing on the V key it's switching between the cameras. I want that if I will press on the V key again it will switch between the two camera back fcam to be true and vcam to be false and so on each time pressing on the V key to switch between the cameras.


Combining mesh on the fly without using gameObject I procedurally generate chunks and use the marching cube algorithm to create meshes in 3D. At first, I just created a gameObject for each cube (of course, I knew it was not optimized, but I wanted to see if the algorithm worked). For now I stock all gamesObject in child of "blocks" but it would be much more optimized to directly merge the meshes between them and only create a single gameObject. However, i did not find any way to directly merge the meshes between them. So my question is is there a way to directly merge meshes between them without having to use gameObject? (don't worry about texturing) Here's the code public static GameObject GenerateChunk(int ,, map, int chunkSize, Vector3 chunkPosition) GameObject blocks new GameObject("BlockList") GameObject newMesh int cubeVertices new int 8 create each mesh in a gameObject as child of "blocks" for (int x 0 x lt chunkSize x ) for (int z 0 z lt chunkSize z ) for (int y 0 y lt chunkSize y ) define the vertices (cubeVertices) Vector3 cubePosition new Vector3(chunkPosition.x x, chunkPosition.y y, chunkPosition.z z) newMesh GenerateCube(cubePosition, cubeVertices) if (newMesh ! null) newMesh.transform.parent blocks.transform combine every children of "blocks" and delete them MeshFilter filters blocks.GetComponentsInChildren lt MeshFilter gt () List lt CombineInstance gt combine new List lt CombineInstance gt () for (int i 0 i lt filters.Length i ) if (filters i .sharedMesh null) continue for (int j 0 j lt filters i .sharedMesh.subMeshCount j ) CombineInstance ci new CombineInstance mesh filters i .sharedMesh, subMeshIndex j, transform filters i .transform.localToWorldMatrix combine.Add(ci) Destroy(filters i .gameObject) create the chunk and set the final mesh with the CombineMeshes function GameObject chunk new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer)) chunk.GetComponent lt MeshFilter gt ().mesh.CombineMeshes(combine.ToArray(), true, true) Destroy(blocks) return chunk


Why do I see " lt " and " gt " in Unity C code? I copied Unity code from a website and now it contains stuff like amp amp lt T amp amp gt which my IDE flags as an error. It looks like the intended text has been corrupted somehow. What is this supposed to be, and how can I correct it? public class Tree amp lt T amp gt public T Data get set public IEnumerable amp lt Tree amp lt T amp gt amp gt Childs get set public bool Opened get set public Tree() Childs Enumerable.Empty amp lt Tree amp lt T amp gt amp gt () Opened true


Internet Access is always set to required in unity android player settings I am using unity 2019.4.2f1, I want to remove the internet access permission from the final android manifest file created by unity but, because this option is locked I am not able to remove the permission. Let me know if there is any workaround to do so or disable this option somehow.


Approximately circular range of motion on a square tile grid I've been working on a grid based tactics style game to learn the ropes of Unity. I have an issue with movement range for a player unit. Let's say the units move range is 3 spaces.. If I set up each grid tile with 4 neighbours (up down left right), I get this movement range If I give each tile diagonal neighbours too 8 in total, I get this What I'm actually looking for is what you'd see in these type of games traditionally, like this Here is the code that finds the unit move range list, starting at tile (5, 5). It adds the initial tile node and its neighbours to the movelist, then works outward looping through all their neighbours. It's based off a youtube tutorial. public HashSet lt Node gt getUnitMovementOptions() float , cost new float mapSizeX, mapSizeY HashSet lt Node gt moveList new HashSet lt Node gt () HashSet lt Node gt tempMoveList new HashSet lt Node gt () HashSet lt Node gt finalMoveList new HashSet lt Node gt () int moveSpeed 3 Node unitStartNode graph 5, 5 finalMoveList.Add(unitStartNode) Initial costs for the neighbouring nodes foreach (Node n in unitStartNode.neighbours) cost n.x, n.y costToEnterTile(n.x, n.y, unitStartNode.x, unitStartNode.y) if (moveSpeed cost n.x, n.y gt 0) moveList.Add(n) finalMoveList.UnionWith(moveList) while (moveList.Count ! 0) foreach (Node n in moveList) foreach (Node neighbour in n.neighbours) if (!finalMoveList.Contains(neighbour)) cost neighbour.x, neighbour.y costToEnterTile(neighbour.x, neighbour.y, n.x, n.y) cost n.x, n.y if (moveSpeed cost neighbour.x, neighbour.y gt 0) tempMoveList.Add(neighbour) moveList tempMoveList finalMoveList.UnionWith(moveList) tempMoveList new HashSet lt Node gt () Debug.Log( quot Total move spaces for this unit is quot finalMoveList.Count) return finalMoveList Here is the costToEnterTile function public float costToEnterTile(int targetX, int targetY, int sourceX, int sourceY) Tile t tileTypes tiles targetX, targetY get current tile type float cost t.movementCost diagonal if (sourceX ! targetX amp amp sourceY ! targetY) cost 0.3f return cost If I tamper with the cost value in here, I can get different results in the movement range overall shape, but it's a bit hit and miss depending on the movement range. Can anyone offer insights in to what path I need to head down to solve this?


can't make my unity character move so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https docs.unity3d.com Manual ScriptingRootMotion.html If you ask I'll give you my project . EDIT ok so I made some advances void OnAnimatorMove() m Rigidbody.MovePosition(m Rigidbody.position m Movement m Animator.deltaPosition.magnitude 10000) m Rigidbody.MoveRotation(m Rotation) Debug.Log("m Animator.deltaPosition.magnitude " m Animator.deltaPosition.magnitude) m Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ?


Hide "No custom tool available" window I have this annoying window in the bottom right of the scene view. From the manual, it seems like I opened it by clicking on the wrench amp scribe button next to the movement buttons. How do I make it do away now? Restarting doesn't make a difference, neither does creating a brand new project. The documentation say this appears it I've clicked on the tools icon and there aren't any custom tools (which I'm sure I have done). Surely is should vanish after a while though.


Unity development build not connecting to profiler my development build( with auto connect profiler checked ) is not working. The build runs correctly but no data is displayed in the profiler window. In the console, it says failed to connect.


How can i press the key, show the text and choose if i want to take the item? It's working fine right now, showing the text and then press the key and it takes the item but, i want something like resident evil, the text is not showing until you press acction button. How can i do that? The key script var TheKey GameObject private var playerNextToKey false var showMessage boolean false var nearKey boolean false var hasCollided boolean false var labelText String "" function OnGUI() if (hasCollided true) GUI.Box(Rect(140,Screen.height 50,Screen.width 300,120),(labelText)) function Update () if (Input.GetKeyDown(KeyCode.E) amp amp playerNextToKey true) TheKey.active false function OnTriggerEnter (theCollider Collider) if (theCollider.tag "Player") nearKey true playerNextToKey true hasCollided true labelText " Vas a coger la llave?" function OnTriggerExit (theCollider Collider) if (theCollider.tag "Player") nearKey false playerNextToKey false hasCollided false