Sprite always starts flipped Everytime I start the game, or I swap animator controllers in the inspector (in runtime), the character is flipped in X axis until I start moving him. How do I prevent this to happen? This happens to me everytime I start a new project and I grow tired of this. Update 8 animations which are all idle ones of just 1 frame Down DownRight Right UpRight Up The last 3 have the Sprite Renderer's flipX enabled within their animations UpLeft Left DownLeft In the middle of the transitions, sprite remains flipped until it reaches 1 or 1. I recorded recently a video to display the issue. https www.youtube.com watch?v dC09snKvHAM Same as above but in 1080p and showing entire Unity window. https www.youtube.com watch?v Ww3GkUvb7bc 2nd update PlayerControls.cs using UnityEngine using System.Collections public class PlayerControls MonoBehaviour Rigidbody2D rb PlayerStats pStats Animator anim void Awake () rb GetComponent lt Rigidbody2D gt () pStats GetComponent lt PlayerStats gt () anim GetComponent lt Animator gt () void Update () if (Input.GetAxisRaw("Vertical") gt 0) rb.velocity new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0) if (Input.GetAxisRaw("Vertical") lt 0) rb.velocity new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0) if (Input.GetAxisRaw("Horizontal") lt 0) rb.velocity new Vector3( pStats.pMoveSpeed, rb.velocity.y, 0) if (Input.GetAxisRaw("Horizontal") gt 0) rb.velocity new Vector3(pStats.pMoveSpeed, rb.velocity.y, 0) if (Input.GetButton("Vertical") Input.GetButton("Horizontal")) anim.SetFloat("OrientationY", Input.GetAxisRaw("Vertical")) anim.SetFloat("OrientationX", Input.GetAxisRaw("Horizontal")) PlayerStats.cs using UnityEngine using System.Collections public class PlayerStats MonoBehaviour public string pName public string pClass public int pLevel public float pExperience public float pBasicDamage public float pMoveSpeed public string pClassList Animator anim public RuntimeAnimatorController animCtrl void Awake() anim GetComponent lt Animator gt () void Update() pLevel 1 (int)pExperience 240 if (!CheckAssignedClass()) pClass "Warrior" Debug.LogWarning("Player class not found. Using 'Warrior' as default.") if (Input.GetKeyDown(KeyCode.J)) SetClass(pClass) bool CheckAssignedClass() bool found false var i 0 for (i 0 i lt pClassList.Length i ) if (pClassList i pClass) found true break else found false return found void SetClass(string className) switch (className) case "Warrior" anim.runtimeAnimatorController animCtrl 0 break case "Archer" anim.runtimeAnimatorController animCtrl 1 break case "Mage" anim.runtimeAnimatorController animCtrl 2 break default anim.runtimeAnimatorController animCtrl 0 break


Decreasing distance for a Configurable Joint at run time Unity I have written a script that uses ConfigurableJoint to connect a ball to a hing so that it moves in a fixed circular path around the hinge. The problem is that I want to decrease the distance between hinge and ball with time. In other words, I wamt to reduce the radius of circular path on which the ball is moving. I have created a rough image to demonstrate what I'm trying to do And below is the code that I am using to create the joint joint gameObject.AddComponent lt ConfigurableJoint gt () joint.anchor transform.transform.InverseTransformPoint(closestHinge.position) joint.xMotion ConfigurableJointMotion.Locked joint.yMotion ConfigurableJointMotion.Limited joint.zMotion ConfigurableJointMotion.Locked


How to initiate manually an animation in Unity? I have a prefab and I want to control when an animation is initiated. I can't seem to figure out how to do that. I have already created the animation clip, the animator component for the prefab, and the animator controller. The animation works, when I enter play mode in the unity editor (it plays automatically), but I want to control when the animation occurs when providing input (such as pressing on the space bar or clicking on the prefab). How would I go about doing that?


How to change TPS camera angle in Unity I'm very new to Unity and this may simply be a failure of google fu but I hope someone here can help me out. I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts. I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code. using System.Collections using System.Collections.Generic using UnityEngine public class CameraFollowPlayer MonoBehaviour GameObject target Start is called before the first frame update void Start() target transform.parent.gameObject Update is called once per frame void Update() transform.LookAt(target.transform.position) The problem with this is the angle this leaves the camera pointing at in game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the LookAt instruction to result in a shallower X axis rotation of the camera?


Issues with spine animation alpha in iOS We are seeing a ton of artifacts and strangeness with alpha on iOS for our spine animation assets. You can see an example of one of these grid like artifacts here, but we're also seeing pixelation etc. Does anyone know why this is happening, whether we need to make adjustments or change certain settings to address this issue?


Ball Speed is not increasing as per code I am working on small project , but now I have a problem . The problem is The Player speed (Ball speed) is not increasing as per the code . In the beginning ball speed increases , but as the time goes the speed becomes constant . I made Gravity as 50 in Y Axis . So here is the C Script attached to the ball using UnityEngine using System.Collections using UnityEngine.UI public class Ball Script MonoBehaviour Ball Physics Variables private Rigidbody Ball Rigid public float Ball Speed 10f private float Speed Change Time 1.0f UI Text public Text My Ball Speed Text public Text My Key Use this for initialization void Start () Ball Rigid GetComponent lt Rigidbody gt () My Ball Speed Text.text Ball Speed.ToString () " km h" My Key.text "No Key Pressed" Update is called once per frame void Update () Restart game if(transform.position.y lt 7.0f) Application.LoadLevel(0) Ball Automatic Movement script Starts here Speed Change Time Interval () Ball Rigid.AddForce (new Vector3 (Ball Speed 1 Time.deltaTime, 0, 0)) Ball Automatic Movement script Ends here if(Input.GetKeyDown(KeyCode.LeftArrow)) Ball Rigid.MovePosition(new Vector3(transform.position.x , transform.position.y , transform.position.z 1.0f)) My Key.text "Left Arrow Pressed" if(Input.GetKeyDown(KeyCode.RightArrow)) Ball Rigid.MovePosition(new Vector3(transform.position.x , transform.position.y , transform.position.z 1.0f)) My Key.text "Right Arrow Pressed" This Fixed update stops the ball from bouncing void FixedUpdate() Vector3 currentVelocity Ball Rigid.velocity if (currentVelocity.y lt 0f) return currentVelocity.y 0f Ball Rigid.velocity currentVelocity This function increases the ball speed in every 1 second void Speed Change Time Interval () Speed Change Time Speed Change Time Time.deltaTime if(Speed Change Time lt 0) Ball Speed Ball Speed 10 Speed Change Time 1.0f print(Ball Speed) My Ball Speed Text.text Ball Speed.ToString () " km h" Here FixedUpdate () stops the ball from bouncing and Speed Change Time Interval () function increases the ball speed in every second . But it works some extent . Then there is no change in speed of the ball . Here is the video of the game ( Recorded with Jing , so file is in .swf format . Sorry for that ( ) Link http www.mediafire.com download ibk4ffjm3y6i96y Ball Vid.swf File size 9.28 MB So what is the problem of this script . If my method is wrong not good please suggest me a good one ). Hope you will help me to figure it out . Thanks , Regards NB )


3D Unity characters without Maya I have been writing 2D iOS games for a while and I'm looking into getting into 3D. I want to know if Maya is required for making 3D sprites or if you can easily make your 3D sprites using just Unity 3D. They won't be detailed, just about the size shape and detail level of Crossy Road sprites


How to clip what is outside scroll view when using a custom UI element? I have created a custom UI element (that use CanvasRenderer). Here is code Mesh mesh new Mesh() Rect drawArea GetComponent lt RectTransform gt ().rect using (VertexHelper helper new VertexHelper()) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMin), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMin), Color.white, Vector2.zero) helper.AddTriangle(0, 1, 2) helper.AddTriangle(2, 3, 0) helper.FillMesh(mesh) var canvas GetComponent lt CanvasRenderer gt () canvas.SetMesh(mesh) canvas.SetMaterial(Material, null) It creates a simple rectangle that is same size as rect transform. It works great. However if I put this inside a scroll view, everything that is outside scroll area viewport is rendered (while it should be clipped). The scrolling works as it should (rectangle get scrolled by changing position when scrollbar is used). I have tried to call canvas.EnableRectClipping(...) but without success.


NullReferenceException Error For Respawning I am making an infinite runner game, and I am having issues with killing and respawning the player. I have a coroutine setup on the GameMaster objec which is the respawn and on the player I have a method that calls that coroutine. But when ever the player hits an enemy I get a Null Reference Exception and I am not sure why this is happining. Here is the entire error NullReferenceException Object reference not set to an instance of an object Player.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets Script Player.cs 32) Here is the line that when I double click on the error it goes to. This line is on the player. StartCoroutine(GetComponent lt GameMaster gt ().RespawnPlayer()) This is the method that the above line is in. This method is on the player. void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "Enemy") Debug.Log("HIT") Destroy(col.gameObject) StartCoroutine(GetComponent lt GameMaster gt ().RespawnPlayer()) Here is the coroutine that the above method is trying to call. This method is on the GameMaster GameObject and this object never gets destoryed or setActive false. public IEnumerator RespawnPlayer() player.GetComponent lt SpriteRenderer gt ().enabled false player.GetComponent lt BoxCollider2D gt ().enabled false player.GetComponent lt movemnt gt ().enabled false yield return new WaitForSeconds(respawnDelay) adMenu.SetActive(true) If anybody can give any suggestions that would be great!


Drag Object to Collide Unity Please help, I am developing a 2D game for a school project and I want to drag the apple to the think box then when it collides, the apple will go back to the original position then it will add 1 point to the score. I'm just new to Unity. So please help


Jumping onto higher ground Collider issues What's the general solution to the following character animation problem (I'm using Unity)? You have a character with a capsule collider and a jump animation that allows you to jump onto higher ground (such s boxes, etc.). The character shouldn't be able to jump unrealistically high so she goes into a crouched posture while in the air and the collider is scaled accordingly in an animation curve. However when the character jumps onto the box to land, the character animation (and collider) want to extend back to wards the ground but there is not enough space and either collision detection fails and the character falls into the geometry or the collider starts a collision fight with the box and keeps bumping up and down, keeping the character in an airborne state. Please see screenshots to get a better idea... What would be a good way to work around this problem?


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


How do I use playerprefs to make ui slider keep the sound settings? I have not use playerprefs before, I want to know how to keep the change of the audio when the player change it throughout the game.


How To Display a friend list Using Play fab? I m making a multiplayer game using playfab. One player send a friend request Second player then not display a player name?? I want the access(display) a player name??? see the referance, Code ListingPrefab.cs public class ListingPrefab MonoBehaviour public static ListingPrefab Instance public Text playerNameText FriendRequest.cs public class FriendRequest MonoBehaviour public GameObject listingPrefab btn public Transform panel parent Display Friend void DisplayFriends(List lt FriendInfo gt friendsCache) foreach (FriendInfo f in friendsCache) I think problem is here GameObject listfriend Instantiate(listingPrefab) ListingPrefab templisting listfriend.GetComponent lt ListingPrefab gt () templisting.transform.SetParent(panel, true) PlayerPrefs.GetString("PlayerName", ListingPrefab.Instance.playerNameText.text.ToString()) PlayerPrefs.SetString("PlayerName", ListingPrefab.Instance.playerNameText.text.ToString()) Debug.Log("playername " templisting.playerNameText friendsearch) Debug.Log("helloone" f.TitleDisplayName) templisting.playerNameText.text f.TitleDisplayName TitleDisplayName PlayFab unique username for this friend. void DisplayPlayFabError(PlayFabError error) Debug.LogError(error.GenerateErrorReport()) void DisplayError(string error) Debug.LogError(error) Getfriend List lt FriendInfo gt friends null public void GetFriends() you can call button click PlayFabClientAPI.GetFriendsList(new GetFriendsListRequest IncludeSteamFriends false, IncludeFacebookFriends false , result gt friends result.Friends DisplayFriends( friends) triggers your UI , DisplayPlayFabError) Debug.Log("Inside GetFriends") Add friend enum FriendIdType PlayFabId, Username, Email, DisplayName void AddFriend(FriendIdType idType, string friendId) var request new AddFriendRequest() switch (idType) case FriendIdType.PlayFabId request.FriendPlayFabId friendId break case FriendIdType.Username request.FriendUsername friendId break case FriendIdType.Email request.FriendEmail friendId break case FriendIdType.DisplayName request.FriendTitleDisplayName friendId break Execute request and update friends when we are done PlayFabClientAPI.AddFriend(request, result gt Debug.Log("Friend added successfully!") Add a friend , DisplayPlayFabError) string friendsearch SerializeField GameObject friendpanel public void InputFriendID(string inputfriendid) friendsearch inputfriendid public void SubmitFriendRequest() AddFriend(FriendIdType.PlayFabId, friendsearch) public void OpenCloseFriends() friendpanel.SetActive(!friendpanel.activeInHierarchy) Prerequisites SDK Unity The title ID is set in the PlayFabSharedSettings object (alaready i have) The project can successfully log in a user (alaready i have) The title has at least two registered users (alaready i have) image I have 15 Player. How To access a PlayerName??


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?


How to add user created data to drop down menu options So I'm trying to make it that I can have a dropdown that will have user created info appear in it. List lt engines gt engineList new List lt engines gt () public Dropdown engineSelect public class engines public string engineName public int featureNumber public int totalDevPoints public string optimizedGenre public engines(string name, int feature, int totalPoints, string opt) engineName name featureNumber feature totalDevPoints totalPoints optimizedGenre opt engines playerEngine new engines(engineName, numFeature, 0, whatGenre) Pretend player set engineName, numFeature, and whatGenre with text fields. I wanted to have it that the drop down would add in whatever new engines the player makes. How would I do that? I want to have it say select engine and then the player would pick from dropdown from engines they made(only saying engine names).


How to keep loading screen for minimum time? Making my first game and stuck at keeping the loading screen visible for some time. It shows for an instance and disappears. By using loadasync the previous scene runs in the background? Do i have to pause everything and then move to the next scene? Thank you! The code is as follows public void LoadNextLevel() StartCoroutine(LoadAsyncronously()) IEnumerator LoadAsyncronously() int nextSceneIndex SceneManager.GetActiveScene().buildIndex 1 loadingScreen.SetActive(true) AsyncOperation operation SceneManager.LoadSceneAsync(nextSceneIndex) float progress Mathf.Clamp01(operation.progress 0.9f) slide.value progress yield return new WaitForSeconds(2) SceneManager.LoadSceneAsync(nextSceneIndex)


Interpolation on Rigidbody2D not working I'm trying to achieve smooth movement for a ball. I seem to be failing to achieve this and now I've created a sample scene, which shows my setup from the game and the problem exists in that sample scene, as well. I've uploaded the sample project to github https github.com iQew PhysicsTesting (open Assets Scenes SampleScene) Here's a recording of the problem. It's a bit more extreme here than it is in the editor, but it shows the problem even better because of it https imgur.com a ByzwKlg Scenario I have a 2D mobile game (android) using Unity 2019.4.14f1 with URP. The camera does not move and will always have the same settings. The playfield consists of a certain area, which is blocked in by walls, which have a BoxCollider2D on them. The ball is a simple sprite with a CircleCollider2D, RigidBody2D and a Trail Renderer. I have deleted all quality settings except the quot Low quot one, which has VSync Count set to quot Don't Sync quot . In the Awake block of a controller script I set the Application.targetFrameRate to 60. In the Start block I use BallRigidBody2D.AddForce(new Vector2(1f, 10f), ForceMode2D.Impulse) to make the ball move. The RigidBody2D of the Ball has the following settings Body Type Dynamic Material DefaultBall (a Physics2D material with friction 0 bounciness 1) Simulated true Use Auto Mass false Mass 0.025f Linear Drag 0 Angular Drag 0 Gravity Scale 0 Collision Detection Continous Sleeping Mode Start Awake Interpolate Interpolate All other project settings are at default. When I launch the game, the ball starts moving as expected. Most of the time the movement is smooth, but there is stuttering every now and then. I am wondering, if there is a way to make this stuttering go away. The tutorials I found on the internet, which solve this exact problem set the Interpolation mode of the RigidBody2D to quot Interpolate quot , but I did that and there's no change. There are no other scripts interfering with the physics calculation at all. So, I assume this has to do with some kind of project settings? Using a smaller Fixed Timestep does not help, in fact it gets a lot worse, if I use 1 120 for example. Any help would be greatly appreciated!


added a pipeline and now my terrain is pink...how do I fix it? I needed to add a pipeline to my world because an asset required it. I was following the directions here. Since adding the pipeline, my terrain is pink. I found a references that stated the pipelines do not support terrain, there are problems with more than 4 textures (I have 1) etc...but this was a year ago. Is this fixable or am I at choice between no pipeline or buying pipeline enabled terrain (and hence redoing all of my scenes)? What is the solution? Thnx Matt


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


How to get which gameobject the mouse is over in Unity? So I'm working on a simple drag n drop based trading card game for my own amusement. There is a card inspector included. What I want to achieve is to change values in the inspector (which has its own Inspector.cs, so I would change the variables in it) based on which card I hover over with my mouse. Each card has its own Card.cs attached from which I want to read the values of the current card. If I try to do this from within the Inspector.cs by something like this Name.text gameobject.GetComponent lt Card gt ().Name , then obviously it won't work, because using gameobject in the current context is not valid. So solution No1 would be to properly reference the gameobject over which the mouse is, which I don't know how to do. When I try to do the same from within Card.cs, I cannot use an event trigger OnPointerEnter and run the code through that, because I have to have a reference to the gameobject that contains that function. ( And I cannot do that in a prefab, only in gameobject already existing in the level.) So could anyone tell me how I could achieve what I want, please?


How to make a 2D sprite slowly vanish as it crosses a line as if disappearing behind a wall? ...Except there is no wall. Only one of its edges. Here is what I mean. Notice how the lines "sink" into the center square. I've been trying to do something very similar, in Unity. My approach is to detect when the lines come into contact with the center square (hexagon, in my case), and first initiate an animation that decreases the width of the lines, precisely timed via math to last exactly as long as needed. But there's a problem. The animation doesn't play. I've spent the last few hours debugging it, to no avail, and now have finally given up, because the problem is too complex to post here. Too many variables. Are there any better methods of achieving this? My own, even if it had worked, wouldn't have been perfect, because the width would've decreased on both sides (of the line running in the middle of the thick squares or hexagons that are to disappear), giving it a strange, swallowing effect, but I'd be satisfied, since it's just a practice project. So, I'm giving up on this approach. What are easier ways to do this? (Preferably in Unity, but I'll take anything.) Hasty edit Keep in mind that my "lines" are not sprites but line renderers, but I'm looking for ways to work on either.


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


When creating a game, what are some architectural desgin concepts I can use to be able to port my game from single to multiplayer? I am a software developer but, I mostly develop games in Unity. I have experience creating single player games as well as multiplayer games. I am at a crossroads where I am in the middle of development of a proof of concept or small demo and all of a sudden I am asked to turn it into a multiplayer game without prior knowledge of this I turn around and say it would add 50 to development time because I basically have to start over from scratch because I didn't necessarily take into account that later down the road they might want to change the experience from single to multiplayer. So with all of that out of the way, are there any different methodologies out there that would make it easier on the developer to port a game from single player to multiplayer? I have thought of a possible way of doing this by just setting the game up as single player, however, making my functions where they are easily able to wrap them using Commands and RPCs. But I find this may or may not help me and is only dependent on what the requirements are. My biggest time killer when it comes to porting these PoC's is typically the UI. Most of the time my requirements are so that the UI will be the same shared UI for all clients and having to update it for each action performed on it and dealing with handling ClientAuthority. (Any tips for dealing with this would be greatly appreciated too) Think of this as something like, making something with Legos in multiplayer and having shared instructions based on the step the user is on. Summary What are different ways that I can design a small demo concept where I can easily port it to multiplayer later on, or make my game where it is "multiplayer friendly" ? Or should I try to stay away from this type of thinking altogether and just develop a single player aspect and just develop a multiplayer aspect, arguments for and against this concept are sought after.


How can i make my soldier to patrol over the space stationin random? I mean i want to bake all the places in the space station and make the soldier to move automatic around the spaceship to random places. What i did so far is placing the soldier at a start point. Added a camera as child to the soldier. Added a nav mesh agent component to the soldier. Attached a script to the soldier It's not my script. I don't want the soldier for now to chase only to walk randomly around the space station. I didn't change any of the setting on the Nav Mesh Agent component in the inspector and i didn't Should i change anything in the nav mesh agent component and if so what ? How do select or set what areas to bake so the character will know to walk to this areas or if i want to select all the areas ? How do i tell the character when to turn right or left in case there is a wall ? Could be also random to turn left or right. Depending if there is left and right ways or maybe there is also straight way so that's 3 possible ways to move to. clicked the Bake button yet. I didn't write yet the script. using UnityEngine using System.Collections public class SoldiersPatrol MonoBehaviour


Relative vertical alignment of 3 Texts on Canvas This is a menu that appears if I press Enter on the RE4 inventory if an item is selected. I have drawn a thin red rectangle around it And here is a video that shows some of the menu's effects. I am familiar with a simple text canvas. I understand that I need to make each line a separate "Text" object so that I can scroll up and down through them. Here is what I have so far The problem that I'm facing now is that the Canvas will be scaled at runtime. I don't work with fixed values. This is a problem since I don't see how I could easily make it so that each TextLine object fills 33,3 of the canvas. Am I right to assume that I can only solve this by making a scripts that holds a reference to each TextLine object and which then calculates their position when the scale of Canvas is known? Or is there any easier solution? Thank you!


Creating a list of buttons dynamically in code I have a list of contacts. I need to create a scrollable list of buttons that are created dynamically so I can add each contact name as the button text. How would I do this all in code? My biggest concern is making sure the sizes stay consistent. I haven't had to do that in code before. EDIT And here is the code to add the buttons to this for (int i 0 i lt count i ) if (i gt 0) crt.sizeDelta new Vector2(crt.sizeDelta.x, crt.sizeDelta.y initHeight) GameObject contactButton Instantiate(Resources.Load("Contact Button")) as GameObject contactButton.transform.parent contactsList.transform contactButton.GetComponentInChildren lt Text gt ().text names i


How can I search for players in the same wifi in Unity? I am creating a game in Unity and I would like to create an ability for players to join the game that others have created on the same wifi. I would like it to be as effortless as possible(e.g. players don't have to find out their wifi, etc). The game is cross platform you could have one player on PC, other on Android device, etc. Now I know that there is a game that has similar mechanism to what I would like to achieve SpaceTeam. Basically you select whether you use BT or wifi, and wait for other players to join. How can I do this in Unity, or something similar that satisfies my needs?


Not able to find the constraints option in the Rigidbody component I am working on a game tutorial right now and I need to freeze constraints for a model prefab. I add a Rigidbody component and I want to freeze rotations on the x and z axes. However, I am not able to find the option in the component. Is there another way to access rotation constraints (I do not want to code the constraints at the moment)? Or is there something I am missing in the new version. Please do let me know. Thanks I am using Unity 5.6.7f1 Personal


Using points to unlock next scene in Unity Below is my code and I'm a beginning game designer trying to make my first game for art school teehee! ) I'm not sure how to unlock the next level with a scene I've already made called Rust Room Any ideas? o I also attached the error codes I'm getting! using System.Collections using System.Collections.Generic using UnityEngine.SceneManagement public class Example HUD hud int points const int ScorePrefix "Score " int score public void LoadLevel() if ("Score 45") load the nextlevel SceneManager.LoadScene(SceneManager.GetSceneByName(Rust Room)().buildIndex 1)


Unity 5 3rd Person Controller runs by default. How to change this? I have been working with the Third Person Controller of the Standard Assets (called Sample Assets in the beta versions) in Unity 5. When the player press the forward button, the character runs by default, and walks if you hold Left Shift, and I want to swap that. However, The controller makes use of Blend Trees, and have two scripts to manage movement and input and it's far too complex for me and so I need your help. How can I change the controller so that the player walks by default and has to hold Shift to run?


how do i make AI enemy in unity 2D? How do i make a AI enemy that go to player and if enemy arrives at collision (ex. stone collider) rotating to path , (unity 2D top view)? (Enemy has a face sprite and animator component) In this pic , I want to do ai enemy following player but when arrives to wall so it's face changes the path and following again . 2 if enemy 1 arrives to enemy2 so enemy face change the path for follow player


How to find position of the edge of an object? I have two planes and I want to put both planes one after another so that I can form a road. I set them from the editor and that was very easy but I wanted to do this from code. So in the code void Start() secondRoad.position firstRoad.position But this just set the second plane in the center of the first plane, kind of overlapping. But I want the second plane to be placed next to the first plane where it ends right the edge of the first plane. How will I do this?


"Overloading" GameObject? I would like to show weapons and health items in an inventory grid. The item can be rotated in the grid, and it occupies a certain region in the grid. Currently I store this information (where the item is located, if it is rotated, etc.) in an additional array. However, this is not elegant and error prone. I would therefore like to ask if it is possible to somehow store this additional information directly in the weapon or health GameObject. Ideally I would like to be able to do something like this Pistol.GridProps.Rotation 90 Pistol.GridProps.Row 5 Pistol.GridProps.Col 3 Is it possible to add something like "GridProps" to all my game objects? Thank you!


How do you rotate RigidBody2D along a given access using velocity and not transform? I am trying to rotate my player along the centre of the world in Unity3D. All the tutorials and references I have looked through till now have left me to this working code void MoveAlongCurve(bool moveClockwise) if (!moveClockwise) timeCounter moveSpeed Time.fixedDeltaTime else timeCounter moveSpeed Time.fixedDeltaTime float x Mathf.Cos (timeCounter) float y Mathf.Sin (timeCounter) transform.position new Vector3 (distFromCentre x, distFromCentre y,0) Also this seems to work fine as well transform.RotateAround (Vector3.zero,new Vector3(0,0,1),speed) Now my question is how do i move my player using velocity? I was forced to keep my body as 'kinematic rigidbody2D' however I want my player to be a 'dynamic rigidbody2D'. My reason for this is several 1. Movement via velocity makes it independent of the timeCounter. 2. Dynamic Bodies enable collisionDetection. Hence it is basically a requirement for my game. Thank you so much for taking the time to read this! Any suggestions or nudges in the right direction would be greatly appreciated and if you find anything wrong in my code or approach please comment!


How to read a data from multiple selected text files in unity This question is based off of a previous one. How to read a data from text file in unity But I cant get the code to work for my purpose. I want to be able to choose which CSV files needs to be edited instead of just assigning one file. Here is the code private void readData() TextAsset csvFile Resources.Load("Assets Resources Test1.csv") as TextAsset string records csvFile.text.Split(lineSeperater) foreach (string record in records) string fields record.Split(fieldSeperator) foreach (string field in fields) contentArea.text field " t" contentArea.text ' n' I want to access the file using a given link and then write to it. but for some reason it keep saying "Object reference not set to an instance of an object" referring to "string records csvFile.text.Split(lineSeperater) " I'm new to coding so it might be missing something silly. but as far as i know it should make sense? as csvFile is given the usl, but the url is not being found when its searching for csvFile.text, but then again, i might be completely wrong. Could someone maybe help me and guide me in the right direction?


Unity input manager use multiple keys Is it possible to use multiple keys so that they combined will do the action? Say for instance you want a jump attack that would require two buttons to be pressed at the same time. in this case space mouse 1 ? I tried creating that however it didnt seem to take my input. Does anyone know how this can be achieved?


Applying movement to a Rigid Body Isometric in Unity 3D I'm making an isometric dungeon crawler. I initially used transform to get isometric movement and things worked well, but I couldn't use collision which meant it was unsuitable. So I'm now trying to use Rigidbody and I'm having some weird issues. First of all, this is the code I currently have public class CharControllerRigid MonoBehaviour SerializeField private Rigidbody characterRigid private Vector3 inputVector void Start() characterRigid GetComponent lt Rigidbody gt () void Update() inputVector new Vector3(Input.GetAxis("Horizontal") 10f, characterRigid.velocity.y, Input.GetAxisRaw("Vertical")) transform.LookAt(transform.position new Vector3(inputVector.x, 0, inputVector.z)) private void FixedUpdate() characterRigid.velocity inputVector I have two issues First, how do I get the movement to work on an isometric plain? Second, how do I get the movement to work in all directions? Current when I move left and right the movement is good, but up and down are really slow in comparison.


How can I make the cursor avoid something completely? I wrote some code for a UI button that causes the mouse to avoid it. I realize this is kind of a weird thing to do in a game design wise, but this is a really weird game. I need a button that is not only unclickable, but also unhoverable. I got it mostly working, but I cannot seem to change the position before the mouse is drawn, probably because mouse movement is handled by the OS, unless there is a problem with my code that I missed. As a result, pushing the mouse against the button boundaries results in a stutter. The mouse briefly appears over the button before I can move it, so it is still possible to click the button. A demonstration of the button avoidance and stutter https youtu.be 7tgIrJ vMDg DllImport("user32.dll") public static extern bool SetCursorPos(int X, int Y) DllImport("user32.dll") public static extern bool GetCursorPos(out Point pos) ... void Update () var mousePos Input.mousePosition if (Application.isFocused amp amp isOver) Get the current mouse position from OS so we can change it Point cursorPos GetCursorPos(out cursorPos) if (oldMousePos.x gt xMin amp amp oldMousePos.x lt xMax) Coming from above or below. Figure out which one and move mouse accordingly if (oldMousePos.y gt uiPos.y) cursorPos.y (int)(rt.rect.height 2 (mousePos.y uiPos.y)) else cursorPos.y (int)(rt.rect.height 2 (uiPos.y mousePos.y)) else Coming from either left or right. if (oldMousePos.x lt uiPos.x) cursorPos.x (int)(rt.rect.width 2 (uiPos.x mousePos.x)) else cursorPos.x (int)(rt.rect.width 2 (mousePos.x uiPos.x)) Give new coordinates to OS to update mouse position SetCursorPos(cursorPos.x, cursorPos.y) else track the old position to know what direction they moved their mouse from so we can put it back oldMousePos mousePos I tried using the Cursor API to force it to software mode thinking that might fix it, but it still stutters, and I would prefer to use the default cursor anyway, and hardware mode if possible. Is there any way to work around this or remove the stutter?


Why the break point is not working with the unity3d editor? The visual studio version is 16.8.3 Visual studio community 2019 The editor version is 2019.4.15f1 personal On other project I have opened it's working fine. It also worked fine on this project but then something went wrong now not sure why the break point s are not working with this project ! In the editor I did double click on a script attached to gameobject and it opened the visual studio then I clicked on the left side to add a break point and did Attach to Unity but the break point on the left is broken with yellow warning. I tried to close and re open both visual studio and the editor. In the editor I did Edit gt Preferences gt External Tools and this is the settings I also clicked on the Regenerate project files. But nothing worked so far.


Some meshes are visible in game view while others are not I have a FPS character in unity. The FPS character is divided into a few different pieces (upper arm, lower arm, hand, fingers, etc). I exported it from blender, so I'm using the camera that got converted from the blender camera. For some reason, the mesh is not showing up in the game view camera vision. I did a little bit of testing and found out that If I move the camera away, the mesh shows up, so the mesh isn't invisible or anything I put a version of the character that I imported from blender earlier as a test(different rest pose and less animations attached to it) in the same location as the FPS character, and attached the same animator to it. When I did that, you can see the earlier version but not the newest one The same thing happens even if I change the camera The camera has a field of view of about 67, and a focal length of 18. Near is set to the lowest value possible. Both characters are visible in scene view, just not in game view.


Shader that "cuts" hole through all geometry How can I create a shader that "cuts" through all geometry, only rendering the clearing background in Unity? An example That's a prism in a huge white box shaped room. The surface of the prism is just rendering the skybox of the scene (a starry sky). I used multiple cameras, which is pretty inefficient... There must be a way with just shaders. How can I do this?


Facebook link gives "This game is not available for your phone" I am developing a game in Unity and have connected to FB using the plugin. I am able to login and send a request to another user with no problems. However, when I click on the notification I get the message "This game is not available for your phone". Everything is set up as it should be and both users are defined as developers for the app. The only thing is that I have not yet published the app in FB. Is that a requirement?


Changing text occurs error move initialization code to the Awake or Start function I have GameManager class that has Log method using UnityEngine using UnityEngine.UI public class GameManager MonoBehaviour public static GameManager Instance SerializeField private ScrollRect m GUIConsoleContainer SerializeField private UnityEngine.UI.Text m GUIConsole ... void Awake() Instance this ... public void Log(string message) m GUIConsole.text m GUIConsole.text message " n" GameManager class has static instance, so I can invoke Log method in anywhere like this GameManager.Instance.Log("Helloworld") However it works only first time. After invoke Log again, Unity gives me this error message get isActiveAndEnabled can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEngine.UI.Text set text(String) I assigned reference of m GUIConsoleContainer and m GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error. How should I avoid this error message? Using Unity 2018.2.1f1. p.s. Error coming from here, another class called NetworkManager void OnReceivedBytes(IAsyncResult result) try if(m Socket null) return int resultLength m Socket.EndReceive(result) if(resultLength 0) Shutdown() return Log("Received " m RecvBuffer 0 ) lt lt Error coming from here ... ... And this is where it call OnReceivedBytes using UnityEngine using UnityEngine.UI using System using System.Collections using System.Net using System.Net.Sockets public class NetworkManager MonoBehaviour private Socket m Socket void Start() m Socket new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) m Socket.Connect("localhost", 1337) if(m Socket.Connected) Log("Connected.") m Socket.BeginReceive( m RecvBuffer, 0, m RecvBuffer.Length, SocketFlags.None, new System.AsyncCallback(OnReceivedBytes), null ) else Log("Failed to Connect.") ...


Discoordinated Chromatic Aberration Effect The game Teleglitch heavily utilizes the CA effect with screen distortion. I am trying to achieve this effect. Issue 1. How to not apply the effect onto the floor? (solved) They render the screen then apply the CA effect. However, the floor is not rendered with the post processing effect. Issue 2. How to have discoordinated position for each rendered CA effect? Currently I have three offsets for each channel red, green, and blue. However, I cannot assign different offsets for the channels for certain areas only. What would be a way to have discoordinated positions?


Assigning script to multiple objects So I have multiple gameobjects that needs to be interactable and I've put them all in one gameobject container. But the thing is I still have to attach the script into each of the gameobjects that needs to be interactable for it to work and that seems kinda iffy when a scenario comes that I have to add more gameObjects. Is it possible to just put the script in the container object? I tried this on my container object and I'm pretty sure I'm doing something wrong. public GameObject spriteHandler GameObject sprite1 GameObject sprite2 GameObject sprite3 private void Start() sprite1 spriteHandler.transform.GetChild(0).gameObject sprite2 spriteHandler.transform.GetChild(1).gameObject sprite3 spriteHandler.transform.GetChild(2).gameObject void OnMouseDown() Debug.Log( quot Clicked quot )


What's the difference between UnityEngine.Random and System.Random? What's the different between this int randomNumber UnityEngine.Random.Range(0, 10) and this on top of the class private System.Random rnd new System.Random() inside a methode of the same class int randomNumber rnd.Next(0, 10) I know System.Random must always be initialized on the top of your class what's by UnityEngine.Random is not needed. I know also that System.Random works with a intern "clock" and the "random" number is based on that. My question is now are there some other difference between UnityEngine.Random and System.Random and witch code is better to use for an Unity project?


How to make UI text longer? I'm working on a menu that needs a wordy description, but I've noticed that it only shows 4 letters, then cuts off and this doesn't seem right. I right click, select UI text and again, it only displays 4 words, even though I can write a lot more there. Am I doing something wrong here? I'm not sure how to get past this and I want to ask if anyone knows how to get past this? It seems like such a strange limit to put on the UI canvas.


What is the reason that people avoid PlayerPrefs to store character data and coins etc? PlayerPrefs are easy to implement and i think it can be used to store important game data like selected character and coins and completed quests for small games, but i have read too much to make me ask this question that why not use it, and what is the other options for storing important game data in


How do I set horizonal Field of View by code as in Inspector? I have a camera that I have set to RenderType Base Projection Perspective FOV Axis Horizontal Field of View 75 Physical Camera False Clipping Planes Near 0.3, Far 1000 If I set Field of View values during gameplay in the Inspector, it works as expected. For example, I type 75, and the camera behaves as I think it should. I'm comparing with Resident Evil 4. It has a camera cheat, and if I select FOV 75 in this cheat, the Resident Evil 4 camera behaves like my Unity game camera. However, when I set the camera.fieldOfView to a 75 by code, the Inspector shows 104, and the code does not look as it looks when I type 75 in the Inspector. camera.fieldOfView however returns 75. What is going on here, and how do I fix it? Thank you!


Can I legally modify the Unity splash to fit the game's theme? I've been working on a retro game, and I was wondering whether I could change the Unity logo to make it fit the game's style (eg. pixelating the logo). I know how to do this, but my question is whether it is illegal, assuming I have a Plus, Pro, or Enterprise licence for Unity that allows me to edit this splash screen at all.


How is the density of a collider determined? I read here that, once determining the density of a Buoyancy Effector, "Colliders with a higher density sink, those with a lower density float, and those with the same density appear suspended in the fluid." However, I did not find a density field in my CircleCollider2D. What I found is that If I increase the mass of the attached RigidBody2D, then the body sinks into the fluid since apparently its density increases. If I keep the mass but decrease the size of of the circle collider, then again the body sinks into the fluid indicating that its density increases. So my conjecture is that the density is calculated by the mass of the rigid body, divided by the volume of the collider. But I did not find the formula in the Unity manual. Is this correct?


Multiple Input.GetKeyDown happens in low frame rate There is a code that needs to be invoke each time user pressed specific button in my game. So I used Input.GetKeyDown to achieve that, but some reason, that code invokes multiple times even I keep pressing the button. After some tests, I figured out this happens a lot when the game has low frame late. In a very laggy moment, GetKeyDown returns true very many times. void Update() if(Input.GetKeyDown(KeyCode.RightArrow)) print("Pressed") I saw a similar issue in here but couldn't find any related information. https forum.unity.com threads problems with input at low framerates.16828 My game is a very input sensitive game, so my code when the user each time pressed a specific button always invoke when they pressed. I checked my keyboard is something wrong, but there was no problem with my keyboard. Why does this happen? According to the Unity doc, it said Returns true during the frame the user starts pressing down the key identified by name If I used wrong way, then how do I check each time user pressed a button? Using Unity 2019.1.0f2.


Trying to find a solution for instant knockback in multiplayer game I'm making a server authoritative fast paced multiplayer game. I'm trying to implement wack hammers, they are a melee weapon that knocks close players, in other words, that sets their velocity to inverse of their mass to the direction aimed at the force of the hit. Even if the enemy player is only seen getting knocked after the client input gets processed on the server and after the enemy's position and velocity get sent back, I want to make it seem like your action appeared instantly. I've tried one thing when you knock a player, that player gets predicted for a short amount of time instead of being interpolated. That way, players appears to have been knocked out instantly, but there's an issue with that. When should I stop predicting? And how? When you think about it, the prediction is done on your own client time. The positions and velocities of other players are a few millisec old, so when you try to interpolate between your local quot futur quot predicted player position to the quot old quot server player position, you essentially move the other players back in time, and it looks real bad. I'm not quite sure what to try to hide this issue. I can't possibly predict the enemy player's position forward in time, its movement can get too chaotic. I've already watched the GDC talk from Overwatch's and Rocket League's netcode a million time, I'm not sure if they can help me with my issue. Edit I still haven t found the best solution yet but there s some useful information over at https forums.unrealengine.com development discussion c gameplay programming 1455487 responsive knock back in multiplayer game


Wrong Second position of LineRenderer I'm drawing some kind of bullet trace effect with LineRenderer in my 2D Game Project with Unity. At some position, setting position of LineRender result weird In the above screenshot, you can see two types of lines are exists. Pure red lines are result of Debug.DrawRay which is only renders in Scene view, not actual game play, and another lines which has yellow to red gradient are actual line renders I want to draw. I used exactly same code for rendering both two, Debug.DrawRay() and LineRenderer.SetPosition(), but as you can see only DrawRay works as I expected and LineRenderers are cutted and pointing wrong direction. Here's the code I'm trying void Fire() Vector3 shootDirection m ShootPoint.right RaycastHit2D hit Physics2D.Raycast(m ShootPoint.position, shootDirection, m Range) Debug.DrawRay(m ShootPoint.position, shootDirection.normalized m Range, Color.red, 20) On Hit, set end position where it hits if (hit) CreateBulletTrace(m ShootPoint.position, hit.point) Otherwise, render straight until it's range else CreateBulletTrace(m ShootPoint.position, shootDirection.normalized m Range) void CreateBulletTrace(Vector3 startPos, Vector3 endPos) GameObject bulletTraceObj Instantiate(m BulletTraceLineRendererPrefab) LineRenderer bulletTraceLineRenderer bulletTraceObj.GetComponent lt LineRenderer gt () bulletTraceLineRenderer.useWorldSpace true bulletTraceLineRenderer.SetPosition(0, startPos) bulletTraceLineRenderer.SetPosition(1, endPos) Destroy(bulletTraceObj, 0.1f) Note that LineRenderer checked use world space to true. What am I missing? Using Unity 2019.1.0f2.


A canvas to let through a given layer I have two canvases, both of them having a UI element on them. At some point, both canvases will be active in the game (I just act like so, I want to make sure that my game works even if that's the case) and I want one of them to never block the other canvas's layer. These two, let's say Canvas1 is on layer UI and is responsible for character jumping. Canvas2 is on layer toggle time scale and it's job is to switch between timescale 0 and 1. I want Canvas2 to be ALWAYS accessible, so its layer, toggle time scale is NOT blocked by the first canvas. I tried messing around with the Blocking Mask but that didn't help, sometimes the ray still gets blocked out. How to set up those Blocking Masks for my canvases to work?


How can I prevent picking up health items when I'm already at max health? This is what I have so far.. public class Per10HealthCollect MonoBehavior void OnTriggerEnter(Collider other) if (GlobalHealth.healthValue gt 91) GlobalHealth.healthValue 100 else GlobalHealth.healthValue 10 GetComponent lt CapsuleCollider gt ().Enabled false this.gameObject.SetActive(false)


Do realtime reflection probes and precomputed GI work on iOS in Unity 5? Seems they don't from my tests but just to double check. My setup is made up of a few objects marked as static, all sharing a standard shader material with some emissive color, GI set only to precompute and a realtime reflection probe (set to render on every frame) attached to the player, which is the object that moves and passes near the emissive objects. The player has a metallic material, also standard shader based. In the editor, this generates reflections on the player as it passes near an emissive object, as you'd expect. On iOS, the player looks dull, very dark, and no reflections appear on its surface. I also tried setting instead the probe to Custom and tell it to render from within a script, since I can't just pre bake the probes, because the static objects are brought in at runtime. This doesn't seem to work either the probe doesn't seem to render anything. Any ideas?


Objects rendering only on editor, but not on build (they get invisible) Everything works fine in the editor, but when I build the game, none of the objects in the scene are rendered, and only the skybox and UI text is visible. But although they aren't appearing, they are working as normally (i.e. these objects' triggers work normally when the determined event occurs, like for example, colliding to a specified object, or in other words, they are invisible). I searched for this issue but didn't found any answer. Could it be my cheap computer's fault (Intel Celeron without an external graphics card)? In editor game mode In buit game I ran both the editor and the built game in the same quality, and also tried to run it in Fastest quality, but no, it made no difference in the built game. Also, there is no object tagged with "Editor only", only one have a custom tag and all the others are "Untagged". And the camera's culling mask is set to "Everything". The result is the same either for web or Windows. Edit OK, I built for Android and the objects render normally. So, I'm not completely sure, but probably it's my PC that can't render the objects, because both building for web plugin and desktop have this disappointing result, but for Android it works perfectly (even the shadows, which wasn't being cast in the editor), so...


why command is not executing on local player I am getting very strange behavior, if my player instantiate as host (Server Player) then my command function runs perfectly and certain object become instantiate but if I join the host then my Command doesn't execute on my local player but runs on all other clients. void Start() if (isLocalPlayer) Debug.Log("It is VR Player spawn Start") SetVRLocalPlayerSetting() InstantiateMimicVRHeadAndController() CmdInstantiateMimicVRHeadAndController() else Debug.Log("It is not vr Player its not isLocalPlayer") DisableSelectedMonobevaiourScripts() Command This function have a problem public void CmdInstantiateMimicVRHeadAndController() Debug.Log("instantiateing the controller and head object") vrHeadCopyObj (GameObject) Instantiate(vrHeadObjPrefab) vrRightCtrlCopyObj (GameObject) Instantiate(vrRightCtrlPrefab) vrLeftCtrlCopyObj (GameObject) Instantiate(vrLeftCtrlPrefab) spawn the bullet on the clients NetworkServer.Spawn(vrHeadCopyObj) NetworkServer.Spawn(vrRightCtrlCopyObj) NetworkServer.Spawn(vrLeftCtrlCopyObj)


How do I draw a tilemap within unity3d? I'm pretty new to Unity and after a bit of googling around I have come up with this code to draw my tilemap (the script is attached to my camera). I am simply trying to use nested for loops to draw a grid of grass tiles, here is my code public class DrawMap MonoBehaviour Use this for initialization void Start () Sprite grass (Sprite)Instantiate(Resources.Load("Grass")) float x, y for (int i 0 i lt 20 i ) for (int j 0 j lt 20 j ) x i 1.28f y j 1.28f Instantiate(grass, new Vector3 (x, y, 0f), Quaternion.identity) Update is called once per frame void Update () I keep getting an error where I initialize "grass" saying the it cannot cast the source type from the destination type. I created "grass" to be a prefab from a slice of a spritesheet that i imported. Any help would be greatly appreciated


Unity2D How to destroy spawned object once it exit out of camera's view? I'm trying to destroy spawned objects once it exit out of camera view automatically straight away. You see I'm trying to make a flappy brids type of game but things also comes in from the bottom and if they get a really high score then things will be spawned in from above and from the left side. So, so far this is what my game looks like (I'm still working on it). However I'm having problems with deleting spawned objects once it exit out of camera's view, I tried all sorts of things like private var hasAppeared boolean function Start () hasAppeared false function Update() if (GetComponent. lt Renderer gt ().isVisible) hasAppeared true if (hasAppeared) if (!GetComponent. lt Renderer gt ().isVisible) Destroy(gameObject) But with this script, it doesn't destroy the game object quickly enough that and only some of them is being deleted. I also tried this method public void OnBecameInvisible() Destroy(gameObject) But not all of them is being deleted as well and it also takes a long time for any of my game objects to be destroyed. My last result was this script, it destroys the game object straight away once it exit out of the camera's view (which is what I want) but only these sides works where as the other's don't, I think it destroys my enemies (spawned objects) before it has even entered the camera's view. How do I get the script to work on this side? This is my script void Update () DestroyAllEnemy () public void DestroyAllEnemy() GameObject enemies GameObject.FindGameObjectsWithTag ("enemy") if ((enemies.Length gt 0) amp amp (camera ! null)) for (int i (enemies.Length 1) i gt 0 i ) just a precaution if ((enemies i ! null) amp amp ((camera.WorldToViewportPoint (enemies i .transform.position).x gt 1.03f) (enemies i .transform.position.y lt 6f))) Destroy (enemies i ) Thank you ).


Getting neighbors of hex tiles in 3D space I have a hex tiled model like attached below. Each of the hex tiles are separate objects meaning I can access each of the hex tiles individually inside Unity Now in my program I want to be able to get the 6 neighboring tiles of the selected tile. At first I thought I would get the 6 edges of the current tile and then check to see if any of the remaining tiles have those edges in common but that would be very expensive if I want to compute neighbors of all the tiles. Any ideas??


Unity Editor Get Mouse coordinates on left click on Scene Editor I need a simple script which does the following When I left click somewhere in the Editor Scene (doesnt matter if there is an object under the cursor or not) Do NOT deselect the current selection in the Inspector. Do not select the object under the cursor. and Just print the mouse X and Z interception with the Y Plane in the Debug.Log() i stumbled on many solutions but somehow i couldnt get this to work. i tried HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) and Tools.current Tool.None both seem to do nothing ..... X.x EDIT Happens that "HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) " needs to be inside public void OnSceneGUI() and called every frame to "block" the mouse clicks on the editor. i thought it toggles it off. still the problem of the mouse coordinates persists.


Why is Particle System Not Visible Without Scene Window Viewing the Origin? I have a particle system, which is supposed to be highlighting an important game object, but the Particle System doesn't show on the game window unless the Scene window camera has the Origin (0,0,0) in view. The origin is at the corner of my UI canvases, in which you can see the two white lines marking the edges. Take a look at these screenshots. On the 1st screenshot, the particle system is not visible. The 2nd screenshot was taken just moments later and the particle system is completely visible (and the number of particles is as if it had already been emitting the whole time.) The only difference is that I slightly rotated the camera of the Scene Window in between screenshots. The camera was rotated down just a tiny bit to put the origin visible in the scene view. The particle system immediately becomes visible on the game window as soon as I rotate the SceneView camera so that the Origin is in view. This is Unity version 5.6.0f3. There are other questions about particle systems not working, but the cause and solutions appear to be very different. Here are things I've already tried The particle system is already set to "Play on Awake" both before and after rotating the camera. I've ensured that all of components and game objects are visible and enabled both before rotating toward the origin and after. All of the particle settings (size, etc.) are correct both before rotating to the origin and after. Why is the particle system not visible without the origin in the scene view?


360 Orbital Camera Controller I have a stationary cube in my scene that I'm orbiting a camera around. I have my MainCamera nested under a GameObject that I'm calling 'OrbitalCamera'. I setup the script so that a click (or tap) and drag will rotate the camera around the object in space so it feels like you're rotating the cube (ie if I click the top of a face on the cube, and pull down, I'm rotating the X value) but you'll actually be rotating the camera. For the most part, my script works. However, after rotating the Y so much, the camera is upside down and the X gets inverted. Here's my script public class OrbitalCamera MonoBehaviour public bool cameraEnabled SerializeField private float touchSensitivity SerializeField private float scrollSensitivity SerializeField private float orbitDampening protected Transform xFormCamera protected Transform xFormParent protected Vector3 localRotation protected float cameraDistance void Start () cameraEnabled true xFormCamera transform xFormParent transform.parent cameraDistance transform.position.z 1 void LateUpdate () if (cameraEnabled) TODO FIX PROBLEM WHERE WHEN CAMERA IS ROTATED TO BE UPSIDEDOWN, CONTROLS GET INVERSED if (Input.GetMouseButton(0)) if (Input.GetAxis("Mouse X") ! 0 Input.GetAxis("Mouse Y") ! 0) localRotation.x Input.GetAxis("Mouse X") touchSensitivity localRotation.y Input.GetAxis("Mouse Y") touchSensitivity Quaternion qt Quaternion.Euler(localRotation.y, localRotation.x, 0) xFormParent.rotation Quaternion.Lerp(xFormParent.rotation, qt, Time.deltaTime orbitDampening) Is there a good method to achieve this type of 360 camera? I'd like dragging from right to left to always move the camera left and dragging left to right to always move the camera right no matter how the camera is oriented.


Too Low Amount of Tris in Statistics Window, Only in the Tens (Unity) I'm working on a mobile game, and for optimization it would be useful to see the correct amount of polygons rendered. However in the Statistics window the amount of polygons displayed are suspiciously low, only 62. Getting the poly count this low would be quite an achievement. I'm using the Universal Rendering Pipeline. Would there be a way to fix this?


Top down off screen indicator, Unity3D C I'm working on a top down 3D game where things spawn off camera. Movement only occurs on 2 axis (x and z). Rotation is about y axis. The player is in the center of the camera and needs to have indicators at the edge of the screen to show where the item is relative to the players location. I've managed to figure out the distance from my player to the target just using the distance between 2 Vector3 points. However, I can't figure out how to translate this into a direction angle for an indicator arrow that I have instantiated as a child of the canvas UI and make it point to the edge of the screen.


How to divide sprite sheet, but keeping the in same png? first post here, but couldn't find an exact answer in your database, so guess I'll have to ask. I want to know how it is possible to create a ".META" file for a .png so you can extract individual sprites in a spritesheet without having to save all the sprites in individual .png's. I know it's possible since the developer in the tutorial HERE is using a spritesheet like that. Thank you very much in advance.


Unity Change Text with Time (Text Flashes) I am trying to display instructions within the Unity game. The idea is to have the instructions appear over time. For example, "instruction 1" then wait 5 seconds and show "instruction 2" instead of instruction 1 (on the same spot, in this case, I am changing the "message" variable in the code to change the instructions). This code does change the instructions but the problem is that it does it in a haphazard fashion. It appears that "instruction 1" is replaced with "instruction 2" and then it reverts back to "instruction 1" within a second and then back to "instruction 2" so instead of just 1 appearing 1 disappearing 2 appearing etc in a smooth fashion, it does this weird flashing thing before proceeding to the next instruction. How could I fix this? using UnityEngine using System.Collections using UnityEngine.UI public class Growing MonoBehaviour public Text instructions public string message void Start () instructions.text message void Update () Instructions() other code to begin moving a game object IEnumerator Instructions() run instructions message "GET READY FOR YOUR FOCUSED BREATHING EXERCISE" yield return new WaitForSecondsRealtime(5) message "MAKE SURE YOUR BODY IS COMFORTABLE" yield return new WaitForSecondsRealtime(5)


Objects with custom shaders cast grayscale shadows when lightmapped Unity 5 seems to be able to calculate colored shadows from objects mapped with standart shader and legacy shaders. What should I do to make my custom shader to cast colored shadows as well?


Get object length and width divided by two? I have googled and found a script for the following task Make the camera move to touched position. However, this script will jump to x and y positions on an object, while i would like for it to move to the middle of the object, and then only be able to jump to others. using UnityEngine using System.Collections public class TapToMove MonoBehaviour flag to check if the user has tapped clicked. Set to true on click. Reset to false on reaching destination private bool flagTouchCoords false destination point private Vector3 cameraDestination alter this to change the speed of the movement of player gameobject public float duration 100.0f vertical position of the gameobject private float yAxis void Start() save the y axis value of gameobject yAxis gameObject.transform.position.z Update is called once per frame void Update() check if the screen is touched clicked if ((Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) (Input.GetMouseButtonDown(0))) declare a variable of RaycastHit struct RaycastHit hit Create a Ray on the tapped clicked position Ray ray for unity editor if UNITY EDITOR ray Camera.main.ScreenPointToRay(Input.mousePosition) for touch device elif (UNITY ANDROID UNITY IPHONE UNITY WP8) ray Camera.main.ScreenPointToRay(Input.GetTouch(0).position) endif Check if the ray hits any collider if (Physics.Raycast(ray, out hit)) set a flag to indicate to move the gameobject flagTouchCoords true save the click tap position cameraDestination hit.point as we do not want to change the y axis value based on touch position, reset it to original y axis value cameraDestination.z yAxis Debug.Log(cameraDestination) check if the flag for movement is true and the current gameobject position is not same as the clicked tapped position if (flagTouchCoords amp amp !Mathf.Approximately(gameObject.transform.position.magnitude, cameraDestination.magnitude)) amp amp !(V3Equal(transform.position, endPoint))) move the gameobject to the desired position gameObject.transform.position Vector3.Lerp(gameObject.transform.position, cameraDestination, 1 (duration (Vector3.Distance(gameObject.transform.position, cameraDestination)))) So this is how the game looks. The script moves correctly, but will jump at different positions when it hits the collider on the lily pads. I could reduce the collider, but I feel like there should be an easy way to get length and width of a collider, and reduce it by 2 to make the camera move directly in the middle. Anyone care to help? Thanks in advance. )


In Unity, how to get reference of descendant? I'm trying to get descendant game object, not a child. Let's assume that I have a GameObject and it's hierachy looks like this Weapon Hands metarig upper arm.L upper arm.R forearm.L.001 hand.L.001 weapon.L.001 AttackDetection(!) Sword I want to access "AttackDetection" from Weapon(Root) in script. But when I try this void Start() attackDetectionGObject this.transform.Find("AttackDetection").gameObject It fails with this NullReferenceException Object reference not set to an instance of an object Looks like transform.Find just looking up it's own child, not descendant. I try to find way to solve this problem, but there's nothing I found. Any advice will be very very appreciate it.


Handling an item database with procedurally generated items? Let's say you have an item database which has every item in your game. This works fine for regular items like a Health Potion, a normal Iron Sword etc, because these items have ItemID's so we can get an exact copy of this item. But what if we have an Iron Sword with an enchantment ' 5 Fire Damage'? (or whatever) If you were to save that item to a player's inventory, exit the game and load the game, the item will load as a regular Iron Sword, because it still has that ID. Specifically, how would you save that item to a file? I'm using Unity, so to save the Player's inventory, I use PlayerPrefs.SetInt("Inventory " i, inventory i .ItemId ) Would you create a custom item ID for every item with enchantments or is there a better way around this?


Rotating a gameworld using quaternion I'm a hobbyist programmer at best and I had an idea I wanted to test in Unity, I wanted to rotate the game world around 90 degrees, to this end I've been learning a tiny bit about quaternions, in this simple test I have a empty game object at position 0,0,0 and 2 cubes placed so only one will be in the foreground at once (both children of the empty game object). I simply want to rotate the parent object on a mouse up like so. if (Input.GetMouseButtonUp(0)) Quaternion newrot Quaternion.Euler (0,90,0) transform.rotation Quaternion.Slerp (transform.rotation,newrot,0.05f) The problem I am having is that this does not do the rotation in a single click and never reaches 90 degrees, it only ever tends towards 90 (for fun I decided to click for 2 minutes and only got up to 89.99999 ... well you get the picture). Can someone tell me what I am doing wrong and if there is a better way of doing this?


How can I make outline shader like "Life is Strange"? I want to make sketch shader like life strange. shader has two part 1.animated dashed line 2.noisy outline I like to know how can I make noisy outline? see outline of objects First I tried to make outline by copying of incoming vertex data and scaled according to normal direction then Cull Back.but I think it's something like Image effect because outline sometimes move inside of object. anyway I will appreciate if someone help me to Implement this shader ) What I tried I used edge detection and animate it by vertex shader but this isn't good like above gifs.


How can I tell if a Gameobject is currently touching another Gameobject with a specific tag? I've seen similar questions to this here on Stack Exchange Game Development, but none of the answers to them have helped my problem. I am working in Unity 2019.2.18f1 with Visual Studios 2019 Community. What I want to know how to tell when one Gameobject (the player) is currently touching another game object with a tag name of "Block". When the player collides with a "block" I want it to set jumpPossible true But when it leaves the block (by jumping or falling off) jumpPossible false What I currently have in my PlayerController script (the important stuff anyways) private void OnCollisionEnter(Collision collision) if (collision.gameObject.CompareTag("Block")) jumpPossible true private void OnCollisionExit(Collision collision) if (collision.gameObject.CompareTag("Block")) jumpPossible false The problem I am having is when the player is currently on a block and then touches another block. When it leaves the one of the blocks, it will set jumpPossible false and so you can't jump. What I want for this script to do is whenever the player is touching any Gameobject with a tag of "Block" it should allow it to jump.


fading from one scene to another not working I am using the following code to fade from one scene to another, but it doesn't fade. It just loads the next scene without fading. I suspect there's something wrong with the image I'm using. I used a black .png image with dimensions 425 344 that I downloaded from Google. How can I solve this issue? Fading.cs (I added this to an empty game object) public Texture2D fadeOutTexture public float fadeSpeed 0.8f private int drawDepth 1000 private float alpha 1.0f private int fadeDir 1 void onGUI () alpha fadeDir fadeSpeed Time.deltaTime alpha Mathf.Clamp01(alpha) GUI.color new Color (GUI.color.g, GUI.color.b, alpha) GUI.depth drawDepth GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture) public float BeginFade (int direction) fadeDir direction return (fadeSpeed) void onLevelWasLoaded() BeginFade ( 1) In the script of the trigger object IEnumerator gameScene2() float fadeTime GameObject.Find ("FadeObject").GetComponent lt Fading gt ().BeginFade(1) yield return new WaitForSeconds(fadeTime) Application.LoadLevel("Scene2") These are the image settings for the black .png image


ToonRamp Shader Normal Maps How to keep strict lighting bands? I'm trying to achieve a shading similar to the one on this image Image 1 https imgur.com a eTTvSCD To get something similar to this I wrote a toon ramp shader (similar to the one in the Standard Assets) with normal maps. The shader works, and without a normal map you can see the lighting bands strictly defined, with visible seams separating them (Image 2). But once you add a normal map, the toon bands won' t have well defined seams anymore, and will blend smoothly all across the mesh (Image 3). Image 2 amp 3 https imgur.com a SI3BxED This is my current shader Shader "Custom ToonRampWithNormals" Properties Color ("Color", Color) (1,1,1,1) MainTex ("Albedo (RGB)", 2D) "white" BumpMap("Bumpmap", 2D) "bump" Ramp("Toon Ramp", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Ramp Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D Ramp half4 LightingRamp(SurfaceOutput s, half3 lightDir, half atten) half NdotL dot(s.Normal, lightDir) half diff NdotL 0.5 0.5 half3 ramp tex2D( Ramp, float2(diff,diff)).rgb half4 c c.rgb s.Albedo LightColor0.rgb ramp atten c.a s.Alpha return c struct Input float2 uv MainTex float2 uv BumpMap sampler2D MainTex sampler2D BumpMap half Glossiness fixed4 Color UNITY INSTANCING BUFFER START(Props) put more per instance properties here UNITY INSTANCING BUFFER END(Props) void surf (Input IN, inout SurfaceOutput o) Albedo comes from a texture tinted by color fixed4 c tex2D ( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Normal UnpackNormal(tex2D( BumpMap, IN.uv BumpMap)) o.Alpha c.a ENDCG FallBack "Diffuse" So, what have I done wrong? How can I have well defined lighting bands and have normal mapping? If you can think of a better way to achieve something similar to the reference or have any thoughts about it please share, any contribution is much appreciated.


Animator Component gets removed automatically Unity I am creating a simple scaling animation on image (in Unity). When I play game in unity editor, the animator component get removed automatically. Here I am copying snapshop of Inspector of Image. What should I correct?


How to add a fluorescent effect on an image in Unity I have recently been attempting to create a true on screen representation of a fluorescent orange colour on an image. Whereby, I believe post processing with unity will deliver the best results. Thus, I was wondering if someone could kindly guide me through the steps to add a fluorescent effect to my image? As a reference I would like to try match pantone 804c on screen. Image in question I have tried to follow tutorials like this, but unfortunately they all are working on 3D scenes. I have a pre existing jpg image that I want to modify.


How to FindGameObjectsWithTag then cast the array of GameObjects to an Array of Interfaces I have a few GameObjects that implement a common Interface IsTree. I need to call the function doTreeThing() on each of those IsTrees after getting a reference to each of them via FindGameObjectsWithTag("tree"). This line complains that it cannot implicitly convert from GameObject to IsTree IsTree trees GameObject.FindGameObjectsWithTag("tree") So then I tried to leave the GameObject an iterate over it to convert each individual object inside to an IsTree. GameObject trees GameObject.FindGameObjectsWithTag("tree") foreach (GameObject tree in trees) IsTree isTree (IsTree)tree isTree.doTreeThing() But this complains that it also cannot convert GameObject to IsTree. Then I got a little desperate and tried to make my IsTree into a GameObject. public class IsTree GameObject public System.DateTime getAge() return null GameObject is a sealed type. (I don't really know what that means besides that this does not work) So how do I get this array of GameObjects into an array of SomeInterface?


Adding Score to score canvas after collision Simply a player has to move through pipes falling down, once the player moves through the gap it should add a score and increase the scoring after each pipe the player goes through, pretty basic. I have made a prefab object and it is a block with a collider on it and another collider that acts as a trigger behind it stretched out so it can be accessed on both sides. I then added to the main scene canvas textmeshpro added a script with the following code however, when the player hits the collider the score does not increase in the scene. But if I remove the GetComponent then it increases by increments of 4 in the inspector. using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() GetComponent lt UnityEngine.UI.Text gt ().text Score.ToString() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score


How to do camera follow without drag and drop in Inspector in Unity? How to do camera following an object with special tag without drag and drop into Inspector? I have 2 prefab model they are not into hierarchy for the moment when player start play. To load selected model into scene I'm using the below code. public GameObject players void Start () LoadPlayer () private void LoadPlayer() GameObject player Instantiate(players PlayerPrefs.GetInt(MyModel") ) Because in other scene I can change my player model but I can't follow it using in c script for camera public Transform cause of I can't drop it in that place in Inspector. So in what way I can find current player object when game start to follow it by camera?


How can I do unit testing in Unity? How to implement Unit Test at Unity3D. I wonder if it would be possible to extend the Unity editor to have some sort of testing framework in it. Is there any guideline to implement it? Any reference like book, blog? Any working example or project?


Surface Depth Intersection Shader I recently asked a question about the creating an accurate Depth Intersection Shader. When creating this in a fragment vertex shader it could be achieved by the following code SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" Pass CGPROGRAM pragma target 3.0 pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 float3 normal NORMAL struct v2f float2 uv TEXCOORD0 sampler2D MainTex float4 MainTex ST sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength v2f vert(appdata v, out float4 vertex SV POSITION) v2f o vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag (v2f i, UNITY VPOS TYPE vpos VPOS) SV Target float2 screenuv vpos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(vpos.z) float intersect 0 if(diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) return fixed4(lerp(tex2D( MainTex, i.uv) Color, GlowColor, pow(intersect, 4))) ENDCG However, when I try to put the same logic into a surface shader, the result does not show any depth intersections. SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows alpha fade Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex struct Input float2 uv MainTex float4 screenPos float eyeDepth half Glossiness half Metallic sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. See https docs.unity3d.com Manual GPUInstancing.html for more information about instancing. pragma instancing options assumeuniformscaling UNITY INSTANCING CBUFFER START(Props) put more per instance properties here UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float2 screenuv IN.screenPos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(IN.screenPos.z) float intersect 0 if (diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) fixed4 col fixed4(lerp(tex2D( MainTex, IN.uv MainTex) Color, GlowColor, pow(intersect, 4))) o.Albedo col.rgb o.Alpha col.a o.Metallic Metallic o.Smoothness Glossiness ENDCG


RTS Unit AI When to let the unit stop (due to local avoidence) I am developing an RTS like game, that have units that move and attack. I implemented path finding and local avoidance. One problem is when multiple units being ordered to the exact same position, they can never reach the position due local avoidance and collision. Only this will make the units scratch each other, this will also cause the unit not able to STOP, as the unit might be still far from the target position. And whether stopped or not is important for battle (unit can only attack when stopped). I studied how SC2 handles this, it appears that the units will stop after a few seconds of scratching. PS, I have used group formation to avoid the situation, but it can not be avoided, when the group are ordered to goto some impossible position, and they would cluster at the edge of the valid navmesh.


How to make a script's Gizmo toggleable in the Gizmos menu in Unity3D? I've implemented Gizmos for a few behaviours, and I'd like to make them toggleable in the Gizmos menu, just like the built in ones. Is this achievable?


Move a ball horizontally left and right but restricting forwards and backwards motion unity 2d I am trying to develop an endless runner where there is a sphere as the player and it is moving left and right following the position of a finger on a touch screen. However, when I try to do this I cannot get the player to lock on the Y axis. I want a constant force that speeds up overtime which I have using the constant force 2d supplied by unity. I have two versions of code, the first follows the finger but the player is able to move up and down as well using UnityEngine using System.Collections public class Test MonoBehaviour public GameObject character public float speed 500.0f void Start() Input.multiTouchEnabled false void Update() if (Input.touchCount 1 amp amp Input.GetTouch(0).phase TouchPhase.Moved) Vector2 target Camera.main.ScreenToWorldPoint( new Vector2(Input.mousePosition.x, Input.mousePosition.y)) character.transform.Translate(Vector3.MoveTowards(character.transform.position, target, speed Time.deltaTime) character.transform.position) The second code I have allows the player to move left and right by tapping rather than following but is still sloppy using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody2D rb public float sidewaysForce 500f Start is called before the first frame update void Start() rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update() foreach (Touch touch in Input.touches) if (touch.position.x lt Screen.width 2) rb.velocity new Vector2(sidewaysForce 1, rb.velocity.y) if (touch.position.x gt Screen.width 2) rb.velocity new Vector2(sidewaysForce 1, rb.velocity.y) Any help on this would be awesome Thanks!!!


How can I prevent the knob from resizing when I use the Slider? I am using the Unity Slider component. I have a custom background and custom knob. But whenever I move the slider, my knob's size becomes distorted. It is 100x100 pixels, and when I set it to its native size, it does so. But I soon as I move the slider, it cuts its height in half. How can I prevent this from happening?


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


Line renderer's baked mesh not moving correctly with the line I used LineRenderer' Bakemesh to create a mesh around the line drawn, it is placed exactly, but when the line moves, the mesh is not following its movement.


How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d? I have two character in my game enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way void FixedUpdate() if (CanMove) transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) public void StartMove(bool canMove) CanMove canMove TargetPlayer GameObject.FindGameObjectWithTag(Tag).transform rigidbody2D.gravityScale 0 This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good looking? Edit I need to make good looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the current player position. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air(( Edit 2 I was thinking about destroying that object anyway, but to my mind this will not look good the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself.


Unity UI Input Field suddenly malfunctioned I'm using Unity 5.0.1f1, and my UI Input Fields are not working as they are supposed to. I have an Input Field that is placed in a Panel and inside a Canvas. It has a Text component in which I can set text that the Input Field will display. When I change value of this Text component, the changes are not reflected on the Input Field, it seems to be reset to the value of Input Field (Script) Text of the Input Field. If I enter Play mode, I can input text normally but when I build and run on my Android phone, I cannot input anything. Has anyone encountered this problem? How can I solve this?


Get rotation of camera in Google VR I'm trying to move child of camera object smooth. To implement that, I need to know the movement of x and y axis, like Input.GetAxis in general PC platforms. I saw the documentation and examples of Google VR, but there's not much explained well. One thing I found is GvrControllerInput.Gyro, but it's said it's deprecated and use GvrControllerInputDevice.Gyro instead, but there's no Gyro value in GvrControllerInputDevice. Seems like basic usage is totally changed, so they are not providing static methods, and force to using internal method of the object, but couldn't find any related information about this. So, how do I get gyro from GvrControllerInputDevice? Or is there an alternative way to make child object rotate smooth from their parent? Any advice will very appreciate it!


Set Layer of UI Object being Dragged In my game, I have an inventory system with slots and images in those slots. The images are by default disabled, but when an item is added to the slot, the image component becomes enabled. I have implemented a very simple drag and drop system for moving objects around in the inventory using IBeginDragHandler, IDragHandler, and IEndDragHandler. As I am dragging an item from one slot to another, I want the item image to be rendered in front of the slots and the rest of the inventory. Currently, when dragging an item image, it renders behind the empty slots. I don't want to use hierarchy order to organize the layers of these slots because moving items around is very dynamic and the hierarchy order of the slots changes seemingly randomly when I press play. Is there another way to ensure that the item image being dragged is "closer to the camera" or in front of the rest of the inventory? Thanks.


How to revert to MonoDevelop's old "ctrl tab" behavior? I believe MonoDevelop (bundled with Unity3D) has changed its ctrl tab and ctrl shift tab behavior and I would like to get back to the old behavior, as the new way frustrates my workflow. Ctrl tab (and ctrl shift tab) previously (and ought to) go to the "last viewed tab", in a similar way to how alt tab works on Windows. Unfortunately there seems to have been a change and now it goes to the "tab on the left of the current one". An example of why this is frustrating quickly looking at a class definition, you hit F12 to load the definition (perhaps in a new tab), and then you want to go back to the code you were working on. Previously you could hit ctrl tab and you'd be back there. Now you can't do that and you have to actually remember what you were doing, which isn't good for my workflow (read ailing memory). I'm not sure when the change happened, or if it's a setting somewhere (I can't find it). I'm running Unity 5.1.2p2 and its bundled MonoDev 4.0.1. Noticed it after a clean install of Windows 10. How can I fix this to revert to the old behaviour, or is there some other method to jump back to the last viewed tab? It seems pedantic but it has a major impact on my productivity.


Using unity Rigidbody 2D gravity, how to add to velocity? I am creating a top down game, and have an object I want to create a small bouncy illusion for. Since I dont have anything to collide with I'll have to do it with Scripts. Without Unity I would probably do something like function fall () this.vertical speed this.vertical speed GRAVITY if (this.vertical speed gt TERMINAL VELOCITY) this.vertical speed TERMINAL VELOCITY this.vertical position this.vertical position this.vertical speed However in Unity we have the Rigidbody 2D, so I want to somehow use that for this. if I set rigidBody.velocity new Vector2(1, 0) speed delta , it gets a constant speed, and ignores gravity. How can I add gravity? i.e I want to create a curve like


How to create a standard pbr material with shader graph? I want to create a standard pbr material that is editable with the shader graph, but when I install the package and go the Create gt Shader tab, I only have 2 graph options Empty Shader Graph, and Sub Graph. Isn't there a shader graph that starts me off with a basic pbr material with color and reflections? I'm using unity 2020, and the default render pipeline. Do I need to switch to ldrp or hdrp?


How to Handle Lighting from a 3D Game Engine with a Roguelike Game using Shadowcasting Normally the shadowcasting will, from the player position, set a brightness amount to each relevant tile. Yet I'm making a roguelike with a 3D map, and Unity has lighting. Currently I have the player piece with a point light, and game objects that haven't been seen yet are set to inactive. but it doesn't have the same effect. Has anyone resolved this situation? Any suggestions? Addendum Screen shots I somewhat like the effect as it is in the screenshots I'd like to be able to control the amount of light in each 'tile' if possible.


Unity Disable push on dynamic Rigidbody2D objects I have a player, and several NPCs. I also have several static colliders in the world (trees, water, fence, etc), I want my NPCs to collide with this, so the Rigidbody2D needs to be dynamic, since kinematic does not collide with static colliders (colliders without a rigidbody). My problem is that since both player and NPC have dynamic rigidbodies, they push each other when they collide. I could disable this by setting the following in the NPC script void OnCollisionEnter2D(Collision2D other) if (other.gameObject.name "Player") isMoving false myRigidBody.isKinematic true However, the NPC still gets pushed a few pixels before it stops, its barely noticable, but it is noticable, and if you keep colliding with the NPC you could move it as far as you wanted (tedious, but possible). I've spent a few hours looking and cannot find a good solution to this. I want my NPC to collide with static colliders, but I don't want them to get pushed by the player. How can I solve this?