How to give a Jerk Effect when the player is moving left of right float amttomove Input.GetAxis("Horizontal") playerspeed Time.deltaTime transform.Translate (Vector3.right amttomove) Currently, I have above script in Update function to move the object to left or right.But this movement is way smoother.To give it more realistic feel, I want it to have a slight jerk when it stops moving to left or right and not just stop right there and then. What exactly needs to be done to have that effect?


Mathf.Hermite not available in Mathf I see here that Hermite should be function in the class Mathf. However, when I try to use it, the compiler tells me that Mathf doesn't contain a definition for Hermite. This is an example float fNewDistance Mathf.Hermite( initialDistance, GoalDistance, fTime) What am I doing wrong here? Thank you!


How to draw a line in 3d space? I have a top down billiard game. And on click tap the ball moves in the clicked direction like in the image below Now, I want a line to be drawn in the direction where the mouse is hovers or the finger is swiped, here is my update code void Update () this should make the line, why not working? Vector3 forward transform.forward Debug.DrawRay(transform.position, forward) Debug.DrawLine(transform.position, transform.position forward 10000) if (Input.GetMouseButtonDown (0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit, 100.0f)) Vector3 startPos transform.position Vector3 clickPos new Vector3(hit.point.x, hit.point.y, transform.position.z) Vector3 direction Direction (clickPos startPos) direction rb.velocity new Vector3(direction.x 5, direction.y 5, 0) I tried DrawLine, Drawray, any ideas?


what happens when you set transform.position in Unity? Unity has both transform.positionandtransform.localPosition. When I do transform.position.x 3f does unity automatically update transform.localposition? and vice versa? Why can I not see this when I go to the definition of transform.position in VS?


I found out how to rotate both Sphere and Cube (1) like a Turret facing a target but why is it so hard? I just added 3 objects to my scene to a new project. To be sure where the problem is I created a new project. Then added to the scene 2 Cubes and 1 Sphere 1 empty GameObject. Cube is the target. Sphere and Cube (1) are the Turret and both are childs of the empty GameObject. The script is attached to the empty GameObject. The logic say if I will rotate the empty GameObject both Sphere and Cube (1) will rotate at the same time. But I found that if I'm not setting both Sphere and Cube (1) same direction before running the game they will never face to the target only the Sphere. I had to figure out where is the Sphere facing direction before running the game and change the Cube (1) to face the same direction of the Sphere on the Z Blue axis. I can't figure out yet and understand why is it so hard to rotate two objects at the same time to be facing the same direction (target). Now it's working once the sphere and the cube (1) are facing same direction before running the game. It didn't work if I made them childs or parents or changed the Cube (1) position to 0,0,0 nothing. They were both rotating but never faced the target only the Sphere faced the target. So now each time I want to rotate two objects at the same time to face another gameobject like a turret, or cannon or anything that is built of two parts I need first to make them facing same direction ? I guess I did something wrong but not sure what. The script using System.Collections using System.Collections.Generic using UnityEngine public class Rotateturret MonoBehaviour public float speed 3.0f public GameObject m target null Vector3 m lastKnownPosition Vector3.zero Quaternion m lookAtRotation private void Start() Update is called once per frame void Update() if (m target) if (m lastKnownPosition ! m target.transform.position) m lastKnownPosition m target.transform.position m lookAtRotation Quaternion.LookRotation(m lastKnownPosition transform.position) if (transform.rotation ! m lookAtRotation) transform.rotation Quaternion.RotateTowards(transform.rotation, m lookAtRotation, speed Time.deltaTime) bool SetTarget(GameObject target) if (!target) return false m target target return true Here is a link for a short video clip I recorded showing what I mean Video clip of the problem


Reuse and Interact With Multi Layer Tile Maps I'm new to game development and try to make a game where buildings are created in tile maps. My problem is that I need to interact with these buildings and I want to reuse the buildings I created. Now I would like to export these two layers to a single sprite or prefab to create multiple buildings and to make them clickable. Is there a way to achieve this or do I have the wrong approach? EDIT My current setup looks like this Two tile maps One tile map contains the wall of the building. Another tile map contains decoration like door or window. My problem is, that I am not able to export these tile maps as one prefab to reproduce it or to attach scrips. I am looking for a way to combine these two layers into one resource ( The building with all its decorations, doors, windows), so that I can place them anywhere I want and make them clickable as a game object.


Keep state in Unity editor without hitting serialization In my game I have a MonoBehaviour WorldView that, when created at editor time, initializes a large dictionary. Later from a Editor WorldViewEditor I call WorldView.SetBlock() that tries to access this dictionary, but finds it empty. If I understand correctly this is because my editor doesn't access the same WorldView instance, but rather a copy it received through serializing and de serializing my original instance. Pushing this dictionary through the serializing process is a performance nightmare and not supported by Unity out of the box. This dictionary should never be shown in any editor, is private to the instance and initialization will be called every time the scene is loaded. This sounds like a perfect case for keeping it somewhere outside the serialization process. I could try to leverage ISerializationCallbackReceiver but this still requires me to pull the entire dictionary through some serialization process. I'm looking into keeping everything state related in a separate library outside of unity, but this has it own downsides. Is there a way to put this dictionary in a place where its state is kept?


Bring GameObject in front of GUI Texture I have a GUI Texture that dims the screen, however I want certain game objects to not be dimmed. I tried putting them in front of the GUI Texture, but it doesn't work. How can I do this?


Player appears in front of objects even if it's in the background I have a player in Z 0 and a fence object that I want it to be in from of the player so I set it to Z 1, it's a 2D game but in the 3D view I can see that the fence is actually in front of the player but in the 2D view the player is displayed in front. Here are a couple of screenshots. 3D view, fence in front of player 2D view, player in front of fence Any idea how to fix this?


Nestling into contact with a group of physics objects without exerting forces on them I'm making a pool game, and would like the circle (imaginary) to be in contact with the table and balls, and to fit perfectly as a ball would. Now I thought I would use Rigidbody and lerp the position of the circle to the raycast hit, and its collider it would force it into a fitting position. The problem I encountered is that since it has a collider, it also pushes the balls, which I do not want. So my question is, how do I make an object act like it's touching amp blocked by other GameObjects with Colliders and Rigidbodies, without pushing them?


How can I manipulate a layer with click and drag functionality? This works well on clicking layers but not click and dragging layers. public class FishClicker MonoBehaviour public LayerMask whatIsFish public float clickRadius 0.1f void Update() if (Input.GetMouseButtonDown(0)) var mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) var hit Physics2D.OverlapCircle(mousePos, clickRadius, whatIsFish) if (hit ! null) var fish hit.GetComponentInParent lt Fish gt () if (fish ! null) fish.DoClickThing() for DoClickThing() this works public void ControlFishClick() screenPos myCam.WorldToScreenPoint(transform.position) Vector3 v3 Input.mousePosition screenPos angleOffset (Mathf.Atan2(transform.right.y, transform.right.x) Mathf.Atan2(v3.y, v3.x)) Mathf.Rad2Deg for DoDragThing() i want this to work public void ControlFishDrag() stopMovement true rigid2D.velocity new Vector2(0, 0) Vector3 v3 Input.mousePosition screenPos float angle Mathf.Atan2(v3.y, v3.x) Mathf.Rad2Deg transform.eulerAngles new Vector3(0, 0, angle angleOffset) print(stopMovement) for DoReleaseClick() i want this public void ControlFishUp() stopMovement false SnapToPosition()


Show 3D elements on 2D background I'll make a navigation menu in my game and had the good idee to this the enemies to start games or go to the gun store. The problem is when I look in game mode, the enemy named ZomBear in hierarchy and gun are away. The ZomBear and the gun are 3D elements that I will show on a canvas named StartScreen in hierarchy. How Can I do that? (Click on image to see full size) Notes by the hierarchy Everything that begin whit Btn are button elements. StartScreen, PlayButtons and LevelButtons is a panel Gun and ZomBear are 3D elements form the Prefab folder. Here you have also a screen from aside


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


How do I create a circular progress bar in Unity3D 5? I am new to programming and Unity3D. I want to show a circular progress bar starting invisible and growing in 3 seconds to a circular line when reloading is done. How can I do that?


How to set default pose of model from Blender? (Exported as FBX) I have a model that has lots of animation clips(actions). Before export as FBX, I set the pose to named "default" pose and exported as FBX like this. But in Unity, it's changed to first animation clip in animation list in Blender! I try to fix it, but there is nothing I can do. I can't change the order of animations in Blender and Unity either. This wasn't first time, I had same issues before but I just ignored because it's fine in game play, but I really want to fix it this time. What I want is set "default" pose in edit mode in Unity(not play mode). How do I set "default" pose as default, not first animation clip in the list? Using Blender 2.78, and Unity 2017.3.0f3.


Programmatically creating sprite animations in Unity Some background I have a set of animated gifs which I've converted to spritesheets, which are then imported into Unity as multiple sprites. The end result is that each spritesheet in the Unity editor contains a list of sprites named xxxxxxx yyy zzz for example 1313000 000 000 to 1313000 000 014, followed by 1313000 001 000 to 1313000 001 008, followed by 1313001 000 000 to 1313001 000 031, and so on. Now, I would like to make simple sprite animations out of this spritesheet. In the example above, 1313000.anim should contain all sprites beginning with 1313000 played in numerical order, 1313001.anim should contain all sprites beginning with 1313001, etc. etc. This isn't hard to do by hand highlight desired range of sprites, drag and drop but we're talking about a lot of animations. Creating an editor script which lets me right click a spritesheet and generate a series of .anim files seemed the best solution, but I'm turning up conflicting info on the subject. Getting a sprite array from the spritesheet is simple enough, but programmatically creating an animation is something very few people seem to have discussed. Essentially, is it possible and practical to create and populate sprite animations from an editor script?


VS code doesn't recognise new Unity Files Vs code was working fine for some time, and suddenly it stopped supporting new unity c classes Also, there is no regenerate project files option in unity I tried restarting unity and vscode, but no success.... Also, assemblyCSharp doesn't add new files to it....


Visual Studio not updating files made in Unity In the past Visual Studio simply updated solution based on files added in Unity but now all of them have to be added manually and they are as miscellaneous when they are added. How can I fix it?


Touch control pan 3D map I'm working on recreating the board game quot Hex quot as a mobile game. I'm working on implementing zoom and pan features using two fingers. I feel like I managed to get the zoom to work, but the pan moves more than I want it to and I feel like it is because I'm missing something and must be somewhere in the conversion to World Space coordinates. if I could get some help it would be greatly appreciated. For reference, oldMidpoint is initialized to 0 earlier on. Touch touchA Input.GetTouch(0) Touch touchB Input.GetTouch(1) Vector3 midpoint (touchA.position touchB.position) 2 if(midpoint ! oldMidpoint) if(oldMidpoint Vector3.zero) oldMidpoint midpoint Vector3 moveDistance oldMidpoint midpoint moveDistance.y 0 Camera.main.transform.Translate(moveDistance, Space.World) oldMidpoint midpoint


In Unity, how do I create a drag and drop object? I have a 2d scene. I want the player to be able to pick up an object, move it around the scene and drop it somewhere. I can't find any way to do this, and all of the resources for Unity are really daunting and I can't find anything relevant to what I'm doing. I've tried adding the drag rigidbody script to both my camera and the sprite I want to drag, to no effect. Where can I find relevant documentation for stuff like this? Basic things like how to implement a script or what objects I need to attach these scripts to the stuff on the unity website is a little too advanced.


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


How to playlay multiple Particle Systems when colliding with multiple obstacles using object pooling? I have two types of particle, one for each player Player 1 (Red Particle) Player 2 (Blue Particle) When player 1 collides with an obstacle then I want to play the red particle system, and when player 2 collides with an obstacle then I want to play the blue particle system. Code TouchControll.cs public GameObject PlayersPartical void OnTriggerEnter2D(Collider2D other) here my player collided with obstacle foreach (Transform child in transform) if (child.tag "point") GameObject partical Instantiate(twopartical Random.Range(0,1) , transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() GameObject partical Instantiate(PlayersPartical, transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() ObjectPooler.Instance.SpawnFromPool("redandbluepartical", transform.position, Quaternion.identity) ObjectPooler.cs public static ObjectPooler Instance public void Awake() Instance this System.Serializable public class Pool public string tag public GameObject prefab1 public GameObject prefab2 public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt pooldictionary which gameobject you should be pool void Start () pooldictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) add a pool in list Queue lt GameObject gt objectpool new Queue lt GameObject gt () for(int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab1) GameObject obj1 Instantiate(pool.prefab2) obj.SetActive(false) obj1.SetActive(false) objectpool.Enqueue(obj) pooldictionary.Add(pool.tag, objectpool) public GameObject SpawnFromPool(string tag,Vector3 position,Quaternion rotation) two tag red and blue partical if(!pooldictionary.ContainsKey(tag)) Debug.Log("doesnot exist" tag) return null GameObject objecttospawn pooldictionary tag .Dequeue() here how to call my trigger objecttospawn.SetActive(true) objecttospawn.transform.position position pos objecttospawn.transform.rotation rotation rotation pooldictionary tag .Enqueue(objecttospawn) return objecttospawn Image1 Image2 How do I call these particles?


I can add event animation but I can't add keyframe? I am trying to add animation to my UI panel but the problem is I can't add a keyframe to my animation (the button is grayed out). But I can add event animation (the button is not grayed out). Here is the video of what's happening. Anyone know how I can resolve my problem?


Is there anyway to disable the script "gameplay" from running once you start the simulation? Was following the tutorial in this video https oxmond.com how to make multiple copies of a gameobject on how to duplicate object. I want to modify my code I learned from this tutorial https www.youtube.com watch?v OR0e 1UBEOU amp t 4178s so that the bird will increase its size proportion to the distance travel and when scale gt certain value, it break into 2 identical bird object that possess the same properties as the first one. I already did the part size increase in proportion to the distance travel. Now I create an empty game object and attach the script quot explode quot together with prefab of the bird object to it but how to write the proper code to carry out the function if the main bird object is destroyed then it run the code quot explode quot to duplicate bird? using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour Vector3 OldPosition Vector3 DistanceDifference float TotalDistance 0 Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 void start() OldPosition transform.position private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1) DistanceDifference transform.position OldPosition TotalDistance DistanceDifference.magnitude OldPosition transform.position transform.localScale new Vector3(0.2f Mathf.Abs((TotalDistance 0.2f)), 0.2f Mathf.Abs(TotalDistance 0.2f) , TotalDistance 0.5f) if (transform.position.y gt 20.00 transform.position.y lt 20.00 transform.position.x gt 23 transform.position.x lt 23) string currentSceneName SceneManager.GetActiveScene().name SceneManager.LoadScene(currentSceneName) void OnMouseDown() GetComponent lt SpriteRenderer gt ().color Color.red private void OnMouseUp() GetComponent lt SpriteRenderer gt ().color Color.white Vector2 directionToInitialPosition initialPosition transform.position GetComponent lt Rigidbody2D gt ().AddForce(directionToInitialPosition launchPower) GetComponent lt Rigidbody2D gt ().gravityScale 1 birdWasLaunched true private void OnMouseDrag() Vector3 newPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position new Vector3(newPosition.x, newPosition.y) This the 2nd script to duplicate the bird but i'm not sure what the correct codes I have to put in if the 1st game object destroy, then it duplicate 2 bird? using System.Collections using System.Collections.Generic using UnityEngine public class Explode MonoBehaviour public GameObject Bird Update is called once per frame void Update() (if Destroy(Bird)) GameObject BirdClone Instantiate(Bird)


Why does the following code print logs even after the game object is detroyed? I have the following in a script attached to a game object in a unity scene. When I run this scene and press 'E', I get the following logs. (The game object is destroyed too) In destroy After destroy void Update () if(Input.GetKey(KeyCode.E)) Debug.Log ("In destroy") Destroy (gameObject) Debug.Log ("After destroy") My question is that if the game object is destroyed, then why does the execution continue to the code which logs "After destroy"?


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.


How can I create a custom List of GameObject inspector which works like the default one in Unity? I need to drag and drop GameObject to ObjectField. drag and drop a group of GameObjects to list name. The main problem is either do 1 or 2 work. I need the function same as unity List Inspector for future devolvement. Code as follow. static SerializedProperty ThisList public override void OnInspectorGUI() ThisList serializedObject.FindProperty("G") List name call G serializedObject.Update() Show(ThisList) serializedObject.ApplyModifiedProperties() public static void Show(SerializedProperty list) EditorGUILayout.PropertyField(list) EditorGUI.indentLevel 1 if (list.isExpanded) EditorGUILayout.PropertyField(list.FindPropertyRelative("Array.size")) ShowElements(list) EditorGUI.indentLevel 1 private static GameObject a new GameObject 50000 private static void ShowElements(SerializedProperty list) This code can drag and drop GameObject to ObjectField. for (int i 0 i lt list.arraySize i ) list.GetArrayElementAtIndex(i).objectReferenceValue EditorGUILayout.ObjectField("OBj", list.GetArrayElementAtIndex(i).objectReferenceValue, typeof(GameObject)) This code can drag and drop a group of GameObjects to list name. if (Event.current.type EventType.DragUpdated) DragAndDrop.visualMode DragAndDropVisualMode.Copy Event.current.Use() else if (Event.current.type EventType.DragPerform) for (int j 0 j lt DragAndDrop.objectReferences.Length j ) a j (DragAndDrop.objectReferences j as GameObject) Event.current.Use() However, it not work when both codes together. If EditorGUILayout.PropertyField(list, true) I can get the same result as the unity function. but I cant Custom the List. (such as add name, change position, add button...)


Seams between tiled textured cubes I've created a textured cube in Blender, which I have uv mapped like this The tiles are 256x256, and I've mapped the coordinates exactly at the edges (e.g. x 256, y 512). I then export my model as an fbx file to Unity. In Unity, if I put many cubes adjacent to each other, seams appear between the cubes, like this I think I understand why this happens, because the uv coordinates are exactly on the edges, and thus two faces sample from the same points along an edge. I could solve this in some ways By making the uv tiles smaller, but it would look ugly with patterns. By adding some space between the tiles in the texture, and aligning the uv coordinates to them. My question is there a better proper way for achieving this? UPDATE So, about half a year later I still have issues with the seams. I've tried many things Start uv coordinates at 256.5 instead of 256, and so on... Turned of mipmapping. Set wrap mode to clamp. Set filter mode to point filter. Edge padded the texture atlas with first 4px, 8px, 16px, 32px. But still bleeding occurs at certain angles. Also updated the uv coordinates accordingly. Changed my atlas to be of Power of 2 instead, i.e. 1024x1024 instead of 1024x768. Set quot Non Power of 2 quot in Unity to None so Unity doesn't rescale my texture to nearest Power of 2. Set texture format to Automatic Truecolor instead of Compressed. With 32px edge padding it actually gets a lot better, but it still isn't perfect, I guess I could go on and try even more padding, but my textures will get bigger and bigger. I understand now that it is the mip levels that are causing the bleeding. At far distances I don't think this is a problem, but I can see this occuring just about 5 7 units away from the player, if the player is looking down. I believe there is something trivial about this that I'm missing. This is really a showstopper for me, forever grateful to the one who helps me solve this. Thanks in advance! This is how I have edge padded my texture (lines not visible on real texture), the problem does not only occur when the faces has such extremes distinct difference in colors as this one. It also occurs when the faces have patterns.


Unity Odd distortion on default material cube Does anyone know what causes this strange effect that looks like ripples? This is simply the default material on a cube and should be perfectly smooth. (Clear example at top right of image) Another example


Player must places the object in the preset position I want to know how to do like this video https youtu.be 6gouxqSxeG8 At the minute 3 09, the player can put the street vendor in the predetermined location (with the green arrow show that place). Please tell me some keyword about this or video tutorial about how to implement it in unity 2d. Thanks.


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


Flatten transform hierarchy at build time Nested hierarchies cause a performance overhead when they include moving objects. Every time a GameObject moves, altering its transform, we need to let every game system that might care about this know. Rendering, physics, and every parent and child of the GameObject needs to be informed of this movement in order to match. As the scope of a game increases, and the number of game objects skyrockets, just the overhead of sending out all these messages can become a performance problem. However, nested hierarchies are useful in organising a scene and keeping logical groups of gameobjects separate. What options exist to save performance whilst keeping the hierarchy? Is there any pre existing solution to flatten a hierarchy when building only?


Change animation speed through the editor in Unity How can I change the speed of the animation through the editor if I have the following animation structure? I would like Adult1 walk to play faster.


Make a flying object rotate so the camera sees the rotation When I attach a camera to my flying object (plane), when I rotate the object, the camera is perfectly following it so you can't really "feel" the plane rotating. I want to create the effect that you see in flying games where you see the plane rotating along the x axis (so you see the nose go up and tail down) while also semi following the plane, creating a better effect. How do I achieve this?


Unity3d Cross platform Input GUI Depth I'm creating my GUI controls in Unity 5.3 I have a joystick in which overlays a swipe pad. Originally all of the controls were working fine. However, now the touch pad is overlaying the Joystick. In previous verisons you could focus the window GUI.FocusWindow(0) I've tried reassign the order by making one a child of the other and vise versa yet nothing works. Does anyone know how to control the Z index of the controls, or make one overlay the other. I've looked at the GUI depth documentation, but I don't see how I could apply that here. Does anyone know how to control the depth of cross platform controls in unity?


Find out reason for automatic break Soon after I press the Play button, the Unity break button automatically gets activated Unity gets into Pause mode I have attached the Unity debugger to my C code, but Visual Studio doesn't break. How could I find out the reason why Unity goes into Break mode? Thank you! Edit Per request, here is the button before pressing Play And here is what the console looks like after the error occured


Ice transition particle effect We are small indie team developing a casual mobile game. We are trying to implement an effect like the normal to ice block transition in Angry Birds 2 How can we implement an effect like this in Unity?


Unity (UNET) Pass custom data when creating and joining a match in multiplayer I've written some simple stuff to make a lobby for matchmaking. Now I want to pass some extra info besides the match name to the lobby. Something like Player's avatar and a number of players connected and what not. Thereto, I also want to pass information to the game from the players. For example, two players connect to a match and the character pick starts. For this I want to have the player's info regarding the characters they've picked and the character's weapons info (e.g. customized weapons info). I store all that in a json file and load from it to a class object. Is it ok to add these classes to, say, the player connection prefab that holds Network Identity or is it done somehow differently? Can someone maybe help me with that in the context of Unity 2018 (i.e. give some advice or referrences to some relevant information)? Appreciate all the help and thanks in advance.


Creating a working game with Unity3D? I recently start learning Unity3D and following VTC's video tutorials and others tutorial, so far i've found it very easy to work it and to create stuff, i havent got to the part where i need to script anything YET. While i still havent hit the scripting part yet i did like to ask Do i really need to script anything to make a simple game with it ? (why am i asking this ? until now from the tutorials i've been watching it seems that unity3d has most of the physics and codes needs to create a working version of a simple game, for example making falling crates, the rigidbody functions, it taking into account flags and grass being touched by the wind and moving) What are some simple examples of where will i be scripting for ? (just wondering if there will be something to script for even for a simple game and what would that be) When i build the finish project will it compile everything as if it was a VS project and make a working version without the need of any other wrappers for it is data, etc ? (this is sort of self replied by their webpage but i just wanted to confirm if i got this right) I am aware those might be subjective questions but while i am unexperienced with it and havent found anything related to those questions yet or havent meet the end of a project to be able to confirm for myself i would like to receive some advices and information in regards this. PS i did a search but i was not sure of what should i look for to find answer for this kinda of questions so if this is a duplicate of any sort let me know and i will delete it once i am pointed out for the duplicate. Best regards.


Recalculating Stats After Any Change? I have four sources of a character's stats changing (in order of calculation) Due to leveling up (base stats) Equipment changing (calculated after base stats) A passive skill being toggled on or off (calculated after equipment stats) Being afflicted by a buff debuff (calculated after passive skill stats) My question is, if any of these sources causes a change, should I recalculate everything from base stats, or store "sets" of the stats after each change (i.e. save a copy of the stats after passive skill changes, so if the player is hit by a "defense down" status effect, I only have to recalculate from skill stats). Unless there's a better way to deal with this problem, I don't know which of these two options is better.


I have a game based on combining 2 ingredients to create a product. What is the best way to code this? (Unity) So to go a bit more in depth, in my game, you can combine a variety of ingredients to make a product. For example, you could combine water and dirt to make mud. What I am currently doing to achieve this is by listing each combination possibility that a particular ingredient has. The one thing i managed to do to make it a little more efficient is that I managed to remove duplicates (So for example, if i have coded ingredientA IngredientB Cheese, there isn't another entry for IngredientB Ingredient A Cheese). The problem I have with my method is that it is very annoying adding new ingredients. If i do so, I have to go back to every previous ingredient i have coded, and add it's interaction with the ingredient(s) i want to add. The amount of ingredients I have means this is becoming increasingly time consuming. Is there a better way to do this? This is a Unity game, coded in C . Let me know if you need any further info.


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


How to add the sound effect of a ball rolling, based on his velocity? I have a ball which roll (like all ball does ) ) ... My ball can roll on different type of surfaces (2 or 3) and at different velocity. I don't know how to approach to reproduce in my game the sound effect. I can assume to do Get an Sfx of a rolling ball Run in loop if my ball is moving then ? Well.. i need some help. Thanks


Unity game crashes when opened on some computers but not all I'm facing a weird issue where every time I attempt to run a Unity application, it just crashes with no error message or log being generated. I tried running the game, it works on some computers (3) but fails on most (35). Upon attempting to run the application, I get a box that pops up for a second with a red exclamation point, which then crashes. See screenshot below I have found people having similar problems, but no real solution. https forum.unity.com threads solved crash when running any unity application.599953 https forum.unity.com threads crash when opening any unity application.873133 My game is made in Unity (v2018.1.9f2). Attaching the error logs for your reference. Unfortunately, I do not have the admin privileges to try the citrix solution in lab computers (since they are controlled by the University office). Error logs https pastebin.com mcMaD9im https pastebin.com M0e9a9GG https pastebin.com DSRrU8bZ


Procedural Islands Voronoi Pattern I'm trying to keep this as simple as possible, as I've found out the last few days this is a very difficult topic. I'd like to generate multiple flat islands, formed by a voronoi diagram. I've followed a long and (for me) difficult tutorial of building a procedural hexagonal grid just to find out it looks to artificial. I'd like to create a plane with faces divided in a voronoi diagram, and extrude multiple groups upwards to create islands. With that I'd like to achieve something similar as this http applemagazine.com wp content uploads 2015 10 image2.jpg Please help to get me started in the right direction, since my approach might be wrong in itself. EDIT I've found this https github.com jceipek Unity delaunay. Which draws lines in a voronoi diagram. Now I'm guessing the next step is to convert this to a mesh. Then I'd have to highlight random faces to be extruded to create the islands. Maybe this could be done with perlin noise, which I've just learned about. Extruding might not be the best way. Maybe deleting the faces that won't be land, and creating fall of edges (Like Wardy said). I'm doing my best to figure this out on my own, but any help is greatly appreciated.


Rushing water in Unity How would I go about creating a river with rushing water? I can do the texture around it but I'm stuck on the actual water part. This is in Unity3D.


Is Mogre (essentially Ogre, but C ) dead? If so what would be a viable alternative to it? I've been looking around for a 3D engine where I can use C to replace Unity lately, but haven't really come up with much. Ogre looked promising, but it wasn't C however Mogre is. Sadly looks like it hasn't been updated since Feb. 2014. With the said are there any viable alternatives to it, or Unity? Or better yet is there a nightly I missed somewhere for Mogre?


How to link my weapons with their corresponding ammo supply in the Unity Inspector? In my game I would like to implement a universal ammo and weapon system that would be usable for any kind of weapon. So I declared an ammo class using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Ammo public int MaxAmmo public int CurrentAmmo public Ammo(int maxAmmo) MaxAmmo maxAmmo public void MaxOutType() CurrentAmmo MaxAmmo public void GetAmmo(int amount) CurrentAmmo amount public void UseAmmo(int numOf) CurrentAmmo numOf Then I created a script to hold different Ammo types using System.Collections using System.Collections.Generic using UnityEngine public class AmmoSystem MonoBehaviour SerializeField public Ammo Basic new Ammo(200) public Ammo Rockets new Ammo(50) public Ammo AirRockets new Ammo(75) public Ammo Cells new Ammo(150) To organize my project I decided to make two weapon scripts one for nonphysical(Raycast) projectiles called RaycastingWeapon and an another for physical ones(like a rocket launcher) called PhysicalProjectileWeapon My plan was to create unique weapons using these two scripts from the inspector. These would use different kinds of ammo but would share the same script with different properties. The essential aspect here is that I would like to be able to select an ammo type from the inspector using a dropdown menu for example. Is it possible somehow or are there a better way of doing that?


Override the position of bodypart with script on top of animation I have a character with an Idle and Move animation. Now I want to create an Attack animation. Here I want the hand to move towards the mouse position and back, using a script. The other hand should still follow the Idle or Move animation. When I use a script in FixedUpdate() to do this the position of the hand still follows the animation. If I use LateUpdate() and set hand.transform.position, this seems to represent the local position and not global position. Is there a proper way to create this Attack animation? using UnityEngine public class Attack MonoBehaviour public Camera camera public Transform body public Transform hand public string button public float time 5f public float begin 3f public float end 6f float step 0f bool pressed false float currentTime 0f int direction 1 private void Start() step (end begin) time private void Update() if (!pressed amp amp Input.GetButtonDown(button)) pressed true private void LateUpdate() if (pressed) setCurrentTime() Vector2 mouse camera.ScreenToWorldPoint(Input.mousePosition) Vector2 direction (mouse (Vector2)body.position).normalized hand.position (Vector2)body.position direction (begin (step currentTime)) void setCurrentTime() currentTime currentTime direction Time.deltaTime At End if (currentTime gt time 2) float overhead currentTime (time 2) currentTime currentTime overhead direction 1 Back at Begin if (currentTime lt 0f) pressed false currentTime 0f direction 1


Changing text through a cursor hover trigger In my game I have several house groups (see image below), I want to show a specific message when the mouse hovers a specific house group. For some reason, this only works on the first switch case (house) but fails on the second switch (house2). The default case doesn't work either. I verified that the case house2 is found by the engine. By not working I mean the text does not appear. Do you have any idea about the problem? Code public class MouseIsOver MonoBehaviour private Image TipImage private Text textObject public string text private bool displayInfo void Start () TipImage GameObject.Find("realtyInformation").GetComponent lt Image gt () textObject GameObject.Find("realtyInformationText").GetComponent lt Text gt () TipImage.enabled false void Update() Display() void Display () if (displayInfo) switch (text.ToLower()) case "house" textObject.text "house text1" break case "house2" textObject.text "house text2" break default textObject.text "Click on the building" break else TipImage.enabled false textObject.text "" TipImage.enabled true private void OnMouseOver() displayInfo true private void OnMouseExit() displayInfo false


How do i make an object to be visible only on a particular layer? Please refer the image below to understand. I am working on 2D game. I have three elements "background(layer 0), foreground(layer 1) and the object". I have used sprite renderer to set background and foreground images. Object gets instantiated during runtime. How do i make Part A of the object invisible? I want to make object visible only on foreground. If the object is completely on the background, it should be completely invisible. if the object is completely on foreground, it should be completely visible. Part A and Part B are just for reference. It is one single object. The goal to be achieved is the image below


How to convert a premade mesh into voxels so I can use algorithms such as marching cubes I have a mesh that was created in a 3D program which is the terrain the player will walk on. I want to allow the terrain to be deformable by the player, but for it to be smooth (not like Minecraft). From what I have read from existing questions similar to mine, I need to use an algorithm such as Marching Cubes (which I don't understand yet). From what I understand, those types of algorithms are suited for procedural generation. My question is How do I convert my mesh into voxels so that I can use algorithms such as Marching cubes? Is it simply a matter of cutting up my mesh in chunks? If it helps, I will be using C and Unity 3D.


How to create a looping or spherical world? I wish to create a 3D first person world, in which the player, once they reach one end of the map are unknowingly transported back to the opposite end, or a spherical world with a surface where the player can walk on while still experiencing gravity like normal. Unfortunately I couldn't find a good solution for doing that in either unity or ue. Any ideas would be appreciated.


Do i lose performance doing this public class TileObject MonoBehaviour some code was here public PlayerAnimator playerAnimator some code was here public void SetTileObject(int xPos, int yPos, TileData tileData) some code was here if (tileData.player) playerAnimator new PlayerAnimator() And my question do i lose any performances(or memory) doing this instead of inheritance or something else.(tileObject can be other than player)


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.


Call a function by name in Unity This might be a bit misplaced but is there a way to call a function by name in Unity? I've tried Invoke(string, float) but that doesn't accept parameters. I've tried StartCoroutine but that requires a yield return new statement. I've also tried reflection, like this Type thisType this.GetType() MethodInfo theMethod thisType.GetMethod(TheCommandString) theMethod.Invoke(this, userParameters) But this doesn't even compile giving an error of NullReferenceException Object reference not set to an instance of an object and I don't really know why. Thanks for the help guys.


How to always land a square box in 90 degree How can i Always Land a box in 90 degree Here What i want Here what i don't want public Rigidbody2D boxRb public float jumpSpeed public Vector3 rotation public float rotationSpeed public bool rotationEnabled public float gravityMultiplier void FixedUpdate() if (Input.GetMouseButtonDown(0)) boxRb.velocity jumpSpeed Vector2.up if (rotationEnabled true) transform.Rotate(rotation rotationSpeed Time.deltaTime) if (Input.GetMouseButtonDown(1)) boxRb.velocity Vector2.up Physics2D.gravity.y (gravityMultiplier 1) Time.deltaTime void OnCollisionEnter2D(Collision2D collision) rotationEnabled false Debug.Log("Collided") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX transform.Rotate(0, 0, 90f) void OnCollisionStay2D(Collision2D collision) rotationEnabled false Debug.Log("In collison") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX void OnCollisionExit2D(Collision2D collision) rotationEnabled true Debug.Log("Free") rotationSpeed 10f


How can I detect continuous touches pressed with Unity 4.6's UI elements? I've recently switched to Unity 4.6. My previous workflow when creating continuous input controls (the kind where you measure continuous touch input on a single button) was to create a GUITexture and then perform hit testing on that texture as long as a finger was touching the screen. With the new GUI there seems to be no way to measure this type of input, as GUITextures objects can no longer be created and the new UI types don't support hit testing. I'm talking about a button that's supposed to act like a car accelerator where, for example, a simple OnClick() doesn't work because I need to measure if the button is being pressed continuously rather than it working as an on off toggle. How can I implement this?


Unity2D Item selection previous button not working! I'm having a problem with my item selection script. As you can see in the video, button 3 (when the previous button is pressed) goes straight to button 1, instead of going to button 2 and then button 1. Can anyone help me with this issue! Thank you. My script is listed below int activeObject 0 public GameObject tool01, tool02, tool03, tool04, tool05, tool06 public int max number of objects in the button press code public void Right() increment the active object, wrapping around to 0 activeObject if (activeObject gt max number of objects) activeObject 0 here's another way to do this that eliminates the conditional logic just pick one of them don't do them both look up the modulus operator ( ) activeObject (activeObject 1) max number of objects RightActivateObject (activeObject) public void Left() activeObject if (activeObject lt 0) activeObject max number of objects here's another way to do this that eliminates the conditional logic just pick one of them don't do them both look up the modulus operator ( ) activeObject (activeObject 1) 1 LeftActivateObject (activeObject) activate the selected object void RightActivateObject(int activeObject) switch (activeObject) case 0 tool01.SetActive(true) tool02.SetActive(false) tool03.SetActive(false) break case 1 tool01.SetActive(false) tool02.SetActive(true) tool03.SetActive(false) break case 2 tool01.SetActive(false) tool02.SetActive(false) tool03.SetActive(true) break void LeftActivateObject(int activeObject) switch (activeObject) case 0 tool04.SetActive(false) tool05.SetActive(true) tool06.SetActive(false) break case 1 tool04.SetActive(false) tool05.SetActive(false) tool06.SetActive(true) break case 2 tool04.SetActive(true) tool05.SetActive(false) tool06.SetActive(false) break


Model mesh overlapping while animating in Unity but not in Blender I made an FPS model in blender and created reload animation when I imported that model in Unity I saw that while the magazine ejecting from the rifle it overlapped some of the gun parts. Then I went back to the blender and changed some keyframes and positions in the blender but in Unity, it showed me the same problem. I tried many times it looks fine in the blender but in the Unity, it has the same problem.


How to create a custom set of coordinates based on two points in Unity? As the title says, I am having problems finding a way to create a new set of local coordinates based on two points. Here is an example Consider that the two gameObjects are not one parent of another, therefore I cannot use something like transform.localPosition, furthermore I tried using transform.TransformPoint(), however the latter works only if if I want to create it with respect to a single point. I think it is a silly question, yet I am not finding a way to solve it, so any help is greatly appreciated!


What's the point of HiddenInInspector (as opposite to NonSerialized )? I understand the difference between HiddenInInspector and NonSerialized , what I'm missing is the use case for HiddenInInspector so far every time I've encountered it, it was used by developers who weren't aware of NonSerialized , that would actually have meant to use that. The result is that they risked to get unexpected values when the variable in question was deserialized. So, in which case it turns out to be useful to hide something from the inspector but to serialize it? If there is such case, are there any known precautions to take in order to prevent unexpected behaviour?


Exporting scene during gameplay to FBX In Unity is there a way to add a menu button during gameplay that allows the player to export the current scene as an fbx file? My googling and research shows that its possible to do this while developing the game but wondering if there is a way to add this functionality for the gameplay itself. Any suggestions on how if this can be done?


Character Model crashes game (Unity VR) I am creating a VR game. Currently, I'm testing it on an Android device. Now I when I run the application it runs smoothly and without any issue. However when I add the following model And attempt to look at it the game crashes. The model you see doesn't have any scripts on him only a transform component and an animator. Has anyone tried something similar? or have an idea what the issue might be? Update i have also tried this following scene So i tried to isolate the character completely from my original scene. So i made this Again if i have the character in the scene it crashes. if i remove the character it runs perfectly fine. Another update If i remove the animator component from the model it works fine?


Mesh fading to transparent I have a 2D Mesh object generated at runtime painted all with uniform color. I want that mesh to have its color fade to transparent color close to the edges. Despite I searched everywhere I could not find any solution. Unfortunately I'm not into Shader programming enough to build logically my solution. EDIT According to wondra's reply my mesh is not fan shaped. It has a non regular hole in it. How can I achieve this?


In Unity3D, try to load a png into a Texture2D in an Editor script and then run PackTextures, but they need Readable flag to be set I am trying to automatically create a texture atlas from a set of generated png files in an Editor script. The problem is that I can't seem to be able to load a png into a Texture3D without it being inaccessible by the PackTextures method. I have tried a few different ways to load the PNGs, such as Resources.LoadAssetAtPath(...), AssetDatabase.LoadAssetAtPath(...) and a few more. Since all of this is done in OnPostprocessAllAssets, I don't want to have to do any manual editing of the textures. I just want to be able to drop a PNG into a certain folder and get an updated atlas. Answers such as this seem to suggest manual editing. The actual error message is "Texture atlas needs textures to have Readable flag set!". So the question is, is it possible to do this kind of post processing in Unity3D? Is there any way to import a PNG into a Texture2D with the Readable flag set, without having to manually change it?


How to efficiently batch blocks and reduce drawcalls in a voxel like game To fully get the benefits of GPU instancing in Unity in a voxel like game I'm trying to batch as many static blocks as possible (the terrain won't be destructible, and I can't set these blocks to 'static' since I'll later need to assing different properties for each instance) I see two possible solutions for this kind of problem Creating a prefab for every possible block in my game, and batching togheter blocks with the same material mesh uvs pros won't need giant textureAtlas for storing albedo textures cons certain scenes with many differing terrain blocks may be hard to batch efficiently, and adding a property to every type of block would mean changing every block prefab (a nightmare if I have more than a handful of biomes) Creating a single block prefab and offset it's UVs with MaterialBlocks directly in the fragment shader pros every scene involving terrain blocks should at least in theory be efficiently batched, a single prefab to describe every type of terrain block cons needs a giant texture Atlas, and if it doesn't fits all of the block textures in the game more textures will be needed and I'll be limited in the future in the amount of blocks my game can have (unless I create different materials with different texture bindings, defeating the purpose of this solution), fragment shader overhead for every type of block in the scene Am I missing something here? Is there a different approach? If not, which one of the two would you consider the most appropriate in this scenario?


Custom shadow mapping in Unity. Works with preservative Light view but not with Orthographic So about a week ago I decided to make my own shadow mapping technique in Unity based on my understanding of the whole thing. The entire experience was somewhat successful. I learned a lot and I get to correct a lot of things such as the MVP matrix and the math behind it. One thing though didn't work as planned and I don't know why. First lets talk about what worked. I wrote a replacement shader that will show the depth of every object based on the Light Position perspective. Therefore I made a custom Light GameObject that act as a camera light with that replacement shader attached to it, and I record everything the Light sees into a render texture. Then I made a second Camera which is basically a child of the main camera, and sees what the main camera see with the exception of the replacement Shader that I attached previously to the Light gameobject. again I recorded everything from the camera to a render texture as well. After that, I wrote a basic Shader that does a basic light calculation and make a the shadow comparison between the two textures, and determines whether a fragment in a shadow or light. Also, I added a shadow Bias as well to eliminate any artifacts. struct appdata float4 position POSITION float3 normal NORMAL float2 uv TEXCOORD0 struct v2f float4 position SV POSITION float2 uv TEXCOORD0 float3 normal TEXCOORD1 float3 worldPos TEXCOORD2 float4 Tint sampler2D MainTex sampler2D SahdowMap Light, SahdowMap View float4 MainTex ST float4x4 WorldToCamera, WorldToLight float3 LightDir1 v2f VertexProgram(appdata v) v2f i i.position UnityObjectToClipPos(v.position) i.worldPos mul(unity ObjectToWorld, v.position) i.normal UnityObjectToWorldNormal(v.normal) i.uv TRANSFORM TEX(v.uv, MainTex) return i float Shadow Cal(v2f i, sampler2D DepthMap,float4x4 space) float4 projected2 mul(space, float4(i.worldPos, 1.0f)) float2 uv ( projected2.xy projected2.w) 0.5 0.5 float Shadow tex2D(DepthMap, uv).r if (uv.y gt 1.0) Shadow 0.0 return Shadow float4 FragmentProgram (v2f i) SV TARGET float LightDepth Shadow Cal(i, SahdowMap Light, WorldToLight) float ViewDepth Shadow Cal(i, SahdowMap View, WorldToCamera) float bias max(0.05 (1.0 dot(i.normal, LightDir1)), 0.015) float Shadow LightDepth bias lt ViewDepth ? 0 1 float4 Texture tex2D( MainTex, i.uv) float3 lightpos LightDir1 i.worldPos return saturate(dot(lightpos, i.normal)) Tint Texture Shadow The problem is when the Light is on perspective, this works perfectly fine as shown above, but when I switch the light camera to Orthographic this happen I tried many different things to fix it but I failed. I would love your insight in this whole thing, your thought, solution or even a suggestions. You are free to download the whole project as a package here Download Special thanks to DMGregory.


I installed Linux Build Support, but I need an archive to build, how can I get this? I m building a game for Mac, Windows and Linux, I builded the Windows and Mac game, but in Linux, says that need a x86 64 archive, like the image shows, what do I do?


Streaming 3d model unity android I want to include a feature in my game that allows me to host raw 3d models (.fbx .obj etc., not AssetBundles) on a server. The game should download these files, save them to the device and load them into a scene. I want to support multiple file formats, so writing my own parser is not an option! First idea Use the WWW class to load the model data, save it as a String in the player prefs, and load it if requested.(the last part is the problem) Second idea Use the WWW class to load the model data, extract the jar file containing StreamingAssets folder to the sdcard. Writing the model data into a new file in this directory. Creating a new ZIP..ah...JAR archive from the folder and replacing the old .jar file.Of course I would need an Android Plugin and a archive java library for that. Then the Models will be loaded from the Ressources.(this is a pretty weird idea and cannot be the right way) Do you know, if that works?Has anybody ever done something like that? UPDATE 1 I tried to use the obj loader from samed tar k et n's comment, but I got this error ArgumentNullException Argument cannot be null. Parameter name key System.Collections.Generic.Dictionary 2 System.String,UnityEngine.Material .get Item (System.String key) (at Users builduser buildslave mono runtime and classlibs build mcs class corlib System.Collections.Generic Dictionary.cs 136) GeometryBuffer.PopulateMeshes (UnityEngine.GameObject gs, System.Collections.Generic.Dictionary 2 mats) (at Assets OBJ src GeometryBuffer.cs 145) OBJ.Build () (at Assets OBJ src OBJ.cs 236) OBJ lt Load gt c Iterator0.MoveNext () (at Assets OBJ src OBJ.cs 63) Replacing line 145 in GeometryBuffer.css with gs i .GetComponent lt Renderer gt ().material new Material(Shader.Find("Standard")) did resolve the runtime error and a Material, OBJ (Mesh Filter) and Mesh Renderer Component have been added, but it still show a model. UPDATE 2 I am behind a proxy so loading the model from the web didn't work. Loading .obj files from file lt path to obj gt works perfectly fine though.


Enemy walks to the nearest player? I'm trying making my enemy goes to the nearest player to him but what i get is kind of hesitated or shaking. I think is from the first line on Update but i don't know how to solve it. Here is my script private Animator enemy anim private NavMeshAgent mAgent private GameObject player public GameObject dead point public int farPoint, dead point number,player number public float dist public bool enemt run, enemy atack false void Start() mAgent GetComponent lt NavMeshAgent gt () enemy anim GetComponent lt Animator gt () player GameObject.FindGameObjectsWithTag("Player") dead point GameObject.FindGameObjectsWithTag("dead point") 3 points enemy dirction() void Update() player number Random.Range(0,player.Length) dead point number dead point.Length dist Vector3.Distance(transform.position, player player number .transform.position) if (player ! null amp amp dist lt 5.1f) mAgent.destination player player number .transform.position if (dist lt 1.2f) enemy atack true else enemy atack false else if (dead point number gt 0) mAgent.destination dead point farPoint .transform.position else mAgent.destination player player number .transform.position if (mAgent.remainingDistance lt 1.5f) enemy atack true else enemy atack false enemt run true mAgent.speed 1.0f enemy anim.SetBool("run", enemt run) enemy anim.SetBool("attack", enemy atack) end update void enemy dirction() if (dead point number gt 0) farPoint Random.Range(0, dead point.Length) mAgent.destination dead point farPoint .transform.position else


Animating a rigged 3D model in untiy I made this 3D model of sonic in Blender complete with its own rig for animating. I would like to use this for testing 3D movement in unity along with the animator tool. However, when I export the fbx file to my unity project it shows up as intended with the armature and the mesh, however, moving the individual components of the rig have no effect on the mesh? I'm not sure why this isn't working like blender, any help in regards to reading material or any options I have left unchecked that prevent this from working would be greatly appreciated! I know I havent given much information here, but I havent been able to find a good tutorial on any of this that doesnt involve importing animations from another program, I just want to be able to rig and animate a model I made in blender using Unitys animator tool.


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


Unity3d How to freeze a Animation in the Editor Is it possible to freeze my Animation in the Editor at a specific frame? I made a simple camera animation, I try to select a specific frame inside of that animation and pause it, so I can work in the editor with everything positioned at the current positions at that specific frame. This does not work at the moment. If I select my desired frame and then select another object, then my animation is set to start again. This makes it very hard to work in the editor and prepare the animation. EDIT Ok I try to explain it more simple. Let's assume I am animating the main camera and I have three animation points, A, B, and C. (I know I have more, but lets just assume it for this example to simplify it) At A the camera is obviously at the start position At at B it is somewhere in between A and C At C the camera is at the end position What I need is to pause the animation at B, so my animation object stays at this position the whole time, even though when it has no focus and another object is selected. This would make it much easier for me to place objects exactly where I need them. What actually happens is that my animated object (maincamera) is set to it's "start position", but I need it to stay in place, so I can place other objects perfectly. I hope that was clear enough. (side note as you can see this is bugged, the rotation is weird now...)


How to determine size of art assets for Unity UI? Previously when I made games, I used ui assets from the asset store. Working with those assets was easy as the backgrounds were plain. However, I'm now working on a game where custom graphics are used for UI. So, I need to specify size of backgrounds,icons etc to the art team. I understand how aspect ratio works with regards to unity camera, but having trouble understanding the relation between camera size and Canvas. For example, for a camera size of 4.6, an image size of 517X920 will cover the whole screen in 9 16 aspect. However, the same image is considerably larger when used as UI image under the Canvas. Can someone please help me understand how Canvas deals with image sizes?


Communication between Photon Cloud game and web server I am creating a multiplayer game using Photon Cloud (Photon Unity Network). For storage of player data (profile, inventory, achievments) I use web server (asp.net mvc amp sql server). How to organize the communication between the game client and the web server? I see two ways Use WWW class and send requests direct to web server var www new WWW("http mygame.com api user.get?id 1") Each time creates a new connection to the web server Use Photon Cloud Webhooks and send requests through Photon servers PhotonNetwork.WebRpc("user.get?id 1") Photon Servers play a Proxy or Relay role between client and web server mdash http doc.photonengine.com en realtime current reference webrpc Which way do you recommend? The first way is simple but each time creates a new connection to the web server. The second way use one persistent connection between client and Photon server but there is a delay between connecting the Photon server to the web server.


How to add isometric (rts alike) perspective and scolling in unity? I want to develop some RTS simulation game. Therefore I need a camera perspective like one knows it from Anno 1602 1404, as well as the camera scrolling. I think this is called isometric perspective (and scrolling). But I honestly have no clue how to manage this. I tried some things I found on google, but they were not satisfying. Can you give me some good tutorials or advice for managing this? Thanks in advance


How to add friction to Unity HingeJoint? I attach a rigidbody to a HingeJoint in Unity. It's attached no at the the center of an anchor of a joint. To stop it from falling I set Use Motor true, Target Velocity 0 and apply some force to the motor. However, this does not help, see video http g.recordit.co JJ0cmfT1Mb.gif Here is the sample project https drive.google.com open?id 0B8QGeF3SuAgTNnozX05wTVJGZHc Screen from sample project to reproduce the issue (there is no code) How can I apply a friction to a joint to stop rigidbody from moving? Setting spring with damper or applying a limit is not an option for me, because I need to rotate the rigidbody correctly when I apply enough torque (force) to a motor. If I switch damper limit on and off, the rigidbody will move faster when it is rotated in a direction of falling and slower when it is rotated in opposite direction.


LookAt only in Z axis I'm fairly new to game development, like many of us asking questions here Currently, I'm trying my luck working on a simple space shooter. I'm trying to add some enemy ships with movement, they will only move forwards, but, at all time, will be facing the player ship I have that figured out, after playing with many options, LookAt was my saviour, but now, I'm having an issue, they do rate to face the player, but they also rotate on the Y axis This is how they are in the editor looking This is the position setting Their properties Their code using UnityEngine public class AlienMovement MonoBehaviour public GameObject PlayerShip public float speed Use this for initialization void Start () GetComponent lt Rigidbody gt ().velocity transform.up speed 1 Update is called once per frame void Update () transform.LookAt (PlayerShip.transform, Vector3.up) And how they look once the game is running (frame still) Transform properties for the one on the right Any idea what I'm doing wrong?


Unity using raw mocap data without actually moving the character I play around with animations and unitys raw motion capture data asset pack. My problem is as followed I have an idle, walkforward and a runforward animation and play them based on the keyboard input. But i realized when i move my character backwards (using a movement script) but still playing the walkforward animation the character basically moves backward and forward at the same time. So how can i play the animation but without actually effecting the position of the character? Thank you


How to keep the ball on zigzag movement? I recently make a zig zag movement it works perfectly but after the ball hit the collider or obstacle the ball is changing their direction like just forward, not zig zag anymore I've tried to update the velocity after collide but it's same, also I have tried to constant the magnitude but that's not what I want here my script public float magnitude public float forwardSpeed public float horizontalSpeed private Vector2 horizontalAxis private Vector2 negationVector public Rigidbody2D rb2d public m GameManager GameManager public bool isOver false private void Awake() horizontalAxis Vector2.right negationVector new Vector2( 1f, 0) private void Start() GameManager FindObjectOfType lt m GameManager gt () UpdateVelocity() private void Update() if (Input.GetMouseButtonDown(0)) ReverseHorizontalVector() UpdateVelocity() private void ReverseHorizontalVector() horizontalAxis negationVector private void UpdateVelocity() Vector2 velocity GetCompositeVelocity() rb2d.velocity velocity private Vector2 GetCompositeVelocity() Vector2 forward Vector2.up forwardSpeed Vector2 horizontal horizontalAxis horizontalSpeed Vector2 composite (forward horizontal) return Vector2.ClampMagnitude(composite, magnitude) private void OnCollisionEnter2D(Collision2D collision) UpdateVelocity() private void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject.CompareTag( quot Goal quot )) GameManager.IncreaseScore() if (collision.gameObject.CompareTag( quot L quot ) collision.gameObject.CompareTag( quot R quot ) collision.gameObject.CompareTag( quot Death quot ) collision.gameObject.CompareTag( quot Player quot )) StartCoroutine( GameManager.waitAfterDeath()) isOver true like I said before the ball zig zag but after colliding the movement change like that.


Fading alpha color with overall time. It's working but I need some help with some things to fix change add This is more or less what I wanted, It's working in general but there are things to fix add change using System.Collections using System.Collections.Generic using UnityEngine public class FadeInOutSaveGameText MonoBehaviour public Animator animator public Canvas canvas public float fadingSpeed private bool stopFading false Start is called before the first frame update void Start() StartCoroutine(OverAllTime(5f)) IEnumerator CanvasAlphaChangeOverTime(Canvas canvas, float duration) var alphaColor canvas.GetComponent lt CanvasGroup gt ().alpha while (true) alphaColor (Mathf.Sin(Time.time duration) 1.0f) 2.0f canvas.GetComponent lt CanvasGroup gt ().alpha alphaColor if(stopFading true) break yield return null IEnumerator OverAllTime(float time) StartCoroutine(CanvasAlphaChangeOverTime(canvas, fadingSpeed)) yield return new WaitForSeconds(time) stopFading true StopCoroutine( quot CanvasAlphaChangeOverTime quot ) Things to fix change Does the line StopCoroutine really work ? If I'm not using the helper flag and make break inside the loop then the fading weill never stop. Should I use a helper flag and break only or also StopCoroutine ? When the CanvasAlphaChangeOverTime Coroutine stop then the fading also stop at the same point it is. but I want it to finish fading first depending on the fading direction. If it was changing to the 0 then first finish fading to 0 then stop the Coroutine and same if it was more then 0.5 changing to the 1 then first finish changing to 1 then stop the Coroutine. Things to add An option to change the fadingSpeed in real time while the fading is working ? How to do it ?


I want a variable field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid? I want a field I declared (float attackRange) to be only declared when inheriting class set "bool haveLongRangeAttack" is set to true. I wanted to use Compiler Directives for this purpose. Here is the code I wrote using UnityEngine public abstract class Enemy lt T gt MonoBehaviour where T Enemy lt T gt SerializeField protected bool haveCloseRangeAttack false, haveLongRangeAttack false if haveLongRangeAttack true SerializeField protected float attackRange 1f endif SerializeField protected GameObject mainCharacter null protected GameObject enemy null protected virtual void ChasePlayer() if(haveCloseRangeAttack) ... else if(haveLongRangeAttack) ... I don't know if it is right way to of do what I want or using Compiler Directives so please review my code and tell me if there is a problem, or if there is a better way. It was before 6 months when I started writing code, and C was my first language. I am trying to learn new things concepts and writing at my own style. So there will be another way (maybe more efficient) if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me... TY for taking time . ! PS There is no compiler directives tag in Tags section. Maybe it will be useful to add this tag.


How do I interpolate an object's rotation on a Z axis based on mouse position? I need to apply rotation to an object, based on the mouse movement around it to a z axis only. Let's take this picture Violet current mouse position Blue mouse movement Red the object to be rotated I use this script and it works fine mousePos Input.mousePosition screenPos Camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, transform.position.z Camera.main.transform.position.z)) transform.rotation.eulerAngles.z Mathf.Atan2((screenPos.y transform.position.y), (screenPos.x transform.position.x)) Mathf.Rad2Deg but... it work's in real time which I don't want, so I need to interpolate it. I used Quaternion.Lerp Slerp and I got a strange result. When I move the mouse too fast (rotate it around the cube) it lerps to mouse's new position (which is ok) but it changes the rotation direction when the angle changes from 180 to 180 or 180 to 180. It's because of Quaternion math probably, to be precise Quaternion decides to switch the rotation direction, because it found a shorter path. The question How do I smoothly (with lerp) rotate the object (on a z axis) to look at the mouse position so it doesn't make the above glitch when lerping?


Add singleton to an existing gameobject in Unity via script I did notice that if I assign scripts that generate singleton classes (for my managers), to an empty game object, everything works fine. Now I would like to start the scene with the empty game object, attach the main game manager singleton, and in the game manager singleton I would like to attach to it the other manager singleton classes. Although I am not sure how you actually do so. Do you run addComponent to the main game manager, and they will be attached to the existing gameobject? The gameobject that I use for the main gamemanager is set to not be destroyed on load the doubt is if I should run addComponent on the scripts, or create a reference from the gamemanager script and instantiate it from there. I did look for examples on the subject, but the only thing that I found is the reference to add a script to a game object and I am not sure if that's actually what is supposed to be done.


Creating palette from irregular sprites in Unity I want to create a palette based on a number of PNGs in Unity 2D. I am struggling to understand the slicing logic. Let's say I have a sprite 588x547, and I set PPU to 128. So obviously the sprite cannot be divided into 128 parts So the right and the bottom part are not going to appear on my palette. Now I would like the grid to start in the center. The tiles on the sides are not "full" tiles, but I still want them on my palette in the end, so I kind of want Unity to fill up the border tiles for me with void till they reach the 128x128 size Is there a way to achieve this? Or am I conceptually misunderstanding something? Given a bunch of PNGs, all of them different pixel sizes, none dividable by 128, how do you create a palette from them to paint on a 128 PPU grid? I had a look at external tools like TexturePacker and Showbox, but did't manage to achieve a nice 128 dividable grid from my sprites.


LineRenderer not working using Vuforia in Unity So I'm trying to render a line that shows up when camera sees an image target and moves around with it. Very typical AR application. But my line renderer doesn't seem to show at all. Here's the code using UnityEngine using System.Collections public class myLine MonoBehaviour Creates a line renderer that follows a Sin() function and animates it. public Color c1 Color.yellow public Color c2 Color.red public int lengthOfLineRenderer 20 void Start() LineRenderer lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material(Shader.Find("Particles Additive")) lineRenderer.widthMultiplier 0.2f lineRenderer.positionCount lengthOfLineRenderer A simple 2 color gradient with a fixed alpha of 1.0f. float alpha 1.0f Gradient gradient new Gradient() gradient.SetKeys( new GradientColorKey new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) ) lineRenderer.colorGradient gradient void Update() LineRenderer lineRenderer GetComponent lt LineRenderer gt () var t Time.time for (int i 0 i lt lengthOfLineRenderer i ) lineRenderer.SetPosition(i, new Vector3(i 0.5f, Mathf.Sin(i t), 0.0f)) and here's my set up I also tried attaching the script directly to the ImageTarget and nothing happened.


Make zoomable Camera and Environment follow player smoothly I am making a 2D side scroller racing game. The Player is a car that moves on a 2D terrain already created. The Camera follows the Player. I also wanted to created more depth by making the background follow the y axis of player so that the background doesn't look like a plain picture. The effect I want to replicate is that when the player jumps the camera just zooms out. I am using a perspective camera so it zooms out by moving it slightly farther away from the Player. Unfortunately, the effect isn't smooth. The platform is using 2D edge collider. The movement gave me motion sickness and I just don't know what I should be doing to make this follow nicely. I have tried using smooth damp that gave me spring effect which isn't needed here. I used Lerp which just doesn't work at all. It's dang slow and when I make it fast it just same undesirable behaviour. The MoveTowards works a bit but not quite really. The smoothness is just not what I want. For reference, my game is pretty much same like the I hate zombies. check video https youtu.be YQZoBC1hVyk?t 31s attached is my code. Vector3 newPos public Vector3 camOffSet Vector2.zero public float speed 2 Vector3 velocity Vector3.zero void FixedUpdate() if (CarController.Instance ! null) newPos CarController.Instance.transform.position camOffSet if (CarController.Instance.IsGrounded) newPos.z 10 else float zz Mathf.Clamp( 10 newPos.y, 20, 10) newPos.z Mathf.Clamp( 10 newPos.y, 20, 10) newPos.x CarController.Instance.transform.position.x (camOffSet.x 3) newPos.x (zz 0.4f) newPos.z Mathf.MoveTowards(transform.position.z, Mathf.Clamp( 10 newPos.y, 20, 10), speed Time.deltaTime) transform.position newPos transform.position Vector3.MoveTowards(transform.position, newPos, speed Time.deltaTime)


Change hero direction in place before movement on a grid based game in Unity I've already implemented a grid based movement with all the necessary animations. Now I would like the make the hero face the direction of the input without moving first and move only if the input direction is the same one he's facing. E.g. if the Hero is standing still facing up, and you press left, he will face left without moving. If you then press left again, he will move on that direction cause he's already facing it. Here's the code void Update() movementDirection.x Input.GetAxisRaw("Horizontal") movementDirection.y Input.GetAxisRaw("Vertical") isMoving Vector2.Distance(transform.position, movePoint.position) gt 0.1f SetAnimator() void FixedUpdate() transform.position Vector2.MoveTowards(transform.position, movePoint.position, movementSpeed Time.fixedDeltaTime) if (!isMoving) if (movementDirection.x ! 0) movePoint.Translate(new Vector2(movementDirection.x, 0f)) else if (movementDirection.y ! 0) movePoint.Translate(new Vector2(0f, movementDirection.y)) private void SetAnimator() animator.SetBool("Moving", isMoving) if (!isMoving amp amp movementDirection ! Vector2.zero) animator.SetFloat("Horizontal", movementDirection.x) animator.SetFloat("Vertical", movementDirection.y) I tried using global variables to compare Hero's direction with the input, and let the Hero move only if they're the same but due to the Update function called every frame as soon as I update the current direction with the input one the hero will start to move void FixedUpdate() Directions latestGivenDirection GetLatestGivenDirection(movementDirection) this wont work, as the next frame will pass the condition and the hero will move if (latestGivenDirection currentDirection) transform.position Vector2.MoveTowards(transform.position, movePoint.position, movementSpeed Time.fixedDeltaTime) if (!isMoving) if (movementDirection.x ! 0) movePoint.Translate(new Vector2(movementDirection.x, 0f)) else if (movementDirection.y ! 0) movePoint.Translate(new Vector2(0f, movementDirection.y)) currentDirection latestGivenDirection How can I achieve such a behaviour?


Add oceans to an earth model with only continents? I have the following earth model, it only has continents I wanted to add water but as you can see, some of the continents are now hidden due to the water sphere being more round than continents I tried the following downscale water sphere, kinda works but only when it's significantly smaller, overall result is then unconvincing. change shader and render queue offset, does not do anything actually. I was hoping that maybe there could be a way to render transparent parts of this earth model as a specific color or eventually another material. Please do not suggest to use another earth model, I wouldn't have asked the question otherwise )


Why is my player spinning after a collision? I've made a very simple 2D top down prototype with Unity. This is the code I use for the player public class PlayerTurnsController MonoBehaviour private Rigidbody2D m rb public float Speed Vector2 m movement void Start() m rb GetComponent lt Rigidbody2D gt () private void Update() var moveHorizontal Input.GetAxis( quot Horizontal quot ) var moveVertical Input.GetAxis( quot Vertical quot ) m movement new Vector2(moveHorizontal, moveVertical) void FixedUpdate() m rb.MovePosition(m rb.position m movement Speed Time.fixedDeltaTime) At the start and while moving everything seems OK. But when I bump into some Colliders, the player sprite starts spinning when it should just stop (not pressing any button anymore) I already tried To set the rotation only when the m Movement Vector is gt 0.1f. But this didn't change anything.


How can I determine which Trigger is hit? I have a GameObject. It has 3 BoxCollider2Ds Body Collider Not a trigger Determines if body is hit Weapon Collider Trigger Determines if weapon is hit Vision Collider Trigger Determines what the GameObject sees I can tell the Body Collider apart from the other colliders, because it has a different method (OnCollisionEnter2D). However, I cannot tell the Weapon Collider and Vision Collider apart. They both access the same method (OnTriggerEnter2D), and pass in the collider they are hitting. I cannot determine which one is hit. I could put each trigger on a separate child GameObject, and send a message to the parent, but this is very slow and feels messy to me. What is the best way I can determine which trigger I am hitting? From the Unity Docs for reference using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public bool characterInQuicksand void OnTriggerEnter2D(Collider2D other) characterInQuicksand true


A 2D Camera Follow Script That Does Not Rotate? I am attempting to make a 2D racing game. So far I have a player car (sprite) and a main camera. I would like to know how to make the main camera follow the player car while still showing signs of movement (I don't want the positions to match exactly in the middle of the screen). My Player Car has a Rigidbody2D and a MoveCar script using UnityEngine using System.Collections public class MoveCar MonoBehaviour public float speed 10f public float gravity 0f void CarMove () if(Input.GetKey(KeyCode.RightArrow)) transform.Translate(Vector2.right speed Time.deltaTime) Update is called once per frame void Update () CarMove() Then there is my Main Camera, its projection is switched to Orthographic and has default settings as well as a FollowCar script using UnityEngine using System.Collections public class FollowCar MonoBehaviour public Transform player public GameObject other public Rigidbody2D rb other.GetComponent lt Rigidbody2D gt void Update() transform.Translate(Vector2.right .5f Time.deltaTime) Vector2.MoveTowards( Vector2 , Vector2 player, I would like to know where to go next or if I'm even going in the right direction. I have no idea how to utilize the MoveTowards() function.


How to change Unity's display settings resolution? Unity displays in poor quality on my computer (the software itself), I was wondering how to change resolution display settings?


Unity2D Sprite flips camera when moving left and right I am using the Unity Engine and coding in C . I have a sprite as a parent with a main camera as a child so that the main camera follows the sprite. However, when pressing 'A' and 'D' to move the camera 'flips 180 degrees' due to me using transform.eulerangles is there anyway that the camera can be excluded from this 'flip'? void Movement () anim.SetFloat ("moveSpeed", Mathf.Abs (Input.GetAxisRaw ("Horizontal"))) if (Input.GetAxisRaw ("Horizontal") gt 0) transform.Translate (Vector3.right moveSpeed Time.deltaTime) transform.eulerAngles new Vector2(0,0) if (Input.GetAxisRaw ("Horizontal") lt 0) transform.Translate (Vector3.right moveSpeed Time.deltaTime) transform.eulerAngles new Vector2(0,180)


How to dynamically construct a reference to a game object by name I have game objects tagged MenuOption0, MenuOption1, MenuOption2, etc. I want to keep a currentIndex var, which gets incremented each time the user swipes on the controller. That swipe should increment the currentIndex var, and switch the reference to a new game object, whose text color will be changed. This is what I'm trying as a test GameObject testText GameObject.Find("MenuOption" 4) TextMeshProUGUI thisTextMesh testText.GetComponent lt TextMeshProUGUI gt () thisTextMesh.color colorWhite How do I dynamically construct a reference to MenuOption1,2,3,4,etc? Or is there a better way to handle this without writing a big long conditional?


Creating Run over by car effect in unity using spotlights only I'm doing a project where I need to simulate a car running the character over. It's happening in a completely dark space, so I want to create it using spotlights moving towards the camera until the screen gets completely white. To create this "bright light" effect, I use volametric lighting on 2 spotlights But when I start moving the spotlights towards the player, the spotlights start moving away from each other (Which makes sense, and can be fixed somewhat by increasing the SpotAngle Range by code while the spotlights are moving). However, when the spotlights get to right in front of the player, they disappear before making the screen completely white. I could use a fade in complete white screen transition, but this complete method seems extremely clunky. Is there another, better way, or maybe a simpler fix to my spotlight moving closer issue?


Character controller going down slopes When I go down slopes with character controller, if the speed is too high, the character just flies off the slope and lands at the bottom. I want my character to "stick" to the slope rather then just jump of it. I came up with code to do so, but it didn't turn out as I planned. Now the character just slides on the slope when I stop pressing the arrows (not staying at its place on the slope). Physics.Raycast (transform.position, Vector3.down, out hit) transform.position transform.position new Vector3(0f, distance hit.distance, 0f) Thanks for the help, i couldn't figure this out all day.


Create lamp shade material How would one go about creating a lamp shade material that lets light through from a light inside the object. I have read that turning of shadow casting for that object should work, however I have turned off Cast Shadows but it doesn't work. Here are some pictures Light off Light on The lampshade remains dark. How can I fix this?


Assigning sprite to a sorting layer through scripting I have few prefabs with sprites which I want to assign to different sorting layers. How can I do it? I am also wondering if sorting layers matter if I use a perspective camera. Do they?


How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick? So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick? CODE public float moveSpeed Rigidbody2D myBody protected Joystick joystick void Start() myBody GetComponent lt Rigidbody2D gt () joystick FindObjectOfType lt Joystick gt () Update is called once per frame void Update() myBody.velocity new Vector2( joystick.Horizontal moveSpeed, joystick.Vertical moveSpeed )


Why does my ship look like it's going backwards instead of fowards? I'm making an Asteroids clone based on this tutorial. I'm stuck on the 5th part of the tutorial. For some reason my ship is going backwards instead of forward or it looks like its going forward, but in the tutorial the ship gos toward the asteroid. In the debug log, the z axis increments in a positive value. so I assume it is going forward but for some reason the ship it self doesnt go towards the asteroid like it does in the tutorial. The ship itself is an fbx export from Maya 2014. Here's an annotated screenshot Full size version It's probably something really stupid, but I just can't figure out why this is happening.


How to make a character sit in Unity? So I've got the animation, it has root motion but activating it in the settings doesn't seem to do much. What would be a good optimized way to have the character sit on the stool with the animation matching the movement? Would I need to do it through code?And if that's the case, could I specify in which frame do the movement? Or add a second animation that is in charge of Root Motion? I know either of these two options I give could work but I'm checking to see if there is a better way or if I'm missing something here. Thanks! EDIT Following DMGregory's comment I disabled the collider to see if it improved... it did change, but it isn't much better EDIT 2 This is how the animation preview looks like (what I'm expecting) Then I just hold the last frame while they're sitting and play the animation backwards for when they're getting off this is just while I get it to work.


How do you make a particle system collision add a force to an object towards the particle system? I have a lightning particle that gets shot at the ground. I want the particles to collide with the object they hit and add an upward force. I tried just entering a negative force in the Collider Force tab but it defaults to 0. If anyone knows a way to do this it would be greatly appreciated! Edit I want to send the cube in the photo upwards by adding a force on its y axis. The Particles should remain as they are.


Assigning function to button in foreach loop causes all buttons to have the same argument value I have a script that generates buttons based on a list of assets. Each button is intended to to add the asset's resource path to a variable called SpawnGlobals.CurrentSelection. When printing the asset resource name of all button within the loop, the different resoruce paths are shown. When printing the value in the select function, the value is always the last item in the asset register list. I do not understand why this is happening. Am I using the foreach loop or lambda incorrectly? void Start () Add Foundry Assets Here SpawnGlobals.asset register.Add (new FoundryAsset ("Test Sphere", "sphere obj")) SpawnGlobals.asset register.Add (new FoundryAsset ("Building Block 10x10x10 01", "BuildingBlock10x10x10 01")) SpawnGlobals.asset register.Add (new FoundryAsset ("Building Block 10x10x10 02", "BuildingBlock10x10x10 02")) SpawnGlobals.asset register.Add (new FoundryAsset ("Building Block 10x10x10 03", "BuildingBlock10x10x10 03")) foreach (FoundryAsset asset in SpawnGlobals.asset register) SpawnGlobals.buttons.Add(Instantiate(button prefab)) GameObject current button SpawnGlobals.buttons.Last () current button.transform.SetParent(master.transform, false) current button.GetComponentInChildren lt Text gt ().text asset.AssetName print (asset.AssetName) current button.GetComponentInChildren lt Button gt ().onClick.AddListener (delegate select(asset.ResourcePath) ) public void select(string selected) print (selected) SpawnGlobals.CurrentSelection selected


Unity Raycast not hitting to BoxCollider2D objects I'm working on 2D and I have a Quad as background. And some wall sprites over this quad I'm instantiating wall prefab sprites over quad when user click to somewhere. But I don't want to instantiate a wall over another wall, so I'm sending a ray from camera to click point and if hit object is a wall object I won't instantiate. Here my code RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) Physics.Raycast(ray, out hit,Mathf.Infinity) If it hits ground, not another objects (like walls) if(hit.transform.name "GroundQuad") Instantiate (wall, Input.mousePosition, Quaternion.identity) But it's still creating wall objects. Tried Debug.Log() to print hitted object's name to console and moved pointer all over game screen, it's always GroundQuad. So ray not hitting to wall objects. Can you tell me what is I'm missing? Is it a problem with Layer Collision Matrix ?


Unity Canvas blocking objects in Editor I think I am missing something really basic here..., I'm creating a 2D game in unity, and the UI Canvas (with the setting "Screen Space Overlay") is blocking exactly a quarter of my workspace. I can not select any objects on the top right part of the screen. Is there any fix to this?, or do I have to move the camera down half of the screen? Thanks


Unity using 40 GPU for just a UI interface on ultra but 90 on low? So I made some software using unity for my FRC team. All this application is, is just a User Interface with labels, input fields, buttons, etc... When I choose the quality to be on Ultra, I will get about 50 GPU usage but when on very low, I got 90 , close to 100 . How can I optimize my software to use much less of the GPU(Preferably less than 15 )? I am measuring with the Task Manager Performance Menu