Using PlayerPrefs to save audio volume throughout scenes in Unity I have game that plays music. I have a mute toggle button that will mute my game music when you press on it, it will also un mute it when you press it again. I'm having problems with saving the audio volume when a scene is loaded. (I tried using DontDestoryOnLoad but my mute script is attach to my main menu canvas so its saving the canvas as well, which I do not want. I find using playerprefs a lot easier). For example, when I click on my mute button, it mutes my game, I play the game, die, restart the game and the volume is being restarted as well. Even though I used playerprefs to try and solve the problem it didn't work, it still did the same thing. Anyway this is my script public bool mute public static Vector3 target void Start () PlayerPrefs.GetFloat("mute") void Update() PlayerPrefs.GetFloat("mute") private void Muted () mute !mute if (mute) gameObject.GetComponent lt AudioSource gt ().volume 0 PlayerPrefs.SetFloat("mute", 0) else gameObject.GetComponent lt AudioSource gt ().volume 1 PlayerPrefs.SetFloat("mute", 1)


Elongated and straight terrain perlin noise Why am I getting this kind of results with my perlin noise ? The terrain is wide or elongated or straight at the variations of the noise function. This is the way I generate terrain public void GenTerrain() for (int x 0 x lt this.size.x x ) for (int y 0 y lt this.size.y y ) float xCoord (float)(x offsetMirror origin.x) this.size.x scale float yCoord (float)(y offsetMirror origin.y) this.size.y scale float noise Mathf.PerlinNoise(xCoord, yCoord) if (noise gt 0.6f) this x, y .terrainType TerrainType.Grass else if(noise gt 0.5f) this x, y .terrainType TerrainType.Sand This is the way I add chunks of terrain void Start() maps new Dictionary lt Vector2Int, Map gt () Res.LoadMaterials() void AddNeighbours(Vector2Int position) int length 32 for(int x length x lt length x ) for(int y length y lt length y ) Vector2Int addPos new Vector2Int((x size) position.x, (y size) position.y) CheckAndAddMap(addPos) void CheckAndAddMap(Vector2Int addPos) if (!maps.ContainsKey(addPos)) AddMap(addPos) void AddMap(Vector2Int origin) Map map new Map(new Vector2Int(size, size), origin) maps.Add(origin, map) MapMesh mapMesh new MapMesh(map) foreach (KeyValuePair lt TerrainType, MeshData gt kv in mapMesh.meshes) MeshData meshData kv.Value TerrainType terrainType kv.Key GameObject go new GameObject( quot Mesh quot ) go.transform.SetParent(this.transform) go.transform.localPosition new Vector3(mapMesh.map.origin.x, mapMesh.map.origin.y, (int)kv.Key) MeshFilter meshFilter go.AddComponent lt MeshFilter gt () meshFilter.mesh meshData.mesh MeshRenderer mr go.AddComponent lt MeshRenderer gt () mr.material Res.mats terrainType.ToString() Update is called once per frame void Update() Vector2Int playerPosition ConvertPlayerPositionToTiles(ShootBehaviour.PlayerInstance.transform.position) AddNeighbours(playerPosition size) private Vector2Int ConvertPlayerPositionToTiles(Vector3 position) Vector2Int result new Vector2Int() result.x (int)position.x size result.y (int)position.y size return result


Unity Smooth collision I'm making a topdown 2D RPG in Unity. All moveable objects have Rigidbody2D components with gravity set to 0, linear drag set to 5 and different masses. Walls are stationary boxes with BoxCollider2Ds. Here's my problem http a.pomf.se nifmcn.webm The rock is not particularly easy to see, but if you watch when I'm trying to walk into a wall, the player kind of jags in and out of the wall. Of course, this is because I'm moving the player by moving it's Rigidbody2D, for example rigidbody2D.transform.position Vector3.up Time.deltaTime speed The box then throws the player in the opposite direction of what he was going. What's a good way of stopping a player from moving in the direction he's trying to go? More specifically, how do you detect which way he's going? Do you find the angle between the player and the object wall? This is kind of an open question, but I think it's extremely important.


2D physics without "rebound" I'm trying to get my 2D top down shooter to use some physics. I want the player and enemies not be able to exist in the same position, in other words, use collisions. My first attempt was to use a CharacterController, but I could not get my other game objects to collide with my player, even though I had a RigidBody2D and a BoxCollider2D on them. Obviously, due to using a CharacterController, I was not able to add these components on my player. Going one step back, I removed the CharacterController, and rather opted to go the Rigidbody2D route. This worked partially. I now get collisions on my player when he walks into other gameobjects (with RB2D and BC2D on them), but there seems to be a quot rebound quot anomaly occurring my player moves around after collision. I've tried playing around with the settings on the RigidBody2D on the player, but it does not seem to have any effect. This is my PlayerMovement script void Update() HandleRotation() HandleMovement() void HandleRotation() var mousePos Input.mousePosition mousePos.z 5.23f var objectPos Camera.main.WorldToScreenPoint(transform.position) mousePos.x objectPos.x mousePos.y objectPos.y float angle Mathf.Atan2(mousePos.y, mousePos.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(new Vector3(0, 0, angle)) void HandleMovement() float horizontal Input.GetAxisRaw(Constants.Axis.Horizontal) float vertical Input.GetAxisRaw(Constants.Axis.Vertical) Vector3 direction new Vector3(horizontal, vertical, 0f).normalized if (direction.magnitude gt 0.1f) var speed (Input.GetKey(KeyCode.LeftShift) Input.GetKey(KeyCode.RightShift)) ? mobileController.runningSpeed mobileController.walkingSpeed var moveVector (direction speed) transform.position mobileController.rigidbody2d.MovePosition(moveVector) var camPosition new Vector3(mobileController.transform.position.x, mobileController.transform.position.y, 10) cam.position camPosition The settings on my Player I would like my player to stop dead in his tracks when colliding with another RigidBody2D. Is this possible? And if so, how would I go about doing that?


Unity3D Facebook login into the game Verification on Server Side I don't need to know the specific code required for that, but I want to understand at high level how can I implement that and what SDKs I have to use to achieve that. Facebook PHP SDKs Ok If I want to perform login with Facebook into my web page. Unity3D's Facebook SDK Ok If I want to perform login inside my App without a server (apart Facebook's servers of course). What I want to achieve is User login into facebook from the App (just once, and eventually the option to log out on request of user, or to relog if login data expires) Login is verified by my Server (actually a user should really have a facebook account) Do not embed stuff like Facebook App ID in my App source code. My server will store some data for each user and to identify users I need to be able to use some unique data provided by Facebook like session token etc. Of course the session token may change so I need anyway to be able to identify the user (to avoid losing memorized data).


How to start simple game development with Unity 5 I want to start developing games with Unity because it's easy to learn, but I don't know where to start. My questions are Which preparations should I make for a game? Are there any tips and tricks for efficient work? Do I need special equipment? Thank you for your response!


Create prefab asset from object without creating object in the scene I am writing an editor tool that is supposed to generate prefab objects from a parsed TMX file. Since this is a special case because I don't want to instantiate objects, but rather create them there are not much documentation on how to do this. I have come up with a way that actually creates an .prefab file from a gameobject. But the problem is that when I do this, the gameobject itself is created and put into the hierarchy. I only want the .prefab asset file. This is they way I am doing it now. static void ConvertFile(string filepath) This function returns a "new GameObject()" with attached components However, this function still puts the new game object in the scene amp hierarchy which is not what I want GameObject mapObject mapLoader.fromFile (filepath) string filename System.IO.Path.GetFileNameWithoutExtension (filepath) Create prefab file from an object PrefabUtility.CreatePrefab ("Assets " filename ".prefab", mapObject) public GameObject fromFile(string filepath) Removed code that parses file for easy read GameObject gameObject new GameObject () return gameObject


Unity 2d, Place object nearest to a coordinate without overlap? I am working on a game similar to Pool (Carrom actually). I need to place coins at the center of the board or nearest possible to it without overlapping any other coins. This is a 2d game.


How to make a character that moves like a slinky? I have a school assignment to make a 2D platformer game, with a character that moves like a slinky (Animated example from the assignment linked above) At first, the character needs to grow in height over time When the player presses a button, the character starts to bend toward the next platform Its height when you press the button determines whether it will hit the next platform After that it must shrink to its initial size, and it goes over again. How can I approach this?


Causing Update loop with Coroutine Unity Total Noob Alert! lt 7 days with C and Unity My Win Game screen becomes SetActive and my Player is SetActive false when you are standing in a trigger and crouch. That all works fine except you cant see the crouch animation because he is IMMEDIATELY SetActive false. I tried to delay this by creating a coroutine. The problem with that is this is all happening in the Update function (or whatever it's called) because of the getkeydown for crouch. That gets called once per frame so my coroutine is trying to go off once per frame. I tried creating a bool called isCoroutineStarted and set it to false and then set it to true in the Coroutine to break the loop but that didn't work either. Don't know what to do so I reverted it back to before where it doesn't show my crouch animation. Here's my script (It's attached to a Game Object with the trigger) using System.Collections using System.Collections.Generic using UnityEngine public class xxxxxx MonoBehaviour public bool xxx false SerializeField private GameObject youWinUI SerializeField private GameObject player Determines whether or not the player is standing on the xxxxx void OnTriggerEnter2D (Collider2D other) xxx true void OnTriggerExit2D (Collider2D other) xxx false Turns on Win screen and makes player disappear when crouch on xxx void Update () if (Input.GetKeyDown (KeyCode.S) amp amp xxx true) youWinUI.SetActive (true) player.SetActive (false) P.S. ignore the x's no stealsies lol. Also this piece of script works as intended I just want a delay so you can see the crouch animation.


Collision2d Unity To Change Another Scripts Int Value I am looking to decrease the value stored in my script "progress" which takes 1 away from a value curHealth, when the Player sprite to which this script "collision", is attacked touching the Enemy 2d box collider. The decreasing of the value doesn't happen when the two objects touch. Both the Player and the Enemy have 2dbox colliders and other shape 2d colliders. using System.Collections using System.Collections.Generic using UnityEngine public class collision MonoBehaviour public progress Progress GameObject.FindGameObjectWithTag("HealthBar").GetComponent lt progress gt () void OnCollisionStay2d(Collision2D coll) if (coll.gameObject.name "Enemy") Progress.curHealth 1


The name 'txt' does not exist in the current context I am getting the error The name 'txt' does not exist in the current context and I am unsure why this is happening. I am very new to programming in C so sorry if the answer is obvious. I am trying to make my ammo count change on screen and have been told to use txt.GetComponent lt UnityEngine.UI.Text gt ().text ammo.ToString() but that gives me the error and I am unsure why. This code is supposed to spawn in bullets for my gun but that part of the script is not important. The problem is that error. If you could tell me what the problem is that would be greatly appreciated. Here is my code using System.Collections using System.Collections.Generic using UnityEngine.UI using UnityEngine public class PL MonoBehaviour public GameObject bulletPrefab public Camera playerCamera private Coroutine hasCourutineRunYet null public int ammo 165 65 enemies in total, needs tons of ammo public GameObject axe public Text Ammmo Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) if (hasCourutineRunYet null) hasCourutineRunYet StartCoroutine(BulletShot()) if (ammo 0) GameObject.Find( quot wp shotgun quot ).SetActive(false) axe.SetActive(true) txt.GetComponent lt UnityEngine.UI.Text gt ().text ammo.ToString() IEnumerator BulletShot() GameObject bulletObject Instantiate(bulletPrefab) bulletObject.transform.position playerCamera.transform.position playerCamera.transform.forward bulletObject.transform.forward playerCamera.transform.forward yield return new WaitForSeconds(1.0f) hasCourutineRunYet null ammo


The rightmost part of the game screen is truncated in HTML I created a game that, when I play it in Unity, looks like this But when I build it in WebGL, the rightmost part of the screen (with the red player character in it) is truncated Play it in browser on itch.io to confirm. It looks the same when I open the HTML file locally, so the problem is with the WebGL version and not with itch. Only when I click the "full screen" button, the rightmost part is shown. What am I doing wrong?


"Hold to jump higher" suddenly outputs a much higher jump I'm programming my first game in Unity and I'd like to make a very controllable jump. The idea is to apply an upward force while the player is still pressing the jump button, and then after some time ignore jump input. Kinda like how Mario and Mega Man jump. Problem is, somehow, my character occasionaly jumps much higher than it normally does. I set three variables on the inspector jumpImpulse the initial speed after pressing the jump button riseAcc the acceleration applied to the character while holding the jump button maxJumpHoldTime the longest possible time one might hold the button while still rising. if ((onGround onPlatform) amp amp Input.GetButtonDown("Jump")) GetButtonDown prevents holding jump and keeping jumping rb.AddForce(Vector2(0,(jumpImpulse rb.mass)), ForceMode2D.Impulse) force that starts the jump itself. rb.mass makes F ma into F ma m gt F a, so "Force" is actually acceleration. This is to better control mass and jump mechanics. jumping true DEBUG debugJumped true if (jumping amp amp Input.GetButton("Jump")) rb.AddForce(Vector2(0,(riseAcc rb.mass)), ForceMode2D.Force) first acceleration jumpHoldTime Time.deltaTime if (jumpHoldTime gt maxJumpHoldTime) jumping false else jumping false jumpHoldTime 0 Made this so I know how high the character jumps. if (debugJumped amp amp (!onGround) amp amp rb.velocity.y lt 0) Debug.Log ("Jump height is " transform.position.y) debugJumped false In the console, the jump height is listed normally as 2.376213, but sometimes it appears as 5.008272. It appeared once as 2.377432. Also, this variation seems to appear more frequently when I'm also moving the character left or right. And I'm not sure if this is related, but there are many times when I press the jump button and the character simply doesn't jump. Also, I put everything here under the FixedUpdate function.


How do I make an object not appear grey regardless of distance? My moon texture is on a plane 500m away and I would like to know if there is a way to keep displaying the texture As opposed to it turning grey as pictured here regardless of the distance it is from the camera. Any help is greatly appreciated, Thanks.


Loading a web page in unity Hello I need to open a page in unity and save some of it's contents but I have absolutely no idea how I should do it. Thanks for help.


Non invocable memeber 'Text.text' can not be used as a method Trying to change text in a text box, and have multiple lines on it, i found something online talking about quot n quot but this came up. Non invocable memeber 'Text.text' can not be used as a method. This is my code private void Start() if (creditEnding) startText.text( quot You, died? n well you should get some sleep anyways quot )


Unity Capture And Display Live Camera Feed I want to display the video using the device camera on specific part of the screen on iOS, android and Editor. I was able to find the WebCamTexture which display the camera video on the Quad (3D Object). Now I want to record the video and save it on the disk. Is there are way to do that ? Or is there a better way to do that using unity or through plugin ?


When when pressing on the G key one of parts is scaling slower then the other? Each Prefab is built with canvas and two panels childs of the canvas. I'm scaling the two panels. The automatic mode part is working fine. The problem is with the G key. When I press once on G it's scaling both panels up to maxSize then when pressing on G once again it's scaling the panels back down to minSize. But when I press on G quick in the middle while it's scaling them it should turn the scaling side in the middle. For example if I press G and both panels start scaling to maxSize if in the middle I press on G again it should scale them both to minSize without getting first to the maxSize. But in this case one of panels is keep scaling to maxSize a bit and then move back to minSize. But they both should turn side in the middle at once. It seems like one of them have a lag he turn sides a bit after the first one. using System.Collections using System.Collections.Generic using UnityEngine public class Scaling MonoBehaviour public GameObject Prefab public int numberOf 1 public float duration 1f public Vector3 minSize public Vector3 maxSize public bool scaleUp false public Coroutine scaleCoroutine public bool automatic false public bool coroutineIsRunning false private List lt GameObject gt parts new List lt GameObject gt () private void Start() for (int i 0 i lt numberOf i ) GameObject objecttest Instantiate(Prefab) foreach (Transform child in objecttest.transform) parts.Add(child.gameObject) private void Update() if (automatic) if (!coroutineIsRunning) Scale() else if (Input.GetKeyDown(KeyCode.G)) Scale() private void Scale() scaleUp !scaleUp if (scaleCoroutine ! null) StopCoroutine(scaleCoroutine) for (int i 0 i lt parts.Count i ) if (scaleUp) scaleCoroutine StartCoroutine(ScaleOverTime(parts i , maxSize, duration)) else scaleCoroutine StartCoroutine(ScaleOverTime(parts i , minSize, duration)) private IEnumerator ScaleOverTime(GameObject targetObj, Vector3 toScale, float duration) float counter 0 Vector3 startScaleSize targetObj.transform.localScale coroutineIsRunning true while (counter lt duration) counter Time.deltaTime targetObj.transform.localScale Vector3.Lerp(startScaleSize, toScale, counter duration) if (counter gt duration) coroutineIsRunning false yield return null


Unity sprites are no longer batched after the object rotates moves With Unity 5 and access to the profiler, I'm running our game through some stress tests so I can find where our performance issues are. While testing having 1024 units on the screen with 4 selection box corners each I ran into an odd problem. When I select all the units, 4096 selection box objects come into existence, my draw calls go from 25 to 50 with 50 batches. Now when I tell the units to move, they rotate and the number of batches climbs up to 2090 and the draw calls climb to 2090 and stay there even after the units stop rotating or moving. If I then reselect all the units, the selection boxes are destroyed and re instantiated (I know, not the best way) and the batches and draw calls go back down to 50 from 2090. What is causing this, and how would I go about fixing it? After Selecting All Units After having them rotate and move After Re selecting Them All


Check if all gameobjects are destroyed I am making a shooting game, where I have a countdown as I destroy enemies. I want to implement logic when all the game objects are destroyed within the given time, and the countdown reaches zero. How do I do that?


How to optimize two pass operations on an array with Unity Coroutines I am working on simulating vacuum decompression in a 2D top down environment. I have 2 2 dimensional arrays one that stores the pressure at a location, and one that stores the vector of fluid flow. The algorithm looks likes this private void Flow() Diffuse() Vectorize() private void Vectorize() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... Vector2 flowVector calculate the resultant vector from the pressure differentials O(1) op ... vector x,y flowVector private void Diffuse() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... float newPressure calculate the new pressure from the pressure differentials O(1) op ... pressure x,y newPressure The problem is that as the area of the simulation space increases, the performance continues to drop off as the iteration steps block the update loop. I want to convert these to Coroutines in such a way that both yield but more or less maintain a lockstep appearance. Since flow is dependent on pressure differential, and pressure differential is partially dependent on flow, if an order has to be enforced, then Diffuse should take precedence. My initial attempt followed the following form IEnumerable Flow() StartCoroutine(Diffuse()) yield return null StartCoroutine(Vectorize()) IEnumerable Vectorize() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... Vector2 flowVector calculate the resultant vector from the pressure differentials O(1) op ... vector x,y flowVector yield return null IEnumerable Diffuse() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... float newPressure calculate the new pressure from the pressure differentials O(1) op ... pressure x,y newPressure yield return null This tended to cause a jittery simulation. Even on a small 20x20 simulation field, there was noticeable difference between the first and second solutions. Are there any tricks to coroutines that will allow a more lockstep simulation that scales well? Any suggestions on optimization is welcomed as well.


How can I have cutouts in a texture? I want to be able to have a gameobject that's basically just a black box on top of everything else. Then I want to be able to place other gameobjects which are just gradients on top of that and they should "cut out" of the black texture like this How can I achieve this sort of effect? Please keep in mind that I have pretty much no experience with shaders ) Here's a video that might help explain what I'm trying to achieve https www.youtube.com watch?v L1dd4fkVSAM


How to make AI detect a target behind a wall, who is only partially exposed? I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger. So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed. I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target?


Unity right mouse drag turn How would I use my right mouse button to turn a player character in unity, while only turning in the direction and speed of the drag? Not sure if I'm meant to post this here or stackoverflow. EDIT game is 3D EDIT2 Hold right click and drag to turn the camera Edit3 Got this code using System.Collections using System.Collections.Generic using UnityEngine public class Control MonoBehaviour public int speed public Transform tf Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButton(1)) tf.eulerAngles new Vector3 (0, Input.GetAxis("Mouse X") speed, 0) Code works, but after moving the mouse in the specified direction the character jumps back to its original position and kinda does this glitchy turn while moving the mouse (keeps jumping back to original position) nevermind, I think that I figured it out


How to blend motions with Mecanim I'm struggling with Mecanim. My concern is to blend straight turning animations with strafe animation for a humanoid character. I downloaded a SampleAsset from unity and took Ethan character as example. The animator uses a blendtree which naturally blend idle walking running animations with a smooth turning left right animations. In this case the Ethan character cannot strafe. I'm trying to understand how to blend strafe movement with it's actual straight turning blending motion. Was I somewhat clear?


Detecting mouse clicks in Unity UI Beta I want my game script to detect mouse clicks everywhere on my screen, except one corner where I have a pair of buttons to control the sound and will be handled separately. To help identify this corner, I've created a soundPanel object with the Rect Transform component (available in the Unity 4 Beta 17 ) and have sized positioned it appropriately in the editor in my UI layer. In my game's script, I have passed in this corner object, and tried using it in the following way bool tap (Input.GetMouseButtonDown(0) Input.GetMouseButtonUp(0)) amp amp !soundPanel.rect.Contains(Input.mousePosition) Clicking in the soundPanel still triggers a tap. I figured this is because the mouse position and soundPanel.Rect are not in the same coordinate space. Since the documentation on the new Unity Beta UI is a bit lacking hard to find, I tried converting the mouse coordinates to everything I could if (Input.GetMouseButtonDown(0) Input.GetMouseButtonUp(0)) if (soundPanel.rect.Contains(Input.mousePosition)) print("Raw") if (soundPanel.rect.Contains(camera.ScreenToViewportPoint(Input.mousePosition))) print("ScreenToViewportPoint") if (soundPanel.rect.Contains(camera.ScreenToWorldPoint(Input.mousePosition))) print("ScreenToWorldPoint") if (soundPanel.rect.Contains(camera.ViewportToScreenPoint(Input.mousePosition))) print("ViewportToScreenPoint") if (soundPanel.rect.Contains(camera.ViewportToWorldPoint(Input.mousePosition))) print("ViewportToWorldPoint") if (soundPanel.rect.Contains(camera.WorldToScreenPoint(Input.mousePosition))) print("WorldToScreenPoint") if (soundPanel.rect.Contains(camera.WorldToViewportPoint(Input.mousePosition))) print("WorldToViewportPoint") print(" ") When I click with the above code, "ScreenToViewportPoint" and "ScreenToWorldPoint" print no matter where I click, and no others trigger. I suspect I need to transform the soundPanel somehow. Here is the Hierarchy, Scene, and Inspector. The selected rect is the soundPanel, and it is in the bottom right of the UI Canvas


Canvas enabling is not working I have a canvas with two buttons in it and I want to enable it on the button click, but when I try to enable it, it doesn't work. However, when I try to disable it on button click it does work. Here is my code public GameObject mycanvas public void onClick() mycanvas.SetActive(true) Can someone please tell me what I am doing wrong?


Destroy the enemy only if the animation is played and touch the enemy I am using Unity. I want to attack an enemy with a knife. So I created an object (the knife) and put an attacking animation to it. Now I want to destroy the enemy only if the attacking animation is played and the knife touches the enemy. And if the animation is not played and the knife touches the enemy it should show a game over screen.


How do I detect if my object is grounded? I am trying to detect when an object is grounded. My script right now is using System.Collections using System.Collections.Generic using UnityEngine public class playermovement MonoBehaviour public CharacterController2D controller public Rigidbody2D rb float horizontalMove 0f public float runSpeed 40f Vector2 forceapplied public bool isGrounded public float NumberJumps 0f public float MaxJumps 2 public float jumpHeight 7f public CircleCollider2D bc void Start() forceapplied new Vector2(0.0f, 30f) void Update() if(bc.gameObject.name quot Grid quot ) isGrounded true NumberJumps 0 horizontalMove Input.GetAxisRaw( quot Horizontal quot ) runSpeed if (NumberJumps gt MaxJumps 1) isGrounded false private void FixedUpdate() if (isGrounded) if (Input.GetButtonDown( quot Jump quot )) rb.AddForce(Vector2.up jumpHeight) NumberJumps 1 controller.Move(horizontalMove Time.fixedDeltaTime, false, false) In the inspector it always says that Isgrounded is false. Can someone please help?


OnTriggerExit() called when game object with collider component gets re parented I have an object Hand, with a rigid body attached to it. In every Update() call, the user's hand controller rotation and position are tracked. In my scene, there is an object Pin, with a mesh collider attached to it. In OnTriggerEnter() (inside the Hand class), Pin becomes re parented to Hand. (Pin's original parent is something else.) My scene also contains other objects with colliders. However, these other objects do not get re parented only Pin does. Once this re parenting takes place, OnTriggerExit() (in the Hand class) is called immediately. This is surprising to me I had expected OnTriggerStay() (in the Hand class) to be invoked instead, since Hand is still in contact with Pin. Is such behaviour by design? Is there an elegant way of working around such behaviour? UPDATE In response to this comment Does the pin object have a parent before it becomes a part of the hand? Yes. As mentioned in my post, Pin's original parent is something else. Or is it placed inside another collider? And does the pin leave any of these collider areas when the parenting takes place? As mentioned in my post, Pin itself has a mesh collider component attached to it. Perhaps I am not understanding the question correctly... You can prevent the hand's script from getting this OnTriggerExit by adding a seperate rigidbody to the pin. I added a separate rigid body to the pin (setting isKinematic to true), but OnTriggerExit() inside the Hand class is still called immediately after Pin gets re parented. MORE INFORMATION Pin's original parent (before it gets re parented to Hand) does not itself have a collider component. When OnTriggerExit(Collider collider) gets called immediately after the re parenting takes place, the collider argument passed to the method is the Pin itself.


How to file down a fingernail mesh? I am creating a nail salon 3D game where I need to implement nail filing mechanics. I have tried out approaches including mesh deformation but I'm concerned about performance as I am targeting mobile platforms. How can I shape a nail efficiently for mobile devices?


Is a custom coordinate system possible in Unity Is it possible to create a custom coordinate system (i.e the one using double for coordinates or the one dividing the world into 'chunks' of safe size) not constrained by the floating point precision limitations in Unity, and make systems using the built in coordinate system use that one instead somehow? Thanks!


How to display full website in Unity WebGL? I want to display the complete website within the WebGL in Unity. I have tried Awesomium plugin but it doesn't work in WebGL. Please tell me is there any way to display the webpage. Thank you.


Load a specific sprite by name from a SpriteSheet with Resources.Load I want to avoid loading all the sprites from a sprite sheet into a dictionary. Is there a way to access the specific sprite inside the sheet. Right now I'm using this code prefabImage.sprite Resources.Load lt Sprite gt (spritePath spriteName) But this loads a single sprite. Can I change spritePath to somehow point inside the sprite sheet?


Unity Setting up the Universal Rendering Pipeline for Layer Masking I've been watching this video about Field of View (Player) by CodeMonkey which explains on how to set up a scriptable rendering pipeline for the layer unmasking masking of objects. However, the interface changed with the latest updates. There's an Opaque Layer Mask and there's a Transparent Layer Mask. I've followed the Render Features as described in the video but I wasn't able to get the masking done correctly as there's these two options that I can't seem to figure out what it does. I tried toggling to and from layers to see which one is meant to be in the other one but this is the best I could get For simplicity's sake, these are the layers that I am using Characters (things I want to see when the Field of View mask is over them) player enemy friendly dead Field of view (the unmasking layer) Fog of war (the thing that makes everything have a black transparent fog) UI (the layer that I want to see regardless of the where the Field of view mask is) As of right now, I could see the Field of View and the UI. Everything else is missing. I have asked in their own community however, no one reached out to me. Let me know in the comments if you need more info. edit 1 to reproduce create the following layers (Player, Enemy, FogOfWar, FieldOfView, Wall, UI) Set a game object with sprite component to player, enemy. Set them to the Player and Enemy respectively. This one, we want to see if the field of view layer is on top of it. They will be invisible if the field of view is not on top of it. Place a Sprite Renderer (a square) and set it to the Wall. This one, we want to see regardless if it's masked or not. If the field of view layer is not on top of it, this should be darkened by the fog of war. Set a Mesh Renderer (A simple plane would do) to Field of view and set it above the player and enemy. Make sure the face of the plane is facing the camera. This object would reveal or hide the Player and the Enemy layer. If this is on top of the FogOfWar, the area that the FieldOfView is upon will be invisible. That way, the sprites underneath it is not darkened. Have a sprite renderer (A square) and set it to black with 50 opacity and make it cover the the Player, Enemy, and FieldOfView. Set this to FogOfWar Create a button, and set it to UI layer Create a universal rendering pipeline. head over to the options and add the settings (keep in mind, I don't know what to set here. The Opaque and Transparent Layer Mask are my problem.) a. Opaque Layer Mask Wall, FogOfWar, FieldOfView b. Transparent Layer Mask Player, Enemy For the render features, add these three Behind Masks contain Player amp Enemy edit 2 I forgot. I have three cameras. All orthographic. They only render a specific layer. Main Camera Culling Mask is Wall Character Camera Culling Masks are Player and Enemy UI Camera Culling Masks is UI Character and UI camera have a depth. UI Camera's depth is 0. Character Camera's depth is 1. I want to render the UI below the characters. Hence, I separated them into their own camera.


Unity3D Blender Bounding box rotated on import For some reason my bounding box is always tilted when i import to unity. I've checked for loose geometry and everything but there's nothing.


Disable global fog from camera Does anyone know how to disable global fog from a particular camera? I have two cameras in my scene one is a mini map camera, where I need to disable global fog. I have checked this answer and the wiki, but have found nothing that works.


Same dimension feel no matter what FOV Does anyone know a formula, way, ... to make a FPS player feel like an object has the same size on different FOVs (given that it's at the same distance of the player, of course)? I know that this can't be done perfectly, because of the distortion various FOVs cause and the position of the object (near the edges of the FOV more distortion). Let's ignore these distortions, and aim for a same size feel for objects that are directly in front of the player (so in the exact center of the FOV). To clarify things a bit further I want 1 object in my game to have the same scale feel on different FOVs, not my entire game world. I've tried giving it a percentage of the frustrum height, but that doesn't seem to give me consistent results. Note I'm using vertical field of view in my game.


Unity3D C Drag object smoothly on it's x axis that's already bouncing In my scene, I have a bouncing ball that collides with a cube. On each collision the ball returns to the same height. How can I get the ball to smoothly move along the x axis by dragging my finger across the screen, while at the same time having no effect on the y or z values? The y position is changing every frame depending on the state of the jump, so setting it's y position to transform.position.y in the Update function causes the movement to be jittery if the frame renders when it isn't caught up with the position of the ball. Also, I set the interpolate value of the rigidbody to interpolate to get a smoother jumping motion, not sure if this is relevant to my problem or not. Here is where I am at so far with little success. A few mobile games that replicate what I'm trying to achieve in terms of ball movement are Hop, Color Hop, and Splashy! void Update() if (Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Moved) Control sliding using touch input. Vector2 touchDeltaPosition Input.GetTouch(0).deltaPosition transform.Translate(touchDeltaPosition.x slidingSpeed, 0, 0) transform.position new Vector3 (Mathf.Clamp(transform.position.x, xPosLimit, xPosLimit), transform.position.y, transform.position.z)


How do I calculate sprites frame usage on my platform's ram? I plan on building a 2d game for mobile and possibly pc. I also plan on using sprites frames for the animation of my 2d game. What's stopping me from doing so is because I can't figure out if the sprites frames containing the animation is gonna use up a lot of RAM on my device. Does anybody here know what I'm talking about?


Unity Android Button Select (Highlight) by touch, before clicking I have a multiplatform game with dozens of buttons in many menus. I used the animated buttons setup to have a normal state and highlight state. Highlight will most of the time resize the button with a nice anim AS WELL as make a dedicated text box appear with extra information. So far so good. Everything works perfectly on PC. However, as I am testing my build on android, I cannot find how to access the "highlight" state since touching the screen click and it execute the on click () associated. What I need is a way to select a button when it is first touched, since selected highlight (somewhat) then if it is touched (clicked) a second time while selected then to do the on click ( ) function. I have a few theory on how to do it, but it would require recreating every of my 80 or so buttons as well as changing everything from using the Unity GUI system to make my own C version which would take weeks. I am also trying a few other way to achieve the same thing. One of which is using the "button.select()" to select the button on its first click. That works. problem is I cannot seem to write a way to do "if (thisbutton.IsSelected true)" that just refuses to work.


Unity stats framerate vs Time.deltaTime Googling around, a way for calculating framerate and displaying it as text ingame is using 1 Time.deltaTime. However, comparing this against unity stats FPS shows 2 different FPS. Which of it is incorrect? If 1 Time.deltaTime is incorrect, how does one go about calculating FPS? Below is a screenshot of the FPS difference, as seen in the profiler, fps is well below 100 FPS whereas calculated FPS stays around 60.


Unity How to don't ignore a layer when Raycasting? For example Physics.Raycast(ray, out hit, range, layerMask), let's say layerMask groundMask. What I want to do is only return true if it didn't hit a ground mask. Like what I mean is like quot Ignore raycast except groundMask quot . Is there anyway to do this? Some example origin (groundmask) (other mask) return false because there is a ground mask in a range origin (other mask) return true because there is no ground mask in a range


Preventing character's movement if it won't fit(Unity2D) I'm creating a pacman game copy and I set up my movement. But there's a problem. My character can try to go up whenever I press but in the original you cannot go if there's a wall above you or your character won't fit. For example in this situation you can still go up but you'll bounce off wall. So my question is how to prevent character from movement if there's a wall or it won't fit there.


Flare fading when moving camera I have been trying to do a sun in Unity 3D. I have used a sphere with a texture and a flare. The problem is that when I move the camera the flare fades until it disappears when the sun is almost out of view, as shown in the image I've tried changing the fade value fron the flare but I can't see any difference. Does anybody know if this is a normal behaviour or if it can be fixed so the flare is always the same as long as the sun is in view? Thank you!


Does pixels per unit property affect performance of the game in Unity? The Sprite import inspector has a Pixels Per Unit setting that controls the size of the sprite objects when they're added to the scene Will Unity resize the sprite at run time or will it be resized after me changing the property and saved for the future?


What determines the hit detection ordering for graphic elements in Unity (2d game)? I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated. Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered. How do you control the order in which buttons are registered by the mouse?


How to create a 3D grid in Unity3D? What is a easy way to generate a 3D "hollow" and square grid around a central point, more like a cube (that can vary in size), with each cell being evenly spaced (based on a value)? Note I know how to make a 2D grid but not a 3D one. Edit I'll try to explain it more I'm looking for a way to create a grid at every face of a cube (6 faces) at runtime, that lets suppose is 3x3x3m, and each cell being every 1 meter apart from each other. Something like that


How to make the capsule collider that comes with character controller follow the animations I'm making a 3D endless running game like subway surf. When I swipe press down arrow the slide animation starts but the capsule collider isn't following along as it doesn't slides along with the character. Searched a lot on this on the forums, one possible answer is to attach the collider with some bone. I tried doing so, but couldn't make it. As I'm fairly new to Unity please provide some insights to how to overcome this situation. Here are the screen shots of the collider not following the sliding animation


How can I reduce a bezier curve using a slider till all points converge to it's original midpoint I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet). I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves. I would like achieve this using a float slider (with values from 0 to 1) in editor mode.


Can I detect collision on specific collider? I'm a beginner with Unity and I'm developing my very first 2D game. My game character needs to have an automatic right left movement but I'm struggling with the colliders on the walls (I made a tilemap object and set a collision for each wall on it). I need my character to detect the collision on the Right wall and turn to the left but I just can't find a way to name (I don't even know if you can do this) and detect a specific collider collision so I can make an if statement on the player script. How can I detect a specific collision collider and refer this on my player script? Here is the code I'm using for it (it isn't working) void OnCollisionEnter2D(Collision2D collision) if (collision.collider.gameObject.name "Right Facing Wall") runForwards false else if (collision.collider.gameObject.name "Left Facing Wall") runForwards true


I have a problem rotating a 2D game object after collision I'm developing a simple flip game where a cube flips and the bar a it collides with should start rotating after collision. Most snips involve destroying an object, but that's not my case. Here is my code using UnityEngine public class CheckI MonoBehaviour float x public Rigidbody2D rb2d void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "bar") x Time.deltaTime 10 transform.rotation Quaternion.Euler(0, 0, x) How do I start rotation after collision?


How to make a text box where text "types" smoothly I want to create a textbox that behaves like most textboxes seen in other games where the text appears gradually. So far this has been my attempt at it but unfortunately, the text appears very unevenly and slow even when changing the letter pause to an insanely low amount. public float letterPause 0.1f IEnumerator TypeText() number of char typed per loop int len 3 for (int i 0 i lt text.Length i len) if (i len gt text.Length) ibubbletext.text text.Substring(i, text.Length i) else ibubbletext.text text.Substring(i, len) yield return new WaitForSeconds(letterPause)


Unity Set rotation of object using angle between two points? I have a LineRenderer that draws a line between two points, Vector3 startPos and Vector3 endPos. How can I get the angle between these points, and apply it to an objects transform rotation, so that it points in that direction? Here is my code that draws a line between 2 points by dragging your mouse, if you want to test just Replace the Interact methods with Input.MouseButtonDown(1), hold and up. Vector3 startPos Vector3 endPos float angle LineRenderer lr private void Awake() lr GetComponent lt LineRenderer gt () lr.useWorldSpace true public override void InteractOnDown() base.InteractOnDown() lr.enabled true lr.positionCount 2 startPos PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point lr.SetPosition(0, startPos) public override void InteractOnHold() base.InteractOnHold() endPos PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point lr.SetPosition(1, endPos) public override void InteractOnUp() base.InteractOnUp() lr.positionCount 0 lr.enabled false


Unity How to make an array of video clips and play them? I have 26 video files which I have to put in an array and play for different objects. So far I have written this from what I know using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Video public class videomanager MonoBehaviour public VideoClip vids private VideoPlayer vp Use this for initialization void Start () vids new VideoClip 25 vp gameObject.GetComponent lt VideoPlayer gt () Update is called once per frame void Update () I have attached this script on a plane on which I am playing the video. Before that, I had 26 different planes, one for each different video, but I think it would be better if I could play them on a single plane and change the video according to logic. I am not sure how I should load them into my player and play them.


2D Camera Movement Temporal Reprojection Having an Orthographic Camera with its View Projection Matrix given from the current and last frame, how to reproject the previous frame to the new one?


In Unity, Change which mouse button is used to scroll in ScrollRect I've created a new ScrollView in Unity. How do I change which mouse button is used to scroll in ScrollRect (through script or in the editor). By default it's the left mouse button. I'd like to be able to change this to another mouse button. I'd also like to be able to use a keyboard key and disable it altogether (via script without also disabling the scrollbars), but mainly I at least want to change it from the left mouse button.


How can I make billiard without using Rigidbody? Unity's physics engine isn't deterministic (ie. the results aren't always the same on all computers) so I haven't Idea that how billiard games Implemented.Is there a way to Implementing fake and deterministic physic in unity? I mean I want to make billiard without using Rigidbody http www.bezzmedia.com swfspot tutorials flash8 8 Ball Pool I found this open source project that didn't use physic! this is what I need but unfortunately it's full c and I haven't enough time to convert it to c http downloads.sourceforge.net foobillard foobillard 3.0 win32 2 bin.zip


Unity 2D Sprite Bending between Hinge Joints I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built in physics, but it doesn't look very good art wise. Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort? I would prefer to keep using multiple game objects to represent the tentacle.


Unity Ads showing test ads I am implementing Unity Ads in my game and for some reason I have the test ads showing up in my production version of my app. I have the advertisements initialized with test ads turned off and I have even gone into my settings on the Unity Ads admin and set it to force test ads to be off. I'm not sure what else to do here. Here is how I am initializing Advertisement.Initialize("myID", false)


Unity sizeDelta of an Image update opposite to what it should I have an IEnumerator coroutine in which I call the UIManager script to update the Image size to fit the text size but it doesn't happen. when I use yield return new WaitForEndOfFrame() it sometimes solve the problem. but I don't want to use it. edit I tested the code like I was suggested in an empty unity project and it still happens, the width should change according to the text size but it happens opposite (when the text is small the width of the image is large and when the text is large the width of the image is small) (it only happens correctly at the first time the width of the image fits the text width) public class Example MonoBehaviour public Image image public Text text private int k 0 public void ButtonClick() text.text (k 2 0) ? "10" "10 10" image.rectTransform.sizeDelta new Vector2(text.rectTransform.rect.width, 30) k edit Solved! thanks for the help, Canvas.ForceUpdateCanvases() did the trick


Filling Closed Shapes Game Engine Unity 5.1 Developing on Windows 7 Hello, I am using Vectrosity to draw some some shapes on screen run time. I also need to fill these shapes and none of them are really trivial shapes. So after doing some research I figured the best way would be to do it by creating a run time mesh. Now this almost works for me but has a big issue. This is my process. 1) I have defined my complex shapes as a set of 2D vertices that I extracted from Illustrator. These vertices I feed to the Vectrosity's Catmul spline function to create my shapes. 2) I then project these vertices in the real space using ScreenToWorldPoint to get 3D vertices. 3) I then pass these vertices to a program that Triangulates these points to a mesh (I use the classic Triangulate script on wiki) 4) I then clean up a little and align Now all this works well if the camera is not rotated and the forward vector of the camera is orthogonal to the XY plane. The moment I rotate the camera the alignment of the mesh and the vector lines is completely gone. Here is the image of the vectorline and mesh when the camera is not rotated And here is the image when the camera is rotated Here is the function that projects the point into 3D space void DrawPolygon () Vector2 tempVerts new Vector2 allLinePoints.Count for(int i 0 i lt allLinePoints.Count i ) Vector3 projectedPoint Camera.main.ScreenToWorldPoint(new Vector3(allLinePoints i .x, allLinePoints i .y, 10.0f)) tempVerts i new Vector2(projectedPoint.x, projectedPoint.y) polyTarget.SendMessage("Create", tempVerts) This message is sent to a generic Triangulation script. Here it is using UnityEngine using System.Collections using System.Linq public class CreatePolygon MonoBehaviour public Material meshMaterial public void Create (Vector2 verts) Triangulator tr new Triangulator (verts) int indices tr.Triangulate () Create the Vector3 vertices Vector3 vertices new Vector3 verts.Length for (int i 0 i lt vertices.Length i ) vertices i new Vector3(verts i .x, verts i .y, 0) Create the mesh Mesh msh new Mesh() msh.vertices vertices msh.triangles indices msh.RecalculateNormals() msh.RecalculateBounds() Set up game object with mesh gameObject.AddComponent(typeof(MeshRenderer)) MeshFilter filter gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter filter.mesh msh GetComponent lt Renderer gt ().material meshMaterial StartCoroutine (FlipNormal ()) public void ResetMesh (Vector2 verts) Triangulator tr new Triangulator (verts) int indices tr.Triangulate () Create the Vector3 vertices Vector3 vertices new Vector3 verts.Length for (int i 0 i lt vertices.Length i ) vertices i new Vector3(verts i .x, verts i .y, 0) Create the mesh Mesh msh new Mesh() msh.vertices vertices msh.triangles indices msh.RecalculateNormals() msh.RecalculateBounds() Set up game object with mesh MeshFilter filter GetComponent lt MeshFilter gt () filter.mesh msh GetComponent lt Renderer gt ().material meshMaterial StartCoroutine (FlipNormal ()) IEnumerator FlipNormal() yield return new WaitForSeconds (0.1f) Mesh mesh (GetComponent lt MeshFilter gt () as MeshFilter).mesh mesh.uv mesh.uv.Select(o gt new Vector2(1 o.x, o.y)).ToArray() mesh.triangles mesh.triangles.Reverse().ToArray() Now this seems to be an obvious problem to have but I am just not being able to crack it. I have a feeling the solution is some mathematics that is completely escaping me right now. Can someone please help and point me to the right direction. I need to be able to align the mesh to the outline even when the camera is rotated.


Unity2D Child class inheriting onCollisionEnter() methods I may be an idiot for asking this but I can't seem to solve it myself, I have a GenericWeapon class which has a onCollisionEnter() method which I want applying to all child classes which inherit from it, here is the code public void onCollisionEnter(Collider target) Debug.Log("Collided with player!") if(target.GetComponent lt Player gt ()) bc2d.enabled false rb2d.Sleep() equip(target.GetComponent lt Player gt ()) My child class is the following using System.Collections using System.Collections.Generic using UnityEngine public class RangedWeapon GenericWeapon Start is called before the first frame update void Start() Update is called once per frame void Update() public void attack() and my in GameObject has the RangedWeapon class as a component however the GameObject does not seem to be picking up any collisions with the player. Could someone point out where I'm going wrong with this?


Is it necessary to know some programming language before learning to use Unity I had learnt a bit of Java programming in school...is there any other programming language that I should learn to be able to work using Unity?


Transform check should return null, but returns as initialized instead In my Player script, I initialize my FirePoint transform using GameObject.Find in the Awake function. In the editor, I purposely misspelled the name of FirePoint to test if the null check inside of my Fire function will print an error to the console. The only error that shows up is from the Awake function giving a NullReferenceException, but why don't I see my Debug.LogError? Instead, the else statement prints that the FirePoint is not null. public class Player MonoBehaviour HideInInspector public Transform FirePoint private void Awake() FirePoint GameObject.Find("FirePoint").transform private void Fire() if (FirePoint null) Debug.LogError("FirePoint is null.") else print("FirePoint is NOT null.")


How to create pixel perfect noise shader? I would like to know how they created the pixel perfect noise shader in monument valley 2 in that b w level (example picture). I think it starts with a billboard shader, but I have no clue how to scale the texture to it's native size. I'm using ShaderLab (unity, mobile platforms)


Tire mesh rotates faster than wheelcollider in Unity I have a car in Unity. Scripts are C . I have noticed that my tire meshes' rotation is faster than whellcollider rotation. I am using this code for wheel rotation flWheel.localEulerAngles new Vector3(flWheel.localEulerAngles.x, flWheelCollider.steerAngle flWheel.localEulerAngles.z, flWheel.localEulerAngles.z) frWheel.localEulerAngles new Vector3(frWheel.localEulerAngles.x, frWheelCollider.steerAngle frWheel.localEulerAngles.z, frWheel.localEulerAngles.z) flWheel.Rotate(flWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) frWheel.Rotate(frWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) rlWheel.Rotate(rlWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) rrWheel.Rotate(rrWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) I found this from here Does anyone know how to fix this? Edit Using AquaGeneral's answer I could able to solve rotation problem. But now front right tire position changed to rear left tire position and rear right tire rotated 180 on Y axis. need help


In Unity3D, what is the relation between inertiaTensor and inertiaTensorRotation? In unity3d there are two properties on rigidbody that correspond to the moment of inertia tensor. One of them is rigidbody.inertiaTensor, which I know is the diagonal of the inertia tensor, The other is rigidody.inertiaTensorRotation, which I don't quite understand. I have, though, created a rigidbody in such a way that I get it to be other number than Quatenion.identity, but I still don't see the connection. Can I describe the products of inertia tensor with the rotation or ... what is the relation between them and where would I require them?


How to have a point light with no falloff in Unity 3D? Does anyone know of a good strategy to make point lights with no falloff, eg. anything in the radius of the light will be 100 illumination while anything outside the radius will be 0 illumination. I want to use this as a sort of 3D line of sight drawing. The line of sight is a big sphere originating from the character's head that I thought would be a clever idea to have that represented as a point light, however with the falloff it doesn't correctly show where the edge of the line of site is. I've tried a few solutions, such as a custom falloff package (doesn't seem to have the options I want) and a few shaders, but I am terrible at shaders so it's difficult for me to debug. I'll post the shader here in case somebody can tell me if I'm being dumb, otherwise if someone can point me to a different solution that would be great. Thanks! Here's a shader I tried, but it just turns everything invisible and it's not immediately obvious to me why Shader "Custom No Falloff v2" Properties Color("Color", Color) (1,1,1,1) MainTex("Texture", 2D) "white" SubShader Tags "Queue" "Transparent" Pass Blend SrcAlpha OneMinusSrcAlpha Tags "LightMode" "ForwardAdd" CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" include "Lighting.cginc" compile shader into multiple variants, with and without shadows pragma multi compile fwdadd fullshadows shadow helper functions and macros include "AutoLight.cginc" sampler2D MainTex float4 MainTex ST fixed4 Color struct v2f float2 uv TEXCOORD0 SHADOW COORDS(1) put shadows data into TEXCOORD1 float4 pos SV POSITION v2f vert(appdata base v) v2f o o.pos UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) TRANSFER SHADOW(o) return o fixed4 frag(v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) Color compute shadow attenuation (1.0 fully lit, 0.0 fully shadowed) fixed shadow SHADOW ATTENUATION(i) if (shadow lt 0.5) return fixed4(0.0156862745, 0, 0.23529411764,1.0) or any other color for shadow return col ENDCG shadow casting support UsePass "Legacy Shaders VertexLit SHADOWCASTER"


Unity3D (5.1) NavMesh Agent Error This is my first post in GameDev StackExchange, so please excuse me if I make any mistakes on best practices here (if I do, please refer me so I can learn). I'm making a prototype where I have 2 types of enemy units Uninfected and Infected. The Uninfected are to seek out Infected via AI pathfinding. However, I came across an issue when implementing the NavMesh in the scene. If the Player collides with an Uninfected, they go flying backwards. If they hit the walls, the walls collectively get hit. Here's some screenshots. Example 1 http s7.photobucket.com user Korudo media GameDev RoboInfect 20Scene 20 20WallWeirdness1 zpsg0k2wbyk.png.html Example 2 http s7.photobucket.com user Korudo media GameDev RoboInfect 20Scene 20 20WallWeirdness1 zpsg0k2wbyk.png.html Thanks in advance.


Understanding Screen Position Node in Unity Shader Graph I'm struggling to understand what exactly the Screen Position node outputs in Unity's Shader Graph. I'm using the screen position with scene depth to calculate the distance between two objects. Every tutorial I saw (like Brackey's forcefield one) is using the alpha channel of the Screen Position output I read that the Screen Position node outputs the mesh vertex screen positions. Does it means the 2D position on the screen projection? Or the vertex 3D position from the eye space? And more importantly, what is exactly the apha channel of this output? (I have the feeling this is related to the quot clip space W component quot in the documentation)


Unity Interrupting Animations When I interrupt an Animator Controller during an Animation and reopen it the Armature gets stuck (more or less) at the point where the previous Animation was interrupted. How can I safely and instantly quit an animation without destroying it? Please watch the Video to fully comprehend the problem https youtu.be O9X5SBATHRw Screenshot of Problem Screenshot of Animator Controller Part of the Weapon Switch Script disableWeaponModel(weaponNameList activeWeapon ) Disable active Weapon Model if (holsteredWeapon 1) If player carries only 1 weapon holsteredWeapon activeWeapon Active Weapon is holstered else Player already carries 2 weapons actionDropGun() Active Weapon is thrown (New LOD generated) activeWeapon getWeaponIDfromLOD(targetName) Active Weapon is set to Target LOD setWeaponVars(activeWeapon) Set all variables to the active Weapon setWeaponModel(weaponNameList activeWeapon ) Set Weapon Model to the active Weapon setAnimator(weaponNameList activeWeapon ) Set Animations to the active Weapon setAnimator(string name) Function from above (last code line) void setAnimator(string name) Add new guns here if (name "MP5A3") currentWeaponAnimation MP5A3 Animation else if (name "Rpk 74") currentWeaponAnimation Rpk74 Animation else if (name "Skorpion") currentWeaponAnimation Skorpion Animation Variables from setAnimator(string name)


How to scale an object in one direction without moving the opposite edge? I am using Unity. In my game, I have an SpriteRenderer and I'd like it to increase its size I'd like it to lengthen to the right, without moving the left edge. I tried changing its scale to something bigger than its original scale and it changes into something like this, growing to both the left and the right I also tried to increase its position together with its scale but then it didn't work. Editor's note this is where you tell us how it "didn't work". What exactly did you try, what results did you get, and how did those results differ from what you wanted? My Object is configured like this in UnityEngine


Adding components to a GameObject referenced within code So in my project, I have a class called ComponentRegistry. The idea of this class is to store a dictionary of components and their names. For example public Dictionary lt string, MonoBehaviour gt registry public MonoBehaviour testComponent void Start() registry new Dictionary lt string, MonoBehaviour gt () registry.Add ("TestComponent", testComponent) public MonoBehaviour GetScript(string name) return registry name Then in a separate class, I will access this dictionary using a string in order to retrieve the associated component, subsequently adding the associated component to the gameObject. foreach (string comp in blockInfo.components) For each of the components that need to be added gameObject.AddComponent(ScriptMaster.compReg.GetScript(comp)) I know this is incorrect, but the idea is there Just for understanding, compReg is an instance of the ComponentRegister class stored as a static variable within my ScriptMaster class. But no matter what I try, I have not been able to get this to work. I have switched endlessly between different formatting of adding components to gameObjects, alternating between using Components and MonoBehaviours, adding by type. Thank you for any insight.


Unity LoadLevelAdditive and baked light scene settings I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light. So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive). Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ... So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override? Thanks.


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


How do I size my map in blender so it will be the right size in unity? I am working on a fps game but I cant get the size right of my map in blender, every time I export it to a .fbx file (unity won't work if it is a .blend file) it is a super small plane floor in unity the player controller is 10 as big as the map. I don't know what to do.


Enum or Inheritance for event based interaction? I am currently considering two possibilities to a centralised interaction system within my game. Consider that you want to produce different results for different types of objects within the game world you interact with a signpost and dialogue appears, or interact with an item on the ground and it gets added to your inventory with a notification. Essentially, I cannot decide whether it would be more efficient to implement such functionality all within one centralised place or to spread each function out over separate events. Option 1 Centralised This is what I have started coding. One Interact class which contains several "Types" of possible events in my game. When the player "interacts" with an object implementing this script, it will implement the functionality that it is set to in the Editor. This means I drag and drop this Event Script onto a prefab and can automatically tweak its functionality within a couple of seconds and have it ready to go in the game world. I have simplified the general consensus of my code into this block for readability public string eventName public enum EventType Movement 0, Dialogue 1, NPC 2, ItemCollect 3, Teleport 4, Cutscene 5, Switch 6, Custom 7 public EventType eventType INITIALIZATION private void Awake() SetupEvent(eventType) public void Activate(bool calledFromTrigger false) if (autoTrigger amp amp !calledFromTrigger) return Debug.Log("Activated " name "!") StartEvent(eventType) private void StartEvent(EventType type) switch (type) case EventType.Movement MovePlatform() break case EventType.Dialogue break case EventType.NPC break case EventType.ItemCollect break case EventType.Cutscene break case EventType.Switch break case EventType.Custom break Resulting in Option 2 Inheritance It is as if I have a little devil and angel on my shoulder, one tugging me towards the easy and half finished code of the former example, and another urging me to redesign what I am doing into a much cleaner and abstracted approach. In the previous example, all "event types" (Movement, Dialogue, Item Collection etc.) were handled by enums that were passed through a Switch statement to check which method should be executed based on the parameters inputted into the Unity Editor for that specific Game Object. In this system, there would be a base "Interactible" class, which various classes would inherit from to implement functionality. The Activate() method would be overridden in the children for each specific class. public class NPC Interactible public override void Activate() NPC Code... The unfortunate downside to this is that I can't just use one prefab for all my events and change them based on the custom editor that I define. I would have to create a custom editor for each possible child of the Interactible class, and instead of selecting which type of event I want it to be from a simple drop down, I will have to swap out different scripts for different functionality.


How to move player on unity3D? I checked the input settings. I added a speed value. I also added Time.deltaTime, but the body is not moving. using UnityEngine using System.Collections public class PlayerController MonoBehaviour public float speed private Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement speed)


Selecting Dictionary item based on custom classes instead of keys I am attempting to write my own path finding code for a game I'm working on that will implement a form of the A algorithm. I store my nodes of the path finding system as a class called nodes and add these to a dictionary with their position in world space as the key for the dictionary. Here's the problem. At one point I need to test the dictionary and return from it the node with the lowest "f" value. I came across the morelinq MinBy function with seemed promising, but so far have not had any luck getting it to work. Here is a stripped down version of the code using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using MoreLinq public class GMove MonoBehaviour public Dictionary lt Vector3, Node gt vectorNodesOpen new Dictionary lt Vector3,Node gt () public Dictionary lt Vector3, Node gt vectorNodesClosed new Dictionary lt Vector3,Node gt () private KeyValuePair lt Vector3, Node gt currentNode new KeyValuePair lt Vector3,Node gt () private bool goal private bool findingPath void Start() goal false findingPath false public void addNodes() several nodes get added to the dictionary based on the A algorithm ending way point and beginning waypoint are stored as Vector3 public class Node public int h get set public int g get set public int f get set public Vector3 pos get set public Vector3 parentNodeVector get set void Update() if(findingPath) while (!goal) currentNode new KeyValuePair lt Vector3, Node gt (vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) This is the line in which I'm attempting to get the node in the open list with the smallest f value. vectorNodesClosed.Add(vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) vectorNodesOpen.Remove(vectorNodesOpen.MinBy(x gt x.Value.f).Key) remove current from open. if (currentNode.Value.pos waypointEnd) if current node end position we are done. goal true addNodes(currentNode.Value.pos, waypointEnd) Add and update nodes The line that is giving me trouble is the first line inside the while loop. I need a way to return the Dictionary item with the smallest "F" value, this would be pretty easy if it were an integer but the F value resides in the Node class. I don't have to use MoreLinq, I would be happy to do it any other way that someone can come up with. Cheers! One more note the code above is incomplete in an effort to minimize it down to only what is necessary to understand the problem more complete code can be provided if necessary.


How can I draw lines in editor between waypoints when creating the waypoints? public List lt Vector3 gt destinations new List lt Vector3 gt () public int numberOfDestionations public float moveSpeed 5f public bool loop false public bool moveBack false public Text textCounter private Coroutine movementCoroutine private bool pause false private bool coroutineRunning false private Vector3 startPosition private int countDestionations private void Start() for (int i 0 i lt numberOfDestionations i ) destinations.Add(new Vector3(UnityEngine.Random.Range( 300, 25), 1f, 0)) 25, 1f, 0) if(i gt 0) Gizmos.DrawLine(destinations i , destinations i 1 ) I'm trying to use gizmos but getting exception ArgumentOutOfRangeException Index was out of range. Must be non negative and less than the size of the collection. Parameter name index On line 33 Gizmos.DrawLine(destinations i , destinations i 1 ) I want that while it's creating the vectors draw lines from the current created vector destination and the next one. A line from index 0 to index 1 to index 2 and so on. So when running the game I will see a net of all the lines connected between the vectors destinations.


How to offset a 2D GameObject by a pixel amount? I'm extremely new to game creation. I'm playing around with creating a 2D Unity game. The scene is setup from the default Unity 5 2D template. Following a tutorial, I've created a TerrainManager GameObject and Script. The script instantiates tiles and sets their position using a standard double loop. I've found a 2D isometric tile set. Each tile is visually rendered as rotated around the vertical axis by 45 degrees, creating more of a diamond shape rather than a square. This requires that every second tile be offset by half the tile width on the x axis, and half the tile height on the y axis. As each tile is of a different height, one can not simply offset the tile on the Y axis by half its height. Each terrain "layer" is 16px tall in the PNG. Some PNGs have a single "layer", some have multiple "layers". (For instance, a single layer water tile is 83px in height, while a dual layer "grass on top of dirt" layer is 99px in height. As the game object expects the transform.position as a Vector3 in (I assume) game units, I do not know how to compose this using pixel values. So the question I have is, how do I achieve the 16px y axis offset of the game object? I'm more than happy to provide additional details if needed.


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


Adding a delay into the middle of a function in Unity In the spot wait 1.5 seconds what would I say to make it wait 1.5 seconds then complete the code after? Here is the code using System.Collections using System.Collections.Generic using UnityEngine public class OnclickHeal MonoBehaviour public PlayerHealth playerHealth public PlayerMovement playerMovement public Inventory Inventory public Button healButton void Start() Button btn healButton.GetComponent lt Button gt () btn.onClick.AddListener(TaskOnClick) void TaskOnClick() playerMovement.moveSpeed 3 wait 1.5 seconds playerMovement.moveSpeed 4 playerHealth.currentHealth 100 Also, the line public Button healButton throws an error error CS0246 The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)


How to avoid material copying error message in Edit mode? I created a component called "AphaGroup" (an analog of the existing CanvasGroup for UI) which should be able to change alpha of the whole game object tree. My component finds all the MeshRenderer components, takes their material.color and changes its alpha. It should work both in play amp edit modes. When it's run in edit mode there is an error in the console when the material is copied for the first time Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMaterial instead. I've read most of the similar questions on the Internet but still haven't found the answer on how to manage this situation properly. How to avoid both this error message and memory leaks? I tried Renderer.material, Renderer.materials and Renderer.GetMaterials, but all they cause the same error.


Rotate the player in a certain way that makes it look like he is sliding I'm trying to make my first game in Unity a 3d platformer inspired by the classic Crash Bandicoot games. I've managed to make most of the movement with the character control script below. However, I don't know how I can do a slide crouch. What I want to do is to rotate and move the player down closer to the ground and give him some more speed that decreases over time until he reaches a normal waking state. I thought about making the player rotate on a specific axis but when he turns the axis doesn't change so now I'm kind of lost in what to do. using UnityEngine public class PlayerMovement MonoBehaviour public CharacterController controller public float speed 10f turnning smoothness public float turnSmoothTime 0.1f float turnSmoothVelocity jump controls public float jumpHeight 3f public float gravity 29.43f Vector3 velocity bool isGrounded gravity check public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask Update is called once per frame void Update() isGrounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if(isGrounded amp amp velocity.y lt 0) velocity.y 1f player movement on both axis float horizontal Input.GetAxisRaw( quot Horizontal quot ) float vertical Input.GetAxisRaw( quot Vertical quot ) Vector3 direction new Vector3(horizontal, 0f, vertical).normalized velocity.y gravity Time.deltaTime controller.Move(velocity Time.deltaTime) if (Input.GetKeyDown( quot space quot ) amp amp isGrounded) velocity.y Mathf.Sqrt(jumpHeight 2f gravity) if (direction.magnitude gt 0.1f) player turning depending on where moving float targetAngle Mathf.Atan2(direction.x, direction.z) Mathf.Rad2Deg float angle Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime) transform.rotation Quaternion.Euler(0f, angle, 0f) controller.Move(direction speed Time.deltaTime)


How could I get composite rigid body into unity I am developing a game, in unity, that has accurate destruction physics and from my understanding unity uses plain old rigid body physics. I was wondering if there was a way to bring composite rigid body physics into unity through a plug in or library or some other way? Thanks, nova edit So composite rigid body physics is almost exact like normal rigid body physics. But the main difference is that in composite rigid body physics all of the assets will not be considered physics based objects until an outside force hits them. For example a building and all of that parts it is made out of will not be processed as physics based objects until say a rocket hits it. This method of composite rigid body physics uses much less memory because it is only processing what is being affect and not everything else.


How to set the z axis bound of the collider of child of an instantiated object to zero I have attached a script to an empty GameObject to instantiate a prefab and the script is using System.Collections using System.Collections.Generic using System.Collections.Specialized using UnityEngine public class Circles MonoBehaviour SerializeField float Xmax SerializeField float Xmin SerializeField float Ymax SerializeField float Ymin SerializeField float outsideMaxsize SerializeField float outsideMinsize float insideMaxsize float insideMinsize public GameObject enemy GameObject enemyObject int enemyNo float Xpos float Ypos float outsideSize float insideSize Start is called before the first frame update void Start() enemyNo Random.Range(0, 4) instantiator() Update is called once per frame void Update() public void instantiator() Xpos Random.Range(Xmin, Xmax) Ypos Random.Range(Ymin, Ymax) outsideSize Random.Range(outsideMinsize, outsideMaxsize) Vector2 circlePos new Vector2(Xpos, Ypos) transform.position circlePos enemyObject GameObject.Instantiate(enemy enemyNo , transform.position, transform.rotation,transform.parent) as GameObject var enemies enemyObject.transform var outsideComponent enemies.GetChild(0) var insideComponent enemies.GetChild(1) outsideComponent.transform.localScale new Vector2(outsideSize, outsideSize) insideMaxsize outsideSize 0.5f insideMinsize 0.15f insideSize Random.Range(insideMinsize, insideMaxsize) insideComponent.transform.localScale new Vector2(insideSize, insideSize) enemyNo Random.Range(0, 4) And I have attached a script to the prefab which is being instantiated and that script is using System using System.Collections using System.Collections.Generic using UnityEngine public class destroyer MonoBehaviour Circles circles CircleCollider2D collider1 Collider2D collider2 private void Start() circles FindObjectOfType lt Circles gt () print( quot 1 max quot collider1.bounds.max) print( quot 1 min quot collider1.bounds.min) print( quot 2 max quot collider2.bounds.max) print( quot 2 min quot collider2.bounds.min) private void OnEnable() collider1 gameObject.transform.GetChild(0).GetComponent lt CircleCollider2D gt () collider2 gameObject.transform.GetChild(1).GetComponent lt Collider2D gt () void OnTriggerStay2D(Collider2D other) print( quot star max quot other.bounds.max) print( quot star min quot other.bounds.min) if (collider1.bounds.Contains(other.bounds.max) amp amp collider1.bounds.Contains(other.bounds.min)) if (other.bounds.Contains(collider2.bounds.max) amp amp other.bounds.Contains(collider2.bounds.min)) Destroy(other.gameObject) Destroy(gameObject) circles.instantiator() the problem is that the z axis bounds of the colliders are coming out to be 15.8 when the prefab is instantiated and when I drag the prefab to scene then the z axis bounds of the collider is 0. I want the z axis bounds of the colliders to be 0 when the prefab is instantiated


How can I check if a point(Vector3) is in Matrix4x4 I'm placing random objects in an imaginary cube in front of my target. I am using following code to do this var center Vector3.zero center.z (m size.z 2) m offset.z center.x m offset.x center.y m offset.y var mat Matrix4x4.TRS(m target.position, m target.rotation, m target.lossyScale) Vector3 pos center new Vector3(Random.Range( m size.x 2, m size.x 2), Random.Range( m size.y 2, m size.y 2), Random.Range( m size.z 2, m size.z 2)) pos mat.MultiplyPoint(pos) m instantiatedObject.Add(Instantiate(m object, pos, Quaternion.identity)) And it's working as expected. but now my problem is as my target moves, the previously placed objects may not be in this imaginary cube anymore. how can I check if my placed objects are in this imaginary cube and if they are not I can remove them?


Calculate position on Isometric grid I created the following tile grid in unity3d The blue dot is the absolute center point (0,0) of both scene space and tile map. Now I am trying to calculate the X Y position of points on the tile map ( the black coordinates). The red coordinates are positions in the scene space. Every calculation I make just gives me a wrong result. Is the tile map roatated the wrong way? Any help really apreciated!


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.


Rotating a gameobject in the Inspector doesn't change direction When I add a Cube to a scene, the blue axis ( forward) of the cube points into a certain direction. When I now change the Y rotation of the cube to 90 in the inspector, the blue arrow doesn't rotate. I would have expected it to rotate with the rotation that I have defined for the cube. What is happening here? To explain more in detail why this is bothering confusing me I want to rebuild the RE4 inventory (which is actual 3D). The items in this inventory can be moved within the "grid" To do that I have created a suitcase and then I added a gun to it As one can see, I have assigned the facing direction properly The blue axis ( forward) points into the direction of the gun. Now I wanted to rotate the gun in such a way that it is shown like in the original RE4 inventory. To do that, I apply a rotation of Y 90. The gun looks correctly now However, the blue axis now faces the wrong direction in my opinion. Why does it not rotate along with the rotation of the gameobject? This really confuses me because now when I want to move the gun left or right, I have to change its X position value instead of changing the Z position value. This just seems wrong to me. Can somebody tell me what I'm missing here? Thank you.


Want some limits in Bullet firing and its stop when i press the shoot button I want some limits or range when my player fire the bullets and when i press the shoot button my fire as been stopped. I use the GetButtonDown from this its fire continuously but its not stopped. and if i use Input.GetButton than its hold the button and fire continuously but in fire there is no gap. So, my problem is that how i stop the bullet fire when i press the shoot button and if choose this (INPUT.GETBUTTON) and its hold the shoot button and its fire continuously than i want some gap on that fire and some limits or range of fire. void Update() if(Input.GetButtonDown("Fire1")) shootRoutine StartCoroutine(PlayerShoot()) else if(Input.GetButtonUp("JumpButton")) StopCoroutine(shootRoutine) shootRoutine null void JumpButton() if(!transform.GetChild(0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (grounded) grounded false myRigidBody.AddForce (new Vector2 (0, jumpPower), ForceMode2D.Impulse) if(myRigidBody.velocity.y gt jumpPower) myRigidBody.velocity new Vector2 (0, jumpPower) animator.SetBool ("isGrounded", grounded) PlayerShoot method IEnumerator PlayerShoot() while(true) if (!transform.GetChild (0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (energy gt 5f) energy 5f energyLevel.value (int) energy energyText.text (int)energy " " GameObject newProjectile Instantiate(projectile, new Vector3(transform.position.x 1.5f, transform.position.y 0.02f, transform.position.z), Quaternion.identity) as GameObject if (GameController.instance.isMusicOn) AudioSource.PlayClipAtPoint(MusicController.instance.audioClips 2 , newProjectile.transform.position) yield return new WaitForSeconds(shootDelay) Wait for 'shootDelay' seconds before starting over again.


Should LOD models be used in mobile games? LOD models are widely used in PC and console games, to optimize performance by reducing the vertex count and texture size for distant objects. However, I'm having a harder time finding out if they are typically used to increase performance in mobile games. I've seen a few people in forums suggest that the CPU overhead for LOD models might actually outweigh the GPU gains on mobile devices. Another consideration is the more limited storage space on mobile, and LOD models textures necessarily increase the total size of a game. Other than that, I can't find much information on the subject. The Unity documentation on LOD models doesn't mention mobile, and the Unity documentation on optimizing for mobile doesn't mention LOD models. I know the first answer to any performance question is usually "profile it and find out for yourself" however, in this case, I am helping to optimize a game that doesn't currently have LOD models, so profiling it would first require commissioning the artists to create enough LOD models that we can realistically profile the performance change. Does the usage of LOD models typically provide noteworthy performance gains in 3D mobile games, or does the overhead for LOD cancel out any gains? The specific title in question is a racing game.


Given a 3d goal point and a turn rate in radius, find max speed to reach goal I'm working on a 3d space sim with AI agents flying ships through space. I am trying to get them to follow a waypoint path nicely, which involves figuring out how fast they can be travelling and still manage to pass through the waypoint. Given a point in 3d space and an an agent that only travels forwards and has a given turning rate in radians second and an acceleration rate, how can I find the maximum speed the ai can travel and still manage to face the point before overshooting it? Can any math wizards lend a hand? public class AIPilot relevant fields from my class float turnRate radians float acceleration Transform transform public float FindMaxSpeedToFace(Vector3 goal) trying to fill the body of this method


Unity game in edit the scene mode all of a sudden became incredibly slow "laggy" So I recently have been working on a game. So far I have very few assets in the game, which are a point light, a piece of terrain (which is textured), a player controller and a tree. Everything was going well until I put the tree in the scene. I made tree and started to add some branches I got to about 8 branches, and then I added 35 leafs. Then the edit scene started to become laggy. When I played the game it was running perfectly. But as soon as I changed the scene back to edit mode it became laggy again. I then deleted the tree to see if that would solve the problem but it seems to have done nothing at all. I would really appreciate if someone could explain why the edit scene is becoming laggy even though there are only a few assets within the game. Thanks, Nova


MeshMemory causing constant spikes I have a ready to launch application, cleaning everything right now. I have these strange spikes on Mesh Memory. The best part of it is that this view below is from a static menu screen, where there are no meshes. I don't even interact with it. Can this be caused by meshes import options or something like that?


Smooth rotation for a bone? I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ? public Transform Target public Vector3 Offset Animator anim Transform chest public float rotation speed public bool aim at traget false void Start() anim GetComponent lt Animator gt () chest anim.GetBoneTransform(HumanBodyBones.Chest) void LateUpdate() if (aim at traget true) smooth rotation to face target chest.LookAt(Target.transform.position) chest.rotation chest.rotation Quaternion.Euler(Offset) else get back to you stand smoothly


Offsetting ground texture doesn't work in WebGL so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving. The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again. heres the code attached to the ground to keep it offsetting constantly using System.Collections using System.Collections.Generic using UnityEngine public class Offset MonoBehaviour public float scrollSpeed public Material mat private float offset Use this for initialization void Start () mat GetComponent lt Renderer gt ().material Update is called once per frame void Update () offset Mathf.Repeat(Time.time scrollSpeed, 1) mat.mainTextureOffset new Vector2(offset, mat.mainTextureOffset.y) What may I be doing wrong, and how can I fix it? Thanks in advance!


How to create a two way teleport system? I'm trying to create a two way teleport system in which players can move into a teleport gameobject, and is then teleported to another linked teleport gameobject. How I was planning to have it work was very simple. On the teleport gameobject's script, it would have a public property to the other teleport's transform in which to teleport the player to. In OnTriggerEnter, I simply set the entering's collider position to that of the linked teleport. void OnTriggerEnter(Collider other) other.transform.position DestinationPoint.position However, when the player's position is changed, it triggers the OnTriggerEnter of the destination teleport, and thus the player gets stuck bouncing back and forth between the two points. What's a good way to prevent this? Some less than ideal solutions I came up with is to offset the position that player teleports too slightly so that he doesn't cause OnTriggerEnter to be called at the destination portal, but I'd like to avoid that.


How to get neigbor pixel coordinates in Unity HLSL shader I am writing Mandelbrot set shader for Unity. I wrote an Image Effect shader and it works. Unfortunately, each point quot shimmers quot on translate scale. This is because, for each shader call I compute value for only one mathematical point, which is infinitesimal. On even small translation, the value can change drastically. So, I would like to compute math value not for one point, but for several. But for this I need to know, which aother points belong to my pixel, and for this I need to know the distance to neighbor pixel. Unfortunately, my incoming values are float and I don't know, how to step to next pixel. How to accomplish?