Using XBox 360 controller in Unity game game doesn't recognize axis movement I have a problem with the usage of XBox controller in Unity game. I connected the controller to the PC and it works fine, I also managed to use it in the game itself I'm using "A" button to fire and Start to start the game and they work properly. However the game doesn't recognize the x axis movement. I'm not sure if the problem is in the input settings or my code. This is how the Horizontal movement is defined in the game This is the code that handles the movement float x Input.GetAxis("Horizontal") Vector3 newPosition new Vector3(transform.position.x x playerXMoveSpeed, 0, 0) newPosition.y transform.position.y newPosition.z 0 transform.position Vector3.Lerp(transform.position, newPosition, playerXMoveSpeed Time.deltaTime) var limit animator.SpriteRenderer.bounds.extents if (transform.position.x limit.x lt leftBorder) var capped transform.position capped.x leftBorder limit.x transform.position capped else if (transform.position.x limit.x gt rightBorder) var capped transform.position capped.x rightBorder limit.x transform.position capped OnMove(gameObject) All variables are more or less self explanatory, the OnMove is a delegate that just applies the transform to the gameObject in question. The entire code is inside a void method called Move(). That method is called inside an if statement if ((Input.GetAxis("Horizontal") ! 0.0f Input.GetButtonDown("Horizontal")) amp amp !IsContinueDisplayed) FollowTouch() Like I said, the game recognizes the other buttons, but not the x axis, it doesn't move the character. The Input.GetButtonDown is there just so keyboard input would be supported also (and it works properly). Can you see the problem with this code or settings? Please advise.


TopDown Island Generation I am trying to generate an island using Simplex Noise. To actually make a island shape i used Amitp's answers to the following questions 1.Fast, simple procedural 2d island generation 2.Generating random Pools or lakes Using them i have snippet of code for generation (width height is 128) for(int y 0 y lt HEIGHT y ) for(int x 0 x lt WIDTH x ) amitp's solution Vector2 vec new Vector2(2 x WIDTH 1, 2 y HEIGHT 2) float d Mathf.Sqrt(vec.x vec.x vec.y vec.y) float noise Noise.Generate((float)x WIDTH 10, (float)y HEIGHT 10) amitp's solution again mapData x, y noise gt 0.3 0.4 d d ? noise 10 0.0f colors x y WIDTH new Color(mapData x, y , mapData x, y , mapData x, y ) This gives me the following unwanted result How do i get fix it to generate properly? Lastly i'm using Unity. EDIT Fixed Changed a couple of things and now i am getting this(still not what i want) with this changed code for(int y 0 y lt HEIGHT y ) for(int x 0 x lt WIDTH x ) amitp's solution Vector2 vec new Vector2(((2 x) WIDTH) 1, ((2 y) HEIGHT) 1) float d Mathf.Sqrt((vec.x vec.x) (vec.y vec.y)) float noise Noise.Generate((float)x WIDTH, (float)y HEIGHT) amitp's solution again mapData x, y noise gt 0.3 0.4 d d ? noise 10 0.0f colors x y WIDTH new Color(mapData x, y , mapData x, y , mapData x, y )


convert clock input into 24 hour format I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24 hour format) to show dayNight effects in scene My code is to transform 12 hours clock cycle into 24 hours is if (todsky.Cycle.Hour gt 0 amp amp todsky.Cycle.Hour lt 11.97) Debug.LogError("1st") var degree 360 hourniddle.transform.eulerAngles.z var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes ConvertMinutesToHours(degreeToMintues) else if (todsky.Cycle.Hour gt 11.97 amp amp todsky.Cycle.Hour lt 23.97) Debug.LogError("2ndt") var degree 360 hourniddle.transform.eulerAngles.z as rotation is anti clock getting rever degree var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes var MintuestTo24HoursMintueCoverstion 720 degreeToMintues add 720 mintues into current minute in order to get 24 hour format ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion) void ConvertMinutesToHours(float mintues) result TimeSpan.FromMinutes(mintues) Debug.LogWarning(result.Hours " " result.TotalHours " " result.Minutes " " result.TotalMinutes) todsky.Cycle.Hour (float) result.TotalHours Debug.LogWarning("setted hours " todsky.Cycle.Hour) But it is not working correctly . have made a clock GUI(360 degree) and as you know it only show 12 digits format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping.


How can I implement Objective C libraries in Unity? I've been a "hardcore" developer for sometime now, as I've always worked with pure code reactive rendering, and contributed to Cocos2d library some time ago , (It is the one I used for my games) . But I've come to realize that most of the work I'm doing by setting up my game environment , user interface and everything else is becoming a bit repetitive, and complicated, as position must be tested each build , debugging sometimes involves exploring the deep down framework and I've decided to try out a full game development environment. Some friends have recommended me Unity for mobile development (If you could give me any better advice I'd be grateful) but my main concern is my custom libraries I built on Objective C for multiplayer real time connectivity, it's probably thousands of lines and I wouldn't like to write them all over again. Is there any way I could invoke my objective c library in Unity ? I know it's probably a vague question but can't seem to find where to start! Any guidance will be highly appreciated!


How to flick gameObject using Touch? I've been searching for a solution for my problem for a while on the web, but i didn't find anything that work properly What i want to do I have a bouncing ball and I want to let the user flick it with his finger (using a swipe gesture or whatever). The ball shouldn't start moving unless the player flick touch the ball. I don't want the ball to move if the player flicks anywhere on the screen, only if the flick touch the ball What i've done so far I've tried to write a script which would detect the touch starting position and the touch end position, and check if the end position is the same as the ball position to make sure that the flick touch the ball. Then the script calculate the direction vector by substrating the start position from the end position. After that i use the AddForce methode and give it the direction vector as a parameter. Here's my code, (it's better than 1000 words ) using UnityEngine using System.Collections public class Movement MonoBehaviour public Vector2 start public Vector2 end public Vector2 direction public Vector2 ballPos public float Flicktime void Start() void Update() ballPos new Vector2(transform.position.x,transform.position.y) if (Input.touchCount gt 0) Touch t Input.touches 0 if (t.phase TouchPhase.Began) start Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0)) if (t.phase TouchPhase.Ended t.phase TouchPhase.Canceled) end Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0)) direction end start if(t.position ballPos) rigidbody2D.velocity direction 2 What's the problem ? The problem is that the code doesn't work. When i launch the game in the Unity Remote 4 app in my android device and try to flick the ball it doesn't move, the inspector shows that the the scripte is calculating the start amp end positions and the direction vector, but the ball doesn't move, it stays in the same position even when the flick touch the ball. So what's the problem ? is there a better way to do it ? Since the ball have a circle collider how to make it detect collision with the player swipe ? Thank's and have a nice weekend !


How to implement the graph for pathfinding using A The game I am working on is based on a maze where each level is procedurally generated. The pathfinding grid is a 2D array where each node holds its connections. Path requests are handled one at a time so there can't be two path calculations going on simultaneously. So far I have each node hold its data required for the A (H,F,G scores and its parent) and manipulate them directly in the algorithm. Since the nodes are the actual nodes and not copies of them, every time the algorithm runs the data changes permanently and I have to manually set them on default values before the next run. So my questions are 1) Is this a valid way of handling pathfinding in a game? 2) What other data manipulation techniques I could use in order to avoid that? If you need a copy of the code it's all on my github under Pathfinding and Managers PathfindingManager.


How to implement efficient Fog of War? I've asked a question how to implement Fog Of War(FOW) with shaders. Well I've got this working. I use the vertex color to identify the alpha of a single vertex. I guess the most of you know what the FOW of Age of Empires was like, anyway I'll shortly explain it You have a map. Everything is unexplored(solid black 100 transparency) at the beginning. When your NPC's other game units explore the world (by moving around mostly) they unshadow the map. That means. Everything in a specific radius (viewrange) around a NPC is visible (0 transparency). Anything that is out of viewrange but already explored is visible but shadowed (50 transparency). So yeah, AoE had relatively huge maps. Requirements was something around 100mhz etc. So it should be relatively easy to implement something to solve this problem actually. Okay. I'm currently adding planes above my world and set the color per vertex. Why do I use many planes ? Unity has a vertex limit of 65.000 per mesh. According to the size of my tiles and the size of my map I need more than one plane. So I actually need a lot of planes. This is obviously pita for my FPS. Well so my question is, what are simple (in sense of performance) techniques to implement a FOW shader? Okay some simplified code what I'm doin so far Setup for (int x 0 x lt (Map.Dimension planeSize) x ) for (int z 0 z lt (Map.Dimension planeSize) z ) CreateMeshAt(x planeSize, 3, z planeSize) Explore (is called from NPCs when walking for example) for (int x ((int) from.x radius) x lt from.x radius x ) for (int z ((int) from.z radius) z lt from.z radius z ) if (from.Distance(x, 1, z) gt radius) continue transparency x tileSize, z tileSize 0.5f Update foreach(GameObject plane in planes) foreach(Vector3 vertex in vertices) Vector3 worldPos GetWorldPos(vertex) vertex.Color new Color(0,0,0, transparency worldPos.x tileSize, worldPos.z tileSize ) My shader just sets the transparency of the vertex now, which comes from the vertex color channel


Unity How to create C classes with different properties like Objects in javascript and put them in an array? I just started my gamedev journey on unity this week and while I have a background with coding, I'm still somewhat of a beginner. Last year I made a text UI based game on the web browser with javascript and have been trying to make the same game on Unity. One of the main features of my game is that you press a button to "go hunting" and I had an array filled with enemies that were objects with different properties such as health, mana, attack, etc... Then I'd randomly pick one of those objects from the array to be chosen as my enemy that I'd fight. I've been trying to figure out the best way to do this with C and I might just be overthinking this. As a bonus, I'd also like to be able to see the individual enemy objects in the array in my inspector if possible so I could tweak the stats within unity. I've looked at scriptableObjects and different things but I am having a hard time putting it all together in an array from within unity. System.Serializable public class playerClass public string playerName public int lvl public int maxHealth public int health public int maxEnergy public int energy public int exp public class playerScript MonoBehaviour public playerClass player This is how I created an object for the player, I want to do something similar for the enemies but put them in an array so I could randomly pick from them. If there is a better way to do this I'd also welcome some advice ) thank you


Unity Photon Networking Cant understand OnPhotonSerializeView In all tutorials I see that an object sends data over the network and receives the data. For sync in the same method Code void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.isWriting) stream.SendNext (transform.position) stream.SendNext (transform.rotation) else Debug.Log("never gets called ") never gets called... transform.position (Vector3)stream.ReceiveNext () transform.rotation (Quaternion)stream.ReceiveNext () But when I test my code, the lower part, where the data gets received, is never executed! I never see the logs. But the object is SYNCHED because it is set in the inspector But the problem is that the object is not interpolated so it looks kind of funny. So, I need to know how can I make the upper method to work so I can do some interpolation stuff.


Everything is set to Bounciness 0 Why am I still bouncing? I am creating a platformer where rather than manipulating the character to get them from the beginning of the level to the end, you manipulate the world. Thus, when you want to make the character 'jump' over a gap, you actually use the land like a slingshot and 'fling' them. This is all working well and good save for one thing whenever I pull my land down and my player falls into it again, it begins to bounce aggressively so! I have made EVERYTHING out of a new physics material with 0 bounce, and I set my default physics to 0 bounce. My player is a rigidbody2D that is moving itself along on top of other rigid bodies. What gives? Why, even though EVERYTHING is set to 'no bouncing allowed' does my game turn into a bouncy house whenever i start to play? EDIT Here is a video of the behavior FlingyJump Bouncing Issues EDIT I have noticed a correlation to the bounce occurring and the spring being active. It have noticed that two things are happening 1) The spring is for some reason transferring force through to the ground piece while being stretched out. 2) The player is bouncing before even ever hitting the ground. I don't know quite how that is possible but it seems like as soon as it is enters the original position of the rigidbody2D for the ground piece it bounces.


Why does collision only work when keys are being pressed? My player object containing a rigidbody that is controlled using Input, is not colliding with an enemy unless keys are pressed. When no keys are pressed, the enemy simply goes through the player without collision. I'm using Unity 5.6.1f1. I figured the problem is in the Patrol class because when I don't attach the script to the enemy object the collision appears to take place fine. But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the enemy object move between points in patrolPoints which are just some empty's in the game world. So, I would like to know if I'm doing it right or is there another way to do it. Patrol.cs public class Patrol MonoBehaviour public Transform patrolPoints public float speed private int currentPoint private bool forward Use this for initialization void Start () transform.position patrolPoints 0 .position currentPoint 0 forward true Update is called once per frame void Update () if (transform.position patrolPoints currentPoint .position) if (currentPoint lt patrolPoints.Length 1 amp amp forward) currentPoint else currentPoint forward false if (currentPoint 0) forward true transform.position Vector3.MoveTowards (transform.position, patrolPoints currentPoint .position, speed Time.deltaTime)


Detecting collisions during animations I am creating a prototype enemy swordsman, and I'd like to be able to parry his attacks, like the parry system from VR Dungeon Knight. This is my method of implementation Parent a sword to his hand that has a child cube trigger collider kinematic rigidbody a custom script called ParryableWeapon. In the animation clip, when he raises his hand before his swing, use an AnimationEvent to tell the ParryableWeapon to start 'listening' for a parry. This is done by checking an internal boolean during OnTriggerEnter of the sword. If the ParryableWeapon collides with another ParryableWeapon while listening, the UnityEvent 'OnParried' is invoked. After the swing completes, use another AnimationEvent to tell ParryableWeapon to stop 'listening'. I have a simple model and animation from the Asset store that I'm using to accomplish this. For some reason, the OnParried event is only being fired every 5 or so swings at a stationary test sword. I played the animation frame by frame, and I found that the enemy swords' position sometimes does not go through the other sword, despite them being on a collision course. In one frame, the enemy sword is to the left of the other, and in the next frame, it is on the other side. It seems that the interpolated frames between the animation keyframes can only sometimes collide with the other sword. What would be the proper way to remedy this? Adding more keyframes to the animation? Some sort of calculation of the sword's path between the two keyframes?


Android black screen with Unity app in subview I've exported an Unity app game I have made to Android Studio. In Android Studio I made a layout and within it I have a framelayout. However, when I run the app the framelayout is completely black, why? Here is my Java code public class UnityPlayerActivity extends Activity protected UnityPlayer mUnityPlayer don't change the name of this variable referenced from native code FrameLayout fl forUnity Button bt groen, bt gul, bt sort Override protected void onCreate(Bundle savedInstanceState) requestWindowFeature(Window.FEATURE NO TITLE) super.onCreate(savedInstanceState) getWindow().setFormat(PixelFormat.RGBX 8888) mUnityPlayer new UnityPlayer(this) if (mUnityPlayer.getSettings().getBoolean("hide status bar", true)) setTheme(android.R.style.Theme NoTitleBar Fullscreen) getWindow().setFlags(WindowManager.LayoutParams.FLAG FULLSCREEN, WindowManager.LayoutParams.FLAG FULLSCREEN) setContentView(R.layout.main) this.fl forUnity (FrameLayout) findViewById(R.id.fl forUnity) this.fl forUnity.addView(mUnityPlayer.getView(), FrameLayout.LayoutParams.MATCH PARENT, FrameLayout.LayoutParams.MATCH PARENT) this.bt groen (Button) findViewById(R.id.bt groen) this.bt gul (Button) findViewById(R.id.bt gul) this.bt sort (Button) findViewById(R.id.bt sort) this.bt groen.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "G") ) this.bt gul.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "Y") ) this.bt sort.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "B") ) mUnityPlayer.requestFocus() Here is my XML lt ?xml version "1.0" encoding "utf 8"? gt lt RelativeLayout xmlns android "http schemas.android.com apk res android" android layout width "match parent" android layout height "match parent" android rowCount "3" android columnCount "10" gt lt FrameLayout android layout width "match parent" android layout height "400dip" android id " id fl forUnity" android background " 00FFFF" android layout centerHorizontal "true" gt lt FrameLayout gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gr n" android id " id bt groen" android layout column "4" android layout row "2" android layout alignTop " id bt sort" android layout toRightOf " id bt sort" android layout toEndOf " id bt sort" android layout marginLeft "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gul" android id " id bt gul" android layout column "9" android layout row "2" android layout alignTop " id bt sort" android layout toLeftOf " id bt sort" android layout toStartOf " id bt sort" android layout marginRight "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Sort" android id " id bt sort" android layout below " id fl forUnity" android layout centerHorizontal "true" android layout margin "10dip" gt lt RelativeLayout gt


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


How to find the closest point on multiple colliders within a box? I need to find the position of the closest point from the bounds of multiple colliders. Right now I'm using OnTriggerStay and collider.ClosestPointOnBounds(). This works great for one collider, but as when I add a new collider, it doesn't update. I've drawn a quick picture to illustrate what I'm trying to say. The black box is the area I want to check in, the red boxes are the colliders with numbers representing the order they entered the black box. The green star is what the code currently says the closest point is, and the blue star is the expected result. The purple star is the position I'm checking for, the blue star should be the closest point to the purple star. I found this answer to a similar question on answers.unity3d.com. However, I feel like that could be very inefficient because there will be many, probably up to 50 of these box checking scripts running at the same time. I've also tried using Physics.BoxCast but that gave very wild results. The area it was checking was very different to what I wanted, and also what I was visualizing with gizmos. Also, the whole idea of boxcasts are very very confusing so I would rather something else. What is the best way to find the closest point on the bounds of multiple colliders within a certain area?


Having 3D material properties depend on shader Disclaimer I apologise if this is somehow a duplicate question or is unclear. I am in the process of writing a 3D scene renderer editor in C using the OpenGL specification. It is actually going surprisingly well considering my past experience (all but none) however I have hit hurdle in designing the way materials work. First, this is how they work now Materials have a diffuse albedo map, a normal bump map, and a specular map. They also have a diffuse albedo colour, and a shininess value for when no specular map is provided. This works fine and all however I noticed Unity's material's properties depend entirely on a shader. This is pretty much what I want as this is wonderfully flexible. I know you can get a list of a shader program's GLSL uniforms as described here but I am struggling with what my Material class should be looking like. Do I have each material hold a map of textures, colours, floats, with the keys being their GLSL uniform name? Or is there a nicer more elegant way? The reason I am against this is because I wouldn't know how to organise the properties in a GUI when all I am given is a uniform name. For example I might have multiple diffuse or specular maps, and I would like to arrange these in a specific manor. Please let me know if this is an awful question, or if I could improve it in any way. My brain hurts right now.


Multiplayer turn based Android iOS We're developing a mobile endless runner game, on Unity3d where you can challenge your Facebook friends. The only interaction between the players is the challenge one player challenges the other, then each player plays when he wants, and after both players finish (when their character dies), their scores are compared to determine the winner. What system would you recommend that would allow us to implement this functionality, considering scalability, cost and ease of use? Thanks in advance!


Mesh made in Blender is correct in Unity3D as a rendered mesh, but "empty" as a collider? I created a simple stair "block" in Blender, and it's rendered correctly, but when I tick "Generate Colliders" and try to use it in a Mesh Collider, there is nothing. (Ps. I need the real mesh as a collider, not just that generated convex one) Maybe a good clue is that my other objects' generated colliders are smaller than the rendered meshes themselves. Maybe this one is scaled to zero? After triangulating And via Unity's automatic triangulation (the original, non triangulated blender model)


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?


Unity Avoid boucing when ground move down I have a sphere amp a quad, when the quad move down, the sphere fall after and bounce back continuously. I dont want to change my project setting like bounciness, gravity,mass and I need the sphere to move freely to jump between quad. How can I do this, thanks


Creating the Vertices and Triangle Indices for Voxel Generated Mesh I am running into a problem with a compute shader I am writing to generate the vertices and triangle indices for a voxel generated mesh. Currently, I am creating an AppendStructuredBuffer of triangle structs which just have the three vertices of a triangle and reading from the AppendStructuredBuffer to the CPU. When read to the CPU, I then read from the buffer and set it in a RWStructuredBuffer in the GPU. Following that, I run a compute shader kernel to parse the triangle buffer. Obviously if I can do this all on the GPU I should since reading and writing between the CPU and GPU is expensive. When trying to put it all in one kernel I run into problems however. Each voxel has a range of possible triangles (0 5) that can form in it. Because of that, I can't simply use the dispatch ID to put it in a RWStructuredBuffer (at least I don't think so). That's why using an AppendStructuredBuffer seems natural it allows for the variable amount of triangles. After getting the array of triangle vertices and array of triangle vertex indices, I bring them back to the CPU and set them to a mesh and render it. In the future I want to use a geometry shader to render the mesh since that is most likely more efficient, but I'm trying to take this one step at a time, and geometry shaders are a whole 'nother beast I know nothing about.


Unity or Monogame or Gamemaker 2 for an experienced application developer? So i know this question has been hammered down several times but please bear with me. I used to be a C .Net application developer but i am no longer employed, i am pretty good at C . I want to get into serious game development and i dunno where to start, i used to work with unity occasionally which is a very little and i kinda find it clunky, like it works but somehow it does not feel right and feels kinda clunky. But it works with tiled map editor without much of a hassle. I Remember using Game maker studio when i was back in college and i found it very good, its a breeze to work with and even have its own tiled map editor, even seems to have some good tutorials, the only con is its price. I was initially inclined towards Monogame cause of my C background, but i neither have time nor money and resources to support me for long enough time to be able to code every single thing from scratch and i am kinda in a pretty bad situation overall right now. It just takes too much time to do anything even to make it work with a tiled map editor, and there are very few tutorials or documentation to start with. It seems like the only option for me is Unity at the moment, cause of ease of access and how easy it is to work with tiled map editor and lots of tutorials. which one do you guys think is good overall? Please keep in mind that i am currently unemployed and have very little resources to support myself, and i am a programmer so i don't even know how to compose music and do art for the game and i'd prefer if it provides some asserts to be used so i wont waste time in learning stuff when i cannot afford to spend time. I will eventually learn them but not now, its not happening now so i prefer something that comes with some sorta free asserts that can be used (mainly music and art), I mean does it even matter if all i am trying to do is earn a decent minimum living? I just want to make simple 2D NES Snes style games with multiplayer support. Thank you.


Why the state of the duration is all the time 7 even if updating the state inside the while in the ienumerator? I want to get the current coroutine state. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef private DepthOfFieldModel.Settings depthOfField private DepthField state void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length DepthOfFieldInit(clipLength) state new DepthField() public void DepthOfFieldInit(float duration) depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, duration)) postProcessingProfile.depthOfField.settings depthOfField public IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof state.duration duration state.focalLength val yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null public struct DepthField public float focalLength public float duration public void Save() SaveGame.Save("depthoffieldstate", state) public void Load() Time.timeScale 1f depthOfField postProcessingProfile.depthOfField.settings DepthField state SaveGame.Load lt DepthField gt ("depthoffieldstate") depthOfField.focalLength state.focalLength StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, state.duration)) postProcessingProfile.depthOfField.settings depthOfField Inside the while loop I'm doing state.duration duration state.focalLength val The focalLength value does change if for example I save onethe game start the focalLength value will be 299 and if I will save after the coroutine has finished the focalLength value is 1. But the coroutine duration value is not changing it keep staying on 7 when saving even if the coroutine has finished and should be 0 it still 7. The value 7 of the duration is coming from the clipLength. I can't get the current duration time of the coroutine. In the Load function I'm starting the coroutine over again but since I'm using the loaded focalLength value and duration value it should look like the coroutine is continue from the last saved point. But I can't get the correct duration value when saving.


UGUI scripts stop my project from building Unity 2019.2.21 I am trying to build out my project to Android and I am getting the following error messages H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Toggle.cs(121,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core DefaultControls.cs(152,13) error CS0103 The name 'Undo' does not exist in the current context H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core GraphicRebuildTracker.cs(24,32) error CS0117 'CanvasRenderer' does not contain a definition for 'onRequestRebuild' H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime EventSystem InputModules StandaloneInputModule.cs(159,25) error CS0234 The type or namespace name 'EditorApplication' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Slider.cs(380,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Scrollbar.cs(168,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Selectable.cs(771,48) error CS0234 The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core InputField.cs(2458,43) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) I tried updating Unity(from 2019.2.12 to current). Deleting some csproj files, and different settings in the Project settings Player. The problematic code is in an if UNITY EDITOR statement, and not meant to execute at all on builds, I guess. if UNITY EDITOR protected override void OnValidate() base.OnValidate() if (!UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) amp amp !Application.isPlaying) CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this) endif if UNITY EDITOR


What is the optimal way to store customisation options? I am trying to understand the most optimal way of storing customisation options within a game, or to be precise, to store all the possible customisation options for multiple different objects. For example, assuming we are making a game about tanks and their customisation, there will be several available tanks that the player can choose from and each of the tanks will have multiple different parts available some parts will be shared across a few tanks, while some will be specific to a tank. I was thinking about a relational database, but I do not know web development, so I was initially thinking to have a table with all the tanks and a table with all the parts, then create a linking table between the two and load the available parts based on the chosen tank but I'm not sure if that would work, or if it would be the most optimal way of doing this. I tried looking for an answer, but I'm not getting any good results. People mention using files, and then parsing the data, but I'm not sure how that will work on a large scale multiple tanks with hundreds of customisation options. What is the most optimal way to to do this? If at all relevant, I am using Unity 5.


Press multiple switches to unlock the door I made 2 scripts, one that is a switcher and one that checks if object is switched (Switch, SwitchCheck). Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked) public var IsPressed boolean false function OnTriggerStay () if (Input.GetKeyDown(KeyCode.JoystickButton1)) IsPressed true Debug.Log("Switch activated") SwitchCheck script (it's on door that should be opened) public var Switch1 Switch public var Switch2 Switch function Update() if (Switch1.IsPressed amp amp Switch2.IsPressed) Destroy (gameObject) Now, he problem here is, that it "does" kind of work...after I press the button like 20 times. My question is, did I write something wrong?


How to set rotations to 0,0,0 in 3ds max for exporting in unity? I'm a modeler in 3ds max and the unity programmer ask me that the object must have pivot with Y up rotations at 0,0,0 but every object that I export in fbx he says don't have rotations at 0,0,0. I tryed different solutions as reset xform freeze rotation rotation to zero .rotation eulerangles 0 0 0 but in unity he have values like this 4.577637e 05, 1.525879e 05, 0 or 90, 1.525879e 05, 0 and so on It's a problem that can I fix in max or the programmer has to fix it in unity? Thanks


Unity trigger method does nothing I have the following script on my object public class PlayMyCube MonoBehaviour SerializeField private Animator myAnimationController private void onTriggerEnter(Collider other) if (other.CompareTag("Player")) myAnimationController.SetBool("playSpin2", true) private void OnTriggerExit(Collider other) if (other.CompareTag("Player")) myAnimationController.SetBool("playSpin2", false) When the player character is inside the first cube's trigger, my second cube should play a spinning animation. When they leave, the second cube should stop. But what happens in the game now is, when the character runs into the trigger, it does nothing. I have configured my trigger object like this I have configured the object that should spin like this And configured the Animation Controller like this And configured my Player object like this What can I do to make this animation play when the player is inside the trigger?


How to set player rotation to direction the player is moving? I'm having an issue with my click to move mechanic. I want the player to move to a specific position in the game when the mouse is clicked (and it does just that) but the issue I'm having is that the player doesn't face the direction in which it is travelling. Lets say I click a position diagonally right to where the player is. Immediately after clicking that point, the character will face that direction and run to it, instead of facing the direction it has to take to get there... if that makes sense. Here's my code snippet public void moveToTargetPosition() Seeker seeker GetComponent lt Seeker gt () seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete) transform.rotation Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(targetPlayerPosition transform.position), Time.fixedDeltaTime lookSpeed) Obviously I'm missing some modifier in here. Any ideas? Thanks!


Unity Facebook "An access token is required to request this resource." I have installed Facebook SDK 7.6 for Unity 5.3. It is fine with login and logout stuff things but I am having a problem when it comes to use FB.API. I want to be able to fetch players' profile pictures and names for my multiplayer game project. Each client has other's facebook profile id but I cannot use those IDs on Graph API I guess. What is the way of getting such public information using Facebook SDK. FB.API(" " facebookID "?fields name", HttpMethod.GET, OnNameReceived)


When is transform width in code not equal to the transform width in inspector? I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way! Gizmos.color Color.red Vector2 pos new Vector2(transform.position.x, transform.position.y) Gizmos.DrawLine(pos transform.sizeDelta, pos transform.sizeDelta) Vector3 corners new Vector3 4 transform.GetWorldCorners(corners) Gizmos.color Color.magenta Gizmos.DrawLine(corners 3 , corners 0 ) Gizmos.DrawLine(corners 0 , corners 1 ) Gizmos.DrawLine(corners 1 , corners 2 ) Gizmos.DrawLine(corners 2 , corners 3 ) The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 30.2 120 2 60)! Why? Is this a bug or an I missing something obvious here?


2D Rivers Lakes in infinite terrain I've been looking into generating lakes and rivers for a 2D infinite tilemap but I'm stuck with how to handle them for an infinite map. I can use noise heightmaps for determining the lakes and the starting points for rivers but for an infinite map I can't use the "flow downhill" or "carve out" technique because the player could come across the river at any point. If I have a river that's a max of 200 tiles long, I'd have to calculate noise map values for 33x33 chunks (my chunks are 6x6 tiles) around the player which feels excessive and very inefficient. I have not found a way to make noise alone work for this, rivers would always be too circular if I find a range narrow enough and they'd encircle lakes, not extend outward. Calculating voronoi cells and putting rivers at certain edges, with some extra noise to make the paths more natural, might work. I just can't seem to find any good examples where they aren't working with known dimension maps.


Unity3d deploy game to android device off site I am using Unity3d to develop my game and my friend with android device wanted to test it. I am natively IOS developer and have no knowledge of deploying Android platform. What do I need other than Unity3d? The scenario here is that I have to send to my friend who is not developer to install and test on his device via internet. We used to have TestFlight App but that is history now.


Restrict render in Blender is not working I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity. How can I fix this?


Understanding Send Message I'm trying to understand the Send Message Function but I'm a bit confused. Currently I have a game object character and I want it to send a message to the main body if one of its children hits something. On the Child object, I have void OnTriggerEnter2D(Collider2D col) Destroy(col.gameObject) Debug.Log(this.name " Hit!") gameObject.SendMessage("PlayerHitting", this.name) On the Parent Object, I have public void PlayerHitting(string Move) Debug.Log("Player hits with " Move) The Destroy code and Debug.Log on the Child work, so it is colliding, but I keep getting an error that there is no reciever. SendMessage PlayerHitting has no receiver! UnityEngine.GameObject SendMessage(String, Object, SendMessageOptions) I don't quite understand how to use Send Message to send messages and notices between objects. Can someone explain?


Start Broadcast Unity Network Discovery I am using the unity NetworkDiscovery component, and I am wondering how I can auto start broadcasting when the server starts, instead of the client having to click on the gui Initialize Broadcast Start Broadcasting. I would like to be able to put some C in my start host function so that the user does not have to do anything.


Difference between DEBUG and DEVELOPMENT BUILD in Unity? I've seen these two special compilation macros in our code base, What's the difference between Debug and DEVELOPEMENT BUILD in Unity? What's the main purpose of using each? if DEBUG Debug.Log("DEBUG") endif if DEVELOPMENT BUILD Debug.Log("DEVELOPMENT BUILD") endif


2 Color Fonts in Unity? (so maybe called 3 Color including transparent alpha?) I have been trying to make my game title screen look better. I realised it was because all my fonts have just one colour. I read some very old threads about a Editor Scripts to extract the font to png format. I then see there is now a way to do it in the 'hamburger' menu of the Font in Inspector. I had to change my font to be not 'Dynamic' then it allowed me to extract a copy to PNG. I opened this in GIMP and added my white inside the outlines of each character (it had been alpha before this, giving a horrible see thru effect on the letters). I put this back into Unity (the new PNG) and used it as the source texture for my Text Shader. However it is still not handling both colours. (Screenshot below). So what can I do using Unity 2020 to achieve better looking text? I've read this (https docs.unity3d.com Packages com.unity.ugui 1.0 manual StyledText.html) and many other pages on Unity site but I am now going around in circles not achieving anything. Thanks for any help. EDIT Since DMGregorys comment. I am posting picture of my import settings on the modified (coloured in) font PNG file EDIT 2 The 3rd screenshot shows the 'Text' objects settings. Note I have changed Material to be my extracted one. 4th screenshot shows that Material's settings enter image description here


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


Animator from another gameobject keeps disappearing from script on play I am working on a gun script and it worked fine until earlier today when I made a change to the script and it stopped working. I put it back, but for some reason now the animator object attached to the script keeps disappearing. using System.Collections using System.Collections.Generic using UnityEngine public class RifleShooting MonoBehaviour private float NextTimeToFire 0f private int CurrentAmmo private bool IsReloading false Space(10) Header("Floats") public float Damage 10.0f public float Range 100.0f public float ImpactForce 60f public float FireRate 15f public float ReloadTime 1.0f Space(10) Header("Others") Space(5) Space(10) Header("Others") Space(5) public int MaxAmmo 10 public Camera FPSCamera public Animator GunAnimations public ParticleSystem MuzzleFlash public GameObject impactEffect public bool AllowedToShoot true Start is called before the first frame update void Start() GunAnimations GetComponent lt Animator gt () if (CurrentAmmo 1) CurrentAmmo MaxAmmo private void OnEnable() IsReloading false GunAnimations.SetBool("Reloading", false) Update is called once per frame void Update() if (IsReloading) return if (CurrentAmmo lt 0) StartCoroutine(Reload()) return if (AllowedToShoot false) return if (Input.GetButton("Fire1") Input.GetButtonDown("Fire1") amp amp Time.time gt NextTimeToFire) NextTimeToFire Time.time 1f FireRate Shoot() IEnumerator Reload() IsReloading true Debug.Log("Reloading...") GunAnimations.SetBool("Reloading", true) GunAnimations.SetBool("IsShooting", false) yield return new WaitForSeconds(ReloadTime .25f) GunAnimations.SetBool("Reloading", false) yield return new WaitForSeconds(.25f) GunAnimations.SetBool("IsShooting", true) CurrentAmmo MaxAmmo IsReloading false void Shoot() shooting script here Also if it helps here is what I see in the console when I try to fire MissingComponentException There is no 'Animator' attached to the "M4A1" game object, but a script is trying to access it.


Add Boo or Python to Unity 5 I'm new to Unity, but I'm more comfortable with Python. Is there any way to use Python as scripting language in Unity 5? I heard there is some language called Boo that has a syntax like Python but it seems Unity just supports C and Javascript. How can I add Boo or Python scripting to Unity 5?


How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity? How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity? I have a component with some scripts on it Script1 and Script2. Inside the Script2.OnDestroy method I have the following line of code GetComponentInParent lt Script1 gt (). I want that line of code to return Script1 whenever I click the Play button inside Unity editor to stop my game. While right now it returns null.


Game shifts to edge of screen when clicking Play button in Unity I m attempting to help my young daughter who is trying to learn Unity. I know very little about the program. Recently, she developed a basic game consisting of a dragon and a person. When she presses the play button, the game shifts to the edge of the screen and does not start. I have attempted to research the issue but with my limited knowledge on the subject I could not find anything. Any help or suggestions would be appreciated! 09 22 After reading the comment and following the recommendations I do believe it s a camera issue. I ve attempted to move the camera around using the X, Y and Z axis is but I can t get it to actually change the view. See the attached screenshot. 10 02 2020 My daughter went back and redid the game from the start. The issue is that the game will not allow her to enter play mode until she places the dragon. However, as soon as she places the dragon and presses play the game moves the camera. So the issue apparently occurs prior to or at the time she places the dragon but because she can't enter play mode prior to this point I'm not sure where the issue occurs.


Dynamically applied texture to GameObject using GUI button In a scene I have multiple different GameObjects (almost 30 kinds) with parent child relationships. At run time (by using a GUI button) I want to change the texture of each clicked GameObject. As the user clicks specific GameObjects, a GUI with a multiple texture button will appear. By clicking on the button, that specific texture will be applied. Is there a smarter way to do this? Do I need to apply a script to every object? I have tried to apply a script with some specific code it's working but not regularly and correctly. Additionally, I want different texture options for each kind of GameObject.


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


How are methods like Awake, Start, and Update called in Unity? I'm developing with Unity 5 and I know that there are some methods you can use like in the code below public class MyGameElement MonoBehaviour private void Awake() private void Start() private void Update() private void FixedUpdate() and more I know what they do but I find it strange that the methods can be private. However they are not called into my code I've written. Here you've an image with code lens (I use VS 2015 Professional for coding) where you can really see that it has zero references. The second 'strange' thing for me is that the methods aren't overwritten. So my question is now is there anything that Unity has implemented into the MonoBehaviour class that the methods can call?


Can I pause Unity Setup download and continue it whenever possible as per convenience(using Unity Hub)? Actually I get only 1.5GB data daily. So it's not possible for me to download the whole Unity setup in a day. So I wanted to know if I can pause and resume download process as per convenience. I am downloading using Unity Hub.


Particle Effects Start Glitching out My particle effects have gone crazy look In my game, bombs drop on castle and then explode For the first few second of my game the particle effects for the explosion works. The particle effects are made using the unity particle systems As you can see below, the particle effects in the scene view are also in the game view However after a few second the particle effects start to glitch out and while they appear in the scene view, they do not appear in the game view Above there is a massive explosion in the scene view but nothing in the game view. I can make the particle effects work by doing a few weird things If I remove the walls on my castle the particles will suddenly work. The walls just contain a sprite renderer component, no script or anything. If I make a looping particle effect when the effect is visible on the game screen the particle effects start working but when I drag it off the screen even though its still working(I see it in the scene view) because its not in the game screen my explosion particle effects instantly stop working. I am super confused about why this is happening.


Player jittering against wall when held down button So, I'm making a top down RPG. Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening? Thanks! PS I'm using transform.translate to move the player, and I'm using C . EDIT I'm also using a 2D Rigidbody, and 2Dbox colliders on both.


Issue with interpolation on a burn shader (lerp and smoothstep) I'm trying to create a simple burn shader. See here for more info on the method I'm using. However, I don't get why replacing the smoothstep with a lerp results in completely different results. Am I missing something from my knowledge of maths? As far as I know they should return similar values given the same parameters. clips materials, using an image as guidance. use clouds or random noise as the slice guide for best results. Shader "Custom Dissolving" Properties MainTex ("Texture (RGB)", 2D) "white" BorderTex ("Border Texture (RGBA)", 2D) "white" EdgeColor ("Edge Color", Color) (1,0,0) EdgeSize ("Edge Size", float) 0.1 SliceGuide ("Slice Guide (RGB)", 2D) "white" SliceAmount ("Slice Amount", Range(0.0, 1)) 0.2 MaterialToggle UseClipInstruction ("Use Clip Instruction", Float) 0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" Cull Off Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM if you're not planning on using shadows, remove "addshadow" for better performance pragma surface surf Lambert alpha addshadow struct Input float2 uv MainTex TEXCOORD0 float2 uv SliceGuide TEXCOORD1 float SliceAmount sampler2D MainTex sampler2D BorderTex sampler2D SliceGuide half SliceAmount half EdgeSize half3 EdgeColor void surf (Input IN, inout SurfaceOutput o) o.Alpha 1 Green is a good color for estimating grayscale values half fragSliceValue tex2D( SliceGuide, IN.uv SliceGuide).g ifdef UseClipInstruction clip(fragSliceValue SliceAmount) else TODO look for an alternative to this if (fragSliceValue SliceAmount lt 0) o.Alpha 0 endif half rampX smoothstep( SliceAmount, SliceAmount EdgeSize, fragSliceValue) half3 ramp tex2D( BorderTex,half2( rampX,0) ) EdgeColor.rgb o.Emission ramp (1 rampX) o.Albedo tex2D( MainTex,IN.uv MainTex) ENDCG Fallback "Diffuse" Left is the result of smoothstep (the provided code), right is what happens when I replace smooth with lerp.


Move around the object using head tracking movement in Unity I am developing an app for Samsung Gear VR with unity.I have added a cube and made the cube move forward on the terrain. Now I need to move around the cube using head tracking movement.I have referred the below link(Flyer VR movement) .But I am not able to understand the code used in it. https unity3d.com learn tutorials topics virtual reality movement vr Can anybody help me doing this in a simple way to move around the cube by head tracking


World coordinates on vertical grid game for different aspect ratios (Unity) new to game development and unity so hopefully someone can help. I want to make a 2D portrait mobile game that will have a grid of constant size where units can move on in Unity. This should support different aspect ratios. To do that I was thinking to cut sections at the top and bottom of the screen for smaller aspect ratios. Additionally, I would like the coordinate system to be natural to the grid, so coordinate (0,0) would be the bottom left tile in the grid, (1,0) would be the tile to the right of that,... To illustrate this concept I drew something quickly I tried with a script that resizes the size of the orthographic camera to fit the content horizontally. Problem I had with that is that I couldn't get a good coordinate system on the grid after the camera gets resized depending on the aspect ratio since the number of horizontal world units varies depending on the aspect ratio. Any thoughts on what would be the best way to do this? Thanks!


Detecting collisions with a wall before Update I'm making a script in unity to control (movement) a character in 3rd person and 3D space. For that I'm using the CharacterController component. All pretty standard inside the update method a Vector3 which will be passed to CharacterController.move is crafted based on the input and collisions, movement and jumping are perfectly fine but I ran into an issue when trying to make a wall jump. There are 3 steps involved in this Get the wall to jump of. Check if the player pres the jump button. Move the player in the desired direction. An this is how I'm doing it void OnControllerColliderHit(ControllerColliderHit hit) if(mController.collisionFlags CollisionFlags.Sides) Get wall normal wallNormal hit.normal isOnAWall true Now inside Update if(Input.GetButtonDown("Jump") amp isOnAWall) jump... And this work fine in most cases but only if player is giving input or last wall has a similar normal as current so obviously the normal isn't refreshing properly, but why? Well, after some testing, I discovered that the OnControllerColliderHitis called after the Update method, and this is what I think is happening Physics engine detect the collision and stops the player Update method not having any input just send it downwards The OnControllerColliderHit method is not triggered(this part I am sure) Are my conclusions correct? How can I fix this? (make the player jump without need to move the stick and just with the button)


How do I prevent inappropriate ads from appearing in my game? My game implements Unity ads, and is designed with a universal audience in mind. As such, I would prefer not to have 18 ads (or even 13 ads depending on the circumstances) appearing in it, especially since it would appeal to younger audiences as well. My question is then, how do I prevent age inappropriate ads from appearing? Is there a way to simply set the age limit or content restrictions on Unity ads? The only setting along those lines that I can find is the COPPA toggle, and that would cause other issues (not to mention that it wouldn't do anything to the ads). I've looked in the dashboard for a while, and I've tried to research it beforehand, but the fact that they've shifted to a centralized services page, redirected all the old links (breaking them in the process), reorganized the settings in the dashboard, and 404d their FAQ post on the topic doesn't help either. Blocking ads based on a rating would work too, as I would have to get one because I am publishing to Google Play. Edit The second link only 404s some of the time. I just happened to get it every time before asking this question. Bad luck, I guess.


How to save variables into a file unity I've wanted to save progress of my game (i don't have the code , sorry) without using PlayerPrefs. If it's possible with UnityEngine.


Unity Unable to blend 2D Light renderers I've followed the documentation on Unity regarding 2D lighting. It said to turn on Alpha blending in the options. But this is how it turns out If Alpha blending is off If Alpha blending is on I'm not entirely sure why it's turning black. These are my settings for the 2D light I've checked my layers, specifically the tile map floor, and it's on the Default layer. I just want my lights to blend well.


Prediction of collision place and time in Unity I have two moving objects. I have chosen trajectories for objects that they would definitely collide if they don't change speed or trajectory. Is there easy way to check at which point and time the objects will collide with given parameters (current object positions, their velocity vectors and speeds or any other parameter accessible from Unity)?


How to delay a timer when it's run the first time in update method not using a coroutine In the code below I am resetting a timer after a duration maxiTime within the update method. I want to delay the timer before it begins to run for a certain duration. I believe this could be done with a coroutine, but I am using StopAllCoroutines, so I need to do this within the update method. How can I get the delay only before the first run? timeElapsed 1 if(timeElapsed gt maxiTime) timeElapsed 0 Debug.Log ("Thank You!")


Unity C Changing Button Color? void OnMouseDown () foreach (Button thisButton in buttonArray) thisButton.GetComponent lt SpriteRenderer gt ().color Color.black GetComponent lt SpriteRenderer gt ().color Color.white This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...


Making a Point Light follow a cube (Unity) I'm trying to have a point light positioned directly above a cube follow wherever the cube goes. However, it doesn't move at all. This is my code for the light using UnityEngine using System.Collections public class SpotlightController MonoBehaviour Use this for initialization void Start() void OnGUI() GUI.Label(new Rect(20,50,500,20), "(" transform.position.x.ToString() ", " transform.position.y.ToString() ", " transform.position.z ")") Update is called once per frame void Update() GameObject cube GameObject.Find("Cube") float xlocation cube.transform.position.x float zlocation cube.transform.position.z transform.TransformPoint(new Vector3(xlocation,transform.position.y, zlocation) Time.smoothDeltaTime) transform.Translate(new Vector3(xlocation, 0, zlocation))


How to create button prompts for interactable objects in Unity? I have a class of objects tagged as interactables that my player can interact with when within range. When my player is near them, I want to display a button prompt at the bottom of the screen, along with a description of the type of interaction possible (for example, "inspect", "use", etc.). I want to account for the possibility that the player might be within range of two or more of them at once, and thus allow him to toggle through them, displaying their button prompts in turn. If my player interacts with something which generates a text box or other modal, I want the button prompt to disappear, but to return when the text box or modal is closed. Any advice on how to go about achieving this? I've done it in the past in different engines, but I have always been unhappy with how convoluted my method was. I'd like to hear how others might tackle this. Given how common this kind of thing is in games, I'm surprised I haven't found a good tutorial on it yet. You can be as general or as specific as you'd like in your answer.


Blocking Physics Raycasts with Unity's 4.6 UI? I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non rectangle shaped UI that's pretty difficult. I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size. Note Canvas Group does not apply to physics.raycast


Room generation with external walls and doors I am looking to implement a means to generate rooms with outer walls with windows and doors from prefab game objects in Unity. The idea is that a group of tiles is defined as a room which I then iterate through to find the outer tiles and then use their external edges to generate the walls of the entire room. Gathering the outer tiles is easy enough and working out the external edges is already implemented. What I need to understand is the best approach for using prefab game objects as the set pieces for walls and floors. Currently for a single wall piece, I have created a quad and made that into a prefab which I then clone, position and rotate into place along the outer edges. The below screenshot shows a room with walls made using the prefab wall GameObject. In this screenshot, the room consists of 12 wall GameObjects. I want to avoid having lots of GameObjects for single wall segments and instead perhaps merge them all into a single mesh on a single GameObject. What I would like to achieve is to be able to create a consistent set of pieces for each outer wall, with windows and doors (most likely cloned from other prefabs) to build a realistic looking room. For example, any single length of a wall would be made up from Wall gt Wall gt Window gt Wall gt Wall Perhaps there is a much easier way to achieve this that I have overlooked but searching for room generation always leads back to examples for dungeon crawlers and roguelikes. I am not creating a dungeon crawler, nor am I generating the environment proceedurally, instead the player will be able to create rooms in a similar fashion to Evil Genius and The Sims. In the current approach, creating a room which is 5x5 would mean that there are a total of 20 wall GameObjects and 25 floor GameObjects. I am not keen on having this many objects in the scene for a single room. I would prefer to be able to create a mesh for the entire room, adding in the vertices and triangles from the prefab mesh to cut down on the number of GameObjects in the scene. Does anyone have any experience with building rooms in this fashion, or are there any clear examples of how to achieve this? I am not sure how to translate and rotate a prefab and then merge the translated meshes into a single mesh. Perhaps I am barking up the wrong tree and there is a better approach but for now, this is the only way I can see which is possible to achieve what I want.


Player object glitching around when there is a low framerate Unity C I just started to make this game, it runs fine on my computer. 60fps, but when I tested it on another computer, with lower fps, the player just started to jitter and glitch around a lot. The game is basically unplayable like that, and I want to make sure that everyone who plays my game will be able to enjoy the full experience. I have pasted the specific part of the code for the movement below. void Update () rb.AddForce (Vector3.forward ForwardSpeed) if (Input.GetKeyDown (KeyCode.A) amp amp side gt maxSideLeft) rb.AddForce ( Vector3.right Speed) side 1 else if (Input.GetKeyDown (KeyCode.D) amp amp side lt maxSideRight) rb.AddForce (Vector3.right Speed) side 1 if (Input.GetKeyDown (KeyCode.W) amp amp level lt maxLevelHeight) rb.AddForce (Vector3.up Speed) level 1 else if (Input.GetKeyDown (KeyCode.S) amp amp level gt minLevelHeight) rb.AddForce ( Vector3.up Speed) level 1 if (Input.GetKeyDown (KeyCode.R) Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene ("Scene1") Time.timeScale 1


Doing object movement in a loop in unity I have a Game Object at position (0, 0, 0). To move it to position (2, 2, 2), I'm using this code below void Update () Vector3 TargetPosition new Vector3(2, 2, 2) transform.position Vector3.MoveTowards(transform.position,TargetPosition, 23 Time.deltaTime) How do I put this movement in a loop like behavior so that whenever the Game Object reaches position (2, 2, 2), it again starts moving from (0, 0, 0) to (2, 2, 2) ?


GameObject's scale gets 0 after being parented in editor 1) Before 2) After being parented. I found a pattern. When adding the child, if the parent's scale.z 0 the child scale.xyz becomes 0 on parenting. If the parent's scale.z ! 0 it works. Another experiment that I tried was, after successfully adding the child(without getting scaled down to 0) and then to make the parent's scale.z 0, the children's scales don't get affected at all. Why?


How to move player out of multiple penetrating colliders? The player in my game can teleport like Noctis from ffxv.The player shots a weapon projectile and then teleports to the projectile. I'm using raycast to calculate the weapon position after thrown. However, I need to check if the weapon is stuck in an unteleportable position after being thrown. It is possible to have multiple penetrating colliders. Ex spear gets sandwiched between two walls that is narrow enough for the weapon to pass through but not tall enough for the player to stand. I want to somehow check for a nearby valid position for after teleporting in that situation. I also want the teleport to fail if the weapon is horizontally in the middle of the "pipe". I could do a bunch of overlapBox checks within a radius distance from the teleport point but that doesn't seem efficient. I want to give the player some leeway when aiming a teleport. Also, the teleport is not immediate. The player can wait some time before teleporting to the weapon. So it is possible for a moving platform to block a raycast from the player. In which case I still want the raycast to succeed. I'm using unity and a custom raycast based 2d character controller for normal movement.


Is there any way to move the sprites inside the sprite editor? I have imported a .png file of a stickman in which I had placed his head, body, two legs, and two hands a bit far apart from each other so that Unity will automatically convert the picture into sprites. Indeed, Unity did convert those body parts into sprites easily but now I have a problem. I made a bone going through the body and another bone going from the body to the head through the transparent area in between the sprites. Also, I have created one bone for each hand and leg and parented them to the bone in the body. The problem is that when I automatically generate geometry then the mesh rendering works completely fine within the body of the stickman, but it doesn't work anywhere else, be it the hands, or the head, or the legs. I can see the mesh only in the body of the stickman and nowhere else. Does this problem arise because the sprites are not connected, or is there any other reason? I am very new to game development, therefore please try to explain it in simple words. Thank You.


How do you create fnt (angelcode format) files from existing bitmaps? I often gets the same problem Someones creates a nice bitmap font for me in form of a sheet nicely formated into a png, like this ...and i need to create the angelcode .fnt atlas for using it (into Unity, libGDX, or countless other engines). Yet, every time I google it, I stumble upon dozen of tools that create .fnt files from rasterized TTF fonts. (BMFont, Fontbuilder, etc.) Correct me if i'm wrong but they don't support exsting images, they always start by generating one from a vector font. I end up semi manually creating the file with an ugly script (the format is quite simple), but it's incredibly tedious. Surely there is a much better way to do that? Especially for monospaced fonts which are very easy to partition... edit I've made a small javascript tool to solve that. if by any chance you're interested, it's here http fontcutter.fbksoft.com


Behaviour Trees How to clean up when a sequence is interrupted? I'll try to show my problem on a minimal example, in reality it's more complex It's a simple behaviour, that repeats quot an action quot that has a certain animation. If a player gets close, this sequence gets interrupted and the AI executes the quot Flee quot action. The interruption happens because the top level selector is quot dynamic quot which in Unity NodeCanvas means, that its higher priority nodes get executed every frame and if they succeed they interrupt the lower priority ones. My problem is shown via the red arrow if the quot action quot gets interrupted, the clean up (in this case quot stop animation quot ) doesn't execute. What is the best practice to handle the clean up? Is my setup flawed? Or should I just be using a different interrupting mechanism? Thanks for any help!


Unity5 mixing animations with different properties Maybe there are tons of questions about this but i dont know what to look for. I have 2 animations, one is aiming a weapon and the other one is shooting. When i aim the weapon i animate only its position upward and a little bit to the left so its in front of the camera. When i shoot, i just rotate it a bit on the x axis. My problem is, when i shoot while the weapon is aimed (animated upwards and left) the whole Weaponholder get back to its initial (not aimed) position. I thought when i just animate the position in one clip and only rotation in another i can mix them together. Am i on the wrong way or just did something wrong? Thank you


Instantiate prefabs at particular vectors using text file (Unity3D game) I need to read a text file containing two pieces of information on each line, and use that information to instantiate a prefab at the correct location in a Unity3D game (c script). The locations are either North, South, East, or West (each a particular vector). For example, the first line of the text file might read landmark1, North In a script, I need to instantiate landmark1 and assign it to case North vector. The below script is what I've got so far. Basically, I can read from the text file but I don't know how to assign that information to different cases. I'm guessing I need to use an array somehow but I'm not sure how to do that here. Any help would be appreciated. Thanks! using System.Collections using System.Collections.Generic using System.Text.RegularExpressions using UnityEngine using System.Linq using System.IO using System public class Landmarks MonoBehaviour spawnable prefab gameobjects public GameObject castle Use this for initialization void Start() StreamReader reader new StreamReader( "C Users ... landmarks.txt") insert full path here String textContents reader.ReadToEnd() string dataArray for (int i 0 i lt (textContents.Length) i ) set case if first line "castle, North" then instantiate object castle at vector 'north'


Unity Third Person Controller Camera Relative Script I'm an newbie in game developing. So i have a script for a camera that i attach to the player. I was wondering how to make a Third Person Controller with WASD controls that moves in the direction that the camera is facing. If you need it here's the camera script that i use using System.Collections using System.Collections.Generic using UnityEngine public class ThirdPersonCamera MonoBehaviour define some constants private const float LOW LIMIT 0.0f private const float HIGH LIMIT 85.0f these will be available in the editor public GameObject theCamera public float followDistance 5.0f public float mouseSensitivityX 4.0f public float mouseSensitivityY 2.0f public float heightOffset 0.5f private variables are hidden in editor private bool isPaused false Use this for initialization void Start () place the camera and set the forward vector to match player theCamera.transform.forward gameObject.transform.forward hide the cursor and lock the cursor to center Cursor.visible false Cursor.lockState CursorLockMode.Locked Update is called once per frame void Update () if escape key (default) is pressed, pause the game (feel free to change this) if (Input.GetButton("Cancel")) flip the isPaused state, hide unhide the cursor, flip the lock state isPaused !isPaused Cursor.visible !Cursor.visible Cursor.lockState Cursor.lockState CursorLockMode.Locked ? CursorLockMode.None CursorLockMode.Locked System.Threading.Thread.Sleep(200) if(!isPaused) if we are not paused, get the mouse movement and adjust the camera position and rotation to reflect this movement around player Vector2 cameraMovement new Vector2(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y")) first we place the camera at the position of the player height offset theCamera.transform.position gameObject.transform.position new Vector3(0,heightOffset,0) next we adjust the rotation based on the captured mouse movement we clamp the pitch (X angle) of the camera to avoid flipping we also adjust the values to account for mouse sensitivity settings theCamera.transform.eulerAngles new Vector3( Mathf.Clamp(theCamera.transform.eulerAngles.x cameraMovement.y mouseSensitivityY, LOW LIMIT, HIGH LIMIT), theCamera.transform.eulerAngles.y cameraMovement.x mouseSensitivityX, 0) then we move out to the desired follow distance theCamera.transform.position theCamera.transform.forward followDistance


Minecraft Type Game Support Blocks OK I have a game that is similar to minecraft in a sense. Players can build castles block by block. I'm using Unity3D and Photon Network for my game and I was wondering how I would handle detecting if blocks have a support system to the ground. Here is the game in question. Let me know what are some solutions besides using rigid bodies I've tried doing that and it has severe performance issues over a network. Thanks Youtube Video of Game


In Unity, why do my animator states wait until the end of each animation to change? I'm trying to make a simple idle walk transition in Animator using Unity. I've set a script that changes the Speed value from the Animator, and it works perfectly when I move the character forward when the game is on. The transitions work well between both animations, except that they don't start automatically after the speed has changed to greater than zero. I've found out that it waits until the animation loop gets to it's end, which makes the game feel dull and not fluid at all. I don't think there's an issue with the code, but I'm attaching it anyway pragma strict var anim Animator function Start () anim GetComponent("Animator") function Update () var move float Input.GetAxis ("Vertical") anim.SetFloat("Speed",move) transform.Rotate(0,Input.GetAxis("Horizontal"),0) transform.Translate(0,0,(Input.GetAxis("Vertical") Time.deltaTime move))


How to detect mouse over for UI image in Unity 5? I have an image that I have setup to move around and zoom in and out from. The trouble is the zoom can be done from anywhere in the scene, but I only want it to zoom when the mouse is hovering over the image. I have tried to use OnMouseEnter, OnMouseOver, event triggers, all three of those without a collider, with a collider, with a trigger collider, and all of that on the image itself and on an empty game object. However none of those have worked...So I am absolutely stumped...Could someone help me out here! Here is my script private float zoom public float zoomSpeed public Image map public float zoomMin public float zoomMax void Update () zoom (Input.GetAxis("Mouse ScrollWheel") Time.deltaTime zoomSpeed) map.transform.localScale new Vector3(map.transform.localScale.x zoom, map.transform.localScale.y zoom, 0) Vector3 scale map.transform.localScale scale new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0) map.transform.localScale scale


Post processing effects not visible on mobile apk build While setting up post processing on a project that I am currently working on, I discovered that post processing effects are not visible on the apk build on mobile. I setup a new Project with URP on Unity 2019.3.0f5 and increased the post processing bloom effect intensity, it works just fine on the editor play mode, however, it is not visible when I build to a mobile apk. Is there a different way of setting up post processing specifically for mobile? Here are screenshots 1 https i.stack.imgur.com uKm5d.jpg Mobile build screenshot(post processing effects are not visible) 2 https i.stack.imgur.com ivQrQ.jpg Unity editor play mode screenshot(post processing effects are visible)


2D character with baseball bat implementation in Unity I'm making a 2D baseball game in Unity and I'd like to know how the player and the bat should be connected. For instance, if I use single sprite for both the player and the bat, then how should the collision between the bat and the ball be detected?


Why use Time.deltaTime in Lerping functions? To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t 0, the value a is returned, at t 1, the value b is returned. At 0.5 the value halfway between a and b is returned. (The following picture is a smoothstep, usually a cubic interpolation) I have been browsing the forums and on this answer I found the following line of code transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime) I thought to myself, "what a fool, he has no idea" but since it had 40 upvotes I gave it a try and sure enough, it worked! float t Time.deltaTime transform.rotation Quaternion.Slerp(transform.rotation, toRotation, t) Debug.Log(t) I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?


Manually creating an instance of object derived from MonoBehaviour I'm currently "newing" an instance of a class I have that derives from MonoBehaviour and store it in a list. The value of this instance is "null" however, even though it has all the fields of my derived class in it so it passes as null in null checks. After more reading it seems it's a bad idea to manually new up an instance of an object that derives from MonoBehaviour. The class is an Actor class. I have a situation where enemy actors are 3D models in my scene and so I want them to derive from MonoBehaviour, but the player actors don't have world representations really. I just have a picture of them in the corner. Similar to Legend of Grimrock. I wanted the 1 Actor class since the data they need is all the same and I wanted to avoid having 2 classes for no seemingly reason other than not newing up a MonoBehaviour derived class. What are my options with this requirement when my player actors don't need MonoBehaviour but my enemy actors do but they all need to have the same properties?


unity JsonUtility.ToJson returns empty string I am trying to use Unity's built in json serialization. It produces empty string. I do not understand why. (I was trying to use NewtonSoft Json.Net but that wasn't working either even though I was following instructions). Here's the serialization code public class Player MonoBehaviour void Start () Mission a new Mission() Id 1, Name "Speak to the Farmer", State MissionState.OnGoing, Parent 1, Type MissionType.Main string json JsonUtility.ToJson(a) System.IO.File.WriteAllText("missions2.json", json) Here's the Mission class Serializable public enum MissionState NotStarted, OnGoing, Finished Serializable public enum MissionType Main, Sideline Serializable public class Mission public Mission() Parent 1 public int Parent get set public int Id get set public string Name get set public string Description get set public MissionState State get set public MissionType Type get set here's the output There are no exceptions thrown. The file missions2.json is created. But the data is as shown above. What is wrong that the serialization produces nothing? Thnx Matt


2D character controller in unity (trying to get old school platformers back) This days I'm trying to create a 2D character controller with unity (using phisics). I'm fairly new to physic engines and it is really hard to get the control feel I'm looking for. I would be really happy if anyone could suggest solution for a problem I'm finding This is my FixedUpdate right now public void FixedUpdate() Vector3 v new Vector3(0, 10000 Time.fixedDeltaTime,0) body.AddForce(v) v.y 0 if(state(MovementState.Left)) v.x walkSpeed Time.fixedDeltaTime v.x if(Mathf.Abs(v.x) gt maxWalkSpeed) v.x maxWalkSpeed else if(state(MovementState.Right)) v.x walkSpeed Time.fixedDeltaTime v.x if(Mathf.Abs(v.x) gt maxWalkSpeed) v.x maxWalkSpeed body.velocity v Debug.Log("Velocity " body.velocity) I'm trying here to just move the rigid body applying a gravity and a linear force for left and right. I have setup a physic material that makes no bouncing and 0 friction when moving and 1 friction with stand still. The main problem is that I have colliders with slopes and the velocity changes from going up (slower) , going down the slope (faster) and walk on a straight collider (normal). How could this be fixed? As you see I'm applying allways same velocity for x axis. For the player I have it setup with a sphere at feet position that is the rigidbody I'm applying forces to. Any other tip that could make my life easier with this are welcomed ). P.D. While coming home I have noticed I could solve this applying a constant force parallel to the surface the player is walking, but don't know if it is best method.


Process for Creating Imposters (For Unity) I'm still working on making a sports stadium with crowd etc. I've been reading a lot about 'Imposters' and 'Billboarding'. I want to explore and learn the imposters technique. But I am stuck at step 1 I have a stadium model made which is empty (no seats or people). All I want at the moment is seats. I have the model made in Maya for a seat. Do I need to make (and import to Unity) both a low poly and high poly version of the model. How exactly is an 'imposter' asset stored in data (specifically if used in Unity)? Do I need to make 2d images textures of many angles of the seat? I do have more questions, but these may be enough to get me started. Thanks as always for any help.


Season system Implementation system in unity So I am planning on implementing a seasons system for a 2D top down game. Each season will have a characteristic terrain feature e.g. summers will have patches of grass spread out .. which I wanna reproduce by green bloat spread around on a 2D plane or quad... These features will need to generate dynamically for every season. The implementation will be simplistic nonetheless... using green bloats for grass patches, blue bloats for waterholes.. Can you guys give me like pointers to solve this problem? Some Reference images Notice how the backdrop background changes for each season Green Patches denotes grass Light blue denotes unfrozen water, dark blue denotes frozen water These bloats are to be generated dynamically, with some conditions like frozen water and unfrozen water need to spawn next to each other Summer Season Monsoon Season Winter Season


How to get the tangent and normal of a collision? In my game, one of my objects casts a ray into a 2d space. If that ray were to hit another object, I'd like to draw a line that is perpendicular to the tangent of the ray's hit point. So when the ray hits the other object, a tangent is formed at the point of contact, and then I'd like to use the linerenderer component to draw a line that is perpendicular to that tangent. I already know how to use the linerenderer to draw lines, but I don't know how to get the tangent and normal from a collision. if (Input.GetMouseButton(0)) Vector2 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.Raycast(cueBall.position, direction, Mathf.Infinity, 1 lt lt LayerMask.NameToLayer("Ball")) if (hit) line1.SetPositions(cueBall.position, hit.point) This is the line from the cueball to the red ball. line2.SetPositions(hit.point, hit.normal) This is supposed to be the predicted trajectory of the red ball.


How to create rounded TV edges effect in Unity? Is there a way to get rounded TV edges like these I want rounded egdes and the distortion effect, but I can't find a way to do this. I am using Unity 2017.


Is Time.deltaTime different on various devices? Can someone say what is wrong with my code. I have custom timer implemented like this float timeRemain 10f void Update() timeRemain Time.deltaTime if(timeRemain lt 0) ...code here. On PC it runs like expected but on Android device timeRemain variable becomes 0 in less then 10 secs. Who can suggest me what happens when i run it on Android device?


Call function after Level loaded I'm stuck in this situation I have a GameObject with a script, that persist trough Level loads. Inside this script, when a condition is meet, i Load a Level, and also call a function. That function is a C Messenger Broadcast() function. The level that I am loading contain the script with the Listener for that Messenger Broadcast. The problem is that the Broadcast occurs before the level has been loaded, and so there is no Messenger Listener that can receive the event. BroadcastException Broadcasting message OnConnectionError but no listener found. I need to do the Broadcast only after the level has been loaded, but I don't know how, or maybe there is a better solution. For a simple example here is the code public class NetworkingManager MonoBehaviour void Start() DontDestroyOnLoad (this) void OnConnectionLost(BaseEvent event ) if(Application.loadedLevelName ! "LoginScreen") Application.LoadLevel ("LoginScreen") Debug.Log ("Disconnected. Reason " event.Params "reason" ) Messenger lt string gt .Broadcast ("OnConnectionError", "Disconnected")


How to manipulate PostProcessing effects settings during execution with c ? I need to change the intensity value of my current Vignette effect depending in specific conditions. So far I haven't been able to achieve this. Please help! Image of what I want to achieve My setup Unity 2019.3.5f1 with URP implemented Post Processing Package (v2) installed Scene with a GameObject Volume component with Vignette and Bloom effect overrides added A monobehaviour component script in the very same GameObject from above My monobehaviour script using UnityEngine using UnityEngine.Rendering.PostProcessing public class PostProcessingHandler MonoBehaviour private PostProcessVolume ppv private Vignette vignette Vignette intensity values SerializeField, Range(0f, 1f) private float lowIntensity 0.25f SerializeField, Range(0f, 1f) private float highIntensity 0.5f private void Start() ppv GetComponent lt PostProcessVolume gt () Debug.Log( ppv) When I try to retrieve PostProcessingVolume component to get it's profile (and further layer manipulation) I always get "null". Image of my setup I've seen several guides posts and even Unity documentation but I cannot get past that starting point of getting the PostProcessingVolume component, what am i missing?


Unity assets turned binary from text I'm working with unity and git, and for some reason, from some point the assets started being Binary files, meaning that they're not visible as normal YAML files, and I cannot see textual git diff results on them. Has anyone experiences it and knows how to revert to the textual format from the binary format?


Why doesn't my wave movement code account for the game object's initial position? I want an object to move like wave. Currently, when I start the game the object's position doesn't account for its initial position. How would I fix this? float amplitudeX 5.0f float amplitudeY 2.5f float omegaX 0.5f float omegaY 2.5f float index public void Update() index Time.deltaTime float x amplitudeX Mathf.Cos (omegaX index) float y Mathf.Abs (amplitudeY Mathf.Sin (omegaY index)) transform.localPosition new Vector3(x,y,0)


How can I change the highlighted color of a Unity button when it's clicked? I was playing around with buttons in Unity, and I wanted to see if I could change a button's highlighted color every time I clicked on it. I added a script in the same GameObject as a button component, and I had a changeColor function attached to the component's OnClick(). The function was in a ButtonScript class written like this public class ButtonScript MonoBehaviour public Button button public void changeColor() Debug.Log ("Changing highlighed color") int r Random.Range (0, 255) int g Random.Range (0, 255) int b Random.Range (0, 255) Color currentColor button.colors.highlightedColor currentColor.r r currentColor.g g currentColor.b b I couldn't do button.colors.highlightedColor new Color(r,g,b) because I got a "Consider storing the value in a temporary variable" error. When I tried a test play and clicked the button multiple times, the highlighted color didn't change. How can I make a function that changes a button's highlighted color when it's clicked, if it's possible?


Do I need a database to support a sign in system to associate a player with their save highscore data? I am making a 2d game with Unity, and in my game I want to add a username and a password for each player, so that when the player signs in, they will get all the data about what they played until the moment they signed in (like their highscore and so on) So my question is do I need to use a database like sqlite, or could this be done with Unity without needing an external database?


Unity max scene limit I want to model the earth 1 1 in unity, but I can only zoom to a certain value in the scne window of unity