On changing a voxel, don't recombine everything again, only modify the changed parts? I'm working on a voxel based game, where destructible structures are made out of cubes. (Some of them has 3000 voxels) I solved the framerate issues by combining them, but after making it able to handle multiple materials, calling the method causes a framerate drop. And it's annoying during runtime, because currently it recombines the whole structure when a voxel is changed (changed material, destroyed voxel, etc). One plan of mine is to decomposite the structures into smaller chunks, and only recombine the affected chunks instead of the whole structure. This increases drawcalls, but decreases framerate drops. By finding a good chunk size and chunk "making" heuristic, it would work I think. My other plan is to modify the combined mesh based on the affected voxels. For example when a voxel is destroyed, find its vertices in the combined mesh, and remove them. Or change those faces' material, etc. But I don't know how to do this. The bottleneck of my mesh combining algorithm is this private static Mesh CombineMeshes(MeshFilter meshFilters, List lt Material gt materials) Each material will have a mesh for it. var subMeshes new List lt Mesh gt () foreach (var material in materials) Make a combiner for each (sub)mesh that is mapped to the right material. var combiners new List lt CombineInstance gt () foreach (var meshFilter in meshFilters) The filter doesn't know what materials are involved, get the renderer. var renderer meshFilter.GetComponent lt MeshRenderer gt () lt (Easy optimization is possible here, give it a try!) Let's see if their materials are the one we want right now. var sharedMaterials renderer.sharedMaterials for (int i 0 i lt sharedMaterials.Length i ) var sharedMaterial sharedMaterials i if (sharedMaterial ! material sharedMaterial null) continue This submesh is the material we're looking for right now. CombineInstance ci new CombineInstance() ci.mesh meshFilter.sharedMesh ci.subMeshIndex 0 With zero it works with "i", every voxel in the structure will have every damagelayer. ci.transform meshFilter.transform.localToWorldMatrix combiners.Add(ci) Flatten into a single mesh. var mesh new Mesh() mesh.indexFormat UnityEngine.Rendering.IndexFormat.UInt32 mesh.CombineMeshes(combiners.ToArray(), true) subMeshes.Add(mesh) foreach (var meshFilter in meshFilters) meshFilter.GetComponent lt MeshRenderer gt ().enabled false The final mesh combine all the material specific meshes as independent submeshes. var finalCombiners new List lt CombineInstance gt () foreach (var mesh in subMeshes) CombineInstance ci new CombineInstance() ci.mesh mesh ci.subMeshIndex 0 ci.transform Matrix4x4.identity finalCombiners.Add(ci) var finalMesh new Mesh() finalMesh.indexFormat UnityEngine.Rendering.IndexFormat.UInt32 finalMesh.CombineMeshes(finalCombiners.ToArray(), false) return finalMesh Could you recommend something? Thanks!


Unity JSON parsing Array of Objects problem error JSON must represent an object type I'm trying to use Json to hold game dialog in a text asset file. I've tried to make a barebones project to test this and it is failing with the Error Message ArgumentException JSON must represent an object type. I have a class called LineData which has a few properties each line of dialog contains. In the Json there are just two lines for now. When I import and parse it to try and make a reference to one of the lines of dialog it fails. Here is all the code dialogJson.JSON "lineID" "BEDROOM DAVE 0001", "lineDialog" "Yaawwn, up i get for another fun packed day.", "lineDuration" 3 , "lineID" "BEDROOM DAVE 0002", "lineDialog" "Well I think I need a cigarette before I get to work!", "lineDuration" 3 LineData.cs using System Serializable public class LineData public string lineID public string lineDialog public float lineDuration GameController.cs using UnityEngine public class GameController MonoBehaviour TextAsset Dialog Data private void Start() Dialog Data Resources.Load lt TextAsset gt ("txt dialogJson") LineData line1 JsonUtility.FromJson lt LineData gt (Dialog Data.text) Debug.Log("line 1 dialog " line1.lineDialog) NOTE I read here (https answers.unity.com questions 1503047 json must represent an object type.html) that Unity "can't parse if the json consists of an array of objects". But I don't understand his explanation on how to get around this. Thanks EDIT I now have it without error, but the debug message is just empty didnt seem to get any data) . Here is the json now after the edits "LineData" "lineID" "BEDROOM DAVE 0001", "lineDialog" "Yaawwn, up i get for another fun packed day.", "lineDuration" 3 , "lineID" "BEDROOM DAVE 0002", "lineDialog" "Well I think I need a cigarette before I get to work!", "lineDuration" 3 I've also altered the GameController.cs like this (but now it says Index is outside array bounds public class GameController MonoBehaviour TextAsset Dialog Data private void Start() LineData lines new LineData 2 Dialog Data Resources.Load lt TextAsset gt ("txt dialogJson") lines JsonUtility.FromJson lt LineData gt (Dialog Data.text) Debug.Log("line 1 dialog " lines 0 .lineDialog)


How does Unity's Entity Component System Work In Practice? On the surface Entity Component seems like a good way to program games. Everything is a game object and those game objects are made up of components. The attraction is components are very flexible, just requiring you to "add" them to a game object to inherit it's functionality. So, obviously a good example might be a platform the character has to jump on. Maybe this thing has a collider, a moving component, maybe a rotating component, or maybe even a rigid "RotatingAndMovingPlatformComponent". Okay, that sounds great, just add all these components to the game object and that's it, you have this extra functionality. However, I find that this level of complexity is where it's usefulness ends. Try this with menus, complex character movement with multiple states, abstract ideas like game modes or game state, and your flexibility and modularity are destroyed. Menus involve a lot of specifics, complex character movement often involves many states meaning either communication between these components is needed or there must be a controlling component made just for this type of character. On top of this, some components will need to rely on game state in some way. I see very little benefit to programming this way over ordinary inheritance. The lack of object structures at compile time makes doing a lot of things very difficult and unreliable. I feel the best and easiest way of going about things would be using larger components with more dependencies. I don't see this as a problem ( more like unreal 4's architecture ), but then I wonder what's the point in the Entity Component architecture.


Assigning relative force to a projectile fired while orbiting a sphere Projectile Not Correctly Inheriting Parent Velocity (Unity3D) So I am trying to incorporate the above person's changes into a script I am making although I'm no great coder and I'm not even sure their solution works best for what I am doing. Essentially what I have right now is a high speed shooter where the player is being pushed around as a physics object on a sphere world rather than using translate for movement. I keep finding solutions that would work really well if I was just translating through xyz space. Using a physics object for my projectile has been working well (I can shoot in one direction and have the projectile hit my in the back after circling around) but once I get up to speed I'm in trouble. I think I've successfully incorporated the projectile portion into my script but currently it keeps shooting on the positive z axis. On top of that, I'm not even sure where to start incorporating the second half. Emitter Script using UnityEngine using System.Collections public class SpaceShoot MonoBehaviour public GameObject Bullet Emitter public GameObject Bullet public GameObject target Player public float Bullet Forward Force 100 public float Bullet Life 60 public float fireInterval 0.05f void Update() if (Input.GetKeyDown(KeyCode.Space)) InvokeRepeating("Fire", float.Epsilon, fireInterval) if (Input.GetKeyUp(KeyCode.Space)) CancelInvoke("Fire") void Fire() GameObject Temporary Bullet Handler Temporary Bullet Handler Instantiate(Bullet, Bullet Emitter.transform.position, Bullet Emitter.transform.rotation) as GameObject Rigidbody Temporary RigidBody Temporary RigidBody Temporary Bullet Handler.GetComponent lt Rigidbody gt () Temporary Bullet Handler.transform.Rotate(Vector3.left 90) Rigidbody target rigidbody target rigidbody target.GetComponent lt Rigidbody gt () Temporary RigidBody.velocity target rigidbody.velocity Temporary RigidBody.AddForce(transform.forward Bullet Forward Force) Destroy(Temporary Bullet Handler, Bullet Life) Edited script as it currently stands. It mostly does what I need although I'm trying to figure out a way to clamp the distance to the origin.


Sampling procedural texture generated in shader? We have a custom Unity surface shader which generates some procedural patterns. However we are getting very bad moire effects when the pattern frequency is too high (made worse by distance, surface angle). I would like to apply some kind of blur on the texture to reduce this moire effect. All of the shader blur examples I can find rely on sampling surrounding pixels from the texture bitmap. Since we've generated the pattern procedurally per pixel, such a bitmap doesn't exist. Does anyone know how we might introduce some kind of blur effect in this case, to reduce the moire? Thank you.


UI Button Click Animation We have animation states for Normal, Highlighted, Pressed and Disabled. How to set animation when a button is clicked?(after button released not pressed)? Thanks in advance


Classes in Unity internal vs public Why are classes created by the game developer in Unity public (by default) when you could just as easily make them internal? For example I go Assets Create C Script. Via the default script template, I have just created a public class that derives from MonoBehaviour. But technically shouldn't this class only have to be internal? If so, I really want to delete that public keyword, because having the word public is a slight distraction to me. Do outside DLLs call functions within the developer created DLL? I don't think so, right? Because the classes in other DLLs wouldn't know what funcitons are in there beforehand anyway. I don't know much about how these DLLs interact with each other, but I get the feeling outside DLLs don't particularly care about the one DLL assembly the game developer himself generates. Take a look at my picture it seems like Unity just jams all developer created scripts in one assembly. Yes, the assembly does reference MonoBehaviour, (so I assume other classes in all the other dlls are public, not internal) but no classes outside of this one need be concerned with the details inside this assembly. It doesn't matter that much. Yes, I could go on living my life peacefully and making my classes public within Unity. But is there any potential drawback, and isn't it considered better practice, to make them internal? If there's nothing wrong with making my classes internal, then I'm going to edit the default template.


Apply a special effect to a scene area My 2D game has a second camera on the scene that renders an upside down image of the scene and distorts it, giving the effect of water reflection. I render this camera first, and on top of it I render the main camera. This is working correctly as expected, however, I want to improve it's performance by performing this process in small sections of the scene instead of the whole screen. I created a trigger to detect which items should be turned upside down and rendered. How can I turn these items and distort them as I did with the whole scene, but only to the GameObjects detected inside the trigger? Note I can't assign them to a layer since the layer is already in use.


How do you handle aspect ratio differences with Unity 2D? I've gotten a lot of answers to this question, but they are all generic and generally not very useful. None of the tutorials talk about aspect ratio and dealing with mobile devices and there are a zillion ways to do it, all seem to have gotcha's and flaws. I really would love to know what successful games have used to handle different aspect ratios on iOS and Android without making a zillion different sized assets. I am strictly speaking mobile, not desktop, specifically with Unity and I don't care about the UI, I only care about the gameplay canvas. Issues I have in mind is when there are key things that have to be in certain places and cannot fall off the screen. Using black bars on top or bottom is unacceptable these days.


How to ensure Unity does not rearrange the sub meshes of a mesh on import? having a bit of a head scratcher problem here. I have my artist's making multiple unique meshes in Maya that contain 3 materials. Each material is assigned to a sub mesh in a specific order. This order is identical across all the meshes being created. When bringing over these meshes to Unity, we have noticed that some meshes keep their material sub mesh order from Maya, and some do not. It's been making code generated material swaps a nightmare. So a few questions 1.) What is Unity's logic when importing meshes and ordering the sub meshes? 2.) Is there a simple way to make sure Unity does NOT reorder the sub meshes material order? 3.) Is there a way on Maya's side when exporting to make sure the sub meshes material order is as intended? Any help or ideas is appreciated. Thanks!!


A shader that casts shadows, doesn't receive shadows and doesn't render any textures models at all? Bit of a strange one but I'm in the situation where i need a shader to essentially render nothing and cast a shadow! I found this though some googling but sadly that casts shadows onto itself which is undesirable.


Video feedback effect with recursive RenderTextures in Unity 2018.3 I have a project where I'm playing with a video feedback effect by rendering a camera to a RenderTexture and pointing the camera at a quad displaying that RenderTexture. This works great normally, but when trying out HDRP, LWRP, (and upgrading materials) or upgrading the entire project to 2018.3, the RenderTexture just stops working and shows black. I also tried with a completely new project and just had a camera, a quad, and a cube. That also didn't work. Is there any obvious reason this wouldn't be working? I spent a while trying out various settings but couldn't find anything that had any effect, so I really don't even know where to start.


Rotate perspective camera to align screen width to procedural object's width (Unity, C ) I give up. After much trying and searching, I have to say I was unable to achieve the following task, for which I must call for your wise advice. In my current Unity 5 application (using C ), there is a procedurally generated object (therefore with variable shape) to which the camera should be aligned when players hit a given key. By aligned, please understand it making the width of the screen parallel to the longest part of the object. The idea is represented in the following picture, where in black one can see the irregular object, in yellow is the bounding box. In other words, it means that I want the camera to be rotated so to align to the longest side of the object's bounding box. I tried that. Still, I was unable to properly calculate the correct angles so to rotate the camera in a way that the horizontal axis of the screen becomes parallel to the width of the objects' bounding box. Any help would be much appreciated.


What is the transformation order when using the Transform Class? I am currently using Unity 5.5 for the first time in a project and I've got some problems regarding transformations. I've got a background in more general 3D graphics meaning that I'm used to manually manage scene graphs and matrix transformation orders. My greatest problem when moving to Unity, and using their built in Transform Class, is that I can't find any information regarding the transformation order of rotation, localrotation, scaling, localscaling, position and localposition. I can't find any good information of this and It's driving me slightly mad. TL DR What's the transformation order of the Transform class?


How to move NavMesh Agent by animation? What's the best way to create a simple moving navmesh agent with animation? (e.g. a human enemy running to player) I have run animation that moves the enemy public void Run () animator.SetFloat ("Speed", 1f) but I am not sure how to combine it with navmesh. In one tutorial I saw Standard Assets ThirdPersonController .Move(...) used for that, but I am not sure if I should use it for that purpose, as I understand it was intended only for player characters? Or should I use animation that runs in place?


Plugins for creating and styling custom Editor Windows like C C Form Designer or Web Inspector ? Unity3d allows to construct window with custom UI. Just need to use EditorGUI EditorGUILayout classes and their static methods. Example of custom window The problem is that all the components have to be added manually via script. Then need to save, switch to Editor, wait for little compile things, and then we can see the result. In web development people use Web Inspector (for example, we can press F12 in chrome, Tab Elements Styles). We can add all needed properties to element and can see the result in real time. EDIT. another example (better than previous) we know C winFormApp, C MFC e.t.c, which has form designer. We can choose any elements and set their properties It would be nice to have similar plugins for Unity So. Does Unity3d have similar tools, utilities, plugins? Utilities to inspect code and editing styles (position, margin, padding, background, width, height, color e.t.c.)?


With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D? So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with TileRenderer.material.SetTextureScale(" MainTex", new Vector2(0.25f, 0.25f)) TileRenderer.material.SetTextureOffset(" MainTex", new Vector2(0 0.25f,0)) but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.


Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop? using System.Collections using System.Collections.Generic using UnityEngine public class Spin MonoBehaviour public Vector3 targetRotation public float duration public bool spinInUpdate false Start is called before the first frame update void Start() if (spinInUpdate false) StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration)) Update is called once per frame void Update() if (spinInUpdate true) transform.Rotate(new Vector3(0, 1, 0)) IEnumerator LerpFunction(Quaternion endValue, float duration) float time 0 Quaternion startValue transform.rotation while (time lt duration) transform.rotation Quaternion.Lerp(startValue, endValue, time duration) time Time.deltaTime yield return null transform.rotation endValue slant I mean this is how it's rotating with the Coroutine the small cube that rotate is in slant When using the Update way it's rotating fine and this is how it should rotating also with the Coroutine for example on the X only The small cube when rotating either in update or in the Coroutine should not be slant. but it's slant in the Coroutine. And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ? About controlling the speed in the Update I just added a global float variable and in the Update transform.Rotate(new Vector3(0, Time.deltaTime rotationSpeed, 0)) and it's working for the speed.


How do you handle pathfinding for non tilemap 2d games? What methods do you use to handle path finding in non tiled 2D games? Tilemap based methods can use A and 3D has NavMesh available. The only success I ve had is with raycasts but it doesn t seem like a great way to handle things with hand draw sprites or uneven terrain.


Player object's model starts to shake after some time I created a default scene in a new project and imported a model from Unity's asset store and then get this strange behavior of the model starting to shake for no reason after some time after starting the game. I also have a script to read keyboard input and then apply forces to the model when the player presses some keys but the shaking of the model starts to happen even when the player does absolutely nothing. I'm really confused and have no idea where to look for a problem and google doesn't seem to have a solution to this either.


I prefer C C over Unity and other tools is it such a big downer for a game developer? We have a big game project using Unity at school. There are 12 of us working on it. My teacher seems to be convinced it's an important tool to teach students, since it makes students look from the high level to the lower level. I can understand his view, and I'm wondering Is unity such an important engine in game development companies? Are there a lot of companies using it because they can't afford to use something else? He is talking like Unity is a big player in game making, but I only see it fit small indie game companies who want to do a game as fast as possible. Do you think Unity is of that much importance in the industry? Does it endanger the value of C skills? It's not that I don't like Unity, it's just that I don't learn anything with it, I prefer to achieve little steps with Ogre or SFML instead. Also, we also have C practice exercises, but those are just practice with theory, nothing much.


Find out triangles that are not occluded from a camera view? For a project i need to find out triangles that are directly seen by the camera user. Triangles that are occluded by other triangles should be ignored. There may be 200 thousand triangles in a model, so raycasting on a CPU is no possibility due to performance. Is there something build in to unity or opengl that can do this? If not how would you approach this problem? Many 3d editing software use techniques, e. g. to select or slice only triangles that are visible.


Unity AudioClip lags when played My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left click inside the game window. Steps I've tried for fixing it Uncompressing the .wav sound file. Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story. How the issue occurs When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and or lagging. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI RequireComponent(typeof(AudioClip)) RequireComponent(typeof(AudioSource)) public class GameProcess MonoBehaviour public Canvas Game public AudioClip explosion AudioSource beatBox Transform btn Vector3 canvasMin Vector3 canvasMax Vector3 pointerMin Vector3 pointerMax Vector3 pointerPos void Start () btn Game.transform.FindChild("Pointer") canvasMin Game.GetComponent lt Collider gt ().bounds.min canvasMax Game.GetComponent lt Collider gt ().bounds.max pointerMin btn.GetComponent lt Collider gt ().bounds.min pointerMax btn.GetComponent lt Collider gt ().bounds.max beatBox GetComponent lt AudioSource gt () void Update () if (Input.GetMouseButton(0)) beatBox.PlayOneShot(explosion) if (!(pointerMin.x lt canvasMin.x) !(pointerMin.y lt canvasMin.y)) if(!(pointerMax.x gt canvasMax.x) !(pointerMax.y gt canvasMax.y)) btn.transform.position Input.mousePosition else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0)


Can I use trilinear filtering for my sprites, but keep their outlines unfiltered? Suppose that I have two images of equal size. They both contain a square https i.stack.imgur.com BI62X.png https i.stack.imgur.com Nev5Z.png When overlapped, both squares will appear next to each other. If both images use Point (no filter), they will contact without issues regardless of the amount of zoom or scale If you use either Bilinear or Trilinear, there will be an artifact visible in certain zoom scale levels Of course, that is to be expected from the very nature of the filters. As much as I would like to just leave it at Point (no filter), my game looks far better using Trilinear instead except of course, for the "borders" or points of contact. The ideal scenario for me as bizarre as it may sound, is to be able to use Trilinear filtering generally, but force the "outlines" of my sprites to stay as if they were Point (no filter). This way, my game looks painterly when zoomed in out (the game isn't pixel art), and I also avoid the "glitch" in specific contacts. Yes, the glitch is only noticeable if you use a scale zoom that is higher than 100 . Unfortunately, due to the nature of the game, the player should be able to zoom in out if they desire, so I can't just pick "the" ideal camera size or sprite scale because it can't be constant. I've tried using Canvas and its Pixel Perfect checkbox to no avail. I didn't really expect that to work though. What can I do to achieve the desired effect, then?


Can you use the RangeAttribute to limit the size of an array? I recently found out about the RangeAttribute and how you could use it to limit the values of your parameter when entering them in in the inspector window. However, I needed to use an array for randomly selecting Prefabs so they can spawn randomly at any given time. The problem is Unity lets me have an array size of zero, but I also want to limit the number of possible prefabs. I was wondering if there is a way to use RangedAttribute to limit the size of an array, and if not is there a different way to achieve this? I have extensive experience in Java and C but recently started in Unity, so I don't know if I'm asking the right questions, so any guidance right now would be greatly appreciated. Thanks. P.S. I would be able to attach the script to give an example if needed.


Simple Line Formation I'm working on the first formation for my game's troops. These should simply stand on land, facing the same direction. To achieve this, I tried to create offsets towards a pivot unit, that is approximately the unit in the center of the formation. The units are (temporary) elements of a squad list withing the Squad class. I divide the List by 2 and get the closest integer, that should be the pivot point of the formation. Now I generate offsets for all units on the left side (Unit 1 to pivot 1) and right (pivot 1 to last unit) based on the distance gaps. This is the code for the line formation. Sadly, the units are only forming a very stange line with no visually detectable system int count (int)(squadMembers.Count 2) pivot squadMembers count center pivot.transform.position switch (type) case FormationType.Line int space 5 for (int i 0 i lt squadMembers.Count i ) Unit tmp squadMembers i int dist 0 if (i gt count) dist (count 1) space center.x dist if (i lt count) dist (count 1) space center.x dist tmp.StartMove(center) break It also appears that this only works along the x axis, any idea how i can realize this with the walking facing direction ov the pivot? Is there any (obvious) error? How can I improve this script? PS Any idea, how I can transform this into a double line (2 Lines behind with half spacing)


Unity3D GameObject as a static function Newbie Unity3D C developer here. I've tried learning Unity3D during my May June college vacation and came across a problem Code 1 CameraObj returnVoid void Start () returnVoid GameObject.Find ("Main Camera").GetComponent lt CameraObj gt () returnVoid.ComponentType () Code 2 GameObject returnDirectLight void Start () returnDirectLight GameObject.Find ("Directional Light") Debug.Log (returnDirectLight.GetComponent lt DRLight gt ().directionString) CameraObj is my custom component. As far as I know, GetComponent is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does GetComponent become a static function here? Does it become abstract in my CameraObj class?


How to save Unity assests to another drive? My C volume has almost no space left. Therefore I want to transfer all my assets to the volume E . And save my new assets automatically on the E volume. I have searched very long in unity for save options of unity assets but nowhere found a setting option for this.


unable to see sprite in scene Getting error as floating point precision limitation I am trying to create game object by dragging image from project window to scene I am getting error as due to floating point precision limitation it is recommended to bring the world coordinates of game object within smaller range I am following ruby's adventure tutorial in unity learning


Handling complex selection mechanics in RTS style game When we look at complex RTSs where a simple left button mouse click can mean twenty or more different things, depending on the game and UI state, the code handling this interaction and assigning the right interaction action to the input can easily end up messy and tightly coupled to everything, creating a ball of mud architecture The Class That Does Everything related to interaction. How can I deal with this situation? Here's an example of the complex selection mechanics that I'm looking for Single left click to select a friendly unit. If friendly unit is in a group, the group is selected. If the group is already selected, select the unit. Single left click to select an enemy unit. If friendly unit group already selected, then issue attack order on unit. If friendly unit group already selected and enemy unit is in an enemy group, then issue attack order on enemy group. Same thing but if target is allied non controllable, then friendlies move towards target. Etc. How can I handle this complex selection system, taking into account complex states?


Instantiate unity sometimes lags the game some times it doesnt I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object A. When i use this object my script instantiates the objects without any freezes or any other problems. Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object B. Now when i want to instatiate object my my game freezes a few frames upon instantiation. Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case. See here a screenshot for object A, and its components See here object B and its components Per request the code that does the instantiation of the objects public class ForLoopVisualization1 MonoBehaviour public DetectorAreaScript ElementDetector public GameObject TowerElement public Transform TowerElementsParent public bool WigglyTower false public float ElementSpacing, Wiggeliness private Collider BuildElementCollider private Transform BuildElementTransform private Vector3 TowerElementPos private int TowerElementCount, CreatedElements private bool StartBuildingTower false private float Delay 0.5f, TowerElementSize Use this for initialization void Start () ElementDetector.DetectedData OnObjectEnterDetector Destroy(TowerElement.GetComponent lt Rigidbody gt ()) TowerElementSize TowerElement.GetComponent lt Collider gt ().bounds.size.y TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) Update is called once per frame void Update () if(StartBuildingTower amp amp CreatedElements lt TowerElementCount) Delay Time.deltaTime if(Delay lt 0) CreatedElements var te Instantiate(TowerElement, TowerElementPos, Quaternion.identity) te.transform.SetParent(TowerElementsParent) if(WigglyTower) TowerElementPos new Vector3(Random.Range( Wiggeliness, Wiggeliness), TowerElementSize ElementSpacing, Random.Range( Wiggeliness, Wiggeliness)) else TowerElementPos new Vector3(0, TowerElementSize ElementSpacing, 0) Delay 0.4f else if(StartBuildingTower) StartBuildingTower false StartCoroutine(EjectVar()) add when bugs are fixed.. void OnObjectEnterDetector(System.Object sender, DetectedVariableData data) if(data.DetectedObjectType DetectedType.Variable) var vals ElementDetector.DetectedVariable.GetVariableValue() TowerElementCount vals.IntValue if(CreatedElements gt 0) foreach (Transform child in TowerElementsParent) Destroy(child.gameObject) CreatedElements 0 TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) StartBuildingTower true IEnumerator EjectVar() yield return new WaitForSeconds(0.8f) ElementDetector.EjectDetectedElement(new Vector3( 1, 0, 1)) If something is unclear let me know so i can clarify the post!


Cardboard VR Mode rendering black in Unity I've searched around and seen this problem is quite common, but none of the fixes I've read have resolved the issue If VR Mode is enabled in the GvrViewerMain prefab, the scene will render as just a black screen. I've set the Graphics API to OpenGLES2, I've disabled Multithreaded Rendering, I've disabled direct render, yet this continues to be an issue. This happens both within unity itself and if it is built and run to my phone. Has anybody encountered this problem do you know of any further steps to take to resolve the issue?


Using an objects velocity to determine if it falling on a player will kill it I've been attempting to make a falling object kill a player, but i still want to make sure the player can touch and interact with the object to move it around without dying. The code i've made so far somewhat works as it wont kill the player when they move it will kill the player when it falls and hits them, but the problem is it only works if they have not moved yet from their spawn position (could also be true for when they have stood still for a second). Here is my code using System.Collections using System.Collections.Generic using UnityEngine public class BoxyKill MonoBehaviour public Rigidbody2D rgbd public CharacterController2D character private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.tag "Player") Debug.Log("Hit player") if (rgbd.velocity.y lt 5f) character.Damage(10) Debug.Log("Hit player 2") Note the 'rgbd' is the boxs and this script is attatched to the object Thanks! UPDATE So as of DMGregorys suggestions i have updated the code and while it works i have encountered the same problem (however a lot more controlable this time) Here is my current code public Rigidbody2D body private float minimumDamageThreshold 10 private float collisionDamageScale .0001f void OnCollisionEnter2D(Collision2D collision) Vector2 normal collision.GetContact(0).normal Vector2 impulse ComputeTotalImpulse(collision) Vector2 myIncidentVelocity body.velocity (impulse body.mass) Vector2 otherIncidentVelocity Vector2.zero var otherBody collision.rigidbody if (otherBody ! null) otherIncidentVelocity otherBody.velocity if (!otherBody.isKinematic) otherIncidentVelocity impulse otherBody.mass Compute how fast each one was moving along the collision normal, Or zero if we were moving against the normal. float myApproach Mathf.Max(0f, Vector3.Dot(myIncidentVelocity, normal)) float otherApproach Mathf.Max(0f, Vector3.Dot(otherIncidentVelocity, normal)) float damage otherApproach myApproach Debug.Log(damage) character.Damage(damage) static Vector2 ComputeTotalImpulse(Collision2D collision) Vector2 impulse Vector2.zero int contactCount collision.contactCount for (int i 0 i lt contactCount i ) var contact collision.GetContact(0) impulse contact.normal contact.normalImpulse impulse.x contact.tangentImpulse contact.normal.y impulse.y contact.tangentImpulse contact.normal.x return impulse It now works and will kill the player, and i have it printing out the damage in the debug for the character script damage function. The only problem is, it will constantly damage the player if it touches the box at all, and the player needs to be able to move the box around so this will slowly kill it. This could be a problem with the variable amounts that i have configured due to a lack of understanding (and a lot of mindless fideling to be honest).


How can I reflect a point about a line in Unity? I am drawing a line using the line renderer in the following way public class MyLineRenderer MonoBehaviour LineRenderer lineRenderer public Vector3 p0, p1 Use this for initialization void Start () lineRenderer gameObject.GetComponent lt LineRenderer gt () lineRenderer.positionCount 2 lineRenderer.SetPosition(0, p0) lineRenderer.SetPosition(1, p1) From the image below, the line P0P1 is known and so is point A. How can a point B, which is the reflection of A about the line P0P1 be found?


In Unity, why does my IndexOutOfRange exception disappear when trying to debug it? I don't get errors when playing from Unity "Game" tab. But when I build an executable (development or not) it stucks. I get "IndexOutOfRange" exception. Which also magically disappears (yes) when I add some debug lines This does not work for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i Out of range b 7 j Out of range submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j This works for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i b 7 j if (a lt 0 a gt 15) now with this never gets out of range Debug.Log("A out of range " a) if (b lt 0 b gt 15) now with this never gets out of range Debug.Log("B out of range " b) submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j I can't find any sense. The exception literally hides from me Additional info maybe is useful x1 (CurrentWalkableTile.x 7) gt 0 ? 7 (int)CurrentWalkableTile.x x2 (CurrentWalkableTile.x 7) lt world.wmap x size ? 7 (world.wmap x size (int)CurrentWalkableTile.x 1) y1 (CurrentWalkableTile.y 7) gt 0 ? 7 (int)CurrentWalkableTile.y y2 (CurrentWalkableTile.y 7) lt world.wmap y size ? 7 (world.wmap y size (int)CurrentWalkableTile.y 1) I'd like to post more information, but I can't even debug to find the problem.


Delay Pause game while displaying countdown 3,2,1 go I have already a running script of countdown and it works fine , the problem is that I want to pause or delay the game while the countdown is displaying, the moment countdown finished the player is already dead. Here is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class jb MonoBehaviour private string countdown "" private bool showCountdown false public AudioSource noise1 public AudioSource noise2 public Sprite sprite2 public Vector2 jump new Vector2 (0,300) private SpriteRenderer spriteRenderer void Start () GetComponent lt Rigidbody2D gt ().velocity Vector2.right speed StartCoroutine(getReady()) spriteRenderer GetComponent lt SpriteRenderer gt () noise1.GetComponent lt AudioSource gt ().Play() Update is called once per frame void Update () if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) Vector2 touchPosition Input.GetTouch(0).position GetComponent lt Rigidbody2D gt ().AddForce(jump) noise1.GetComponent lt AudioSource gt ().Play() Vector2 screen position Camera.main.WorldToScreenPoint (transform.position) if(screen position.y gt Screen.height screen position.y lt 0) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) void OnCollisionEnter2D(Collision2D det) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) IEnumerator Die() PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name ) spriteRenderer.sprite sprite2 yield return new WaitForSeconds (2) SceneManager.LoadScene("score") IEnumerator getReady() showCountdown true countdown "3" yield return new WaitForSeconds (1) countdown "2" yield return new WaitForSeconds (1) countdown "1" yield return new WaitForSeconds (1) countdown "GO" yield return new WaitForSeconds (1) showCountdown true countdown "" void OnGUI () if (showCountdown) GUI.color Color.red GUI.Box ( new Rect (Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box (new Rect (Screen.width 2 90, 75, 180, 140), countdown) what can I do to pause the game? I tried invoke (by creating another function and copying everything over there) in update call but it didn't work.


Unity UI Raw Image with Texture becomes Smaller after Build I am a beginner in the game development world, I have just one quick problem with the UI, as you can see during the Unity Player, the UI (Raw Image w Texture) is normal in size but when I build my game to APK or EXE and run it, the UI is small. Why is this happening and how to fix it?


pick up material from another object is it possible to obtain a material from another object? I'm trying everything and nothing, the only thing I could get was just the color of another object public MeshRenderer takematerial public GameObject Objects for (int i 0 i lt Objects.Length i ) Objects i .GetComponent lt Renderer gt ().material takematerial.material


addressables unity unknown async error public AssetLabelReference imgs List lt IResourceLocation gt myImgs new List lt IResourceLocation gt () SerializeField List lt Texture2D gt loadedImages new List lt Texture2D gt () private void Start() Addressables.LoadResourceLocationsAsync(imgs.labelString).Completed imgReady void imgReady(AsyncOperationHandle lt IList lt IResourceLocation gt gt op) myImgs new List lt IResourceLocation gt (op.Result) insta() void insta() Addressables.LoadAssetsAsync lt Texture2D gt (myImgs, cb) void cb(Texture2D s) loadedImages.Add(s) I get the locations of the images but not the asset themselves I get an error of Exception encountered in operation Resource(Man.png) Unknown error in AsyncOperation UnityEngine.ResourceManagement.Util.DelayedActionManager LateUpdate() (at


since unity upgrade, OnSceneLoaded not getting called on scene start I upgraded my unity project to 2018.3.11f. Since that upgrade, the OnSceneLoaded event is not getting called, even though I am registering the event handler. Here's the class public class SceneSwitcher MonoBehaviour void OnSceneLoaded(Scene scene, LoadSceneMode mode) print("scene loaded " scene.name) void Start() print("SceneSwitcher.Start() called") print("adding event handler to SceneManager") SceneManager.sceneLoaded OnSceneLoaded here's the console output SceneSwitcher.Start() called UnityEngine.MonoBehaviour print(Object) SceneSwitcher Start() (at Assets Scripts SceneSwitcher.cs 45) adding event handler to SceneManager UnityEngine.MonoBehaviour print(Object) SceneSwitcher Start() (at Assets Scripts SceneSwitcher.cs 46) scene loaded 3 is never in the console output. I see others have had this problem, with no answers. This code worked before the upgrade. Now I am stuck. Not sure what I can do. Any help is appreciated. Thnx


How to teleport a game object to an empty game object? I am trying to make a respawn system where if the player touches a plane, (the name of the object is tutlvl1 flrdead) they get teleported to an empty object at player spawn named quot RESPAWN quot . But, several tutorials and unity answers threads lead me to nowhere since they were written from back in 2013 or somewhere around there. Code using System.Collections using System.Collections.Generic using UnityEngine public class deathfloor MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() public gameObject myObject You can name it whatever you want. myObject.transform.position new Vector3(3.076, 1.74, 3.651) How can I fix this to do what I need for my game?


Unity Moving player using Rigidbody with UI Buttons? i have been using transform.positionsince the start but now i want to switch to rigidbody instead since i am facing some collision problems. i can use the keyboard to move the player using this code input new Vector3 (Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")) if (GetComponent lt Rigidbody gt ().velocity.magnitude lt maxmovespeed) GetComponent lt Rigidbody gt ().AddForce (input movespeed) but since i am building for mobile and have added UI buttons for right left on screen, i wish to use those for moving my player. how can i use those buttons to move in that specific direction like left for left only and right for right?


Convert linear velocity to angular velocity for a ball sphere (Rolling Ball Maths) I have a ball moving on a flat plane. I cannot use RigidBody physics, so my object in Kinematic and I am manually handling speed acceleration. The linear movement of the ball is fine, however as the ball does not rotate, it looks odd. Given a speed Vector3, where I am moving on the X amp Z, I need to figure out how to make the ball "roll". I think I a running into Euler Gimbal lock issues by trying this transform.Rotate( 180.0f speed.z (Mathf.PI radius) dt, 0, 180.0f speed.x (Mathf.PI radius) dt ) This formula is loosely based on the angular velocity formula and converting to degree's per second, with dt (deltaTime). My gut instinct says that the solution may lie in Quaternions somewehere...?!


Unity 5.6.0f3 Inspector Tooltips are off in macOS, is me or everyone the same? Running latest version (5.6.0f3) in macOS, my tooltips are always misalign to the left of my screen, is me or anyone else also experience the same? And, it is still misalign even after I reset the layout setting to factory default. Here are the screenshots http imgur.com a dR0Pv Update Filed a bug report.


Unity Bullet spawns in wrong position in client I am making a multiplayer game with prefab shooting, but unfortunately the prefab sometimes spawns in the wrong position when I shoot from a client. The bullet tends to spawn in a location where the player was a few miliseconds ago, making that the bullet sometimes spawns inside of the player which killing the player in the process. For shooting, I currently have this code setup to instantiate the bullet void Update() if (Input.GetMouseButtonDown(0)) float angle GetComponentInChildren lt Weapon gt ().angle CmdShootBullet(angle) rigidbody.AddForce(Quaternion.AngleAxis(angle 180, Vector3.forward) Vector3.right (bulletPrefab.GetComponent lt Bullet gt ().force 7.5f)) Command void CmdShootBullet (float angle) GameObject bullet Instantiate(bulletPrefab, firePoint.position, Quaternion.identity) Bullet bulletScript bullet.GetComponent lt Bullet gt () bulletScript.shotBy gameObject bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) Vector3.right bulletScript.force) NetworkServer.Spawn(bullet) And this is the setup for the location of the player and the gun. The top one is the player, the bottom is the gun. My guess is that it has to do with lag, that the player position does not update soon enough, so how would I make it that the bullet spawns in the position of the player in the client rather than the position of the player in the host?


Buttons only trigger right left movement once, not continually I have a Unity mobile project where I am trying to use right left movement using two UI buttons situated accordingly. The issue is that it only moves the player to the right to the left one time, not continually when the player is holding the button down. I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released. I've tried making the void into a Coroutine, but nothing working works. Here is my code. (rightCallable and leftCallable are attached to the buttons). using System.Collections using System.Collections.Generic using UnityEngine public class playerController MonoBehaviour public GameObject player public float speed 1000f public GameObject left this is so the player may also use the A and D keys if they want, and it works fine. public void Update() var movement Input.GetAxis( quot Horizontal quot ) transform.position new Vector3(movement, 0, 0) Time.deltaTime speed Below is what isn't working public void rightCallable () StartCoroutine( quot moveRight quot ) public void leftCallable () StartCoroutine( quot moveLeft quot ) IEnumerator moveRight() var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null IEnumerator moveLeft () var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null


object reference not set to an instance of an object hello i have a error "object reference not set to an instance of an object" when my ball collide with the spikes.its supose to remove one heart but it doesnt. health code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Health MonoBehaviour public int health public int numOfHearts public Image hearts public Sprite fullHeart Use this for initialization void Start () Update is called once per frame void Update () if (health gt numOfHearts) health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt health) hearts i .sprite fullHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false public void Damage(int dmg) numOfHearts dmg spikes code using System.Collections using System.Collections.Generic using UnityEngine public class Spikes MonoBehaviour private Health Player Use this for initialization void Start () Player GameObject.FindGameObjectWithTag("Player").GetComponent lt Health gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) if (col.CompareTag("Player")) Player.Damage(1) here i have the error.


Build a Unity asset bundle on linux? I'm trying to generate an asset bundle on a remote linux machine and stream the bundle to a running Unity instance. Is it possible to download the same libraries Unity uses and compile on Linux?


How to apply outer glow to a UI game object? Shader? Particle? What's the best or easiest approach to apply an outer glow effect to a UI game object let's say, a popup dialog, so it's a rectangular shape in Unity 2018.3? Is this something that should be done with a shader, or is it a particle effect? Ideally I should be able to specify and perhaps even dynamically adjust the color and size of the glow. Edit image below shows a blue rectangle, which has this subtle, grey glow around it. I'm hoping to generate this glow effect somehow in Unity.


Disable free look camera movement when touch detected on mobile joystick I'm using free joystick pack form asset store and in scene have two cameras (first person and third person). Switching cameras with toggle. Game starts with first person camera. Moving with fixed joystick and rotating camera with swiping on right side of screen. Everything is ok for this step. For third person camera I'm using cinemachine free look camera. Cinemachine camera is reacting to joystick touch inputs. I need to disable camera movement when interacting with joystick. Tested on Android device Cinemachine settings Third Person movement script void Update() if (Application.platform RuntimePlatform.Android Application.platform RuntimePlatform.IPhonePlayer) x joystick.Horizontal z joystick.Vertical else x Input.GetAxis( quot Horizontal quot ) z Input.GetAxis( quot Vertical quot ) Vector3 direction new Vector3(x, 0, z).normalized if (direction.magnitude gt 0.1f) float targetAngle Mathf.Atan2(direction.x, direction.z) Mathf.Rad2Deg camTps.transform.eulerAngles.y float angle Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime) transform.rotation Quaternion.Euler(0f, angle, 0f) Vector3 moveDirection Quaternion.Euler(0f, targetAngle, 0f) Vector3.forward characterController.Move(moveDirection.normalized speedTps Time.deltaTime) Any ideas and suggestions is appreciated


How to use GameManager to get GameOver() from another script? I'm trying to make a gameover text show when the player is leaving the plane area. In GameManager.cs I've written public void GameOver() gameOverText.gameObject.SetActive(true) And in PlayerController.cs I've used the following code private GameManager gameManager and void Update() float horizontalInput Input.GetAxis("Horizontal") float verticalInput Input.GetAxis("Vertical") playerRb.AddForce(Vector3.right speed horizontalInput) playerRb.AddForce(Vector3.forward speed verticalInput) if (transform.position.y lt 4) gameManager.GameOver() But this doesn't really work, and the console is giving me this message Assets Scripts PlayerController.cs(8,25) warning CS0649 Field 'PlayerController.gameManager' is never assigned to, and will always have its default value null I've already used the OnTriggerEnter (for powerups) and OnCollisionEnter (for enemies). How can I get the GameOver text to show when the player leaves the "Plane"?


Unity 2D Cinemachine weird behavior for non rectangular confiner I have been trying to emulate a sort of Megaman X4 way of following the player around platforming levels, where the camera is confined to certain boundaries of such levels. However, all the tutorials and guides out there only show rectangular or square shaped confiners for the virtual cameras, and not odd shapes like an L shaped confiner, when using a weirdly shaped confiner the camera just tends to snap from one position to another and the game ends up feeling bad when that happens. I have tried solving this problem by using dolly tracks, which work nicely... But I end up having tons of virtual cameras to change to on sections that are weirdly shaped since the camera ends up also suddenly snapping on to weird positions on sharp turns and it also tends to get way off track, even when the settings of the virtual camera are configured to have very little damping and if there's no damping the camera just stutters all the time. Is there a way to have this kind of behavior to confine a virtual camera to oddly shaped level boundaries?


How to rotate and move an object in precise time frame My task is to rotate and move an object into a new position and rotation in a given time. Say I have to move a cube from (0,0,0) (0,0,0) to (1,1,1) (0,90,0) in 5 seconds. Could anyone explain to me please how to achieve that? My experiment is private IEnumerator DoMove( float time, Vector3 targetPosition ) foreach(WayPoints wp in tposes) float counter 0 float duration wp.timeStamp while (counter lt duration) counter Time.deltaTime Vector3 curpos cube.transform.position Quaternion crot cube.transform.rotation float time Vector3.Distance(curpos, wp.position.position) (duration counter) Time.deltaTime cube.transform.position Vector3.MoveTowards(curpos, wp.position.position, time) cube.transform.rotation Quaternion.Lerp(crot, wp.position.rotation, time) yield return null Debug.Log( quot Reached position quot wp.position.position quot in time quot Time.time) The cube gets to its position in time, but rotation is late. The end position of the cube should be (2,2,2) (0,120,0), but it stops moving at (2,2,2) (0, 110,0). There are two positions I want the cube to be in (1,1,1) (0,90,0) in 5 seconds (2,2,2) (0,120,0) in next 4 seconds


How do you generate seamless Perlin noise? I've done a research and tried implementing for months, but I've gotten nowhere trying to make seamless tileable Perlin noise. Here is my current Perlin noise file without seamless implementation. In my program, I am calling FractionalBrownianMotion to generate. Each of the research articles have given me issues. In FractionalBrownianMotion I change the call from Perlin to PerlinSeamless. Research Articles How to make one axis tileable simplex noise? Produces broken noise using x2, y2 as period xsize, ysize as map size. Also tried vice versa. Added code public float PerlinSeamless(float x, float y) int width gradientArray.GetLength(0) int length gradientArray.GetLength(1) map size 250 float x1 0, x2 50 float y1 0, y2 50 float dx x2 x1 float dy y2 y1 Sample noise at smaller intervals float s x width float t y length Calculate our 3D coordinates float nx x1 Mathf.Cos(s 2 Mathf.PI) dx (2 Mathf.PI) float ny y1 Mathf.Sin(t 2 Mathf.PI) dy (2 Mathf.PI) float nz t return Perlin3D(nx, ny, nz) public float Perlin3D(float x, float y, float z) y 1 z 2 float xy perlin3DFixed(x, y) float xz perlin3DFixed(x, z) float yz perlin3DFixed(y, z) float yx perlin3DFixed(y, x) float zx perlin3DFixed(z, x) float zy perlin3DFixed(z, y) return xy xz yz yx zx zy private float perlin3DFixed(float a, float b) return Mathf.Sin(Mathf.PI Perlin(a, b)) How do you generate tileable Perlin noise? hashed perm perm int(gridX) per int(gridY) per goes OOB. 3D Perlin Noise Technique does not replicate 2D noise when z value always 0, but using this method for 3D Perlin noise assuming that's the way it's supposed to be I have also tried various implementations of non answer accepted comments in these articles to see only broken noise.


Jittery collisions in Unity 2D I tried to implement a simple movement to my object. My object moves perfectly fine but I'm having issues with its collision. When I keep on moving object towards the obstacle ground, collision are jittery. Here the code for what I've written. using System.Collections using System.Collections.Generic using UnityEngine public class TempScript MonoBehaviour SerializeField float walk speed 5f SerializeField float jump speed 10f SerializeField float max up 7f SerializeField float max low 1.5f void Update() PlayerMovement() void PlayerMovement() if (Input.GetKey(KeyCode.W) amp amp transform.position.y lt max up) transform.position transform.position Vector3.up jump speed Time.deltaTime if (Input.GetKey(KeyCode.S) amp amp transform.position.y gt max low) transform.position transform.position Vector3.down jump speed Time.deltaTime if (Input.GetKey(KeyCode.D)) transform.position transform.position Vector3.right walk speed Time.deltaTime if (Input.GetKey(KeyCode.A)) transform.position transform.position Vector3.left walk speed Time.deltaTime The cube goes below the ground and bounces right back up. making it look like its jittering. what i want is movement should stop when its colliding with object. just like it happens with addForce method. for now you can ignore max up and max down variable, it was just to make sure its in the camera.


Unity SpriteAtlas memory consumption I'm in the process of optimizing my application memory consumption. To do so, I'm using Unity profiler while connecting to an Android device, which runs a development build of the application. The application is using two types of sprite containers Sprite sheets created by the Texture packer. Sprite Atlases created by unity. Using the profiler, it is observed that while the sprite sheets (created by the Texture packer) take the expected amount of RAM, the sprite atlases created by unity consume DOUBLE the expected amount of RAM. For example, the sprite atlas UIATLAS, whose size is 4096x4096 is supposed to consume 16MB of RAM But looking at the profiler, after running "Take Sample", you see the value 32MB My sprite atlas settings are Any help is welcome here. One more comment (please review) UIAtlas belongs to an asset bundle called "atlas ui". It is defined on several directories containing its sprites, all of which belong to the same asset bundle, atlas ui. Is that the correct way to define it? Thanks in advance!


GeForce FPS Counter is not displaying and G SYNC is not working on games developed using Unity I have developed a small game for learning purpose and here is src of that, when I play the game GeForce FPS Counter is not displaying. I thought there might be some kind of bug in my src. So, I installed two popular games developed using Unity. "Life is Strange Before the Storm" FPS not displaying. "INSIDE" FPS displaying. Can anyone tell me what is happening. And also I noticed that when playing "Life is Strange Before the Storm" my CPU and GPU temperature goes hotter than playing "Rise of the Tomb Raider". Note I have played all the game in full screen mode and all settings to highest. UPDATE Firewatch and INSIDE both shows FPS Counter. but, when Enable G SYNC for full screen mode is selected, G SYNC is not working in all the games developed using Unity even when launched in full screen mode. But when I enable Enable G SYNC for windowed and full screen mode then the G SYNC is working. But when it comes to Life is Strange Before the Storm is not showing FPS Counter but shows G SYNC indicator on the screen. Is Unity games not actually runs in Full Screen mode?


Can I run old projects after updating Unity? Today I decided to upgrade unity from 5.0.0 to 5.5.0. But before updating it, I wanted to know Can I run build my projects made in Unity 5.0.0 in Unity 5.5.0?


Switching character and keeping animations in Unity default third person controller This is probably a ridiculous question, but I am doing a school project in Unity and am trying to create a basic game. For movement I want to use third person controller and since this is very basic I wanted to keep the default 3d model of character as well (Ethan). But since it is so colorless I had a friend of mine to color it up and then export it back to unity. The problem is that it's a different model now and animations don't work anymore so I want to know how to correctly switch them to keep default animations? The models are the same otherwise so animations should be possible to apply. Since nothing I tried so far didn't help I really hope someone can give me some instructions.. ) Thanks


How can I ensure a radius variable doesn't get reduced below 0? For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is 1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to 1. using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using System RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 public bool circle true Range(0, 50) public float xradius 15 Range(0, 50) public float yradius 15 LineRenderer line public float drawSpeed 0.3f void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount (segments 1) line.useWorldSpace false private void Update() if (xradius gt 0) if (Input.GetAxis("Mouse X") lt 0) xradius xradius 1 CreatePoints() if (Input.GetAxis("Mouse X") gt 0) xradius xradius 1 CreatePoints() private void CreatePoints() if (circle true) yradius xradius float x float z float change 2 (float)Math.PI segments float angle change for (int i 0 i lt (segments 1) i ) x Mathf.Sin(angle) xradius z Mathf.Cos(angle) yradius line.SetPosition((int)i, new Vector3(x, 0.5f, z)) angle change In the Update I did if (xradius gt 0) But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to 1 not sure how can it be 1 if I set the range in both xradius and yradius to be 0,50 You can see in the screenshot in the Inspector in the right both Xradius and Yradius are 1


2D Lock x Axis on character I am creating an endless runner with a flying character. I want to lock any movement in the x axis so that the character object can only move up and down but still move forward through the scene. I have looked into freezing axes and joints, but this stops the forward movement. Is it possible to edit the below to lock the x axis for character movement only, or is there a setting where i can apply this? using UnityEngine using System.Collections public class moveupdown MonoBehaviour public Vector2 velocity public float uservelocity public Rigidbody2D rb2D void Start() rb2D GetComponent lt Rigidbody2D gt () void FixedUpdate() if (Input.touchCount gt 0 amp amp Input.GetTouch (0).phase TouchPhase.Moved) Vector2 touchDeltaPosition Input.GetTouch (0).deltaPosition rb2D.MovePosition (rb2D.position touchDeltaPosition Time.fixedDeltaTime uservelocity)


Render Occluded pixels to gray color In 3d space, objects can be occluded by another objects. By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn. But, sometime we need to render the occluded object or pixels for game play. To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels. This is the sample images for the case. I guess this can be achieved by some sort of shader. How can I make this effects in Unity 3D Engine? Any hints or idea plz.


Oscillate an object's scale I am able to scale an object using a scaling function I wrote. Internally it builds matrices that are multiplied by each of the vertices to transform them. The parameters I give the scaling function tell it how much to scale the object by as a factor of its current scale. I want my object's scale to smoothly oscillate between two values, so I have used Sin waves to build my scaling factor, which is 1 amplitude (Mathf.Sin(2 Mathf.PI frequency Time.time) Mathf.Sin(2 Mathf.PI frequency (Time.time Time.deltaTime))) The result looks very close to what I want, but with each oscillation, the object gets slightly smaller than before. The problem is that my function is written so that it scales the vertices as a factor of its 'current' scale, which is always changing.


Scene for Computer Screen We are developing a scene that will involve heavily interacting with a "touch screen monitor" in the scene.. Because the workflow of the touch screen will need to be dynamic we are creating a REST API that Unity will fetch JSON data and use that to build out the various parts of the UI. For instance, we get a JSON file that has a list of users and attributes and build out UI elements with that data. The question is should I build out the display and underlying logic as a 2D scene that I add in to our 3D room or just build it all in the 3D scene. I want to abstract away as much of the logic as I can for the interactive screen I want to make sure we can drop this screen in a different Scene down the road without too much reverse engineering. Sorry if this is a straightforward question, my background is software dev, not game design.


How can I deactivate and activate a button? I have a code that keeps a gameObject between scenes, the theme is that this gameObjecte has as a child a button, which I can change the linerenderer color, besides changing the image of the button according to the selected color and thus keep the data between scenes. then when I change to the next scene I deactivate the button with the meteodo "dehabilitar()" and in the others it is not necessary, then when I change to the next scene I deactivate the button and it is not shown, but when I go back to the next scene and call the function " habilitar() "the button is not displayed. If someone can help me in what I have bad in the code or what I lack? PS I did different methods to activate and deactivate the button but the same thing always happens and I leave it like that for a while. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI namesp ace DigitalRubyShared public class CambioColor MonoBehaviour public Button mybutton public LineRenderer p1 public LineRenderer p2 public Sprite colorRojo Color Rojo new Color(1, 0, 0, 1) public Sprite colorAzul Color Azul new Color(0, 0, 1, 1) public static int counter 0 public static bool estado false public static CambioColor estadoCambioColor void Awake() if (estadoCambioColor null) estadoCambioColor this DontDestroyOnLoad(gameObject) else if (estadoCambioColor ! this) Destroy(gameObject) void Start() mybutton GetComponent lt Button gt () p1 GetComponent lt LineRenderer gt () p2 GetComponent lt LineRenderer gt () counter 2 public void changeColor() counter if (counter 1) mybutton.image.overrideSprite colorAzul mybutton.image.sprite colorAzul p1.startColor Azul p1.endColor Azul p2.startColor Azul p2.endColor Azul if (counter 2) mybutton.image.overrideSprite colorRojo mybutton.image.sprite colorRojo p1.startColor Rojo p1.endColor Rojo p2.startColor Rojo p2.endColor Rojo counter 0 public void dehabilitar() if (estado false) mybutton.enabled estado mybutton.gameObject.SetActive(estado) estado true public void habilitar() if(estado true) mybutton.enabled estado mybutton.gameObject.SetActive(estado) estado false Update is called once per frame void Update()


How to implement ECS architecture in C ? As C is a strongly typed language, I'm having great difficulties associating all my data types together so that I can have a clean, if not performant, game loop. Example 1 Keeping Components Together Keeping components together means I need an interface or base class to store them in an array, which would require keeping track of each type separately so that it can be converted back to the derived type before being consumed. The constant type conversion seems like a bad idea in an ECS? To compound the problem, I would prefer to use structs instead of classes for my components, which when cast to an interface will cause boxing. In some simple stop watch tests I've run it seems the casting boxing is 16x slower than just looping over the raw type. (Pseudo code below) IComponent sprite new SpriteComponentStruct() boxing for(int i 0 i lt iComponents.Length i ) var type GetComponentTypeByIndex(i) var system GetSystemWithType(type) SpriteComponent sprite Convert.ChangeType(...) system.Execute(sprite) Example 2 Keeping Components Separate To keep components separately in their own classes managers systems I would likely need a generic class to cut down on the code duplication. The problem I run into here is that looping over each class will require a base class or interface, which at the very least would force me to cast the component types again. (Pseudo code below) ComponentManager lt T gt () where T struct T components can't use with non generic interface to put manager into a list public void AddComponent(T component) ... won't compile type "T" will not cast to type "T" public void AddComponent lt T gt (T Component) ... requires casting and or boxing, which defeats the purpose of keeping components separate public void AddComponent(object component) ... It seems every which way I try to implement a ECS in C ends with hacky non performant code, that's assuming I can get it to compile in the first place. From studying other ECS systems around the net, it seems some side step these issues by using void int pointers or storing component bytes directly in memory (like I believe the new ECS in Unity 2018 does). Either way those are unsafe operations in what's supposed to be a managed memory language. So is C the wrong tool for the job? Am I approaching this incorrectly? I'd love to hear some opinions as this just seem impossible...


2D Camera sizing and movement Apologies if this is a basic question, or been asked a 1,000 times in the past... I'm new to Unity, and having problems understanding some of the basics to do with 2D cameras (orthographic), and while I've read a lot nothing has made me have that 'ah ah!' moment yet. What I'm trying to create is the following (camera position depicted by the box with the pink dashed line) where the yellow filled boxes are made up of a whole bunch of sprites. Overtime, the camera need to move left to right, and then bottom to top... What my issue seems to be is understanding how I can get the camera to display all of the sprites in other words, resize the camera view to fit the background sprite's height, and know when to stop the camera in order to start moving it up. What I'd like to understand is how and why to solve this problem it's the only way I'll learn! Thanks Kieron


How to get Flare elements? Is it possible to get the elements or the textures of a Flare and to change them at runtime? If so, then how do I get them? Pseudocode Flare flare GetComponent lt Flare gt () foreach (Element e in flare) e.Size 10 e.Color Color.green Thanks in advance )


Access buttons individually made by a for loop (old Unity GUI, Unity Editor script) I've got a problem and I am struggling with this for a couple of days now. I am making an Editor script and I want to access buttons individually when created by a for loop. There is a public class ButtonNode which stores some variables of the button like name and size. public class ButtonNode public bool button public string name "O" public float sizeW 25f public void AlterButton() name "P" Then there is my Editor script in which I create the buttons. This is where I get stuck, how do I access these buttons individually? For example, I want to change the name of the button when that button is clicked. How do I do that? Because they are booleans (I don't really know why, this is the legacy GUI) I can't access the transform.name components etc). public static ButtonNode bn new ButtonNode 10 void OnGUI() GUILayout.BeginHorizontal() for (int i 0 i lt bn.length i ) bn i new ButtonNode() if (bn i .button GUILayout.Button(bn i .name i, GUILayout.Width(bn i .sizeW))) bn i .AlterButton() GUILayout.EndHorizontal()


Array with multiple linked objects in Unity This might be too primitive, but for my use case, I need to maintain an array in which two attributes are linked to each other... For example If I want to do Score gathering... Then I need an array which has scores and corresponding player names as each element. So, when I do Array.Sort(PlayerScorearray) I even need the playername to be sorted in the order so that if I want to know the player with lowest score, I just go for the first element and then go to the corresponding player name.. Is it possible to do it in a simpler way? My mind can't think of a simple way to do this. Edit I am using C for scripts


Can I use flat shading on a generated mesh? I tried to generate a mesh from code in Unity. The problem is, that the edges are automatically smoothed. When I import a model into Unity, I can set the smoothing angle of the edges, but is something like this possible with a generated mesh? I would like to have no smoothing at all.


Jump a gameobject when a key is pressed I am working on a platform game,When I press the space bar the object should jump and when I release the space bar it should come down. The code I have used for jump is void Update () transform.Translate(Vector3.right Time.deltaTime) if(Input.GetKey(KeyCode.Space)) rigidbody2D.AddForce(Vector3.up 3) if(Input.GetKeyUp(KeyCode.Space)) rigidbody2D.AddForce(Vector3.down) But when I release the space bar the object is not coming down


Shadow Glitch on Mesh Stitches I use LWRP, one Directional Light and Hard Shadows with 1024 resolution. When I imported this super simple mesh from blender this happened What is this weird line on the stitch of the mesh and how do I fix it? I tried using Soft Shadows with higher quality but it did not help.


How do I use guilayout toggle event to check if true or false? OnGUI() for (int i 0 i lt scenes i ) GUILayout.Toggle(false, SceneManager.GetSceneAt(i).name) if (GUILayout.Toggle(true, "New Scene")) Debug.Log("True now !") First in the loop I'm adding some toggles. Then I want to do that if specific toggle is checked(true) do something and if unchecked(false) do something else. But the way I did it it's just changing the toggle to true automatic.


Get mouse touch position for NGUI event Since I am using NGUI, to capture mouse events I use their methods such as void OnPress (bool isDown) How can I check the mouse touch position that corresponds to this particular OnPress event?


How to create a correct Unity package copy, which will not be replaced when you import? I create a "Package 1" consisting of section A (unique) section B (which will be repeated in all my other packages). This package works correctly is he is alone. Next, I create a "Package 2" consisting of section C (unique) Section B (from Package 1). To save time, I replaced the texture maps in the materials belong to old section A parts and replace this part on section C (directly on models in the Mesh.) I renamed most objects in the scene and in the package as a whole. I delete all prefabs of section A and create prefabs section C , because they are not pick up name changes. The prefabs of section B , I left as is. Now when I import Package 2 in the scene that already contains the Package 1 , it begins the mess Package 1 Files are replaced by Package 2 , even them are named differently. How to avoid it? I can t create each scene from scratch, unfortunately it will lead to the insane time consuming. Huge thanks for your support!


How to set up bloom in Unity Last time I used image effects in Unity it was back when 3.0 was released and for bloom you used the object's alpha to indicate whether it should glow or not. Now in 4.2 I couldn't grasp how to apply the image effect properly. It seemed to put the whole scene to glow and alpha did not affect it. There was no help from the Unity docs which are pretty much just spec sheets for the effects and no proper tutorials around. This leads to couple of questions How do you create something like the screenshots in the Bloom page in the docs? Only the car windows and metal parts glow, but no glow on the concrete. How do you make a light source like the second image on the above link? I tried different shaders and lights on a gameobject but none of them produced anything like that. What does the HDR checkbox in the camera actually do?


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


Third Person Flying Camera I am having issues creating a third person camera for my Rogue Squadron (N64) like game. First I have posted my issue on the official Unity Answers site here. So far my ship is behaving as I want and the camera follows position correctly (XYZ), however, it doesn't rotate how I would like. My first attempt was to set the rotation of the camera to the rotation of the ship and realized that is not what I am looking for either. I have found some information on rotating around a (pivot) point but I am having trouble understanding them. For example, I have found this and this but Im not sure how they work. The end result would be something like the camera found here. Thank you for any help, I would greatly appreciate a description of what you are doing how it works. Lastly this is done in C in Unity. I can provide my code if needed.


Can't go above max speed with RigidBody2D.AddForce() I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top down 2D game (constrained to the x y plane). I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed" going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ) private void WASDMovement() Vector3 translationVector Vector3.zero if (Input.GetKey(KeyCode.W)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.A)) translationVector new Vector3( 1.0f, 0.0f, 0.0f) if (Input.GetKey(KeyCode.S)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.D)) translationVector new Vector3(1.0f, 0.0f, 0.0f) translationVector.Normalize() rigidbody2D.AddForce(translationVector MovementSpeed) Here's a video demonstrating my problem to make it easier to see what I'm doing wrong http youtu.be 9kwKvfDOYoo


How could you create an SSX style snow trail in unity3d? So it SSX (a snowboarding game) when you are snowboarding you leave behind a dents in the snow(like a trail) .It's like how if you take a step in the snow you will leave a footprint behind but with a snowboard you leave a trail of where your snowboard has been. Can you create this or is this not supported by unity? If you can, how? Thanks in advance


Fading back and fourth Unity Image alpha I'm trying to create a way in which if I press a button, it'll highlight other objects whilst at the same time fading other objects. I also have other buttons that will fade and highlight different objects. Some of which may have been modified by the first button. I had done this originally in a really dumb way like so public void Highlight() foreach (Image image in imagesToHighlight) Color c image.color if(c.a lt maxColor) c.a maxColor image.color c foreach (Image image in imagesToFade) Color c image.color if(c.a gt halfColor) c.a halfColor image.color c This works, but I was wanting it to happen gradually to provide a smother transition. I managed to get the fade working, by changing the code to this IEnumerator Fade(Image image) float elapsedTime 0.0f Color c image.color while (elapsedTime lt 1) yield return fadeInstruction elapsedTime Time.deltaTime c.a 1.0f Mathf.Clamp01 (elapsedTime fadeTime) image.color c I then call the method in my foreach loop like so foreach (Image image in imagesToFade) StartCoroutine (Fade (image)) Again, this works fine. The problem I'm having is checking to see if the image is faded, and if it is and needs to be highlighted, it reverses from the fade value to the highlight value (0.5 to 1.0). I thought this would be a simple change as did this IEnumerator HighLight(Image image) float elapsedTime 0.0f Color c image.color while (elapsedTime lt 1 ) yield return fadeInstruction elapsedTime Time.deltaTime c.a Mathf.Clamp01 (elapsedTime fadeTime) image.color c Simply changing the alpha line. However, now my image alphas jump all of the place in the highlight method. I'm at a loss as to how I can fix this. Can someone please tell me what I'm doing wrong?


Unity 5.x Network Synchronization Concepts Bear with me, It will be long read I am working on the new Unity Networking system. I was using Photon and old (legacy) unity network API's before. But as it seems there are some good benefits of the new system than the previous ones, so I want to stick with it. (Despite of it being uncompleted) But there are some points that doesn't make sense to me with the API. Data Sync for example. So, in the old systems (both in Photon and legacy unet) we had functions called OnPhotonSerializeView or OnSerializeNetworkView depending on which API we use. Both API's are very similar as you may know. So in these functions we could send and recieve data between clients and server. Which makes sense, and was really usefull. But aperantly they changed this concept, (or it still exists, and i couldn't find it) There is a new thing called SyncVar , which syncs the data "ONLY" from server to client automatically. (Which really, literally doesn't make sense, I mean why not sync both server to client AND client to server? That would make everything much easier) According to the documents, you can ONLY send data from client to server by using Command 's. Which is basically (as far as I understand), "one way" version of old good RPC calls. Instead of calling function in all other clients, it calls it in the server. So, you can send data to server with function parameters like the way we did it with the old RPC 's before. Which is usefull on point but If this is the only way to send data to server, then it doesn't make any sense to me.. I mean there are variables that needs to be kept synced all the time, back and forth, like position or rotation vectors. And sending them with Command calls, contradicts with the concept of network framework in my mind. We used to avoid this kind of situation before, right? Why make it the obligation now? Or are there simply any other ways to send data from client to server that I couldn't find yet? There is a custom serialization with the SyncVar , with OnSerialization and OnDeserializaton functions. Which really looks like the good old OnSerialize functions but apperantly it's diffrent as it does what the SyncVar does. OnSerialization is only called on server, and Deserialization is only called on client. So we can only send from server to client even with it. If Command is the only way to send data to server, please say so. And clarification about why this concept is reasonable would be really nice. Please enlighten me more with the new concepts of the new UNET framework. Thanks in advance for any help.


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


Preparing a 2D character to export from Blender to Unity? I'm an animator for a game currently, and I don't have Unity (can't download due to too much gigs coupled with slow internet,) but the game designer told me I can use Blender to export animations into Unity. I asked if I needed to prepare multiple files to export, and they told me that I could just have one file with all the animations in it. The game, as stated in the title, is 2D. My problem now is, how do I turn a rig into an actual character with different animations under it? (Right now I only have an 'idle' animation, but need to make running, jumping, walking, etc.) I mean how do I save this 'idle' animation and work on another animation without overwriting the previously finished animation(s)? Thank you much


How to correctly draw a 2D polygon in Unity I'm trying to draw a 2D polygon using GL.Line however I'm not getting a polygon but separated lines instead. In the example below, I would expect a rectangle formed by the spheres My code is the following void OnPostRender( ) GL.PushMatrix ( ) mat.SetPass ( 0 ) GL.LoadOrtho( ) GL.Begin( GL.LINES ) GL.Color( Color.white ) for ( int i 0 i lt spheres.Length i ) currentVector Camera.main.WorldToViewportPoint ( spheres i .transform.position ) GL.Vertex3 ( currentVector.x, currentVector.y , 0 ) GL.End() GL.PopMatrix() Also, I found this tutorial example but is not exactly what i'm looking for, since in the example, all have the same origin point. I'm asumming that the correct way of achieving what I want, would be to call the Gl.Vertex3 method once for each of the 2 points that form each line From A to B (GL.Vertex3 call 2 times) From B to C (GL.Vertex3 call 2 times) From C to D (GL.Vertex3 call 2 times) From D to A (GL.Vertex3 call 2 times) Is this the right way of doing this? Thanks in advance.


Which image effect is this? This is a screenshot from RE7. I have once seen the same image effect in Unity, but I don't remember the name I'm not talking about AA or DOF here, I mean this grainy greenish thing, I don't know how to describe it... At first I thought the name was something like quot Anisotrophic filtering quot , but that didn't bring up anything that looked like it. Can anybody tell me the name of the effect that I see here? Edit It can be seen in the start screen of this video, too https www.youtube.com embed aaN3MNb9ij0?feature oembed Both screenshots look pretty similar to me, so I guess it's the same effect? Edit 2 The pixels seem to shift into red blue the closer they get to the edge of the screens. I have drawn red arrows to region where this effect is very visible to me. These pixels appear as quot shifted quot to me. I think this effect is more visible at the edge of the screen. Thank you.


Consume input events in Unity 4.6 How do I consume the input events in the new 4.6 unity gui system? If I click on a button for instance I don't want anything else non GUI related that might be listening for mouse input to react to the event.


World Canvas InputField cursor precision control from RenderTexture output in Overlay UI How do you have a world canvas input field cursor be controllable from the input being mapped from a UI overlay with its raw image supplied from render texture from a render camera? Described another way World Canvas Input Field gt Render Camera creates renderTexture for gt Screen Overlay UI Raw Texture gt Main Camera How do you have the cursor position be mapped from the Screen Overlay UI Raw Texture?


Player animating the wrong direction once he is rotated I have used the scripting root motion move the player when using an 'inplace' animation. All works correctly until the players rotation is off 0,0,0. This is expected as the movement is along the transform.z axis but how can I account for the rotation in the script and apply it so the movement is correct in game? The gorillacontroller script is the script we are trying to fix On playerGorilla. animator is on the playergorilla. The gorilla1 is the gameobject holding the mesh and the bones for the character. I will also add the transforms are moving this was my silly mistake because I had tool handles in global instead of local. This makes it even more confusing however because all tranform.z (blue axis) are facing the correct way for the animation to work but the animation is only ever playing in the original direction where the rotation is 0,0,0,0. using UnityEngine using System.Collections RequireComponent(typeof(Animator)) public class RootMotionScript MonoBehaviour void OnAnimatorMove() Animator animator GetComponent lt Animator gt () if (animator) Vector3 newPosition transform.position newPosition.z animator.GetFloat("Runspeed") Time.deltaTime transform.position newPosition


Can Cruncher crunch Daz models? I have a number of Daz 3D models that I would like to use in my Unity shooter game. The only problem seemed to be the high poly count of the Daz models. However, I just came across the Cruncher Polyreduction tool (http assetstore.unity3d.com content 4294). Is it possible to use this plugin to incorporate Daz models in my game?


Problem with Animating on local position Unity Currently, I am having a Cube that needs to be animated to roll on its edge. Using unity built in animation feature, I created 4 animations (RotateUp, RotateDown, RotateLeft, RotateRight). At the end of each animation I would put an Event to call a method on my script. To be able to move the object every time the animation is played, I put the cube with animator attached inside a parent object. Below is the script attached to my cube. using System.Collections using System.Collections.Generic using UnityEngine public class RedCubeBehavior MonoBehaviour Animator anim bool isMoveTriggered false void Start() anim gameObject.GetComponent lt Animator gt () void Update() if (Input.GetKeyDown(KeyCode.UpArrow)) MoveUp() else if (Input.GetKeyDown(KeyCode.DownArrow)) MoveDown() else if (Input.GetKeyDown(KeyCode.LeftArrow)) MoveLeft() else if (Input.GetKeyDown(KeyCode.RightArrow)) MoveRight() if (isMoveTriggered) if (IsBackToIdle()) transform.parent.position transform.position transform.localPosition Vector3.zero isMoveTriggered false void AnimationFinished() anim.Play("IdleState") public void MoveUp() if (isMoveTriggered) return else Debug.Log("MoveUp") isMoveTriggered true anim.Play("RotateUp") public void MoveDown() if (isMoveTriggered) return else Debug.Log("MoveDown") isMoveTriggered true anim.Play("RotateDown") public void MoveLeft() if (isMoveTriggered) return else Debug.Log("MoveLeft") isMoveTriggered true anim.Play("RotateLeft") public void MoveRight() if (isMoveTriggered) return else Debug.Log("MoveRight") isMoveTriggered true anim.Play("RotateRight") bool IsBackToIdle() return anim.GetCurrentAnimatorStateInfo(0).IsName("IdleState") Every time the arrow key is pressed the object would rotate but in the end when AnimationFinished() is called, the cube would just roll back to its starting position (because of playing IdleState). It will only work (the object didn't return to its starting position) if I pressed the arrow twice quickly. I've tried to not call the IdleState (which is only an empty state), but what happens next is it just won't play another animation again when triggered. What should I do in order to get it work without having to press the key twice?


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)


Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls)


FullSerializer Update serialized property name Currently we have some ScriptableObjects that are referenced by their name. This comes with some issues as names may change and also they don't have to be unique. We would like to switch to UUIDs. using FullSerializer System.Serializable fsObject(Converter typeof(CharacterDataConverter)) public class CharacterData public CharacterSO player public CharacterSO mentor The mentor field is currently serialized as mentorName. With the changes the serialized field name would be mentorUid. This is handled by the CharacterDataConverter, but this has to be updated all the time when CharacterData class changes and is often forgotten. Much simpler would be to use fsProperty using FullSerializer System.Serializable public class CharacterData fsProperty(Converter typeof(PlayerConverter) public CharacterSO player fsProperty(Converter typeof(CharacterSOConverter), Name quot mentorName quot ) public CharacterSO mentor But this can handle only either mentorName or mentorUid. Is there another solution? Maybe using versioning?


OnInspectorGUI Custom properties are not displayed in the right order I basically made a lot of research and wasn t able to find any solution. So my problem I ve made some variables disappear appear depending on an enum with a custom editor script. But if they appear they do not appear at the position where the normal editor variables would appear override public void OnInspectorGUI() base.OnInspectorGUI() GunCard myScript target as GunCard EditorGUI.indentLevel switch (myScript.aimingControlType) case AimingControlType.Manual myScript.hasAimAssistance EditorGUILayout.Toggle("Has aim assistance", myScript.hasAimAssistance) break case AimingControlType.AutoTargeting myScript.targetPreference (TargetTypes)EditorGUILayout.EnumPopup("Target preference", myScript.targetPreference) myScript.requiresLineOfSight EditorGUILayout.Toggle("Requires line of sight", myScript.requiresLineOfSight) myScript.requiresPossibleTargetOnScreen EditorGUILayout.Toggle("requires possible target on screen", myScript.requiresPossibleTargetOnScreen) break EditorGUI.indentLevel Here is where they appear That are the raw variables in the scriptable object Header("Aiming Controls") public AimingControlType aimingControlType HideInInspector public bool hasAimAssistance HideInInspector public bool requiresLineOfSight TODO implement gt requires 180 HideInInspector public bool requiresPossibleTargetOnScreen TODO implement gt requires 180 HideInInspector public TargetTypes targetPreference HideInInspector public bool isAutoShootWhenAimOnTarget I know I m basically adding new variables to the inspector in my editor Script but it would be really useful to order them. Is there a way to do that? P.S sorry for the funny typo in the picture )


How to place same canvas on multiple cameras in Unity? I know how to do It on one, but I don't know how to do it using multiple cameras, 3 of them are important, i want to show the whole UI except for the minimap. I need to change the camera angle on some spots, while keeping the same canvas for displaying the number of coins XP and the current level.