DontDestroyOnLoad() doesn't work in Unity I have a problem with DontDestroyOnLoad() in Unity. It does not work! My code private static PlayerSpawningScript instance public void Awake() Debug.Log ("PlayerSpawningScript awake") Debug.Log ("Instance " instance) if (instance null) Debug.Log ("Initializing PlayerSpawningScript instance") instance this DontDestroyOnLoad (gameObject) if (instance ! this) Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.") Destroy (gameObject) Debug.Log ("PlayerSpawningScript instance " instance) public void OnDestroy() Debug.Log ("Destroying PlayerSpawningSceript instance " instance.ToString ()) Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?


How can i add a description of gameobject when click on the gameobject? I have this DetectInteractable working script attached to Player (FPSController). I'm using tag to detect interactable objects, each object i want to be interactable i change his tag in the editor to "Interactable". ( Maybe there is a better way to do it without using tag ? It's working but many told me not to use tag. ) I'm using Raycast to hit a gameobject detect if it's "Interactable" and if it does i display on the gameobject his name. For example "Security Door" or "Screen Monitor" or "Surveillance Camera" Now i want to do that if i hit a gameobject with the raycast and it's "Interactable" if i will click the mouse left button it will display a description text description about the gameobject. But this time i want to use some gui box so it will be in front of the screen in the middle and not on the gameobject. The problem is that i need to create a script for every "Interactable" gameobject and make that if i click on a button it will display a description. Then how do i make the script and how can i make that when i attach the script to each gameobject it will make in the inspector a box of text so i can enter and type there the description of the item(GameObject) ? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public Canvas canvas public Text interactableText private RaycastHit whatObjectHit private RotateObject rotateobj private void Start() rotateobj GetComponent lt RotateObject gt () private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (rotateobj.rotating false) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true interactableText.gameObject.SetActive(true) interactableText.text whatObjectHit.collider.gameObject.name print("Hit ! " whatObjectHit.collider.gameObject.name) else image.color Color.white interactableText.gameObject.SetActive(false) print("Not Hit !") else image.color Color.white public class ViewableObject MonoBehaviour public string displayText public bool isInteractable


How to make a changeable color constant for editor materials? Due to the nature of a project I'm working on, the models I got have a bunch of redundant materials on them. I have to fiddle around with some of the colors, but every time I want to change the colors, I have to change each material to the exact same color. Is there any way to declare some kind of swatch that I can change and have those changes just apply to the materials or anywhere else? For instance, in code, you'd just make a readonly Color mainColor, that you'd use wherever you need and could change at will. I'm looking for this kind of behavior in the editor itself.


Render 2D textures on a 3D object's face I am not familiar with 3D graphics, and I'd like to know the right way to render some 2D figures on different points of a wider face of a 3D object. My 3D object is just a cube representing a poker table. I have a 2D png for players' placeholders, and I'd like to render these figures on the 3D object where needed. An alternative solution would be to render the whole face with a big picture containing all the placeholders figures. However, it would be a waste of memory and thus less efficient. What do you suggest?


Making a gameobject move back and forth in Unity So i have this enemy gameobject and i want it to move in a certain pattern like a patrol. So i want him to move from A to B to C then Back to B to A. The script I worked out makes him go from C to A directly but I dont want that. Can someone please help . The Length of PatrolPoint Array in 3 using UnityEngine using System.Collections public class EnemyPatrol MonoBehaviour public Transform patrolPoints An Array of path points to be followed private int currentPoint public float enemySpeed void Start() currentPoint 0 transform.position patrolPoints currentPoint .position Starting Point void Update() if(transform.position patrolPoints currentPoint .position) currentPoint if(currentPoint gt patrolPoints.Length) currentPoint 0 transform.position Vector3.MoveTowards(transform.position , patrolPoints currentPoint .position , enemySpeed Time.deltaTime)


Unity3D and Photon Networking RPG Good time of the day. My question might sound stupid, due to the knowledge you might have, but here it is. I've purchased Diablo 3 a long time ago and been enjoying it since then. Since many of my friend are playing other Blizzard titles, i tried to convince them to purchase Diablo and to play all together. However, they don't want to invest money in the game they don't understand (yet). So i've decided to write a game, which will be similar to the Diablo in the way of interaction and gameplay, but will (obviously) have some unique points in it (since i'm not only doing this for them, but also to educate myself in the game development area). Other this is, i've decided to take Masters in the Game Development (later this march, just got my bachelors in computer security) and wanted to have some basic knowledge about game development. I used to make "RPG" games before, tho only browser style ones using LAMP stack, and have some basic knowledge on storing retrieving data to from server. In order to implement multiplayer part of the game, i've decided to use free package PUN (Photon Unity Networking). Had no problem with creating my first room and spawning a player prefab for every new connection (tho they all move no matter on which client action is performed). Now to the question(s) By using PUN, i'm able to create new room for players (limited to 5), is it possible to set room names BEFORE they are actually initialized by the player? (set of rooms might be stored on MySQL server and retrieved by the API call) Is it possible to save progression of the player on the server, and later pass it back to the spawned player (by PUN). This is my main concern, since i've no actual access to the data processed by the server. (Solution is to create another connection to the "storage" server, and keep both of them "online"?) Does PUN allows you to select which scene should be loaded upon first player entering the room, if so, a bit of pseudo code might be helpful. What will happen to the player, if there is no spots left to join the server (this is just theoretical question, since i'm not going to publish this game, and amount of friends playing games is less than 20) How would one deal with the item equipped, which is received during the gameplay? (This one links to the second question) What i'm talking about is, is it possible to restore player object with the set of data received form the server (if possible, ofcourse) I know, the first suggestion will be to go and to read documentation (i'm in the process of reading it, don't worry). But i've decided to write here, since there are many skilled people out there in this area, who can give me basic understanding on how this whole PUN system works. I would like to thank you for all of the responses, which you are about to post (or maybe not), and again, have a great day.


How do I stop clicks on a button from also triggering my gameplay scripts? My character jumps when I press the right side of screen. The pause button is alsp in the top right corner. So when I press that button, the right side script always triggers and I don't want that to happen. Here the script if (Input.GetMouseButtonDown(0)) float xPosition Input.mousePosition.x if (xPosition gt Screen.width 2 amp amp isGrounded amp amp !isJump) mouse is on the right part of the screen, shoot right rb2d.velocity new Vector3(0, jumpForce, 0) isJump true JumpSoundSfx() if (Input.GetMouseButton(0)) float xPosition Input.mousePosition.x if (xPosition lt Screen.width 2 amp amp !isJump) mouse is on the left part of the screen, so shoot to the left crouch.SetActive(true) stand.SetActive(false)


How can I blend meshes together where they intersect? In a lot of my scenes I have things like this and this All the places I've circled are places where a prefab overlaps with another one or with the terrain. Is there any way to make those lines softer more natural and blend together more? When I can, I try and hide the lines with trees or other items, but that doesn't work in every case. I wonder if I can solve this with something like the soft particles effect. Soft particles in Unity help blur the line between a particle system and a rendered mesh. This keeps you from having jarring hard cut offs and straight lines in something that's supposed to be amorphous. (That's as far as my understanding goes) Can I use something like this to blend my prefabs together?


Unity override Coroutine Loop I have problem, when i override a Coroutine loop from the base code. But it seems that it only execute once. While on the base code it does what it suppouse to do and that is execute forever. protected virtual IEnumerator OnThink(float interval) while (true) yield return new WaitForSeconds(interval) protected override IEnumerator OnThink(float interval) Debug.Log("Execute") yield return StartCoroutine(base.OnThink(interval))


unity lag while moving a sprite I'm trying to build a 2D game for android and after I finished developing the game I noticed that there was lag present when moving objects around. I tested it on a phone much more powerful than my own Sony Xperia z2 and it had more lag, therefore I believe it's not related to RAM. I've disabled vsync using profiler putting the movement in fixedupdate, lateupdate, and even built a new project. This new project has only 1 scene and 3 scripts. One of scripts are attached to this sprite to move it. When running this project I still have lag both on my laptop and on my mobile phone! This is the script using UnityEngine using System.Collections public class PlayerMove MonoBehaviour public Vector2 movement public Vector2 speed private float myTimer Use this for initialization void Start () speed new Vector2(2,0) Update is called once per frame void Update () handleMove () public void handleMove() if (Input.GetKey (KeyCode.UpArrow)) speed.y 2 this.gameObject.rigidbody2D.velocity speed myTimer .3f if (Input.GetKey (KeyCode.DownArrow)) speed.y 2 this.gameObject.rigidbody2D.velocity speed myTimer .3f if (myTimer gt 0) myTimer Time.deltaTime else speed.y 0 this.gameObject.rigidbody2D.velocity speed this is results of profiler


How can I choose a pathfinding target for a unit group and move the group to that target? So I've got some units which should move to a specific position which is given by the player. Currently the units can move there by finding a path with the A algorithm (to be more precise A Pathfinding Library for Unity) I was wondering what the best way to move the units is? When the player has selected e.g. 20 units, some of them are near each other, some of them are far away from the others, what is the best way to navigate them to a single position defined by the user. Obviously they cannot just all have the same target since they would never reach it when the first unit moved to it. Thus what do I have to do? Do I have to assign different targets to each unit or do I calculate the target position relative to the position they were to each other before?


Unity separate shapes on a map into individual objects? Okay, I asked this question yesterday anonymously thus I couldn't edit it so I'm remaking it. Short version I have a transparent map with black borders (Colored map) and I want those shapes formed by these borders to become individual objects in Unity. Is it even possible and if it is, how? Long version I want to make a Grand Strategy type game with provinces and countries. However, I'm not really an experienced graphics nor Unity programmer. I already have a map drawn with the desired black borders with each province being defined by these very borders and each has an unique color (sort of an identifier). Having just this seems plain and complicated to use so I'd like for each province to emit a color corresponding with a selected map type (diplomacy, terrain, domains, etc.). Obviously, this would be hard to do with just a single plain texture therefore I need to make objects and this is where my inexperience blocks me from continuing. Is there anything I can do (in Unity and or Photoshop) that could make the provinces be objects without manually isolating, importing and matching (as a puzzle) each single one? I've already looked at countless questions and answers but still none fit my problem. I'm at my wits' end with this to the point where I'm actually thinking about scrapping the project.


Making the camera look at the player while keeping another object in view I'm working on a sorta football game where I need my player to always be at the center of the camera view while keeping the ball into view, without any vertical movement. The idea would be for the camera to act like the picture below. What I came up with was the following code that I'm using in a LateUpdate. I'm computing a directional vector between the player and the ball and placing my camera behind the player using that data, and then I look at my player. Vector3 ballPosition ballTransform.position Vector3 playerPosition playerTransform.position ballPosition.y 0.0f playerPosition.y 0.0f Vector3 directionVector (ballPosition playerPosition).normalized directionVector.y 0.0f Vector3 newPosition playerTransform.position directionVector 12.0f newPosition.y 9.0f transform.position newPosition transform.LookAt(playerTransform.position) The code itself is working, but the camera movement is a bit nauseous, and when I'm trying to smooth it I end up with the ball leaving the camera field most of the time. Plus when I get too close from the ball I end up with some really quick camera movements which makes the whole thing kinda hard to follow. I tried to use a totally different technique by working with a Cinemachine Camera, but there doesn't seem to be an easy way to achieve such a view. Does anyone have an idea of how to achieve such a thing?


3D Collisions Walking below a slope pushes me through the floor Here's a really short video (less than 30s) of this issue https www.youtube.com watch?v JrKbpTY8cMU When I move the player towards a slope (the player is below it), it pushes the player inside the floor Collider instead of blocking it. I've searched the Internet for a while but haven't found anything about it Do you have something in mind ?Thanks for your time Info I move the player using rigidbody.MovePosition() The collision of the player is a Capsule.


EnemyAI rotating on Y axis in opposite direction After a battle flag has gone off and the player has entered an enemy's battle zone I want to keep track of the player when it moves and make sure the enemy's Z axis is always pointing towards the player. Upon the player entering the battle zone, the enemy automatically marks the player as its target However there is a chance that the Z axis may not be pointing towards the enemy's target when the battle is first initiated. I decided to shoot a ray cast from the Z axis of the enemy when the battle flag goes off and rotate the enemy until the ray and the player intersect thus telling me that enemy's Z Axis is lined up correctly. the enemy always has a reference to its current target. My idea was that as once the enemy spots its target initially, it can save the position of the most recent spotting and then take the delta of the CurrentTargetPosition.x and the LastSpottingPosition.x If the delta is positive rotate right and if the delta is negative rotate left. THE ISSUE my math or logic must be flawed somewhere because although it works sometimes, other times the enemy will randomly rotate itself in the opposite direction and the ray cast will essentially take the long route to hit the player instead of the shortest route as intended. Also the Local Origin of the enemy and the player are at different height respectively but I dont think that should matter in my case Code Below. create ray from enemy position orgin and point it on the Z Axis Ray ray new Ray(CurrentEnemyTransform.position, CurrentEnemyTransform.forward) RaycastHit hit if (Physics.Raycast(ray, out hit, 50f)) Debug.DrawLine(ray.origin, hit.point) ray hits current enemy target if (hit.transform CurrentTargetTransform) check if enemy has seen its target before while in this battle or is it the first time if (enemy.hasTargetLastPosition) replace old last seen position with most recent spotting enemy.ReplaceTargetLastPosition(hit.transform.position) or add the first spotting of target while in this battle else enemy.AddTargetLastPosition(hit.transform.position) ray is not intersectiing with the enemy's current target so rotate to look for it if (hit.transform ! CurrentTargetTransform) check if enemy has seen its target once before in battle if (enemy.hasTargetLastPosition) since last spotting has my target moved more to the left or right? if (enemy.targetLastPosition.value.x gt CurrentTargetTransform.position.x) rotate right CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self) rotate left else CurrentEnemyTransform.Rotate(Vector3.up, 5f, Space.Self) never seen target yet during this battle so default rotation to right till you found it else CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self)


Unity Stuttering character rotation Am working on the controls and camera movement for my character. What I am trying to do is have the character head be able to rotate left and right and then when the head is rotated a certain amount, the whole character rotates around. I have kinda of done it, the head can move smoothly, but it stutters when it starts rotating everything. Hopefully it is visible in this GIF. You may be able to see that the head does rotate smoothly, but when the body starts rotating, it stutters. Here is the code that is in LateUpdate that handles all the rotations. this.current rotation Quaternion.Lerp(this.current rotation, Quaternion.Euler(new Vector3(this.pitch, this.yaw, 0)), this.mouse sensitivity Time.deltaTime) this.cam.transform.rotation this.current rotation this.head.transform.rotation this.current rotation if(this.head.transform.localRotation.y gt 0.3 this.head.transform.localRotation.y lt 0.3) Quaternion from Quaternion.Euler(0, this.player.transform.eulerAngles.y, 0) Quaternion to Quaternion.Euler(0, this.current rotation.eulerAngles.y, 0) Quaternion q Quaternion.Lerp(from, to, this.mouse sensitivity Time.deltaTime) this.player.transform.rotation q


Unity UI making it responsive I am attempting to create a simple Jeopardy game using the UI features of Unity However as im trying to change the size of the screen it does not seem that my UI is responsive Here is it in 16 9 Here it is in 600x900 My Question is. is there a way to make it responsive? Is it even nessary to do so in unity or am i thinking way to much web based? ) Hope someone is able to help me and guide me abit


Runtime Issues on 144Hz Monitors I've recently finished my first ever Unity game. The game runs okay in my end but two of my friends had issues with the game. They both have 144hz monitors and the issues are solved when they lower the refresh rate to 60Hz. The problems are that any object who has a velocity depending on Time.deltatime, it gets halved. Is there a way to fix this on code so that nobody has to reduce their refresh rate when playing? Here is an example code of a snowball projectile's behaviour. The snowball usually stays alive for 3f seconds and that allows him to go across the whole screen but in 144hz runtime, the snowball goes really slow and it does not last enough to even get across the half of the screen. using System.Collections using System.Collections.Generic using UnityEngine public class Snowball MonoBehaviour SerializeField private float speed 20f SerializeField private Rigidbody2D rb SerializeField private GameObject impactEffect Start is called before the first frame update void Start() Destroy(gameObject, 3f) void Update() rb.velocity transform.right speed Time.deltaTime 75 void OnTriggerEnter2D(Collider2D hitInfo) if(hitInfo.CompareTag( quot Player quot ) hitInfo.CompareTag( quot Enemy quot )) Destroy(gameObject) Instantiate(impactEffect, transform.position, transform.rotation) Here is my game if anyone is interested in further examination itch.io link


Player object's model starts to shake after some time I created a default scene in a new project and imported a model from Unity's asset store and then get this strange behavior of the model starting to shake for no reason after some time after starting the game. I also have a script to read keyboard input and then apply forces to the model when the player presses some keys but the shaking of the model starts to happen even when the player does absolutely nothing. I'm really confused and have no idea where to look for a problem and google doesn't seem to have a solution to this either.


Unity UV map, tint change color of texture I have an array of vertices with texture coordinates for a UV map in Unity newUV.Add(new Vector2 (0, 1)) FACE 1 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) newUV.Add(new Vector2 (0, 1)) FACE 2 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) mesh.uv newUV.ToArray() It textures my mesh just fine. How could I go around tinting FACE 1 to a darker color? Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.


Level Selector with possible future levels? Unity I have a level select screen which is a simple grid layout of my levels. The level data comes from a scriptable object for each level. The problem I have is what is the best method for populating the grid of levels that use the scriptable object and is able to add more levels to the grid layout if let's say I add an asset bundle in the future? My thought was that I use a levelDB which holds a list of all of the scriptable objects. Then when an asset bundle is used then it adds the content to the levelDB. The UI would then just use this levelDB to populate the screen. NOTE I have very little to no knowledge of how asset bundles work and what you can, and cannot do with them.


How to Cease the Ragdoll Wiggle Dance When I instantiate a ragdoll object, it collapses nicely, but the movement never stops. It wiggles continuously. I'm using CharacterJoint components. None of the colliders (box and capsule) intersect. They are all spaced by at least a small amount. I tried playing with angular drag of the colliders, but that seems not to work. There do not seem to be any values in the CharacterJoint that affect this. But I'm probably wrong. How can I get the physics to stop quot wiggling quot after a certain threshold?


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


Unity3D Orbit around orbiting object (transform.RotateAround) The best way to explain this is I'm attempting to make a small model solar system (not to scale or anything complicated, just simple rotation as a learning exercise). There's a sun, a planet, and that planet's moon. The planet orbits like normal, however the moon orbiting around the planet shoots off and makes an extremely large and far away orbit. My code is as follows (where "target" is the object being orbited around, and "transform" is the orbiting object itself. Both are "Transform" objects.) public class RotateAndOrbit MonoBehaviour public Transform target public float RotationSpeed 100f public float OrbitDegrees 1f void Update () transform.Rotate(Vector3.up, RotationSpeed Time.deltaTime) transform.RotateAround(target.position, Vector3.up, OrbitDegrees) I'm not sure how to compensate for this or even what my mistake is called, but any help would be appreciated.


Customizing Unity WebGL index.html Hey everyone just some css and styling tips needed! i want to use a game as a 404 page. so i would need on top to be either text or a contact form then some spacing and then the actual game window. iframes dont work that good on mobile devices and by doing a simple div in unity index although on mobile it works rather crude but nice, on desktop the text is going behind the unity game window. any tips please? Note that im adding the style in the index.html and not using the separate css file in the template folder. So to sum up how can i make another div centered in the page and well responsive for mobile above the game container and add a margin on the bottom of that div! Thank you!!


How to keep two objects in the same zone when they collide? I made a zone out of a cylinder with zero height. When one sphere moves to that zone it is fine but if another one moves to the same zone it only shows one sphere. I tried to add a rigid body for each sphere but they collide inside the cylinder and both fly. I want both of them to collide but stay inside the cylinder zone with a distance between them like 2 units.


Add points to a prefab in Unity I have a prefab that looks like this I have created a couple of 'points' in the Hierarchy using 'Create Element' and I would like to attach them to the prefab, however drag and drop over doesn't work. Why is that?


Can running unity of a system with nvidia graphics card speed up the simulation? I have a nvidia GTX 1080 graphics card in my computer, I don't know if unity by default makes use of GPU. Does having a GPU helps to speed up unity simulations.


Bad quality of the sprite in Unity I need to import a few sprites (background platform and sky) into my game scene but it seems that their quality after importing into Unity is too bad (they are blurred). The original resolution of this two images is big enough (2048 X 400 for background) and they are looking very nice in standard Windows image viewer. Here are the settings for these two textures maxSize 2048 Format truecolor TextureType Sprite(2d) nGUI FilterMode point I am using Unity2D 4.5 Target resolution of my project is 1280 800. Can anyone help me to solve these problem? As you can see the grass on foreground looks very bloory (1 picture) Texture settings (2 picture) Original image (3 picture)


Translate position from 3D camera to 2D camera Currently I have 2 cameras, one for viewing the 3D objects (Perspective), and the other camera to view 2D objects (Orthographic). (Also, the view of the camera never intercepts each other.) I am trying to display a 2D object based on the position of a 3D object, like so What I have is the respective 2D and 3D Camera, as well as the Vector3 position of the 3D GameObject. What I have tried public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) var tempPos camera3D.WorldToViewportPoint(position3D) return camera2D.ViewportToWorldPoint(tempPos) The only problem is that the returned position is not completely aligned with the 3D position. Which results in this kind of results Also, I have made sure that both the 3D and 2D object have their pivot point are set correctly in the center, but it still does not work as intended. (I am currently using Unity 2019.1.14f1)


How to stop the RotateAround function to rotate after Keypress in Unity I have a camera follow script and I am rotating the camera with Q and E key to right and left. The Camera is a child of a camHolder object. I came up with this code, which rotates around the player to the right and left, but it's shaking as it tries to keep rotating around the player. I didn't come up with a solution to stop the RotateAround function, instead I tried setting rotateSpeed to 0 after I let go of the key, but that didn't work either. public Transform player public float smoothSpeed 0.125f public float rotateSpeed private Vector3 velocity Vector3.zero SerializeField private Vector3 offset Space public Transform camHolder void LateUpdate () CameraFollowPlayer() void Update() RotateCamera() void CameraFollowPlayer() camHolder.position Vector3.SmoothDamp(transform.position, player.position offset, ref velocity, smoothSpeed Time.deltaTime) transform.LookAt(player.position) void RotateCamera() if(Input.GetKey (KeyCode.E)) rotateSpeed 20f if(rotateSpeed gt 20f) rotateSpeed 20f transform.RotateAround(player.position, transform.up, rotateSpeed Time.deltaTime) else rotateSpeed 0f if(Input.GetKey (KeyCode.Q)) rotateSpeed 20f if(rotateSpeed gt 20f) rotateSpeed 20f transform.RotateAround(player.position, transform.up, rotateSpeed Time.deltaTime) else rotateSpeed 0f


How to launch a prefab at the mouse position I want to use Instantiate(item, new Vector3(...), Quaternion.identity) to land an item at the position that was clicked. My game is using a third person view (example). This is the code that I think I should be using if(Input.GetKeyDown(KeyCode.Mouse0) amp amp cur items gt 0) Instantiate(item, object pos, Quaternion.identity) cur items mouse pos Input.mousePosition object pos Camera.main.WorldToScreenPoint(mouse pos) What am I doing wrong?


Collision prediction of 2 moving objects I have to 2 objects with Collider2D. Both objects are moving, in the very next frame they will either overlap each other or not. How to predict if they would collide on the next frame? I'm thinking of instantiating a temporary object then use collider.Overlap(). But maybe there are better ways to do this.


How do you partition a level and create screen transitions out of these partitions? The levels in Castlevania games, you walk forward and then come to a point on the level where the screen stops scrolling but is not a deadend and there's no door either. They just wanted to transition to the next room for some reason (like a hallway transitioning to another room). I want to create something like this in Unity, using 2.5d (3d characters constrained in 2d plane) question is, do I separate each transition to a scene? But that seems kinda wasteful (I don't know, maybe). Or just one scene and develop the level as a whole and do some camera programming for the transition making sure everything lines up?


Why does the script stop working after respawning? I have a flying enemy that follows the player public class MoveTowardsPlayer MonoBehaviour public float moveSpeed, sightDistance public Rigidbody2D theRB public Transform target private void Start() theRB GetComponent lt Rigidbody2D gt () private void Update() Vector3 targetDir target.position transform.position targetDir targetDir.normalized float dist Vector3.Distance(target.position, transform.position) if (dist lt sightDistance) theRB.velocity targetDir moveSpeed And here is what happens when the enemy dies, and then respawns public void Die() Instantiate(enemyDieEffect, transform.position, transform.rotation) gameObject.SetActive(false) public void Respawn() gameObject.transform.position initialPosition gameObject.SetActive(true) currentHealth maxHealth The enemy respawns if the player dies and goes back to the last checkpoint. Interestingly, if the player dies before reaching any checkpoint, the MoveTowardsPlayer scripts still works after respawning. It only stops working after any of the checkpoints are reached. For the sake of completeness, here is the Checkpoint script, which has absolutely nothing to do with the enemies public class Checkpoint MonoBehaviour private Animator animator public bool isReached Start is called before the first frame update void Start() isReached false animator GetComponent lt Animator gt () private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Player quot )) CheckpointController.instance.DeactivateCheckpoints() animator.SetBool( quot isActive quot , true) CheckpointController.instance.SetSpawnPoint(transform.position) public void ResetCheckpoint() animator.SetBool( quot isActive quot , false)


How to use a decal logo tatoo texture on a object or character? It appears I've misunderstood the purpose of Standard Shader's "Secondary Texture" options. If I wish to map temporary details to an object, what is the Unity appropriate way to do this? I am referring to effects like the following Tatoos Blood Spatters Logos Decals etc... I'm aware that I could have two materials, but this is render inefficient, and I avoid hackish workarounds when I can. Standard practice? EDIT Per the comment below, I will elaborate slightly In my specific case I'd like to have one of two scenerios 1 Areas where a logo can be inserted (player created), pre uv assigned. 2 Drag drop logo placement, similarly, but without constraints. This would mean of course passing UV boundaries.


VertexColor shader is not working correctly in built application I want to change the vertex colors of my mesh. The light sources must not affect the objects with this shader, its lighting must be determined only by its vertices colors, so I turned the Lighting Off. I use this simple shader Shader "VertexColored Simple" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Pass ColorMaterial AmbientAndDiffuse Lighting Off SetTexture MainTex Combine texture primary Fallback "VertexLit" And this script using UnityEngine using System.Collections public class BehaviourScript MonoBehaviour void Start() Color exclrs new Color 11 new Color32(25, 25, 25, 255), new Color32(50, 50, 50, 255), new Color32(75, 75, 75, 255), new Color32(150, 150, 150, 255), new Color32(200, 200, 200, 255), new Color32(255, 255, 255, 255), new Color32(200, 200, 200, 255), new Color32(150, 150, 150, 255), new Color32(75, 75, 75, 75), new Color32(50, 50, 50, 255), new Color32(25, 25, 25, 255), Mesh mesh GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 normals mesh.normals Color colors mesh.colors for(int i 0 i lt vertices.Length i ) for(int j 0 j lt 11 j , i ) colors i exclrs j i mesh.colors colors When the game is launched, in editor I can see this This is EXACTLY what I wanted to achieve! But in built for PC(x86) version I see this Why the results from the editor and from the built .exe differs? What should I do to see my effect in built version? Maybe I need to use an another shader?


Cube that turns every for example 5 seconds 90 degrees I want a cube to rotate 90 degrees every Second Counter should be setable Like in this video at 3.47 the spiky cube that turns 90 degrees https www.youtube.com watch?v bxWpsT4lKXU I have tried to do it but it will not turn 90 degrees smoothly or even 90 degrees, it just turns kind of 90 degrees but I need help I guess. Here is my script public class TurnCubeScript MonoBehaviour public Transform turnCube public float turnSpeed SETTING THE COUNTER FOR OBJECT TO TURN public float setCounter public float counter SETTING THE COUNTER TO SETCOUNTER AFTER COUNTER1 0 public float setCounter1 public float counter1 void Start () setCounter counter setCounter setCounter1 counter1 setCounter1 void Update () TurnTheCube() void TurnTheCube() counter 1 Time.deltaTime if (counter lt 1) SOME TRIES... turnCube.transform.eulerAngles new Vector3 (0, 0, 90 Time.deltaTime turnSpeed) turnCube.Rotate(0, 0, 90 Time.deltaTime turnSpeed) turnCube.rotation Quaternion.Euler(0, 0, rotation) counter1 1 Time.deltaTime GIVES THE CUBE SOME TIME TO TURN if(counter1 lt 1) counter setCounter counter1 setCounter1


How can I support many point light sources in a dynamically generated level in Unity? I'm currently working with a dungeon game which is similar to Dungeon Keeper by Mythic Entertainment. I'm using Unity and developing this game for Ipad 2 and above. Player can modify his dungeon, and I'd written a dungeon generator which creates it. In this case, I can't use lightmaps, because the dungeon has been created dynamically and player can tweak it. I also devised a way to combine separate game objects in a single mesh, so imagine that the entire dungeon (except special objects such as pillars, statues and mobs) is the single mesh. There's many point light sources (10 15 and above) on the stage, but Unity don't allow to use more than 8 light sources per object. So, if all dungeon cells are separated objects, I can use the diffuse or even vertex lit lighting, but if the entire dungeon is a single mesh, there's the hardware limit appears. Ways to solve this problem I'd divised Use separated geometry (tried) bad, because it harms berformance because there's many many many drawcalls (16 17 fps on Ipad 4). Use deffered shading (tried) bad, because it harms performance even more than separated geometry. Use a custom shader (haven't tried) I don't know how. Don't unite all cells in the single mesh but unite groups of cells to reduce the number of separated objects (haven't tried) Use the light manager (haven't tried) I don't know how. ??? How can I deal with it?


Can I run my own loading script during the Unity splash screen? Can I load data in the background while the Unity splash screen is up? If so, how? I am trying to run code during the splash screen, not just load assets. I have not been able to find any information on this in Google or the Unity Documentation.


Separating scene generation and scene starting in Unity? I'm working on a game, where the map is generated, and The map is generated in an Awake(), so when an object's Start() is called, the map should be fully initialized. But the scene's physics world won't be updated till the next FixedUpdate. So when Start() is called, there is a high chance, that physics operations are done in an incorrect world (like raycasting) I tried using Physics.SyncTransforms, but it didn't solve the issue for some reason. (Why?) My next approach was to start the objects with a delay. Precisely after a FixedUpdate. So I started a Coroutine in the Start() method, which waits for a FixedUpdate, then starts the object. But this caused that for example ObjectA's Update() is called before ObjectB's Start coroutine finishes. How could I achieve that scenes won't be started until the scene is fully initialized? Is there a way to tell Unity to call every Start() i.e. 1 frame later? Or how else could I fix this? What is the best solution?


A Pathfinding issues, player node is always off so I am using Sebastian Lague's second video on A pathfinding (https www.youtube.com watch?v nhiFx28e7JY amp list PLFt AvWsXl0cq5Umv3pMC9SPnKjfp9eGW amp index 2), and since he is using a 3d model, and I am using a 2d model, I need to convert some of the values to 2d. It is working fine, but the problem I ran into is that the node that detects the player is always off. Like in here, the cyan node is the node where my player is supposed to be, and the my cursor is where my player actually is. You can see that it is completely off. I am pretty sure this is because some error is produced while I tried to turn 3d into 2d, but I don't know how. Here is my grid script using System.Collections using System.Collections.Generic using UnityEngine public class Grid MonoBehaviour public Transform player public LayerMask unwalkableMask public Vector2 gridWorldSize public float nodeRadius Node , grid float nodeDiameter int gridSizeX, gridSizeY void Start() nodeDiameter nodeRadius 2 gridSizeX Mathf.RoundToInt(gridWorldSize.x nodeDiameter) gridSizeY Mathf.RoundToInt(gridWorldSize.y nodeDiameter) CreateGrid() void CreateGrid() grid new Node gridSizeX,gridSizeY Vector3 worldBottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.up gridWorldSize.y 2 for (int x 0 x lt gridSizeX x ) for (int y 0 y lt gridSizeY y ) Vector3 worldPoint worldBottomLeft Vector3.right (x nodeDiameter nodeRadius) Vector3.up (y nodeDiameter nodeRadius) bool walkable !(Physics2D.OverlapCircle(worldPoint,nodeRadius,unwalkableMask)) grid x,y new Node(walkable,worldPoint) public Node NodeFromWorldPoint(Vector3 worldPosition) float percentX (worldPosition.x gridWorldSize.x 2) gridWorldSize.x float percentY (worldPosition.y gridWorldSize.y 2) gridWorldSize.y percentX Mathf.Clamp01(percentX) percentY Mathf.Clamp01(percentY) int x Mathf.RoundToInt((gridSizeX 1) percentX) int y Mathf.RoundToInt((gridSizeY 1) percentY) return grid x,y void OnDrawGizmos() Gizmos.DrawWireCube(transform.position, new Vector3(gridWorldSize.x, gridWorldSize.y, 1)) if (grid ! null) Node playerNode NodeFromWorldPoint(player.position) foreach (Node n in grid) Gizmos.color (n.walkable)?Color.white Color.red if (playerNode n) Gizmos.color Color.cyan Gizmos.DrawCube(n.worldPosition, Vector3.one (nodeDiameter .1f)) And here is my node script using System.Collections using System.Collections.Generic using UnityEngine public class Node public bool walkable public Vector3 worldPosition public Node(bool walkable, Vector3 worldPos) walkable walkable worldPosition worldPos


How to disable animation root motion I downloaded some animations with root motion from Mixamo and the corresponding character model. After created an animator with those animations and added it to the character game object, the root motion was causing the transform to move around, which was not supposed to happen. I tried to uncheck "Apply Root Motion", and set "Motion Root Motion Node" to "None", but neither of them worked. The only thing that worked is checking "Loop Time Loop Pose", but it doesn't make much sense to mess with root motion, someone even proposed it shouldn't disable root motion. So, how to disable animation root motion? Also I'm confused, is root motion optional? Must I get animations without root motion if it's not needed?


How can I separate gameview from UI most efficiently in Unity? Let me provide an image to illustrate what I mean. It is from a game called Runescape.


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


Why am I unable to edit the Input Field object's script? When attempting to edit an Input Field object's script like so I get the following error Unable to open C Program Files Unity Editor Data UnityExtensions Unity GUISystem UnityEngine.UI.dll Check external application preferences. Why is Unity attempting to open a .dll, here?


Upper Lower angular limits on Y and Z axes My Task I'm trying to replicate this project. I'm using unity as my physics engine. Currently I'm still learning how to work with the different joints unity has to offer. The type of movement I'm looking for is where a body is connected to only one other body and its relative movement can be limited based on angles on different axes. My Problem I'm using Configurable joints for my movement restrictions. The Low Angular X Limit and High Angular X Limit does exactly what I'm looking for since it can have a different uppper and lower rotation limit. Looking at the documentation, it seems that this can only be done on the X axis. The Y and Z axes only have a Angular Y Limit or Angular Z Limit which set the upper as the opposite of the lower limit. My Question Is it possible for the Y and Z axes to have the same lower upper limit system that the X axis has? Is the use of configurable joint good for this task? Thanks in advance )


Tools or techniques for UV unwrapping texturing terrain with features such as roads? I'm trying to create a map similar to Outset island in Loz Wind Waker. Here is an example of what I'm trying to create As you can see, the roads more or less have dedicated tris. However, when I look at the UV data, it looks like a complete mess For reference, this is the texture without any overlays I have no idea how to go about creating a similar effect in my own game are there any tools I can use? What is this technique called?


Gravity well shader for Unity2D I'm trying to find or create a gravity well distortion shader for Unity. I've been looking around and all I can find are "lenses" which bend space around a black hole. I'd rather have a distortion that "pulls" or "bends" the image behind into a small hole. Essentially, what this would look like if viewed from above (ignoring the sphere) I can't seem to find any examples or a common terminology for it.


Trying to make a button in Unity which spawns a character each time it's clicked I have a simple 2D game, I want a UI button to respawn the character (if it's not already present). The first problem I encountered is that the button only works once. I can't go any further before I solve this, so for now it doesn't spawn anything, I just want it to print debug text every time it's clicked. It only does that once, unfortunately. How do I make it call the function each time I click it? using UnityEngine using System.Collections using UnityEngine.EventSystems public class Button Restart MonoBehaviour public Canvas Canvas void Awake() public void Restart() Debug.Log("Restart button was clicked") EventSystem.current.SetSelectedGameObject(null)


3D Menu Attached to an Object? So I'm gathering information for my project, and one of the things I want to achieve is to create a very sophisticated crafting system and weapon modification but I want the weapon customization to look in a specific manner. A very good reference would be Crysis weapon attachments system, where if you open it, your character tilts the weapon and there are few menus popping up, all attached to the weapon, so you can see the menus moving around as your weapon is moving (due to you breathing for example, or walking). Here is a quick image reference So 1st thing comes to my mind is, how in the name of god should I approach this? Pardon if this is quite easy thing to do, I'm just completely new to Unity. (I have solid C background so programming isn't the obstacle) Edit 1 To be precise, I'm wondering how to work out the positioning of the menus in relation to the weapon. So the menu is moving with the weapon and eventually even turn slightly to give that 3D'ish effect.


How do I program procedural generation with objects that must fit together in specific ways? I'm working on a game where I have to procedurally generate a large open room building. I'm using Unity, but I think this applies to any engine. The room is made up of different wall segments. What makes this difficult for me is the ends of the segments have to join with a similar end of another segment. There are 2 types of ends. Flat and angled. The purpose of the angled ends is to create an outside corner. Meaning for example a flat wall then turns into a hallway it would use angled ends to make the transition. The method I tried initially was to define each segment type and what the follow up modules could be. Meaning SegmentA can be followed by SegmentB, SegmentC, and SegmentD. Then I would randomly select which of those to add and place it, then move on and repeat. It works ok, but I feel like there is a better way to do it. It's pretty unwieldy and is kind of prone to bugs. I also run into issues trying to close the loop and return to the original segment.


How do I tell if an object is currently colliding with another object? I can't figure out how to tell if a GameObject is currently colliding with another in Unity. I've looked online and can't find any tutorials or answers that work. Also, what's the difference between a Collision and a Collider w.r.t. Unity? My dilemma I have a third person controller set up and want it to wall jump. I already have an isGrounded function, I just need to test if I'm hitting anything other than the floor. Otherwise I want it to wall jump backwards. I've already tried if (this.OnCollisionEnter) ... if (Collider.OnCollisionEnter) ... But it did not work. I now tried function OnCollisionStay() Debug.Log("Collision") I checked my logs, console and still can't find anything.


How to destroy a clone of an effect attached to an object? I want to use some particle effects into a bonus object that will be destroyed upon contact with the player object. This object as its name suggests will add a certain benefit for the player for a certain amount of time. I was following a tutorial on Youtube. The code from the Tutorial worked fine but there is one problem I was not able to solve the explosion will not be destroyed after the object is collided with player and after the script is triggered because it seems that it was cloned into the scene. The instantiation created a clone of the effect's prefab I referenced into the script. After looking into the internet, I tried to affect the instantiation of the effect into a variable called clone and then destroyed it after the bonus is over but the problem was still present. I researched and I really did not obtain any answer. bonus.cs using System.Collections using System.Collections.Generic using UnityEngine public class bonus MonoBehaviour public float multiplier 2.0f public GameObject pickup effect public float duration 10 private GameObject clone private void OnTriggerEnter(Collider other) if (other.CompareTag("Player")) StartCoroutine( pickup(other)) IEnumerator pickup(Collider player) Debug.Log("You picked a bonus!") spawn cool effect clone Instantiate(pickup effect, transform.position, transform.rotation) apply effect yo the player our.score value 10 player.transform.localScale multiplier GetComponent lt MeshRenderer gt ().enabled false GetComponent lt Collider gt ().enabled false wait x amount of seconds yield return new WaitForSeconds(duration) remove the effect from theplayer player.transform.localScale multiplier Destroy(gameObject) Destroy(clone,4f) I tried disabling the "loop" option in the effect's particle system options but it gave the same results. I disabled the "Play on Awake" option and the effect will not play at all. The script is added directly to the object that is a simple 3D cube with MeshCollider, Mesh Renderer and Box collider. The effect I used is a BigExplosionEffect taken from Unity Particle Pack 5.x from the Asset Store. I would like to know what is exactly wrong? Is it probably related to the effect itself rather than the script? Or is there a far better solution?


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


Understanding Physics Materials I have been reading the documentation about Physics materials, and it really seems very incomplete to me. When I try to work with it, I get so many questions... Maybe can someone help me wrap my head around how it works? Why is there a physics material field for the Rigidbody2D, but also another in the BoxCollider2D? Do they work differently, depending on which you put it? What happens if you put different materials, one on the RB and one in the collider with different settings? If a player is standing in a platform, and you want it to bounce, or slide... do you set that on the player? Or in the platform? Update As suggested in the comments, I did some experimenting and this is what I saw When I put contradicting materials in the RigidBody2D and the Collider2D, the one in the collider seems to take precedence. Not sure what is the purpose of the one in the Rigidbody. If both are the same, well, they just behave like one of them alone. The value isn't added


Mesh Path reduction to simulate traveled path to target I generate that kind of mesh during runtime to display the path to follow to a target (think at something like the path your GPS shows you when you are travelling) I need to reduce the displayed path going from one end to the other to simulate the travel the player did. What can I do to achieve such effect? I can think about vertex modifications at runtime directly from a Monobehaviour class, or a shader(?). Are there any other (smarter?) moves to do here? Is Vertex modification the wiser choice for that kind of case? Thanks.


Unity multiple servers for rooms I have an FPS game that I'd like to make multiplayer. It would need to support multiple matches at once with about 10 players in each. However I want physics to be server authoritative so that means running a Unity instance. How do I have multiple Unity processes running on a server, creating destroy them as needed, having players connect to the instance they need, and so on? How does this vary between uNet Sockets LLAPI Photon Bolt etc? There just seems to be an atrocious lack of information on Unity networking and when people ask online there's almost never any answer, or it's too vague to be useful.


Unity White outline around seams in my character, make it stop! so once upon a time I made a really cool character for my game project and he looked great. Then at some unspecific point in time, my character's UV seams got these awful white outlines around them I assumed the problem was that during some texture revision, I didn't paint past the island seams, so I compared the texture file with an image of the UV output, but in fact I did paint past the seams, so that isn't the problem. I have heard that this may have something to do with antialiasing, but I don't want to turn that off if I can fix the problem another way. Also, notice that the enemy character in the above gif does not suffer from the same problem. What could be causing this? How can I fix it?


Split a region into arrays based on point region I have an array of points forming a grid. I want to split this array into multiple arrays that each contain a region of point. Let's say each point as a value like on this image The points having the same value and being connected would go into the same array. If it was only an array of all the 8 or all the 7, it wou d be easy, but in thsi case I need the arrays to contain connected equal values. For example, the purple region of 1 would make an array, the 8 region on the left would make an array and the one on the right too, but a different one. I just don't know how to use a loop to navigate in the grid and affect each point to an array based on they relation with other points of the same value. As this is the objective, think of the values as biome that I want to assign to an array.


Make one object rotate to face another object in 2D In my 2D project, I have an object that is sometimes above or below another object. Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object. (Here, following Unity's default setup, the z axis is the axis pointing into the screen)


How to Fill the Gap Between Camera Clip Plane And Skybox? I'm talking about the brown greyish area i marked with blue. How can i fill it with something that does fit the environment? I'm looking for a solution like this plugin.


Unity Shadergraph to CPU code? I read that you in theory can get vertex offsets from GPU shader in CPU by transpiling the shader to CPU callable code or creating a compute shader that calls the shader code (are there more ways?). I am wondering how one should approach this if one wants to use a shader from shadergraph. Can I get the same noise textures on CPU as on the nodes in shadergraph (GPU) for example? They can be important in driving the result. I think it is possible to export as hlsl so maybe transpiling can be done automatically.


Projectile movement around spheres of varying gravity I found a game on the Internet called Sagittarius. This game is very fun, and I have a question how can I make the arrow move like it does in this game? I know each sphere has a different gravity, but when I try to use this formula, it's not working as I expect . Can any one help me resolve this problem? Thanks. public List lt PlanetABC gt p new List lt PlanetABC gt () new PlanetABC() x 0.91f, y 1.28f, gravity 5, r 5 , new PlanetABC() x 8.12f, y 1.3f, gravity 3, r 10 void Start () void Update () float gravityOnX 0 float gravityOnY 0 foreach (var planet in p) if (Vector2.Distance(g.transform.position, new Vector2(planet.x, planet.y)) gt planet.r) continue if (planet.x gt g.transform.position.x) gravityOnX planet.gravity else gravityOnX planet.gravity if (planet.y gt g.transform.position.y) gravityOnY planet.gravity else gravityOnY planet.gravity if (currentGravityX gt gravityOnX) currentGravityX Time.deltaTime else currentGravityX Time.deltaTime if (currentGravityY gt gravityOnY) currentGravityY Time.deltaTime else currentGravityY Time.deltaTime Debug.Log(currentGravityX " " currentGravityY) var DEG2RAD Mathf.PI 180 float vx1 Mathf.Cos(angle DEG2RAD) power float vy1 Mathf.Sin(angle DEG2RAD) power float y (0.5f currentGravityY time vy1) time float x (0.5f currentGravityX time vx1) time Vector3 pos g.transform.position pos.x x pos.y y g.transform.position Vector3.Lerp(g.transform.position, pos, Time.deltaTime) time Time.deltaTime Here is the game https gprosser.itch.io sagittarius


How to play and pause animation I want to make play and pause buttons to play and pause sound and also I want it to play and pause animation ,how should I do that? function public void TogglePlay() if (audio.isPlaying) audio.Pause() else audio.Play()


Camera rotation according to target direction I am facing issue when camera is following to my target and target rotates to 90 degree or 90 degree than camera is not rotating.i want smooth rotation according to target when target is change the direction of movement.please help me if you can..thanks in advance.


How to make (or where to get) a half sphere mesh that textures properly? I'm making a game in Unity that involves lots of spheres. Said spheres will have lighting applied to them, but will also be viewed from only one camera angle. Right now, the full spheres look something like this when textured, normal mapped, and lit This is correct. The spheres in my game will only be seen head on, thus I only need to render their top halves. However, if I use the same material on only half a sphere (with a lower resolution, mind you), I get something like this (It's not the exact same material, but it's close enough, and shows the same problem.) This is incorrect. The weird part is I only encounter this issue in compiled builds of the game in the editor, the hemisphere is textured exactly as I expect. At the request of a commentator, here is one of the textures I'm using I'm also using it as a normal map. My question is thus how can I make (or where can I find) a hemisphere that can be properly textured, and why does my current hemisphere mesh only render properly in the Unity editor?


Should I use Coroutines to change variables in inspector smoothly? I want to change the aperture of the depth of field in the camera smoothly by using Mathf.SmoothDamp and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions? Code using System.Collections using UnityEngine using UnityEngine.UI using UnityStandardAssets.ImageEffects public class GameStartController MonoBehaviour public Button startButton public GameObject cubeSpawner Use this for initialization private void Start() startButton startButton.GetComponent lt Button gt () public void StartGame() EnableCubeSpawner() SpawnStartingCubes() HideStartMenu() StartCoroutine("FocusCamera") PlayBackgroundMusic() Enables the cube spawner, so it can start spawning cubes private void EnableCubeSpawner() cubeSpawner.SetActive(true) private void SpawnStartingCubes() cubeSpawner.GetComponent lt CubeSpawner gt ().GenerateStartingCubes() private void PlayBackgroundMusic() var audio GameObject.FindWithTag("Audio").GetComponent lt AudioController gt () audio.PlayBackgroundMusic() private void HideStartMenu() startButton.transform.parent.GetComponent lt CanvasGroup gt ().interactable false startButton.transform.parent.GetComponent lt CanvasGroup gt ().alpha 0f private IEnumerator FocusCamera() var camera GameObject.FindWithTag("MainCamera").GetComponent lt Camera gt () var velocity 0f while (Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture) gt 0.001f) Debug.Log(Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture)) camera.GetComponent lt DepthOfField gt ().aperture Mathf.SmoothDamp(camera.GetComponent lt DepthOfField gt ().aperture, 0f, ref velocity, 0.3f) yield return null camera.GetComponent lt DepthOfField gt ().aperture 0f


Simple animation text color change I apologize in advanced if this is a trivial ask, but I am wondering if it is possible to use an animation to change the color of a Text element from teal white without any lerp, i.e the color instantly changes. My current animation is only the one frame at 0 00 where I do the switch, but you can still see that the color is lerping even though it is the first and only frame. Am I missing something simple or should I just script the change? Fixing the problem is easy (Trivial to script), but I am just curious if there is something in the animation I can change to not have the color lerp? I posted the question here as well, but I never have any luck posting on the Unity forums.


Basic rigidbody movement This is a noob question but, what is the rigidbody movement equivalent of transform.position transform.right speed Time.deltaTime


How do I create a toggle button in Unity Inspector? I want to create a tool similar to Unity's Terrain tool, which has some nice toggle buttons in the inspector How can I achieve similar design to this? I know how to create normal buttons and other UI components in the inspector, but I can not find enough information to make the buttons toggle. So far I have used normal toggles that produce a checkbox var tmp EditorGUILayout.Toggle( SetAmountFieldContent, setValue ) if ( tmp ! setValue ) setValue tmp if ( setValue ) smoothValue false tmp EditorGUILayout.Toggle( SmoothValueFieldContent, smoothValue ) if ( tmp ! smoothValue ) smoothValue tmp if ( smoothValue ) setValue false Setting the toggle GUIStyle to "Button" does not produce the wanted result. The text or image content goes on left of the button instead of inside. var tmp EditorGUILayout.Toggle( SetAmountFieldContent, setValue, "Button" ) Also none of the options found in GUISkin does not seem to help.


C Network flooding I just created a simple MMO in unity3d, then me and my friends test it via LAN and the result is very smooth. But when I hosted it in public (100ms ping) the server became unresponsive and causes random disconnection. Host Setup 1gbps 32gb ram 256 ssd off firewall Server Setup max of 100 players every 100ms update no other updates, just only X and Y location of player by index c sockets w async Server Flow when 100ms tick reaches, server sends position of player base on index in a loop. ex. if (gtick gt 0.1f) for (x lt maxPlayers x ) check ifs couples of ifs here... send sendToWorld(x ... player x .posX ... player x .posY) somewhere, gtick 0, then counts up again... then the result is delay, unresponsive, and random disconnection. maybe it flooding itself, I don't know. but when we test it locally (10 players), it is very smooth and no problem at all. My question is, How can I update all players every 0.1 without server flooding itself?


How to change the virtual joystick Input direction depending on camera rotation so the player moves to its current forward direction? I have a scene set up where the player moves and rotates with Virtual Joystick Input. I have button which rotates the camera to the back of my player at that point I want to change the joystick input direction so it moves my player to towards its current forward direction. The joystick Scripts 1) script to handle events public class joystickEvents extends EventSystems.EventTrigger var position Vector2 Vector2.zero public var joyStickHolder Transform private var pointerUp boolean false function Update() if(position! Vector3.zero amp amp pointerUp) position Vector3.Lerp(position,Vector3.zero,5 Time.deltaTime) public function OnDrag(data EventSystems.PointerEventData) position data.position joyStickHolder.position public function OnPointerUp(data EventSystems.PointerEventData) pointerUp true public function OnPointerDown(data EventSystems.PointerEventData) pointerUp false 2) script for joystick movement public class joystick extends MonoBehaviour var joystickEvents joystickEvents var joystickHolder RectTransform var dir Vector3 private var maxDist float private var direction Vector3 private var magnitude float function Start() maxDist joystickHolder.sizeDelta.x maxDist maxDist 2.5 function OnGUI () if(joystickEvents.position.magnitude gt (maxDist)) magnitude maxDist else magnitude joystickEvents.position.magnitude direction joystickEvents.position.normalized transform.localPosition direction magnitude dir direction (magnitude maxDist) The player controller script takes the variable dir to move around the world. I think this value must changed somehow to so that move the player moves towards its current forward based on joystick input when camera is rotated. Here some part of playerController responsible for player movement public class charcterController extends MonoBehaviour private var controller CharacterController private var moveDirection Vector3 Vector3.zero var speed float 6.0 var joystick joystick reference to the joystick script function Start() controller GetComponent. lt CharacterController gt () function Update() var joyInput Vector3 joystick.dir the dir in joystick script dir Vector3(joyInput.x,0,joyInput.y) if (controller.isGrounded) moveDirection dir moveDirection speed controller.Move(moveDirection Time.deltaTime) rotate() function rotate() if(dir! Vector3.zero) transform.rotation Quaternion.LookRotation(dir)


UDP client code throwing a very nonspecific exception so I'm writing a UDP server and client on a couple of the machines in my virtual reality environment to allow (in this case) data from the location in the environment to trigger some air nozzles. The air nozzles I can control from the computer I have them plugged into, but I need to be able to control them from my machine running Unity. As far as I know, my server is functioning correctly, but I wrote a secondary listener script just to test it on the same machine and the error I'm getting is Exception System.Net.Sockets.SocketException An invalid argument was supplied. not 100 what this means, as I'm fairly new to Unity and software coding. my Client code is as follows public class udplistener MonoBehaviour public IPEndPoint ipep public UdpClient udpListener public int port 13722 Thread udpThread private Process process Use this for initialization void Start () ipep new IPEndPoint (IPAddress.Any, port) udpListener new UdpClient() udpThread new Thread (new ThreadStart(startProcess)) udpThread.IsBackground true udpThread.Start () Update is called once per frame void Update () try while(true) byte recBytes udpListener.Receive (ref ipep) string data System.Text.Encoding.ASCII.GetString (recBytes) UnityEngine.Debug.Log ("Recieved data " data) catch (Exception e) UnityEngine.Debug.Log("Exception " e.ToString()) void startProcess() process new Process() process.StartInfo.UseShellExecute false process.StartInfo.RedirectStandardOutput true process.StartInfo.RedirectStandardError true process.StartInfo.RedirectStandardInput false process.StartInfo.CreateNoWindow false process.StartInfo.WorkingDirectory WorkingDirectory process.StartInfo.WorkingDirectory "" UnityEngine.Debug.Log("Starting client. Stand by...") process.St process.Start() UnityEngine.Debug.Log("Started client") Commented out for thread closing. Not used any more because of UDP client server while(true) ReadStdOut() if (programStopped) return I'm really confused, because I lifted this code out of another portion of our software to create a "backdoor" into the dSPACE (the physical controller portion) machine so I wouldn't have to change a lot of serial communication that is already in place. What is the Exception referencing and what do I need to change?


How to mouse click an object in scene view to select it from editor I have several game objects with colliders in my game. I have enabled Always Show Colliders to keep all of them visible in my scene view. Because the objects are a lot, selecting them from the hierarchy window is a bit cumbersome and really slowing down my workflow. How can I select an object by left mouse clicking on it in the scene view of an editor?


Blending Modes in LWRP Particles I created a particle effect using a material created from Particles Simple Lit shader with an image of white circle tinted red through Start Color setting. On the left I have Alpha Blending Mode and on the right Premultiply Blending Mode. Why do I get black lines on the left?


Creating charging particles using Shuriken I've been trying to create a charging effect using the Shuriken Particle system for the longest time, and I've had little to no luck with it. I've tried setting different curves for the Force over Time and Color over Time, but I always come up empty. However, I've seen examples all over the place for charging particles. The most recent example of charging particles I've seen is from the Space Cowboy game jam entry LOS CUERVOS. The game has a ship with a laser that requires the player to hold a button down before it fires. It looks like this when charging and firing. I'm specifically talking about the particles surrounding the ball of light that's slowly growing in size over time. I was wondering if anyone here knew what I may be doing wrong when going about setting up the particle system. Any suggestions relative to the question would be much appreciative.


Unity 3D Confine a gun rotation within certain degrees I am having troubles making my gun rotate up and down, and have limits, for example, I want the down limit to be 0 degrees, and the up limit to be 90 degrees. Currently I can't figure out how to define that, and when the gun gets to one of the extremes, it gets stuck there and doesn't want to go back. Whats wrong? Here's how I rotate the gun using an on screen joystick float lookAxisX CrossPlatformInputManager.GetAxisRaw("VerticalLook") if ((transform.localEulerAngles.x lt 360 amp amp transform.localEulerAngles.x gt 270) (transform.localEulerAngles.x gt 0) ) transform.localEulerAngles new Vector3( lookAxisX 2f, transform.localEulerAngles.y, transform.localEulerAngles.z) Debug.Log("transform " transform.localEulerAngles) Also right now, when the gun is at the default rotation (facing forward, its X angle is 0, and when it rotates up, it goes from 0 to 359,9, and then at 270 it gets stuck


How can I get separate caches for different coroutines? (Unity) I want to fade out an image, so I have a coroutine FadeOut(). However, I want to have a separate image each time I call FadeOut. If I try to do something like this IEnumerator FadeOut(GameObject image) SpriteRenderer render image.GetComponent lt SpriteRenderer gt () yield return null Ignoring all the color changing code which I took out, how do I make it so that I can save a separate cache for each image I add? I don't want to run GetComponent() each frame, because I'm running on mobile and because I want to think of a clever way to stash the renderer. For example, if I declare the renderer at the top like this private SpriteRenderer render and want to cache it on the first frame of the coroutine, there's the chance that calling FadeOut() on another object will change the renderer to a new object and the first FadeOut() will cancel. Can I make the method static? Will that cache a private version of renderer?


Score does not increment by 1 in Unity I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why. using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score


How to enable CrossPlatformInput in Unity? I'm new to Unity but not a complete programming novice. I'm trying to use the CrossPlatformInput component from the "Car" prefab from Standard Assets. I can't see it appear and when reading the notes file it says this Importing the CrossPlatformInput package adds a menu item to Unity, "CrossPlatformInput", which allows you to enable or disable the CrossPlatformInput in the editor. You must enable the CrossPlatformInput in order to see the control rigs in the editor, and to start using Unity Remote to control your game. So, What is "a menu item" and where do I find it in the Unity UI? How do I enable CrossPlatformInput? I have dragged the prefab called DualTouchControls into my scene but I can't see anything and I'm not sure how to link it to the actual car object.


Difference between Object.Destroy() and GameObject.Destroy() in Unity What is the difference between using Object.Destroy() and GameObject.Destroy() in Unity? I found the following info about that here and here, but it did not answer my question. So, could someone explain the matter foolproof, please?


how to modify multiples BoxCollider on a same game object? I have an game object with multiples BoxCollider attached to it, is there a way to get all the BoxCollider to an array so that I could modify their value individually ?


Wrong contineous rotation to car In my 2d game, I want to rotate car face based on collision detected. But at present after 3 to 4 collision its doing continuous rotation only rather than moving straight after collision. Here is my straight movement related code myRigidbody.MovePosition (transform.position transform.up Time.deltaTime GameManager.Instance.VehicleFreeMovingSpeed) For better collision purpose, I have used Rigidbody position change approach. Here is my collision time code public void OnCollisionEnter2D (Collision2D other) if (other.gameObject.CompareTag (GameConstants.TAG BOUNDARY)) ContactPoint2D contact contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (transform.up, contact.normal) direction reflectedVelocity if (direction ! Vector3.zero amp amp pathGenerator.positionList.Count lt 0) float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg Quaternion targetRot Quaternion.AngleAxis (angle 90f, Vector3.forward) transform.rotation Quaternion.Slerp (transform.rotation, targetRot, 0.1f) if (Quaternion.Angle (transform.rotation, targetRot) lt 5f) transform.rotation targetRot direction Vector3.zero Rotation get applied within other code so that car was changing its face correctly and that method not affecting here that I have checked by placing debug statement. Share you side thought for this.


How can I set the radius the object will rotate around the target? using System.Collections using System.Collections.Generic using UnityEngine public class TargetBehaviour MonoBehaviour Add this script to Cube(2) Header("Add your turret") public GameObject Turret to get the position in worldspace to which this gameObject will rotate around. Header("The axis by which it will rotate around") public Vector3 axis by which axis it will rotate. x,y or z. Header("Angle covered per update") public float angle or the speed of rotation. public float upperLimit, lowerLimit, delay upperLimit amp lowerLimit heighest amp lowest height private float height, prevHeight, time height height it is trying to reach(randomly generated) prevHeight stores last value of height delay in radomness Update is called once per frame void Update() Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update transform.RotateAround(Turret.transform.position, axis.normalized, angle) time Time.deltaTime Sets value of 'height' randomly within 'upperLimit' amp 'lowerLimit' after delay if (time gt delay) prevHeight height height Random.Range(lowerLimit, upperLimit) time 0 Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition) transform.position new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z) Now it's rotating in a constant radius. I set the variable axis to 0,1,0 But if I want the object to rotate around the turret very close to it or very far ? I want to add a radius variable so I can change and set the radius.


Unity UI subpixel rendering antialiasing with Image.fillAmount? I'm using DoTween to tween the fillAmount of a UI Image. When I check the value, it changes smoothly, and in the scene view it appears to transition smooth. However it appears jerky in the game view, and seems to step for each pixel, so it seems resolution dependent. Is there any way to have the UI render subpixels (?) or antialiased so it uses colors between green white to have it appear to move more smoothly? Thanks!


Unity How do I change the color of the "Screen" based on the Object's depth's (as a Screen Effect)? Yesterday I asked and solved my problem Unity How do I change the color of an object based on its depth? Today I tried to change the script(from yesterday) and apply it to the camera and it did not work. Every pixel which is printed on the Display has a depth (float), is that right? Based on that Depth I want every object to fade grey, relative to the screen distance to that "pixel". Is this possible? Or do I have to use that vertex fragment shader on every single Object and Plane and Sky and everything in the world?


Need help with my on collision restart program I tried using the program using UnityEngine private void OnTriggerEnter(Collider other) if (other.tag "setting object tag") Application.LoadLevel(Application.loadedLevel) But the OnTriggerEnter command came up with an error saying "a namespace cannot directly contain members such as fields or methods". And the Application.LoadLevel(Application.loadedLevel) program had an error saying "application.loadedLevel is obsolete, use sceneManager to determine what scenes have been loaded".


Unity3D animation trigger reset How can I reset conditions for animations using an animation controller? I have a door that will open when a boolean property in a script is set to true. This then calls setTrigger on the animator to play the open door condition and then reset the boolean property to false. After 5 seconds I then close the door. However when I change the boolean to true again to open the door, either the setTrigger isn't working again on the animator, or the trigger for the door close is conflicting. How would I resolve this? Is there a way in the animator to set a condition to false when a particular animation has finished? Initially I was using a boolean condition in the animator but ran into the same problem. I looked at the 2D sample project which used trigger instead and assumed this would only fire once. However I guess something else could be wrong. The code in my script is as follows (where anim is the animator component) void Update() if (open) OpenDoor() open false void OpenDoor() anim.SetTrigger ("OpenDoor") Invoke("CloseDoor",5) void CloseDoor() anim.SetTrigger ("CloseDoor") As I say the animation fires correctly the 1st time but not on subsequent times. I'm just trying this by changing the public "open" property in the inspector thanks


How can I detect a long press then activate an animation? How can I detect a long press on a touch screen then activate an animation? And when the finger is released, play another animation smoothly? Let's take for example the main character in Crossy Road when the user presses down, the chicken "squats" and when the user releases their finger, the chicken jumps. Same concept. C .


Preventing Unity from writing to the registry? I see that Unity automatically writes some info to registry when it launches the game. Several people have this problem too Preventing Unity from writing to the registry. How to disable writing to Windows registry? It seems several years have passed but I still can't find how to prevent Unity from writing to registry. I just want to make Unity save amp load settings from file in document folder.


How to render the sprites for a 2D soft body physics system This is not a question as to how to achieve soft body physics, but rather if I have a mass spring system how to modify a sprite with that information. I am using unity so I dont have access to vector based graphics.


How to use a .mtl file in Unity? I want to use a .mtl file to draw my objects in unity. Can I somehow convert a .mtl file into a normal Unity material? My .mtl file is like this newmtl phongE1SG illum 4 Kd 0.00 1.00 0.00 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 Ni 1.00 Ks 0.50 0.50 0.50 Is this the same as a Unity material which has the sliders "albedo", "metallic", "smoothness", etc? Or is there any shader to do it?


how to prevent call on OnValidate() when running game I need OnValidate() to be called only when I am designing my level (placing game objects at their respective positions and setting properties before running the project). But I don't want it to be called when I run the project. I can manually comment it out, but that will take a lot of time, since I have several OnValidate() calls. How can this be done, if it is possible?


RaycastHit2D.point is acting weird when used with circlecast2d When I make circleCast2d intersects with another circle collider, I get a RaycastHit2D.point that doesn't point at the tip of the collision as it states in the documentation. Instead it always points at the centre of the intersected junction or pointC as shown in the figure below. I checked this numerous times with different values to make sure the error was not from my end. Is this intended? If so is there another way where I can actually find the closest point from collider(B) to the centre of collider(A) which corresponds to point(D) in the figure? This is a picture of what looks like A circleCast B collided object C where RaycastHit2D.point is pointing at D where I'd like it to point.


Follow behaviour with transform.LookAt on Unity2d So i've been trying to make an enemy follow my player on Unity2d using transform.LookAt. While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas? follows player transform.position Vector2.MoveTowards(transform.position, target.position, speedEnemy Time.deltaTime) make enemy look towards player transform.LookAt(target)


Rotating an object towards a target on the Y axis I am attempting to rotate a 3D object on its Y axis towards a target it is looking at. I have always struggled with rotations so I would like to try to avoid using Unity's built in functions, i.e transform.LookAt() in order to get used to using rotations. Gotta master the basics first, right? Vector3 currentOrientation transform.rotation.eulerAngles Vector3 directionVector3 transform.position target.transform.position float angle Mathf.Atan2(directionVector3.z, directionVector3.x) Mathf.Rad2Deg currentOrientation.y angle transform.rotation Quaternion.Euler(currentOrientation) However when I do run this, the character is not looking in the correct direction at all! Here is a screen shot with the character's parameters The target object belongs in a hierarchy, where it's position in world space is (150,0,500) Does atan2 somehow behave differently in 3D space vs 2D space? I ask because I've made 2D games where I would just use atan2(y,x) for a character's rotation.


Can't correct perspective of Main Camera in Unity 3D without losing field of view I have been trying to create a space based rails shooter game following a particular online course and I find a tilt(roll) on my spaceship as I move it towards the left and right ends of the screen. https imgur.com Kkg8hp2 (A normal screenshot of my spaceship at default position) This is due to perspective of the camera as I have been told and apparently dragging the camera farther behind the spaceship and decreasing its field of view helps. https imgur.com 0oXJff7 (The tilted spaceship when it's at an end of the game window) But, doing that neutralizes the illusion of speed caused by a greater field of view. I have found a middle point between the two to balance both aspects of the game but I would like to know if there is any way to get higher field of view without making the ship look like it's tilted. Things I have considered doing Added a positionRollFactor which gives the ship some additional roll in the opposite direction of the tilt. (This still doesn't fix the perspective issue in which one half of the ship is more enlarged than the other). Tweaking the field of view by trading off a little of each feature.


Adding Openai's GPT3 to a Unity project? I have a text based project and it has a slot open for Openai's GPT3 model. My project has a terminal module where the user receives emails, I want to go a step further and allow the user to respond to such emails and get some unique response. Here is a rundown of how I want it to work User receives quot email quot , they respond to it, GPT3 steps in and feeds a response into a new quot email quot . So how would I approach this? I think this could be pretty interesting as GPT3 hasn't been implemented in any games yet. I am aware that some beefy hardware may be required but my development computer is quite beefy enough. P.S. Sorry if my title isn't specific enough, closest thing I could think of for this situation.


Should my terrain be one big mesh or several medium ones? While creating a subterranean level with probuilder (irregularly shaped rooms and corridors), I was wondering if I should merge all "terrain" meshes into one or keep them as separate meshes? What are the good practices ? I'm creating each room as I go and its not hard to create openings and align doors vertices (with progrids) but once I start moving them around (like with polybrush) I'm sure it will soon be a nightmare. I can see pros and cons for both. Separate meshes would be easier to edit, duplicate or replace, probably better performances but at the risk of overlaps or holes because it would get hard to keep connected cleanly. I guess with one mesh you take the risk of having it eat memory and computation time, or having it too big to edit easily. I settled on each mesh consisting of a room and all half corridors going out of it, to hide the stitching and keep it simple. Still I wonder if there's a consensus.


sample project that mix unityscript and c I like the simplicity of unityscript, at same time I also like the plenty of c library and open source projects. I prefer to put my model controller logic flow in unityscript using standard unity3d sdk and invoke c extension library. Is there any sample project demonstrate how to mix the two scripts in one project? Your comment welcome


RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.


How to custom UI Slider with Unity UGUI I want to use Unity UGUI to custom a slider and the final looking show be like this And the images I use are But I found it hard to accomplish The handle will be screeched and the fill will not be fully filled with the handle Can somebody tell me how I could accomplish this?


How can you make a jump to a point using the Character Controller? I found an example with which the CharacterController can jump, but it does not work to remake it so that it jumps to a certain point distance, and the jumpHeight itself was calculated for speed and gravity, I found this article on Wikipedia, but I don't even know why to begin. public class ExampleClass MonoBehaviour public float speed 6f public float jumpHeight 8f public float gravity 20f private Vector3 moveDirection Vector3.zero CharacterController controller void Start() controller GetComponent lt CharacterController gt () void Update() if (controller.isGrounded) moveDirection new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) moveDirection transform.TransformDirection(moveDirection) moveDirection speed if (Input.GetButton( quot Jump quot )) moveDirection.y jumpSpeed moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) Method for jump, calling from other script. void Jump(float pointX) I can't find examples for the Character Controller, although I did find one for the Rigidbody.


What's the "right way" to open a websocket connection inside WebGL? The official Unity documentation says that, to run websockets in the WebGL player, you should use this plugin on the Asset Store. Unfortunately, following that link leads to a notice that this asset has been deprecated and is no longer available, with no explanation as to why or what should be done to replace it. With that unavailable, how should I implement WebGL websockets in my game?


Can not access GUIText in instantiated prefab I have a prefab with the following component structure Block Quad RawImage GUIText When I instantiate it and try to access the GUIText, I get the output of 'null'. Here is the code, I am using to access the GUIText public GameObject Block GameObject obj Instantiate(Block, position, orientation) as GameObject GUIText myText obj.GetComponent lt GUIText gt () print(myText) How do I fix this?


Standard Asset package import in unity 2018.3 I am using iMac, I don't see any for import standard package in unity. My working project need to import standard packages. I use unity version unity 2018.3.0f2. Please guide me from where I get the unity standard asset package. Thanks.


How to stop a jump midair and remove y velocity in the process What I want to do is to cut a jump midair by turning off the y velocity when the player releases the jump button (like in Hollow Knight). I managed to do that with rb.velocity new Vector2(rb.velocity.x, 0f) My problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously. I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PlayerController MonoBehaviour public Animator animator private Rigidbody2D rb public float speed private float moveInput public float jumpForce private bool isGrounded public Transform feetPos public float checkRadius public LayerMask whatIsGround private float jumpTimeCounter public float jumpTime private bool isJumping private bool facingRight true public float jumpDownForceY 0 void Start() rb GetComponent lt Rigidbody2D gt () void Update() isGrounded Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround) if (Input.GetButtonDown( quot Jump quot ) amp amp rb.velocity.y 0) rb.AddForce(Vector2.up 700f) if (Mathf.Abs(moveInput) gt 0 amp amp rb.velocity.y 0) animator.SetBool( quot Running quot , true) else animator.SetBool( quot Running quot , false) if (rb.velocity.y 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , false) if (rb.velocity.y gt 0.2) animator.SetBool( quot Jumping quot , true) if (rb.velocity.y lt 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , true) if (isGrounded true amp amp Input.GetButtonDown( quot Jump quot )) isJumping true jumpTimeCounter jumpTime rb.velocity Vector2.up jumpForce if (Input.GetButton( quot Jump quot ) amp amp isJumping true) if (jumpTimeCounter gt 0) rb.velocity Vector2.up jumpForce jumpTimeCounter Time.deltaTime else isJumping false if (Input.GetButtonUp( quot Jump quot )) isJumping false rb.velocity new Vector2(rb.velocity.x, 0f) void FixedUpdate() moveInput Input.GetAxisRaw( quot Horizontal quot ) rb.velocity new Vector2(moveInput speed, rb.velocity.y) Flip(moveInput) private void Flip(float moveInput) if (moveInput gt 0 amp amp !facingRight moveInput lt 0 amp amp facingRight) facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale


How to use touch screen for movement instead of keyboard narrow keys I wrote this code and run the game on my desktop, now I need to build this game for android and I need to change to touch to move the player, what it should be changed in the following code and what is the necessary steps to build my desktop 2D game to be run on android device, the following is the player code pragma strict var speed int 5 function Start () function Update () if(Input.GetAxis("Horizontal") gt 0) if(collided with ! null) if(collided with.tag "Right") collided with null return transform.Translate(Vector3(Input.GetAxis("Horizontal") speed Time.deltaTime,0,0)) if(Input.GetAxis("Horizontal") lt 0) if(collided with ! null) if(collided with.tag "Left") collided with null return transform.Translate(Vector3(Input.GetAxis("Horizontal") speed Time.deltaTime,0,0))


Disable system sounds in Unity? I've got an editor script in Unity 5 that uses the cursor position in the scene view to change objects in the scene when you press the space key. This all works perfectly, except that Unity thinks that space isn't a valid key to press, so it makes the system "boop" sound to let you know that it's invalid or that nothing happened. So, focus is on scene view, I press space, my script triggers, and the mac system "boop" sound activates. It spams the sound if you hold it down. Is there a way to Disable the system boops in Unity or Add space to registered hotkeys stop unity from triggering the system sound for a specific key (just to be clear, the script works, I'm just wondering about disabling the sound)


How do I make my 3d cube move left and right with buttons in Unity with RigidBody.AddForce? How do I make my 3d cube move left and right with buttons in Unity with RigidBody.AddForce()? I can't figure out how to do this in Unity! I'm trying to make my game playable on Android but I can't get my cube to move with buttons!


How to give the effect on the obstacle? I want to the obstacle Scale In and Scale Out using Dotween PlugIn? means some effect?? See this link https www.youtube.com watch?v Tq4t0gx49g amp t 569s Image I want to give a effect on the obstacle? script Obstacle.cs void Update() goTopToDown() void goTopToDown() foreach (Transform item in GetComponentsInChildren lt Transform gt ()) if (item.tag "obstacleobject") some obtsacle slow item.localPosition Vector3.down speed Time.deltaTime move top to down object if (item.tag "movefastobject") some obstacle fast item.localPosition Vector3.down movefastobjectspeed Time.deltaTime move fast object