Aligning a sprite with a tilemap I'm trying to create a hybrid system for my Unity game. I want to use tilemap for collision and use sprites for the world. I drew a sprite onto a 40x40 checkerboard grid as can be seen here. I wanted an easy way to create a collider for this without spending 30 minutes hand placing box colliders and I decided to use a tilemap to place red tiles and use a tilemap collider for collision geometry and just hide the red tiles in game. Issue is, I have no clue how to align the checkerboard with the Unity tilemap grid. Here's a screenshot of the sprite in the unity editor with the tilemap grid visible. If it isn't obvious, then the white lines is the grid for the tilemaps. The cellsize for each cell on the grid isn't the same size as the cells on the checkerboard pattern and I have no idea how to fix it. The PPU (pixels per unit) of the sprite is 140. The PPU for the tileset tile(singular since there is literally only 1 tile in the entire tileset) is also 140. The checkerboard in paint.net is 40x40 and so is the tile. How can I get the cellsize of the grid in unity to match the cell size of the checkerboard.


Local avoidance together with any angle types of A Pathfinding Recently I have been implementing the Block A any angle path finding algorithm in a project I have, for which I need extremely efficient results due to the large number of NPCs. However, I still do not know exactly how to handle the problem of local avoidance between the NPCs moving at the same time in the same scene. So, my question is this what is the best method to implement local avoidance with any angle path finding? Just testing for LOS and steering to the tangent of the predicted encounter is a good enough solution or should a specific AI implementation be included within the pathfinding routine? I would highly appreciate references (academical or not) with state of the art implementations of local avoidance for me to explore the most recent developments in that field. Many thanks.


How do I work around the "You are missing the recommended JDK" error? After switching to 2019.4 LTS I got this error (using Windows 10) You are missing the recommended JDK. Install the recommended version using Unity Hub. I installed the JDK using Unity Hub many times now, still the same error. Tho I don't think it's getting installed. As you can see below, the quot OpenJDK quot checkbox remains blue no matter how many I try to install it. When I tried downloading and installing the JDK (JDK 1.8.0 181) myself I get this error instead You are missing the recommended JDK, versions other than 1.8.0 are not officially supported.


Unity General Prefab I have 2 questions about how i should approach this. I want to make a 2D game, with alot of different creatures. Question one If i have alot of monsters and i'm using ScriptableObjects, since they have very similar variables. How can i make one Enemy prefab which will load the right ScriptableObject information? For example i have an Enemy Prefab, then it will load random monster between Dragon, Frog, Wolf. How can i achive this without creating 3 new Prefabs for each one and instead load just the right ScriptableObject. Question two Should i create new prefab for each monster? Or is approach 1 the right way to do it, if you plan to expand over 100 creatures. Thanks


Persisting unlocked characters in Player Prefs I am working on a character selection menu in Unity. If you have enough coins, you can buy your desired character. Once player buys one, that character must not be locked on game restart, the number of coins must not be changed again, and the lock image (a GameObject I defined under name "wood" and acts as a lock) must disappear. Everything works fine when I buy one character, but when I buy another one, the previous one returns to locked mode, but its image (wood) has already disappeared (I mean, I should have enough coins to re buy an already bought character). I guess there must be something wrong with this code isPlanesold PlayerPrefs.GetInt("isPlanesold") because it changes as a character is bought. Here is my script int isPlanesold public static int chnum character number that must be referenced on another scene public Button WhitePlane public Button YellowPlane public GameObject wood1 public GameObject wood2 void Start () PlayerPrefs.SetString ("BluePlane", "on") if (PlayerPrefs.GetString ("WhitePlane") "on") wood1.SetActive (false) if (PlayerPrefs.GetString ("YellowPlane") "on") wood2.SetActive (false) UIManager2.coin score PlayerPrefs.GetInt ("Score") isPlanesold PlayerPrefs.GetInt ("isPlanesold") public void BuyWhitePlane () if (isPlanesold 1) PlayerPrefs.SetInt ("isPlanesold", 1) chnum 2 PlayerPrefs.Save () SceneManager.LoadScene ("Menu2") else if (UIManager2.coin score gt 1) PlayerPrefs.SetInt ("isPlanesold", 1) chnum 2 PlayerPrefs.SetInt ("Score", UIManager2.coin score ) PlayerPrefs.SetInt ("Score", UIManager2.coin score) PlayerPrefs.Save () PlayerPrefs.SetString ("WhitePlane", "on") SceneManager.LoadScene ("Menu2") else Debug.Log ("You Don't Have The Score") public void BuyYellowPlane () if (isPlanesold 2) PlayerPrefs.SetInt ("isPlanesold", 2) chnum 3 PlayerPrefs.Save () SceneManager.LoadScene ("Menu2") else if (UIManager2.coin score gt 2) PlayerPrefs.SetInt ("isPlanesold", 2) chnum 3 PlayerPrefs.SetInt ("Score", UIManager2.coin score 2) PlayerPrefs.SetInt ("Score", UIManager2.coin score) PlayerPrefs.Save () PlayerPrefs.SetString ("YellowPlane", "on") SceneManager.LoadScene ("Menu2") else Debug.Log ("You Don't Have The Score") PlayerPrefs.SetString ("BluePlane", "on") refers to a character that's unlocked by default.


How to enable antialiasing for SVG Images? My game has vector icons and sprites, like this one Its quality disappoints me. I guess that antialiasing is disabled here for some reason, but have no idea how to turn it on. The problem is only with UI component SVG Image. Sprite Renderer seems to not have this issue Regular Image does not support vector icons. I tried this approach. MSAA is enabled on Camera and in Quality settings. When it's disabled, second sprite becomes exactly the same as first. Unity version 2018.2.7.f1 for Linux Vector graphics package version 1.0.0 preview.23 I will accept a solution or an optimal workaround of any complexity. But please don't suggest using raster images. Why? I have to compress them because the game is for WebGL and I already had problems with memory because of textures. Vector sprites take less memory. Without mipmaps icons are pixelated. With mipmaps, they look blurry. They are all power of two, but at different scales. They are even blurred different, some more, some less. I can't use fixed sized sprites because there's an animation that changes zoom, and canvas will rescale in fullscreen. Vector guns are to the left, raster ones with mipmaps to the right. Thin black border lines are gone.


Why won't my block Spaces Holders hold my blocks when I drag onto them in Unity? In my game I am trying to have numbered blocks and math operators be able to be dragged down into their respectively color coded holders (white holders Numbers, black holders operations). The spawn in color coded blocks called spawners. If you drop a block you were dragging in a space that isn't a holder, then the block would immediately snap back to its respective spawner. However, I am now encountering this issue where 99 of the time when I drop the block onto its respective holder, the block snaps back to its spawner instead of staying there. Here's the minimum reproducible code for dragging the blocks using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems RequireComponent(typeof(Collider2D)) public class DragDrop MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler SerializeField private SpriteRenderer spriteRenderer public SpriteRenderer SpriteRenderer gt this. spriteRenderer HideInInspector public static bool isInSpace HideInInspector public Vector3 initialPos private void Start() initialPos transform.position isInSpace true public void OnDrag(PointerEventData eventData) if (isInSpace false) Vector3 movement new Vector3( x (eventData.delta.x 3) Time.deltaTime, y (eventData.delta.y 3) Time.deltaTime) this.transform.localPosition movement public void OnBeginDrag(PointerEventData eventData) isInSpace false public void OnEndDrag(PointerEventData eventData) if (isInSpace false) transform.position initialPos if UNITY EDITOR private void Reset() this. spriteRenderer this.GetComponent lt SpriteRenderer gt () endif And Here's the code for receiving the blocks using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class RecieveBlock MonoBehaviour, IDropHandler public void OnDrop(PointerEventData Block) if (Block.pointerDrag ! null amp amp Block.pointerDrag.tag gameObject.tag) Block.pointerDrag.GetComponent lt RectTransform gt ().anchoredPosition GetComponent lt RectTransform gt ().anchoredPosition DragDrop.isInSpace true I have no idea why it doesn't set off the isInSpace bool to be true and stay there. Heirarchy Image For Number Blocks Heirarchy Image For Operation Blocks Heirarchy Image For Holder Blocks Thank you for reading.


Unity Copy another object's Y location? I'm creating a Pong clone inside of Unity and was trying to figure how to copy another object (In this case being the Y co od of the Ball Object) How would i go about doing this? I'm using vectors as my method of paddle movement and I want to create a public int AISpeed so that the AI paddle is a little slower in comparison In my mind I assumed it was along the lines of rightPaddle.location.y pongBall.location.y How would I create this?


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


Empty game object (child of player) not changing position correctly when key pressed I've made an empty game object which is the child of the player. It is by default on his right side and following his every move, and I want to make it so that every time a directional key is pressed (WASD) it changes position and stays there. But the way I've made it, it's not working as intended and seemingly goes to random positions every time. Here's the script using System.Collections using System.Collections.Generic using UnityEngine public class ChangePositionAccordingToKey MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.W)) transform.position new Vector3( 0.58f, 3.09f,0) This is probably a dumb question but I am new to coding so I can't figure it out. Any help is greatly appreciated


Can I use the 2d physics engine in a 3d game (or viceversa) in Unity? This is entirely for performance. The 2D physics are less expensive, but I require 3D for some scenes. I never need both at the same time. I know you can have 2D with an orthographic perspective in a 3D engine, but what I want is really the physics engine. Also, is there a way of turning off these engines? I ve made most collisions from scratch and am only using them for some raycasts at the beginning and for some collider rigidbody.casts in not every, but a lot of frames (If I understand correctly, they are calculated from the physics engine in each FixedUpdate()).


Unity Best Random Movement Strategy? As of now, to get random movement of my enemies, I am adding a Rigidbody and a BoxCollider then "throwing" them (i.e. adding velocity) in a random direction for a random amount of time and making them choose a new direction if ever they get outside of their designated area. This does not seem to work that well all the time. Sometimes they manage to get themselves stuck inside obstacles which should be impossible. The more I add guys, the more it seems the physics can't keep up or something with the collisions. Is there a better method to random movement or is "throwing" them perfectly valid? Is my method expensive and terrible? I might have around 50 guys active at a time and perhaps a few hundred to a thousand static obstacles each with their own colliders.


How to prevent collisions between instantiated prefabs I'm creating a virtual creature evolution system like here. This type of project requires to define creatures, which are made of some 3d boxes and simulate them over and over again, making little changes along the way, until the point where they are good enough at a certain task. Basically, I'm using Genetic algorithms. I'm going to be doing a lot of simulation (a few hundred creatures each generation, times X generations, where X could be in the thousands). In order to save time, I want to simulate multiple creatures at once, so I must run collision checks efficiently. Each creature exists on its own and therefore should not be bothered by other colliders except himself and the ground. I have a prefab of a creature. Each creature is made of multiple 3d boxes with colliders. The nodes in the same creature should collide with themselves but should not collide with nodes that are in other creatures (because it should learn to perform based on the environment as it is). What is the most efficient way I could do this? I thought about checking the root of the collision object but that just prevents the collision and doesn't eliminate the useless checks that are being made. I've also looked at solutions involving the "Layer Collision Matrix" but still could not find a way to make it work. Thanks in advance.


Smoothly resize minimap camera rect width and height I have an orthographic camera that is working as a mini map. Now I want to make it resizeable using mouse drag. I have applied some UI beside my minimap camera rect and those UI resizing perfectly with this code. But I have no clue that how to resize my camera rect with mouse drag void Awake() rectTransform transform.GetComponent lt RectTransform gt () public void OnPointerDown(PointerEventData data) if (!resizePanelFeatureActive) return rectTransform.SetAsLastSibling() RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition) public void OnDrag(PointerEventData data) if (!resizePanelFeatureActive) return if (rectTransform null) return Vector2 sizeDelta rectTransform.sizeDelta RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out currentPointerPosition) Vector2 resizeValue currentPointerPosition previousPointerPosition sizeDelta new Vector2(resizeValue.x, resizeValue.y) sizeDelta new Vector2( Mathf.Clamp(sizeDelta.x, minSize.x, maxSize.x), Mathf.Clamp(sizeDelta.y, minSize.y, maxSize.y) ) rectTransform.sizeDelta sizeDelta previousPointerPosition currentPointerPosition


SpriteRenderer batching issue, with Z Position and Order in Layer I have two sprites (they look the same but with different colors) I want them to be positioned like on the image above, so there's a feel like blue is standing on the green one. There are two ways to achieve that Blue block with Order in layer 1, Green block with Order in layer 0 Blue block with lower Z coordinate, so it's physically in front of the green one. Both of the concepts appear to break batching between these two objects. They're on the same atlas (I've tested it by setting the same Z position and Sorting Order and batching works). How can I achieve batching here?


Tracking how many people play my Unity game in which language? In my game the user can change the language of the game and I'd like to know how many people play it in English, German, etc. I'm using Unity, so possibly I would like to implement in Unity Analytics. I was thinking about adding segments for the languages, but in that case if a user tries all languages, the user will appear in all languages' segments. So it won't really provide that much info. A possible solution When the user changes language, we signal a database to decrease the old language's counter and increase the new language's counter. But there must be an easier, built in solution than this.


How to put a reference to my player (already instanced) into a prefab that will be instantiated later I'm making an enemy in my game. He stands at the side of road with a rocket launcher and fires when you get close. It nearly all works fine, except I just need a reference to the players position so that I can make his rocket explode when it reaches the same height on the map as the player car. The enemy is a prefab which is NOT instanced at build time, there a several spawn points all with n chance of spawning a guy there using the prefab. The player IS instanced at build time. And here is my problem.. Although I have put a "public GameObject player" into my variables in the script on the prefab, it doesnt let me drag the already instanced player into it. I've read about a bit, and I see that Unity will not allow this (or at least thats what I gathered!) So after much searching I came up with player GameObject.FindGameObjectWithTag("Player") But i havent even tested yet because the source where i got that advice in the very next comment the guy says I shouldnt do this because it takes too much system resources up. EDIT I have tested it with that line, it does work. But is there a better way But he doesnt say the way that it should be done! And the thread is about 6 years old. So I thought I'd write here again and ask you fine folks for more help. I hope I explained the problem clearly enough, I think i got the terminology right. Basically, the RocketerEnemy prefab is going to be instantiated in runtime, but the PlayerCar is already instantiated by my dragging it into the heirarchy at the beginning of the project. This is stopping me from dragging the PlayerCar object into the box in the Inspector (for the Enemy prefab) . All I really need is the PlayerCar.transform.position.Y value for each frame. THANKS IN ADVANCE !


How to delete a score after collecting all collectibles I'm making a small game for my English class, and in the beginning, you have to collect rocks. I already have the code for counting how many rocks have been picked up, and the GUI to display while the game runs. After the player collects all 9 rocks I would like for the GUI to disappear or delete itself since it won't be used anymore throughout the game, and for new text to appear at the top of the screen saying "Go To The Lottery" I'm still very new to Unity so posting the code, and then following up with a brief explanation as to what does what would be majorly appreciated (but not at all demanded) Both codes are in JavaScript pragma strict static var currentScore int 0 var offsetY float 40 var sizeX float 100 var SizeY float 40 function OnGUI () GUI.Box (new Rect (Screen.width 2 sizeX, offsetY, sizeX, SizeY), "Rocks Collected " currentScore) This is my GameMaster script, which is in a empty game object galled " GM" pragma strict function OnTriggerEnter (info Collider) if (info.name "Player") GameMaster.currentScore 1 Debug.Log ("Picked stone up") Destroy (gameObject) This is my RockCollection script and it's what actually tells the GameMaster script to add 1 to the score and then delete the rock so you can't continuously pick it up


How to make a rigidbody come to rest faster I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C script with the basic vector3 and velocity stuff from a YouTube video using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField private Rigidbody playerBody private Vector3 inputVector private float xMovement private float zMovement SerializeField private float playerSpeed private float maxSpeed Use this for initialization void Start () playerBody GetComponent lt Rigidbody gt () playerSpeed 1 Update is called once per frame void Update () xMovement Input.GetAxisRaw("Horizontal") playerSpeed zMovement Input.GetAxisRaw("Vertical") playerSpeed inputVector new Vector3(xMovement, playerBody.velocity.y, zMovement) playerBody.velocity inputVector It works great with a cube I put it on, except for this if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster?


How can this method to make a text mesh always face the camera be simplified? (Unity c ) Despite a fairly heafty new years I am back trying to learn a bit more coding D This latest feature I am trying to add is a TextMesh that floats above a gameobject when the player is looking at it. I does all work fine (except it kinda shakes a little but I'll look into that another time). But as I wrote the method to make the textMeshObject look at my camera, I just had a niggling feeling it could be written in less lines of code. I actually get this a lot where I write several lines and think it must be able to be simplified, and after the code having several parts like this it can look pretty messed up. Anyways, I thought i'd ask you experts on here if it was possible to do this an simpler (NOTE I only want it to rotate on Y Axis) void FaceTextMeshToCamera() Vector3 origRot textMeshObject.transform.eulerAngles textMeshObject.transform.LookAt(textLookTargetTransform) Vector3 desiredRot textMeshObject.transform.eulerAngles desiredRot.x origRot.x desiredRot.z origRot.z textMeshObject.transform.eulerAngles desiredRot


What takes up more processing power between whole character models or models that are pieced together in Unity? In terms of performance when it comes to animation what takes up more processing power Whole character models or models that are pieced together? (1 object vs multiple objects). I also wonder if animating multiple objects allows us to get a better overall animation quality instead of working with one object (especially if we deal with action packed scenes).


Missing UI options in Inspector window when I import FBX files I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files. In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well. This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.


Problem with Blender model imported to Unity (Lighting problems) I made a simple box in blender and imported it to unity. Now I'm facing with this weird lighting problem I've been messing around with normals, duplicated vertex, lots of things, even lightning properties but still I'm not getting any results at all. Why does this happen and how can I solve it? Source blend file https drive.google.com open?id 1Ze1JBRFBvhnnY w36U2KDe7Q2zcfXsmf


How can I use Unity Assets made by Unity in a commercial project? I know you can't use starter and training etc.. assets made by Unity for commercial purposes, but according to this every Unity asset made by Unity is restricted for commercial use. So that means I can't use Post Processing Stack? That would be disappointing.


Can we measure the distance between and AR marker and camera? I'm in the middle of developing a game in Augmented Reality using Unity and ARToolkit plugin. I wanted to measure the approximate distance between the AR marker and the position of camera. Can anyone help me with a solution to this problem? Thanks in advance.


Timer breaks after changing scenes I am using this script below to move an animation in unity with no root motion. It simply walks across the terrain. I have timer attached also so the animation doesn't start to walk for 60 seconds. This works fine in the scene when played but when I navigate into this scene from another home scene the timer delay doesn't work as I guess it has been triggered already and has already reached the 60 second mark? I have tried using DontDestroyOnLoad but this just recreates the animation in the home scene also. I'm trying to keep the code as simple as possible and maybe add to the code below to fix it void Update () if (Time.time gt 60) transform.Translate (0, 0, Time.deltaTime)


How do mobile games implement time gates unhackably? Is it possible in offline games? I'm thinking about porting my game to Google Play, and it would be free to play with time gates which are skippable if you watch an ad. What are the ways of implementing an unhackable time gating? Is it possible without internet connection? If yes, how? If no, is there a way to implement it without custom backend, using Google Play's services? Or should I care about this at all? Because... It doesn't affect other players... Most of the audience couldn't do it anyway, and if the game stays small, hacks couldn't really spread. Then maybe I should just let them hack those time gates, it's a marginal revenue loss. What do you think?


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.


Add Lerp on only the Y axis I want my camera to be smooth on only the Y axis.How do I do that it? Current code public Transform target public float smoothSpeed 0.3f public float offsetX 1f public float offsetY 1f public float offsetZ 1f void FixedUpdate () Vector3 pos transform.position pos.x target.position.x pos.y target.position.y pos.z target.position.z Vector3 positionz pos.z Vector3 smoothedPosition Vector3.Lerp(transform.position, pos, smoothSpeed) transform.position smoothedPosition


Unity Static Camera Perspective, Walls Obscure Player Pretty simple and common problem here. The world I'm designing is fully explorable, no invisible walls or tricks. It's presented as a single seamless area, a School complex with 9 buildings, some of which have 2 or 3 floors and contain many rooms. The perspective I've chosen is simple, inspired by topdown RPGs A problem arises with walls. They obscure the player. I've tried some shaders which draw a silhouette of the player ontop but I don't like this approach, other objects and decoration remains obscured behind the wall. Some kind of dissolve effect allowing you to see through the walls would be preferable, but writing my own shaders is not my fort ... Another problem is with large buildings outside. The camera is at a fixed distance, about 14 metre's away. If the player walks behind a large building (over 10 metres tall) then the camera cuts off the top of it as it is now within the building. The only way I can think of fixing this is to adjust the distance between player and camera, but some of the buildings are so tall the zoom out looks very unusual and impractical. I suppose this is why you don't see this simplistic camera setup in large explorable games... While I've been developing games for some years now, I've only come to 3D and Unity fairly recently, so there might be a jaw droppingly simple solution which I'm not seeing. Anyway, I'd like to hear some interesting or novel approaches towards fixing these problems, besides the simple ones I've suggested. I hope that's not asking too much.


Calculating orbital elements from Cartesian Vectors I'm having serious troubles with getting my calculations to work. I'm calculating the orbital elements from a position vector, and a velocity vector. (I also know the distance and mass of the bodies around) The equation for angular momentum is as follows h r v The equation for eccentricity is e ((v 2 r )r (r v )v I plug in the position and velocity to get h, and I plug them into the other equation to get the eccentricity. These SHOULD be constants, and not change unless another force is put on them... yet they are not constant. In fact they change as the orbit goes around. In the diagram I have just left a trail to show the orbital path. I should be able to calculate the required information... however they rely on the constants, which are not at all constant. I reference the rigidbody's position and velocity in them, and I've entered the equations in correctly. My code for applying force between planets is as follows void CalculateForce(Transform body) float m1 rbody.mass float m2 body.GetComponent lt Rigidbody gt ().mass float distance Vector3.Distance (transform.position, body.position) float f (m1 m2) Mathf.Pow (distance, 2) Vector3 direction rbody.position body.GetComponent lt Rigidbody gt ().position rbody.AddForce ( direction.normalized f) body.GetComponent lt Rigidbody gt ().AddForce (direction.normalized f) The calculations are coming back incorrect. The eccentricity varies between 0.9 and 1.1. Anything over a 1 is not actually in orbit, and anything less is in orbit. However this remains in orbit as it travels around. Can anybody help? (I've already posted to the space stack exchange and had no luck) Thanks in advance. Update Code used to calculate eccentricity (1001f is the combined weight of both objects) Vector3 pos GetComponent lt Rigidbody2D gt ().position Vector3 vel GetComponent lt Rigidbody2D gt ().velocity Vector3 eccentricity (Mathf.Pow (vel.magnitude, 2.0f) (1001f pos.magnitude)) pos eccentricity Vector3.Dot (pos, vel) vel eccentricity 1001f


Unity Combine two UVs by alpha I'm currently creating a voxel game like Minecraft. To display the damage of blocks, I want to combine the alpha channel of one part of my texture map with the actual texture (like Minecraft does), how could I do that in Unity?


Is there a way to display navmesh agent path in Unity? I'm currently making a prototype for a game I plan to develop. As far as I did, I managed to set up the navigation mesh and my navmeshagents. I would like to display the path they are following when setDestination() is fired. I did some researches but didn't find anything about it. EDIT 1 So I instantiate an empty object with a LineRenderer and I have a line bewteen my agent and the destination. Still I've not all the points when the path has to avoid an obstacle. Furthermore, I wonder if the agent.path does reflect the real path that the agent take as I noticed that it actually follow a "smoothier" path. Here is the code so far GameObject container new GameObject() container.transform.parent agent.gameObject.transform LineRenderer ligne container.AddComponent lt LineRenderer gt () ligne.SetColors(Color.white,Color.white) ligne.SetWidth(0.1f,0.1f) Get def material ligne.gameObject.renderer.material.color Color.white ligne.gameObject.renderer.material.shader Shader.Find("Sprites Default") ligne.gameObject.AddComponent lt LineScript gt () ligne.SetVertexCount(agent.path.corners.Length 1) int i 0 foreach(Vector3 v in p.corners) ligne.SetPosition(i,v) Debug.Log("position agent" g.transform.position) Debug.Log("position corner " v) i ligne.SetPosition(p.corners.Length,agent.destination) ligne.gameObject.tag "ligne" So How can I get the real coordinates my agent is going to walk throught ?


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


implementing daily challenges in games I want to know how can I define daily monthly challenges in my game? Is this something can be defined locally or its need server and external services? And which servers and technologies can implements that? Is persistent connection or needed as server should send messages to clients with no request? Specifically, I use unity.


Put a coroutine on potentially infinite loop I have several coroutines always running. I want to put these coroutines on hold as I set the game to pause mode. Consider the content of these coroutines as follows while (timeleft gt 0) if (pause) continue ... timeleft Time.FixedDeltaTime yield return null I thought that would be okay to insert the if(pause) clause to have the coroutines to wait while pause is up. What, insted happens is that (I guess) these infinite loops make unity not responding so that I have to kill the process. Can I be right in thinking that the system does not like coroutines to be in a potential infinite loop? Or that is just okay and I have to heavily debug somewhere else?


How to hide Game Progress Files saved in Application.persistentDataPath in Unity Android I am developing a game that saves its state in a text file. I am writing that file in Application.persistentDataPath but my issue is that the game progress file is available to user in Data PACKAGE NAME files . How can I hide the game progress file so that user can't access the files ?


A pathfinding for dynamic obstacles and player made blockages? Hi I'm creating a TD in Unity 5 and need some help with my Pathfinding. I'm going to use Arons A pathfinding for my AI which enables me to use dynamic objects and update the path during run time. However in my game I want the player to be able to block the minions with special turrets which will force the minions to attack the "block tower" instead to get past to their destination. How could I accomplish something like this? Image for more clarity


How can I prevent seams from showing up on objects using lower mipmap levels? Disclaimer kindly right click on the images and open them separately so that they're at full size, as there are fine details which don't show up otherwise. Thank you. I made a simple Blender model, it's a cylinder with the top cap removed I've exported the UVs Then imported them into Photoshop, and painted the inner area in yellow and the outer area in red. I made sure I cover well the UV lines I then save the image and load it as texture on the model in Blender. Actually, I just reload it as the image where the UVs are exported, and change the viewport view mode to textured. When I look at the mesh up close, there's yellow everywhere, everything seems fine However, if I start zooming out, I start seeing red (literally and metaphorically) where the texture edges are And the more I zoom, the more I see it Same thing happends in Unity, though the effect seems less pronounced. Up close is fine and yellow Zoom out and you see red at the seams Now, obviously, for this simple example a workaround is to spread the yellow well outside the UV margins, and its fine from all distances. However this is an issue when you try making a complex texture that should tile seamlessly at the edges. In this situation I either make a few lines of pixels overlap (in which case it looks bad from upclose and ok from far away), or I leave them seamless and then I have those seams when seeing it from far away. So my question is, is there something I'm missing, or some extra thing I must do to have my texture look seamless from all distances?


How can I scroll animate up lines reading from a string to ui text? This is the reading lines code if (primaryTarget ! null) var lines primaryTarget.description.Split(' n') text.text quot Item found quot primaryTarget.description else text.text quot quot And this is the script of the description The script is attached to each interactable target(item) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class InteractableItem MonoBehaviour public enum InteractableMode your custom enumeration Description, Action public InteractableMode interactableMode InteractableMode.Description public float distance private bool action true TextArea(1, 10) public string description quot quot public void ActionOnItem() if(interactableMode InteractableMode.Action amp amp distance lt 5f amp amp action true) action false Depending on the amount of text in the string I want to show it in the ui Text. If there is one line then just show the text or even if there are two lines. but if there is a lot of text then split the lines and scroll the lines smooth up so the first line will be disappear or pushed up and bottom lines will come up. In the screenshot you can see on the left the text that show in the ui text on the right the text of the description. The ui text can't show all the text and I don't want the text to overlap other ui's or objects so the idea is to make the text slowly smooth scrolling up.


Unity3d getting terrain height I am making an RTS game in unity like Total War games. As for rendering I am using Graphics draw mesh instanced method and after culling a I can easily render massive amount of soldiers on battlefield also they are animating with shader. I am not using unity gameobjects or unity physic engine(Also they are costly) as only data I am providing is Matrix4 4 to DrawInstancedIndirect method and rendering.Problem is I want to get height of terrain at specific position(to place unit on terrain) So I can pass Y value to Matrix4 4 for rendering. After seraching documentation I found that there are few ways to get height. Terrain.SampleHeight It is easy to get height with this method just need to pass vector position but costly As When there comes 10,000s of units on battlefield 10k calls for sample height kills performance. TerrainData GetHeights Can get heightvalue from it in 2d array but height I get is only for int value i.e 10,500 so there is not any option to get value sayif specific unit is at position 10.52,234.8 TerrainData.GetInterpolatedHeight I can get height for float values but I am getting inconsistant result with it. One option for me is to make flat terrain but it kills immersion. I ran out of ideas here Is there any way I can get of terrain by either terrain texture or by shader ? Sample Image EDIT GetinterpolatedCode for (int i 0 i lt position.Length i ) position is array contains info of all vectors t is terrainData q t.GetInterpolatedHeight(position i .x, position i .z) position i new Vector3(position i .x,q, position i .z) print(position i " " t.GetInterpolatedHeight(position i .x, position i .z))


Application.OpenURL not working I have a public void Public void patreononclick() Application.OpenURL("http www.patreon.com HubakaGs") Which supposed to open my patreon page when a button is tapped. But when i tap the button in the built application, nothing happens. I have assigned the function to the On Click() section of Button (Script). I am building the game for android patform and i use Unity 2017.1.0p4 Personal. How can i make the button to function properly? Update I changed the function to public void patreononclick() Debug.Log ("the game should open patreon") Application.OpenURL("http www.patreon.com HubakaGs") But when the button is clicked, there is no message at the console.


How do I achieve this glowing edge shader? I came across this example, and wanted to know how to achieve a shader that will give me similar results, i.e. the glowing edges. How do I achieve this sort of shader?


Algo for rotating tower towards enemy Unity I have made a grid and placed towers and moving a enemy on it. Now i want to rotate towers face towards enemy when enemy comes in the range of tower. I have a solution that whenever enemy comes to its range ( 2 grids far ) it starts do something, lets say when tower finds enemy is on left side it starts firing like that when enemy moves up down ( when it finds there is a tower on very next tile) tower starts rotating with enemy position uniti enemy's range that is 2 grids far. So its mean tower has to rotate whenever enemy comes to its range and moves up down. What would you people suggest me a optimized way or any helpful scripting function ?..thnx


How can i create a 2 player turn based board game on a separate android device using unity? im trying to make a 2 player turn based board game, i have already made the connection between 2 device. I used photon. They both connect but i don't know how to sync them both to the game. can any one help me? i hope my question is right.


Play games services leaderboard does not work all the time I am trying to login into play services. I got it working. But there were duplicate game objects created. So I added do not destroy on load and now the play services work the first time I access it. But when I go to play game scene, end the game and come back to main menu, I can not seem to load the leaderboards. public class PlayServices MonoBehaviour public static PlayServices services private void Awake() if(services ! null) Destroy(gameObject) else services this DontDestroyOnLoad(gameObject) Use this for initialization private void Start () PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder().Build() PlayGamesPlatform.InitializeInstance(config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate() SignIn()


What format should I choose? I am making models in blender to export them then in unity, and unity can import .blend formats as well as .fbx, so which one is better, is there even any difference.


Cant set up to get input from second analog stick So I know for a fact that the stick on my gamepad is working. The problem is I cant set it up in the Input Manager. I tried all possible Axis configurations and still getting a input values of 0. Here is a screenshot of the configuration.


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


Unity LLAPI Connection Problems NAT Routers? I have created a bespoke networking system using Unity's LLAPI. It works fine on the same machine, and sometimes works even to direct connect across the internet! The problem however, is that it sometimes does not want to connect to other players across the internet. It seems impossible to host the game on some ISPs, as clients cannot detect or connect to them. I assume this is related to Router NAT issues. I would like to know how I can deal with this problem, integrating with Unity's LLAPI.


How to make an object jump an equal height whenever it hits the ground? So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried Used Physics.CheckSphere isGrounded Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer) if(isGrounded ) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) Used Raycast bool groundHit Physics.Raycast(rayPoint.position, transform.up, rayDistance, groundLayer) if(groundHit) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?


Quit from Unity to native iOS app I'm working on iOS application which is going to include a few unity games. And I investigate an opportunity to exit from the Unity game to the native iOS app with games list. I know that the Unity provides methods Application.Quit() and Application.Unload() I haven't try but I'm not sure that Application.Unload() is correct ways to exit from unity to the native iOS app.


Creating a UI health bar image for each enemy object I would like to create a small health bar on top of each enemy in my game. I know how to do this for one enemy, but I'm not completely sure how best to expand it to work for each enemy in the game. I'm guessing I should instantiate the UI health bar prefab somewhere, each time an enemy is spawned maybe? Currently, I don't even have an enemy spawner, I'm just testing by dragging enemy prefabs into the scene. I'll post the relevant scripts. public class EnemyHealthBarController MonoBehaviour private Image remainingHealthImage private EnemyHealth enemyHealth void Start() remainingHealthImage transform.Find("Remaining Health Image").gameObject.GetComponent lt Image gt () enemyHealth GameObject.FindGameObjectWithTag("Enemy").GetComponent lt EnemyHealth gt () void Update() remainingHealthImage.fillAmount enemyHealth.currentHealth enemyHealth.maxHealth if (enemyHealth.isDead) gameObject.SetActive(false) and public class ClampEnemyHealthBar MonoBehaviour private GameObject enemyHealthBar private Vector3 offset void Start() enemyHealthBar GameObject.Find("Enemy Health Bar") offset new Vector3(0f, 30f, 0f) void LateUpdate() Vector3 desiredPosition Camera.main.WorldToScreenPoint(transform.position) offset enemyHealthBar.transform.position desiredPosition Right now, I'm using GameObject.Find to set a reference to the preexisting enemy health bar in the scene. Also, I'm only finding the EnemyHealth component of one of the enemies. How might I better structure this in order to do the kind of thing I'm trying to do?


Animation position leftover I am fairly new to unity and I have encountered this same problem previously. I have a gun with hands and I created an animation that simulates shot movements with properties transform.position and transform.rotation. Root motion is applied and motion curves are generated for the animation.The default state animation for that object has no properties assigned to it and as much as I understand from the animation controller window, the shot animation is completed before the transition to the default state is made. The problem is that on every 3 shots 0.001 is added to the X rotation Y and Z positions are losing some small values. I tried to prolong the animations exit time but the result is the same. I checked the key values and the motion curves, the first and last ones are the same. Why is this happening and how can I fix it ?


Hide an image once all enemies in a zone are defeated In my game there are several buildings that a main character has to free from enemies. I put a kind of a logo above all those have to be released buildings, indicating that a certain building is not free and it has to be released. What I want to achieve is that when I kill all of the enemies near a certain building, the logo above that building has to disappear, indicating means that the building was released. I don't know how to detect this condition of "all nearby enemies defeated" in my script how can I do that, and hide the image when the condition is met?


Is there performance difference between OnCollisionEnter and OnTriggerEnter? Is there performance difference between OnCollisionEnter and OnTriggerEnter? I have around 12 objects all calling OnCollisionEnter when in fact OnTriggerEnter could work as well. So I wonder if the are is any difference PERFORMANCE WISE between the two


Best practice for play location of projectile sound effects? I am encountering an issue where I have a bullet that is destroyed on impact which is cutting off my bullet impact sound effect due to the audio source being destroyed. I like the idea of the sounds being attached to the projectile, but not sure if that is best practice. I can play the sound from an NPC script, but not sure if that will open up other issues. Is this a better approach since the NPC material is quot metal quot so I should store all the quot Metal hit quot sound effects on the NPC? ...vs. having to store all material variations of impact on the projectile?


How to check metadata stored in FBX files? Is there a way to check and edit metadata information stored in FBX files? I'm using 3ds Max's fbx exporter. Can this be done with it or is there any other tool for that? For example adding name, contact info, tags or anything that provides ownership of the file.


How to load sprite from JSON? i know how to load text, but idk how to load texture from json.. this my c public void soalbegin() filepath System.IO.Path.Combine(Application.streamingAssetsPath, "soal.json") StartCoroutine ("Json") soaldata JsonMapper.ToObject(jsonString) IEnumerator Json() if(filepath.Contains(" ")) WWW www new WWW(filepath) yield return www jsonString www.text else jsonString System.IO.File.ReadAllText(filepath) public void OnClick() soalbegin() GameObject.Find("Panel soal gambar Text").GetComponentInChildren lt Text gt ().text soaldata "data" numbersoal "soal" .ToString() this to load text from json i need variable to load sprite texture from link json and this is my json "data" "id" "1", "soal" "siapa tokoh ini", "gambar" " 1.png", "jawaban" "natsu", "shank", "goku", "gildart"


Rotate player to vector3 point? I want my player object rotate to face vector3 point on terrain. public Vector3 RocketPointer public Transform pointer,Player public bool rocket , button move Update is called once per frame void Update() if (button move true) Ray mouseRay Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit mousePoint if (Physics.Raycast(mouseRay, out mousePoint, 100)) RocketPointer mousePoint.point pointer.transform.position RocketPointer if (button move true amp amp Input.GetMouseButtonDown(0)) rotate player object to face rocketpointer point rocket true button move false if (button move false amp amp Input.GetMouseButtonUp(0)) rocket false public void move button() UI button button move !button move


How to get a Read Write Reference to Parent GameObject from a script component attached to it? I have a game object(object) with a script component(myscript) attached. I have a reference to myscript component through getComponent, and I want to change the transform of the gameObject the script is attached to. myscript.gameObject.transform (new value) The above code gives me error, Property 'UnityEngine.GameObject.transform' is read only. Is there a way to get a read write version?


How to Make Saving System More Secure I've been working on an saving system for my 2D RPG game, and I recently encountered an issue my saving system uses PlayerPrefs, which I heard is supposed to be used for things such as settings. I've also heard that it isn't very secure and that people can exploit it. I was wondering whether there was a way to make my saving system more secure. Here's my inventory script that also holds the save function using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class ItemInformation MonoBehaviour These are the assets for the item to change public Text nameText public Text descriptionText public Text regenText public Text amountText This is the identifier for each item public string identifier These are the variables that change with the different items public string itemName public string itemDescription public float itemRegeneration public int itemAmount Starts on awake void Awake() Function to change the object's information and such nameText.text itemName descriptionText.text itemDescription regenText.text quot HEALS quot itemRegeneration quot HP quot Loads game data LoadDataIfNeeded() Function to save game data public void SaveData() string jsonString JsonUtility.ToJson(this) PlayerPrefs.SetString(identifier, jsonString) PlayerPrefs.Save() Loads data if needed public void LoadDataIfNeeded() if (PlayerPrefs.HasKey(identifier)) string jsonInstance PlayerPrefs.GetString(identifier) JsonUtility.FromJsonOverwrite(jsonInstance, this) else SaveData() Updates on every frame void Update() Shows amount of item left amountText.text quot HAVE quot itemAmount


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


Unity When attaching my custom camera script camera shakes when player starts to move fast Here is my player code. Rigidbody rb Vector3 currMovement public float jumpSpeed 10 public float moveSpeed 10 public float rotSpeed 180 float distToGround public float posSmoothTime 0.5f float currPos float targetPos float posVel public float rotSmoothTime 0.5f float currRot float targetRot float rotVel void Start() rb GetComponent lt Rigidbody gt () distToGround GetComponent lt Collider gt ().bounds.extents.y bool isGrounded() return Physics.Raycast(transform.position, Vector3.down, distToGround 0.1f) void Update() Move() void Move() Rotation smoothing. targetRot Input.GetAxisRaw("Horizontal") rotSpeed Time.smoothDeltaTime if (targetRot gt 360) targetRot 360 if (targetRot lt 0) targetRot 360 currRot Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, rotSmoothTime Time.smoothDeltaTime) transform.eulerAngles new Vector3(0, currRot, 0) Movement smoothing. targetPos Input.GetAxisRaw("Vertical") moveSpeed currPos Mathf.SmoothDamp(currPos, targetPos, ref posVel, posSmoothTime Time.smoothDeltaTime) currMovement new Vector3(0, 0, currPos) currMovement transform.rotation currMovement if (isGrounded()) if (Input.GetButtonDown("Jump")) rb.velocity Vector3.up jumpSpeed rb.position currMovement Time.smoothDeltaTime I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script. public Transform player Quaternion targetLook Vector3 targetMove public float smoothLook 0.5f public float smoothMove 0.5f public float distFromPlayer 5, heightFromPlayer 3 Vector3 moveVel void LateUpdate() CameraMove() void CameraMove() targetMove player.position (player.rotation new Vector3(0, heightFromPlayer, distFromPlayer)) transform.position Vector3.SmoothDamp(transform.position, targetMove, ref moveVel, smoothMove) targetLook Quaternion.LookRotation(player.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, targetLook, smoothLook) The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.


How to make pathways corridors in a randomly generated dungeon? I am trying to make a random dungeon generator using Unity. I have been able to setup the rooms properly and connect them to each other using a minimum spanning tree algorithm. I have attached an image below where you can see what I have so far. The next step will be to create pathways corridors to connect the rooms together but I am having difficulty understanding how I am supposed to go about it. I want the corridors to be straight or form an 'L' shape when connecting to each other. So I was wondering if anyone could help me out with this. Any help is appreciated.


How does Unity call "update()" in the scripts? I understand that you can expose your C code to a scripting language such as ChaiScript. From this you can call code that you've made in C . In Unity, however, they have functions in the script, such as Update() that get called. In other words, how do I call script functions from C ?


How to make an Assert.IsNull test pass when the value is reported as ? I've just started using unity tests with the built in editor tests. After making my test and finding out that it constantly failed I debugged the code and found that a static object was set to a new game object when running the test while it is set to null when playing in the editor. Is there a way to force unity to treat the test the in the same way that it treats scripts at run time? Edit After changing some code around i get another strange error does anyone know why "null" isn't "null". The null objects are stored in an array, but that shouldn't make a difference right? Edit Edit (Edit 2?) Here is the code that has the issue public class StatCollector MonoBehaviour public static StatCollector running ensure that there is only one object running at the same time public void Awake () if(running null) DontDestroyOnLoad(gameObject) running this else if(running ! this) DestroyImmediate(gameObject) and here is the test Test public void SingleTest() create gameobjects GameObject collect new GameObject 2 collect 0 new GameObject("one") collect 1 new GameObject("two") collect 0 .AddComponent lt StatCollector gt () see if gameobjects were created correctly if (collect 0 null collect 1 null) Assert.Fail("failed to create game objects") test what happens when the second stat collector is added to the scene collect 1 .AddComponent lt StatCollector gt () collect 0 .GetComponent lt StatCollector gt ().Awake() collect 1 .GetComponent lt StatCollector gt ().Awake() Assert.IsNull(collect 1 ) I'm assuming that there is no way to keep Awake private which is why it is public (just so that the test case has access to it)


Saving total play time could be fine? I'm making a game that needs to save total played time into file (using JSON) for comparing amp resolving data conflicts between local and cloud. I will override outdated one. Currently, I'm just adding Time.realtimeSinceStartup, but is that okay? What if the time is really, really big and couldn't be handled in Unity anymore? Could that eventually happen? If so, what are some alternatives?


Unity Z position issue on gameobject with subcomponents I'm following this tutorial from Ryan Miller on how to create a rig of sorts from a sprite atlas sheet. My intention was to put the panda behind a bamboo, but this is what happened The bamboo's Z position has been set to 2, whilst the Panda's has been set to 6. Here's a 3D look at the problem How do I fix this?


MCS character mouth open is this mo cap animation problem? I have MCS Female Character where I can assigned Mocap to my character. I have downloaded mixamo animation and assigned this to the character but the problem is, the character mouth remains open. I am not 3d artist or animation guy, so here are my question. How can I solve mouth open problem in unity? What is the reason that mouth is open? Either mocap data has open the mouth or what else problem?


Editing attached component property in Unity (C ) This might be more of a general C programming query, but since it's game dev related, I'm putting it here. I am trying to randomise a property in a custom component (C script) across several Unity game objects. hostiles is a list of game objects, each with an attached Stats component. foreach (GameObject gO in hostiles) Randomise spawn area gO.GetComponent lt Stats gt ().AreaNo Random.Range(0, 3) Perhaps unsurprisingly, all of my objects end up with the same value for AreaNo. It seems as though I m reassigning some global version of Stats.AreaNo in my loop, rather than the individual instances. What am I missing? (Sorry in advance for the noobish question!)


pathFinding performance in Unity3d I am making Sniper game in unity 3d. In this game zombies will come randomly towards the sniper and sniper have to kill them. I am using RAIN(indie) for path finding. It works best when zombies are few . As I increase the Zombies( that is 10) the performance decrease a lot. The fbs drops to 25. I want to know is there any technique or steps so I can improve fps Any other technique algorithm that I can use for pathfinding weith good fps. PS I already remove Sensor component from AI. FPS of game without AI is 61


How can I instantiate enemies in a 2D game at a set Viewport Position before my camera enters the room? (Or alternative solution!) I'm currently working on a 2D game where I'm trying to pre populate my level with encounters, I want the enemies already in the room when the player enters. Right now the encounter is triggered upon entering the room when the camera bumps into the collider and the enemies are instantiated at the Viewport position, however because it does it while the camera is moving into the room the position is incorrect. Using hard values isn't an option because the maps could of course change and also I may want them randomly generated at some point. So I guess ultimately the problem is the camera not being in the right position when they instantiate and not wanting enemies to quot pop quot in once it is. Is there a way I can I instantiate an enemy at the same point on the screen regardless of resolution in each specific room at the start of the level? Encounters will have up to 3 enemies and they will always hold the same formation (with spots randomized to add diversity) Here is my instantiating code SerializeField public List lt GameObject gt levelEnemies new List lt GameObject gt () GameObject levelEnemy Vector3 enemyPosition Vector3 viewportPosition new Vector3(0.8f, 0.5f, 10f) Place on the screen I decided I want single enemies to appear Camera cam void Start() Debug.Log( quot Enemy Triggered quot ) cam Camera.main enemyPosition cam.ViewportToWorldPoint(viewportPosition) levelEnemy Instantiate(levelEnemies 0 , enemyPosition, Quaternion.identity) instantiate test enemy at the converted position navigation.DisableNavigation() Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3) Here's what should be happening when the enemy is instantiated (triggered manually through the editor once camera has been moved fully) Here is what happens when the camera collider bumps into the encounter collider Any help in the right direction would be much appreciated or a workaround! Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)


Change texture settings for each object So I'm kinda new to Unity, but I've used it a couple of times before. Here's my issue I have two cubes with a random texture applied to them (drag'n'dropped something from the Asset Store). These cubes have different sizes, where one is a square and one is a rectangle. I want to set the tiling size to be different on them (because they are obviously stretched on the rectangle), but when I click on one and change it, the settings changes for both of them. This is how it looks right now http i.imgur.com JtubBle.png Is it possible to make these settings unique for each object somehow?


How to limit camera pitch (x rotation) between two angles I use this script rotate the camera on its local X axis float v verticalSpeed Input.GetAxis("Mouse Y") transform.Rotate( v, 0, 0) Right now this lets the player look up amp down without limit, wrapping around a full 360 degrees. How can I limit this so they can look only 90 degrees up or 90 degrees down from the horizon?


Uploading APK build to Google Play Console error "You uploaded a debuggable APK or Android App Bundle" I was trying to upload my andoid app apk build to my play console account and I keep getting this error You uploaded a debuggable APK or Android App Bundle. For security reasons you need to disable debugging before it can be published in Google Play. In accordance with the informations given at https developer.android.com studio publish preparing.html publishing configure and https answers.unity.com questions 1653647 you uploaded a debuggable apk or android app bundl.html Here are what I have done so far 1) I have gone to the root folder of my unity project, searched for AndroidManifest.xml, and I found multiple Manifest files, and changed the value of "android debuggable" to false for each of these manifest files that were generated by unity(and I did not edit the google generated manifest files). 2) I have scanned every c file on my project that contains the keyword "Debug" and I have either deleted or commented out the Debug.log lines except on the files generated by google(as a result of the integration of google play services into my game). And yet, I still have the same problem when I try to upload my apk to play console. What else am I missing? Should I also remove the Debug.log lines from google generated c script files?


SerializeField UntiyEvent not properly saving modifications in EditorWindow I'm making a node editor in Unity using an EditorWindow, I'm currently trying to make it so designers can add their own methods to a node using serialized UnityEvents but I haven't been able to get it to function properly. SerializedObject serializedObject new SerializedObject(selectedNode.NodeState) SerializedProperty property serializedObject.GetIterator() property.Next(true) while (property.NextVisible(false)) EditorGUILayout.PropertyField(property) serializedObject.ApplyModifiedProperties() serializedObject.Update() The above code runs through all necessary fields of the class so the user can modify them. Everything functions perfectly with the exception of UnityEvents. They almost do as I intend them to do, except they don't preserve the variable inputs of inserted object's method. If I keep working within the editor window they stay, but if I close the window and re open the inputted variable resets. I thought this may be caused by an issue somewhere else in my code, but all other fields work fine.


How to do collision detection in Unity between Character Controller, Rigidbody Collider and a NavmeshAgent? I would like to know more about how collision detection works in Unity especially when character controllers and NavmeshAgents get involved. For example, how can I detect collision between NavmeshAgent and a CharacterController? I have added a sphere collider to my NavmeshAgent, but it doesn't seem to detect a collision unless I set it to "IsTrigger". I have tried OnCollisionEnter(), OnControllerColliderHit() and OnTriggerEnter(). OnTriggerEnter() seems to be the only one that works and only when I enable "IsTrigger". How come the other two don't work? Shouldn't they? What if I didn't want to make the collider a trigger?


How to make unitypackage from allseen alliance's android sdk? Im making an offline multiplayer for Android device by Unity and I found only one way to do this is the allseenalliance sdk. After download its from here I found that to use it I need to create an .unitypackage file but I cant understand the tutorial they give gt Open a CMD window. gt Add the path to Unity.exe (the Unity IDE) to your PATH, if it is not there already. gt For example, set PATH PATH C Program Files Unity Editor gt CD to each quot unity quot folder in the SDK, and run the following command in each location gt Unity.exe batchmode nographics quit projectPath CD exportPackage Assets AllJoyn.unitypackage gt This command creates the AllJoyn.unitypackage file. Please give me a noob tutorial for this or the package file, thanks. p s Is there another way to connect mobile device without internet in unity3d?


Unity custom shaders and z fighting I've just readed a chapter of Unity iOS Essential by Robert Wiebe. It shows a solution for handling z figthing problem occuring while rendering a street on a plane with the same y offset. Basically it modified Normal Diffuse shader provided by Unity, specifing the (texture?) offset in 1, 1. Here's basically what the shader looks like Shader "Custom ModifiedNormalDiffuse" Properties Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB)", 2D) "white" SubShader Offset 1, 1 THIS IS THE ADDED LINE Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Lambert sampler2D MainTex fixed4 Color struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) half4 c tex2D ( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG FallBack "Diffuse" Ok. That's simple and it works. The author says about it ...we could use a copy of the shader that draw the road at an Offset of 1, 1 so that whenever the two textures are drawn, the road is always drawn last. I don't know CG nor GLSL, but I've a little bit of experience with HLSL. Anyway I can't figure out what exactly is going on. Could anyone explain me what exactly Offset directly does, and how is solves z fighting problems?


Make a background Image to fit multiple objects? In the Hierarchy, I have a GameObject named "Buttons" to which I added an Image component. I would like that the ok sprite to cover (be background of) all the buttons START GAME, OPTIONS, CREDIT and EXIT. But the ok sprite is somewhere in the top left corner behind the START GAME button on its left side and is very small. This happened when I clicked in the Inspector in Image on Set Native Size. I want to make it big enough to cover all the buttons but I'm not sure how.


How do I find an object by type and name, in Unity, using C ? I know that in Unity you can find an object of a certain type, using myObject Object.FindObjectsOfType lt MyType gt (), but that only returns the first object in the scene it finds of that type. How do I make it find the object of a certain type and with a certain name?


How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script using UnityEngine using System.Collections public class hu MonoBehaviour GameObject pauseObjects public bool isPaused void Start () pauseObjects GameObject.FindGameObjectsWithTag("Player") Update is called once per frame void Pause () if(Time.timeScale 1) Time.timeScale 7f else if (Time.timeScale 8f) Time.timeScale 1


I need to move a sprite from point A to point B. I have objX1, objY1, frames, and X2, Y2 I have a custom sprite class in Unity and I'm trying to make a method in where it moves from one point to another. Instead of using an Enumerator for time, I'm using real time game frames using static void methods inside of classes which inherit from a MainGame.cs script attached to the Main Camera, and this is called inside of MainGame's Update() method. So what I have in the end are the following values SpriteID OriginalX OriginalY MoveToX MoveToY CurrentFrames TotalFrames I'm not asking anyone to do the work for me, just that if there's a place I could be directed to in where I could find the math necessary to solve the problem that'd be a huge help. I'm not using any vectors here, just the raw math using only those variables. I don't know if someone has found an answer for calculating it based on update frames... public class Sprite MainGame public static int State 0 public static int CurrentFrames 0 public static int TotalFrames 0 public static void Move(int SpriteID, int OriginalX, int OriginalY, int MoveToX, int MoveToY, int TotalFrames) switch (State) init case 0 CurrentFrames 0 State 1 break run case 1 if (CurrentFrames lt TotalFrames) do math here CurrentFrames if (CurrentFrames gt TotalFrames) State 2 break end case 2 Reset values here Shut off State 3 break EDIT 10212016 456PM What I've figured out so far, now... if (CurrentFrames lt TotalFrames) DistanceX MoveToX OrigX MoveForwardXFloat (float)DistanceX (float)Frames OrigX (int)MoveForwardXFloat


Local avoidance together with any angle types of A Pathfinding Recently I have been implementing the Block A any angle path finding algorithm in a project I have, for which I need extremely efficient results due to the large number of NPCs. However, I still do not know exactly how to handle the problem of local avoidance between the NPCs moving at the same time in the same scene. So, my question is this what is the best method to implement local avoidance with any angle path finding? Just testing for LOS and steering to the tangent of the predicted encounter is a good enough solution or should a specific AI implementation be included within the pathfinding routine? I would highly appreciate references (academical or not) with state of the art implementations of local avoidance for me to explore the most recent developments in that field. Many thanks.


Is it possible to have FixedUpdate execute once every n frames? I'm currently building a small game, and I've created this simple character controller using FixedUpdate, which executes every frame. using UnityEngine public class PlayerMovement MonoBehaviour lt summary gt Check for a key press, and if that key is pressed, move in a specified direction if there are no obstacles. lt summary gt private void MovePlayerOnKey(KeyCode keyCode, Vector3 direction) Collider hitColliders Physics.OverlapSphere(this.transform.position direction, 0.1f) if(Input.GetKey(keyCode) amp amp hitColliders.Length lt 0) this.transform.position direction lt summary gt FixedUpdate is used to ensure that the player is moving in sync with the step of the Physics engine, and not executing a variable amount each frame. lt summary gt public void FixedUpdate() this.MovePlayerOnKey(KeyCode.W, new Vector3(0, 1f, 0)) this.MovePlayerOnKey(KeyCode.A, new Vector3( 1f, 0, 0)) this.MovePlayerOnKey(KeyCode.S, new Vector3(0, 1f, 0)) this.MovePlayerOnKey(KeyCode.D, new Vector3(1f, 0, 0)) While the code itself works, the player moves much too fast for my liking, and I can't change the step of the player either, it has to stay at 1 in order for other game mechanics to function properly. The only solution I can think of is changing how FixedUpdate runs by running it less often. Is it possible to make FixedUpdate run once every n frames?


Game build in unity3d project transfer from a previous developer Can someone help or give me some idea what are the necessary deliverables from a previous developer that I need to ask regarding the game project transfer? The situation is, there is a company that is developing our game in unity3d and it is already available in Apple store and Playstore. They developed it from scratch and on our part, we are just doing the game testing process. So now, we are going to ask them to transfer the entire project development to us. The company is in another country so we are just communicating thru emails, and we never done the communication by video calls. And That's it. what are the things they need to transfer to us? Thanks in advance.


NullReferenceException until tile is spawned I have a tile and tile has enemies spawn positions, and spawner script in it. Everything works fine when tile is spawned, my ray hits the collider in tile and enemies get spawned, but my spawn script is in tile my ray script is in my player so im reaching from my PlayerMove script to spawner script, but until my tile is spawned i get this error NullReferenceException Object reference not set to an instance of an object because tile is not spawned yet after its spawned error stops, but after tile is deleted it starts again how can i get rid of this error. PlayerScript private Spawner spawner private RaycastHit hit private void Update() spawner GameObject.FindGameObjectWithTag("Spawner").GetComponent lt Spawner gt () DrawRay() private void DrawRay() Ray ray Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)) if(Physics.Raycast(ray,out hit)) if(hit.collider.tag "SpawnerCollider") if(hit.distance lt 5) Destroy(hit.collider) spawner.Spawn() SpawnerScript public Transform spawnPos public GameObject fireBall public void Spawn() for (int i 0 i lt spawnPos.Length i ) Instantiate(fireBall, spawnPos i .position, Quaternion.identity)


Collisions and Colliders Does anyone know how to prevent a gameobject from colliding with another gameobject but can still register collisions? Like a ball that can bounce off of the wall or ground and can pass through the player himself. What I have tried Creating two Colliders on the ball(which has a rigidbody component) and making one of them bigger than the other (and turn on quot Is Trigger quot on the bigger collider). Then write code in the OnTriggerEnter and the OnTriggerExit functions to disable enable the smaller collider so that the ball could fly right through the player. But that is completely useless when the ball is not in motion and the player walks over it(because it'll fall straight down through the ground).


Camera that pivots in the direction that the player is moving I'm trying to recreate Rocket League's freeform (non ball locked) camera, which basically is a camera that follows the player but pivots to allows face the direction the player is moving in (not necessarily facing). Here's a video of Rocket League's implementation for reference https www.youtube.com watch?v RSpB6ocrIX8 amp t 37s What are the main things needed to accomplish this?


UV mapping Untextured faces? Im currently trying to texture a (transparent) cylinder. I want the texture image to wrap sideways around the cylinder but not the top and bottom faces, they are supposed to just stay untextured (so transparent, in this case). So what I did (in Blender) is UV unwrap only the side faces and leaving the top and bottom faces as they are. However, this method doesn't seem to work very well, because when I import the .obj in Unity the top and bottom faces are mapped to a "random" place in the texture and therefore have color. My current workaround is to map the top bottom faces to areas in my texture that are transparent, however, this only works when textures have a transparent place, which isn't always the case.


How do I use rigidbody2d.AddForce to apply a force in the direction the object is facing? I'm trying to create a thruster on a spaceship. It should add this thrust in the direction the thruster is facing, but I am at a loss on how to get that direction and send it to AddForce. Am I even heading in the right direction with this script? public float maxThrust FixedUpdate() float moveVertical Input.GetAxis("Vertical") maxThrust Vector3 heading rigidbody2D.transform.eulerAngles Vector2 thrust new Vector2(heading.normalized.x, heading.normalized.z) rigidbody2D.AddForce(thrust moveVertical) Maybe I'm not understanding something with EulerAngles or Vectors, but it sure seems like this would be a straightforward thing to do.


Load all materials with loadallassetbundles before objects? I have a lot of objects as assetbundles and they're growing. I didn't want to have the user to download the materials for every asset because they all share their materials. so I put all the materials in an assetbundle and load it by LoadAllAssets() in the Awake() function so they are present in the game for the assets to use. The problem is that asset load without materials. the ones that have material don't have shader. Is LoadAllAssets() not the answer? what should I do?


Something is preventing my NavMeshAgent from moving I apologize for the vague title. I really wish I could ask something more specific, but I can't. I had my click to move script working fine with the NavMesh. I showed it to my colleague earlier today, and must have accidenntally made a change and saved. Now the guy's not walking. There are no errors and my debugging leads me to believe all code paths are working as expected. When I click on a location, it checks that it is valid on the NavMesh, then updates the NavMeshAgent's destination I am not going to post the code because I don't think the problem resides there, but rather it was something I did in the editor. The character also turns in the correct direction, and starts the walk animation correctly, but it looks like something is blocking its movement, and I can't figure out what that is. The following screenshots will help clarify my situation. Note that the camera is shaking because its position is set to match the character's in Update. The character appears to be colliding with something, which makes it look like the camera is colliding too (note this is not a physics based game in any way). edit here's some more screenshots, showing the person slightly above the ground and their collider (it's the box near their feet). I disabled the collider on the floor so there are no colliders other than the player's.


Image looks GOOD on the editor but BAD (blurry) on the HTML5 export I have a red bar that looks good inside Unity editor, but when I export the build it looks very strange. Any idea on how to fix this? The image on the left is the one with the strange bad looking red bar...


How to move Character according to Camera's look direction? Vector3 newPosition new Vector3( horizontal, 0.0f, vertical) transform.LookAt(newPosition transform.position) transform.Translate(newPosition MoveSpeed Time.deltaTime, Space.World) I'm developing 3d mobile game, you can look around with hold amp sliding the right side of the screen and move with virtual joystick. Goal Moving character to camera's lookDirection Issue is When i push joystick up, character moves to the same direction (world related) And I'm not good at coding that's why i can't solve the problem myself, i would be glad if you help me


Workflow to have character look like Tokyo ghoul re Call to exist I am looking into a lot of different software and now that I got my head around most of them, I was asking mysel if someone knew what has been used to create the characters in the game I mentionned. Not specifically software if there is no information about it, but at least as it been modeld sculpted, etc. Thanks


How can I scale my UI elements to the lesser screen dimension in Unity 5? I want to create a custom mobile pad for my game. The mobile pad consists of two parts (both inside an ui canvas) The D Pad, which will be anchored to the bottom left side. The button group will be anchored to the bottom right side. I would like to resize the element on different resolutions, so that the element (in my case, the D Pad is an image) Has a size of 20 of the minimum of the width and the height. Has pivot of x 0.5, y 0.5. Having anchor of left bottom, its coordinates are (15 , 15 ) wrt the minimum of the width and the height. What I tried is to use an Aspect Ratio Filter in the D Pad image with ratio 1, but it did not work as intended (the coordinates led the image to an unexpected place). Note I am a n00b to Unity. I don't know whether it is right but my Canvas Scaler scales by Constant Pixel Size These images should illustrate what I want to achieve What should I do to make it work like in the pictures? Edit I attached this behavior, based on answer, to handle the change by runtime RequireComponent(typeof(UI.CanvasScaler)) class CanvasSmartScaler MonoBehavior private CanvasScaler scaler void Start() scaler GetComponent lt CanvasScaler gt () void Update() OMITTED CODE here I set the scale mode as in the Editor but right now i am in my mobile device and cannot remember the exact lines if (Screen.currentResolution.width lt Screen.currentResolution.height) scaler.matchWidthOrHeight 0 else scaler.matchWidthOrHeight 1 And attached that behavior to the canvas. However, for my debug exe (just for debug purposes) it always picks the 1 case regardless how do I resize the window. What am I missing?


How can I make 2D fog like in Graveyard Keeper? I really like Graveyard Keeper's fog effect but I can't work out how to make it. It's 2D, and made in Unity. The characters all seem to be 'under' the fog, but the tops of tall trees and buildings poke out. It looks like this The developer has given a bit of information about how it's made on Gamasutra http www.gamasutra.com blogs SvyatoslavCherkasov 20181023 329151 Graveyard Keeper How the graphics effects are made.php "As you see, the tops of houses and trees are seen from the fog. In fact, this effect is really easy to make. The fog consists of a great deal of horizontal clouds spread across all the picture. As a result the upper part of all the sprites is covered with a fewer amount of fog sprites " I used the information from this article, and one of the developer's tweets that included this picture I attempted to recreate it this fog effect. When the character moves up or down the screen, it flickers as it crosses each fog sprite What have I missed? All of the sprites are on the default sorting layer and have sorting order 0. The project, in Graphics Settings Camera Settings has the custom axis and sort axis (0,1,0). The tree and character are on the same z position, and the fog is spread out over several z positions


Unity how to save the number of successive wins? I'm making a trivia game on Unity, everything works fine and now I'm trying to save and retrieve the stats of a game. I have listed most of the stats (score, highscore, points) but now I would like to add the best series of consecutive correct answers, and I don't know how I can exactly set this value. In theory I know that during the game when a correct answer is given, a counter is triggered to record the number of consecutive correct answers and it stops at the wrong answer. Then at the next triggered series the method checks if the new count is the best. But, as I'm a beginner, I don't know how I can save this kind of streak. Could you help me please? In order to understand the context public class ansButtonScript MonoBehaviour public Text txt public Sprite im basic, im corr, im wrong region Pts amp Score public int points 1 string allPts "totalPts" static int totalPts static int score 0 string score "score" static int hiscore 0 string hiScore "hiScore" endregion public AudioClip sound win, sound loose public GameObject correctTxt, wrongTxt region Cache Refs public GameObject canvas, barInt private qManager qManagerCanvas private progBarScript progBarInt private countdownScript barCountdown endregion public void Start() totalPts PlayerPrefs.GetInt( allPts) qManagerCanvas canvas.GetComponent lt qManager gt () progBarInt barInt.GetComponent lt progBarScript gt () barCountdown barInt.GetComponent lt countdownScript gt () public void updateTxt(string str text) txt.text str text GetComponent lt Image gt ().sprite im basic public void SelectButton() if( qManagerCanvas.canPlay) progBarInt.barTimeStop() qManagerCanvas.canPlay false string reponse qManagerCanvas.reponse if(transform.Find("Text").GetComponent lt Text gt ().text reponse) good answer GetComponent lt AudioSource gt ().PlayOneShot(sound win) SFX Win vraiTxt.SetActive(true) animation Correct updateTrue() the answer is shown StartCoroutine(addPoints()) StartCoroutine(next question()) new question else wrong answer GetComponent lt AudioSource gt ().PlayOneShot(sound loose) fauxTxt.SetActive(true) updateFalse() the answer isn't shown StartCoroutine(next question()) new question barCountdown.ResetTimer() IEnumerator addPoints() yield return new WaitForSeconds(2.2f) playerStats.UpMoney points score set the nb of correct answers saveAllPts() save the nb of points PlayerPrefs.SetInt( score, score) save the nb of corr answers SaveBestScore() save best score IEnumerator next question() yield return new WaitForSeconds(3f) qManagerCanvas.tirage() barCountdown.ResetTimer() correctTxt.SetActive(false) wrongTxt.SetActive(false) public void updateTrue() GetComponent lt Image gt ().sprite im corr public void updateFalse() GetComponent lt Image gt ().sprite im wrong public void SaveBestScore() if (score gt PlayerPrefs.GetInt( hiScore)) PlayerPrefs.SetInt( hiScore, score) public void saveAllPts() totalPts points PlayerPrefs.SetInt( allPts, totalPts)


Unity Shadow shows on my Android device but NOT my Windows Mobile device Unity version 2017.1.1f1 Problem I'm using Directional Light. Shadow is not showing in my Windows Mobile device (Lumia 640 XL), but works fine when I run the exact same UWP project as PC (Local Machine) as well as Android. Attempted solutions 1) Quality Setting I even removed the rest of levels and left only 1 level of quality. 2) Both soft and hard shadows, 10 Shadow distance, Stable Fit of shadow projection, very high resolution, low resolution, No Cascade. 3) Tried realtime and mixed light mode. any idea? Thanks in advance for read my question. Screenshots Windows 10 Mobile (Lumia 640 XL) Android (Redmi Note 3)


Need help with a field of view like collision detector! I ran into a trouble while making a field of view for my character. I figured how to make it work with a Linecast, but what I really need is a cone shaped field, so that the character can detect objects or enemies if they get in that field of vision. It also needs to be intersectable by other objects, so OnCollisionEnter won't work. I suspect that Raycasting might solve the problem, but I couldn't quite understand it's workings, because I'm still new. I would really appreciate any ideas that might help to solve it. Here is what I need Here is what I have so far, but this detector is unsuitable, because it can only detect objects in a straight line public Transform sightStart, sightEnd Update is called once per frame public bool objectSpotted false void Update () Raycasting1 () void Raycasting1() Debug.DrawLine(sightStart.position, sightEnd.position, Color.green) objectSpotted Physics2D.Linecast (sightStart.position, sightEnd.position)


Voxel terrain engine Is there some voxel frameworks or extensions for game engines like Unity? I really need a system to dynamically generate voxel ruinable terrains.


Animation works well on preview but not when hitting play I'm using a simple animation where I want to move an sprite just a little bit bellow its current position, and this works well on preview mode in the Animation tab. But as soon as I hit play, the value I'm trying to animate is not the same as the one in the keyframe, the value is lesser than the one I setted. I don't know what I'm doing wrong... I'll append a clip showing this problem. I already tried turning on and off Apply Root Motion and some alike questions, but none of the solution worked for me so far...


Adding underwater shadow to 2D top down boat I have a boat hovercraft sprite in my game. It's topdown 2D view, but it's actually a 3D scene, for better lighting and other effects. I want to add a buoyancy effect, so that the hovercraft floats with the waves and has a little margin for going under water, like a real boat. So when idle or when going off a ramp, when landing in the water it will kinda "bounce" a bit under and then back up. But the problem is the water and boat sprites are on top of each other (because it's 2D). See this picture So it can not go underwater, because then the water will be on top. But I still want those edges of the vehicle to be a bit darker as it floats. I already have an effect that changes the Y value to make it float up and down. But now the edges have to become a bit darker to show they go underwater. I kinda have this idea to add a 3D capsule and make it move up and down through the sprite to simulate this So as the boat and the capsule go down with each wave, it could mask the sprite, and the visible part (marked with black lines in the image below) could be made darker. To simulate the "under water" effect. Later I will also add foam and stuff, but the first problem is the underwater part. So how could I mask my sprite inside this capsule, and more importantly, make the "outsides" (so the parts of the sprite not touching the capsule darker? Any help would be greatly appreciated! )


Fix Unity Line Renderer for pointer drawing a jaggy line I think I'm using the standard Oculus setup from the SDK using the OVRCameraRig. I've also got a LaserPointer. But inside VR on my Rift the line looks like this. Any idea what I'm doing wrong? It used to be straight. Now it's not. I don't know what I changed.


My camera does not rotate around player in 3d open world I want my camera to following behind the player at all times. When the player turns to the left, I would expect the camera would move behind the player while remaining focused on the player. My camera stays focused on the player. However, it does not rotate to stay behind the player. I tried following the directions from here, and here. Neither of which seems to help. Here's my code public class CameraFollow MonoBehaviour private GameObject player private GameObject mainCamera private Vector3 offset private float distance private Vector3 playerPrevPos private Vector3 playerMoveDir Use this for initialization private void Start() player GameObject.FindGameObjectWithTag("Player") mainCamera GameObject.FindGameObjectWithTag("MainCamera") Calculate and store the offset value by getting the distance between the player's position and camera's position. offset transform.position player.transform.position distance offset.magnitude playerPrevPos player.transform.position Update is called once per frame private void Update() private void LateUpdate() playerMoveDir player.transform.position playerPrevPos if (playerMoveDir ! Vector3.zero) playerMoveDir.Normalize() transform.position player.transform.position offset transform.LookAt(player.transform.position) transform.rotation Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime 1) mainCamera.transform.position player.transform.position offset mainCamera.transform.LookAt(player.transform.position) mainCamera.transform.rotation Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime 1) playerPrevPos player.transform.position I have done something a little different, per instructions from a online unity class. My main camera is a subobject of a rootobject, as shown in this picture. I have attached image of the game with the yellow line showing which way the player is facing. The camera is facing in a different direction. Any help would be appreciated. Thnx Matt Follow up from answers I cannot get either solution to work. alejandrodlsp solution doesn't compile (I've added a comment to the answer explaining why). If I do not set offset on Start (aka its always 0), then the camera rotates. The problem is that is at the feet the player and not behind like I wanted. Once I compute offset, then the camera never rotates behind the player.


How to force a custom component on every GameObject? I want to have a custom component which will have a drop down. I want this to be applied to ever GameObject in the project, which means every GameObject in the hierarchy and every GameObject prefab. Something like a transform component. It should not be removable, and it should be added by default when creating new GameObjects. In the drop down, I will select a few options, and I want to store those values in an array on that custom forced component for that GameObject. So if I have 2 new GameObjects in scene named XYZ and ABC, and the component is PQR, I should be able to do this ABC.GetComponent lt PQR gt ().someArrayVar whatever XYZ.GetComponent lt PQR gt ().someArrayVar anotherWhatever Anyone know how to do this? Any help appreciated. Thanks in advance )


How do I position a mesh just outside the camera view? I want to slide in an object into view, coming from the right of the screen. In order to achieve this, I need to position the object next to the camera view, so that it is still not visible, but close enough for a quick slide in. For example, placing the object at X 1000000 (so that it is surely outside the camera view) for safety wouldn't work as it couldn't slide in quickly enough. For a reasonable slide, I would need to have it really close next to the camera view. How could I calculate the object's position for that? Thank you. Edit Here is the script that I'm now using and which I'm still having problems with using System.Collections using System.Collections.Generic using UnityEngine public class NewBehaviourScript MonoBehaviour void Update() float fDist Mathf.Abs(Camera.main.transform.position.z this.transform.position.z) Bounds b BoundsFromTransform(this.transform) this.transform.position GetPointLeftOfCamera(Camera.main, fDist, b.size.magnitude 2) public static Bounds BoundsFromTransform(Transform uTransform) Bounds bounds new Bounds(uTransform.position, Vector3.zero) foreach (Renderer renderer in uTransform.GetComponentsInChildren lt Renderer gt ()) bounds.Encapsulate(renderer.bounds) Vector3 nOff bounds.center uTransform.position return new Bounds(nOff, bounds.size) public static Vector3 GetPointLeftOfCamera(Camera camera, float distance, float goDiameter) 1. var ray camera.ScreenPointToRay(new Vector3(0, camera.pixelHeight 2f, 0)) 2. var borderPoint ray.GetPoint(distance) 3. var leftPlane GeometryUtility.CalculateFrustumPlanes(camera) 0 var frustumLeft leftPlane.normal 4. var halfDiameter goDiameter 2f return borderPoint frustumLeft halfDiameter public static Vector3 GetPointRightOfCamera(Camera camera, float distance, float goDiameter) var ray camera.ScreenPointToRay(new Vector3(camera.pixelWidth 1, camera.pixelHeight 2f, 0)) var borderPoint ray.GetPoint(distance) var rightPlane GeometryUtility.CalculateFrustumPlanes(camera) 1 var frustumRight rightPlane.normal var halfDiameter goDiameter 2f return borderPoint frustumRight halfDiameter


How can I make Iridescence material In unity? One of the characters of the Dota2 that Is called Nyx Assassin has an interesting material effect If you look at the body and feet you can see this effect.It looks like poily polluted water.I like to know how can I make something like that In unity.