How is this rotation done? There is a video here that shows how the camera rotates around Leon. The camera rotates around Leon in a circle, this is not difficult, but I don't understand the timing logic. Once given a short push, the camera keeps rotating for a few more milliseconds. If the camera would only be rotated during the real mouse movement, the camera would not keep rotating a bit after there is no more mouse movement. However, in this video, the camera rotates a few more milliseconds even after the last mouse movement. How could this be accomplished? Specifically, I would like to ask if somebody can tell me if the developers add some extra movement in the direction of the mouse movement which they then "smooth out", or if they "smooth out" the end of the user's mouse movement. Thank you!


Unity Mechanim makes physics behave weirdly I'm developing a 2D Wrestling game in Unity 5 build 5.1.2f1. It's just the beginning so the character only has a number of animation states and a rigidbody2d. This is the state machine and these are the Animator and Rigidbody2D components Note that I'm using Root motion to animate "High Knee" state since I've animated the character jumping in the air(high knee) by animating character's transform. This is the simplest form of code to move the character void Start () rb GetComponent lt Rigidbody2D gt () anim GetComponent lt Animator gt () void Update () print (rb.velocity) if(Input.GetAxis("Horizontal") gt 0) rb.AddForce(new Vector2(0,50)) anim.SetBool("isWalking",true) else if(Input.GetAxis("Horizontal") lt 0) rb.AddForce(new Vector2(0, 50)) anim.SetBool("isWalking",true) else if(Input.GetAxis("Vertical") gt 0) rb.AddForce(new Vector2(50,0)) anim.SetBool("isWalking",true) else if(Input.GetAxis("Vertical") lt 0) rb.AddForce(new Vector2( 50,0)) anim.SetBool("isWalking",true) The Character starts moving in x direction with a constant speed as soon as i press the horizontal keys. But for the y axis, when i press up or down key, character starts at 0 and speeds up really really fast( like 50 milisecs) and then the speed keeps increasing and increasing until i release the key. It still keeps moving but the speed doesn't increase anymore. I'm not sure but i think the former behavior is weird and latter is fine (or vice versa). When i remove all the "anim.SetBool" lines in the above code, speed becomes constant for the y axis too, that is, it starts behaving exactly like the x axis. But when i disable the Animator component, x axis movement starts behaving like y axis, that is, speed starts at 0 and quickly increases and keeps increases as long as the key is held down. When i uncheck the "Apply Root Motion" check box, character doesn't move at all. I don't know what's happening. Any help would be appreciated.


How to make sure an object NEVER passes through an edge collider (2D)? In my top down perspective game, I have a ball that bounces off of walls. The ball should behave in a way where it will always bounce off in a 90 degree angle. The ball can only move up, down, left and right and the walls are slanted so that they should always (theoretically) bounce a ball up, down, left or right. On the ball object, I have a small circle collider 2D and a Rigidbody 2D attached, the walls have a single edge collider 2D attached. Approximately one time out of twelve times, the ball will simply pass through the edge collider, so it's not consistent. How can I make sure that the ball always registers the collision? Here's my setup The script I use to move the ball void Update () switch (direction) case 'u' transform.Translate(0f, ballSpeed Time.deltaTime, 0f) break case 'd' transform.Translate(0f, ballSpeed 1 Time.deltaTime, 0f) break case 'l' transform.Translate(ballSpeed 1 Time.deltaTime, 0f, 0f) break case 'r' transform.Translate(ballSpeed Time.deltaTime, 0f, 0f) break Additional info every wall is it's own object with it's own edge collider. the ball always hits the center of the wall because I center the ball object using the center of the wall it touches. Note I had issues with the ball passing through walls even before I implemented the centering.


Shooting weapons Unity I'm trying to create a falling word game like z type (code here). Once the game starts a few words are displayed on the screen. When the user types a letter and if that matches with the first letter of any of the words displayed, an "activeWord" tag is added to the word. I have also created a laser script that checks if the tag is active and when that happens, it shoots the laser. What's happening right now is that the laser is shot only once i.e when the first letter matches but doesn't shoot a laser when the remaining words are typed. Can someone please have a look at the code and tell me where I'm making a mistake. this is the word display script where the active word is assigned public void RemoveLetter() remove the first letter if its correct and so on for the remaining letters. change the color of the word to red and add the "activeddWord" tag. text.text text.text.Remove(0, 1) text.color Color.red text.gameObject.tag "activeWord" public void RemoveWord() Destroy(gameObject) removes the word from display here is the input manager script public class WordInput MonoBehaviour public WordManager wordManager void Update () foreach (char letter in Input.inputString) wordManager.TypeLetter(letter) EDIT This is the player script where the laser is instantiated public class Player MonoBehaviour public GameObject laserPrefab void Start () transform.position new Vector3(0.0f, 3.92f, 0) player position void Update () Instantiate(laserPrefab, transform.position, Quaternion.identity) This is the updated laser script public class Laser MonoBehaviour public float speed 10.0f private Vector3 laserTarget private void Start() GameObject activeWord GameObject.FindGameObjectWithTag("activeWord") if (activeWord ! null amp amp activeWord.GetComponent lt Text gt ().text.Length gt 0) laserTarget activeWord.transform.position find position of word transform.Translate(laserTarget speed Time.deltaTime) for (int i 0 i lt Input.inputString.Length i ) Debug.Log("Character from input string " Input.inputString i " n" "Character from word displayed " activeWord.GetComponent lt Text gt ().text 0 ) if (Input.inputString i activeWord.GetComponent lt Text gt ().text 0 ) laserTarget activeWord.transform.position find position of word transform.Translate(laserTarget speed Time.deltaTime) shoot the laser After I do this, there are two major errors that I get As soon as I hit play, the laser fires continuously without stopping. The laser still shoots only once after the word is typed...This is the message I get in the console (screenshot attached). There is a difference of one word between the input string and whats displayed on the screen...Can someone please tell me how to rectify these.....


How can I make an object move in a certain direction depending on its spawning point? I'm currently developing a 2D game and I couldn't find a way to figure this out. In the game, I have 4 different balls and 4 different spawning points. Every 2 seconds, a random ball spawns at a random spawning point. What I want to achieve is, as I tried to describe above, lets say a ball spawns on right side, I want it to move towards left, if it spawns upside, I want it to go downwards etc. Here is my spawner code using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public Transform spawnPoints public GameObject balls public float timer 2.0f void Update() timer Time.deltaTime SpawnBalls () void SpawnBalls() int spawnPoints num Random.Range (0, 4) int balls num Random.Range (0, 4) if (timer lt 0) Instantiate (balls balls num , spawnPoints spawnPoints num .position, spawnPoints spawnPoints num .rotation) timer 2.0f And here is my ball movement code using System.Collections using System.Collections.Generic using UnityEngine public class Balls MonoBehaviour public Game game public float speed 0.25f void Start () game FindObjectOfType lt Game gt () void Update () Some if statement transform.Translate (Vector3.left Time.deltaTime speed) else if transform.Translate (Vector3.up Time.deltaTime speed) else if transform.Translate (Vector3.right Time.deltaTime speed) else if transform.Translate (Vector3.down Time.deltaTime speed) I've tried giving spawnpoints tags and creating if statements with gameObject.tag and stuff but couldn't find a way to work it. How can I make it check which spawnpoint the ball spawned at so I can make it move accordingly? Thanks for help.


Need to save UI.Image to png I have ui.Image1 with Mask component and ui.Image2 that is placed inside ui.Image1, then I want to save the result to Texture2d to save the resulting image to png. Sprite sprite sourceImage.sprite Texture2D newText new Texture2D((int)sprite.rect.width,(int)sprite.rect.height) Color newColors sprite.texture.GetPixels((int)sprite.textureRect.x, (int)sprite.textureRect.y, (int)sprite.textureRect.width, (int)sprite.textureRect.height ) newText.SetPixels(newColors) newText.Apply() System.IO.File.WriteAllBytes( SavePath "photo.png", newText.EncodeToPNG()) but I have the error Texture 'mask' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings. If I change the texture type of 'mask' from Sprite to Advanced the mask stop work. Let me know what need to do.


How can I spawn an object where I clicked in a 3D space, but spawn it in a 2D location? I have a game where I have an object sat on a 3D plane and I want to click above it to drop an object. Wherever I click I want the object to drop where I clicked on the Z axis, but on a fixed position on the X and Y axis. Please see the below image I am using the following code to do that, which I have attached to my long cube (the platform). using System.Collections using System.Collections.Generic using UnityEngine public class clickBehaviour MonoBehaviour public GameObject GameCube Ray ray RaycastHit hit Update is called once per frame void Update() ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit)) if (Input.GetButtonDown("Fire1")) GameObject obj Instantiate(GameCube, new Vector3( 75, 9, hit.point.z), Quaternion.identity) as GameObject Debug.Log(hit.point) GameCube refers to the GameObject of the smaller cube on top of the platform. What seems to be happening, is that when the user clicks a block appears. If the mouse is low down the screen on click then it appears where it should be. If it is higher up the screen it appears off in one direction away from where it should be. I believe this is because Unity is picking up the click way in the background, but I'm dropping the new cube in the foreground. Because of this the Z coordinate is then quite a way off. The further in the background I click the further off it is. How can I have the cubes always appear in the correct position, above the platform? I'm guessing this is a common requirement, but struggling to work out how to do it, or what to Google to find out more info. Thanks


Saving settings when exiting the application I created a static class CustomPlayerPrefs, it has a WriteToDisk() method that writes the saves to disk. For saving I am using Application.quiting event RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen) static void Init() Application.quitting WriteToDisk But on android it never works. I know that applications are not closed but paused, but it doesn't even work when I restart the device or force the application to stop. How to fix this or how to make it better? Need IOS and Android support.


How to set the Y position of Camera to another object's y position, but only once, not continuously? Essentially, I want to set the camera's Y position to another GameObject's Y position, but I only want to do this one. If you do cam.transform.position new Vector3(0, thing.transform.position.y, 0), it will continuously update to that object's y. Even if I store the Y float in a variable and set the camera's y to that it still continuously updates. It is only supposed to happen once.


Cannot implicitly convert type 'T' to 'UnityEngine.Vector3' I'm trying to use C generics on a method in order to send a Vector3 (position) as a parameter. I can print the value correctly but can't store it on a local variable. I also can't access its x, y or z attributes separately. I'm implementing a state machine. My intention is to use generics for allowing sending different parameters to the different states. The value will be sent to an "Enter" method which will be called once on each state every time that state is set to active or current. So for example the player will be on the DefaultState something happens change state to HeroTeleportingState while sending it it's new position This is my Enter method on the HeroTeleportingState class void IState.Enter lt T gt (T newPosition) The following line prints the correct value Debug.Log("move this hero to " newPosition) The following lines don't work pos newPosition pos.x newPosition.x The method call is just something like currentlyRunningState.Enter(Vector3.one) pos newPosition gives me the following error on Visual studio (I'm paraphrasing cause my visual studio is in spanish) Cannot implicitly convert type 'T' to 'UnityEngine.Vector3' And pos.x newPosition.x gives me something like 'T' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type 'T' could be found EDIT IState interface public interface IState void Enter lt T gt (T value) void Execute() void Exit()


How can I control ads frequency? This question was already asked a while ago, and I wanted to check the present situation Can I control ads frequency from the dashboard? (e.g. frequency capping in Admob) Can I control ads frequency through Unity IAP API? If not, does that mean that I need to implement all that "frequency control" functionality manually?


unity How to change the default behaviour of the touchpad trackpad in laptop? I'm using unity on my laptop. Normally, i can customize my touchpad in most of 3d app but in unity i can't find a way to do it ? is it possible to customize it at user level without hard coding it ? I just want the touchpad to behave like most app 2 fingers pinch to zoom, 2 fingers drag to rotate view etc.


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


Why the main menu is not working on the second time when pressing on escape key to back to the main menu? I have two scenes. Main Menu and the main scene. The game start when only the main menu is loading. When I click on the New Game button it's loading the main scene and removing the main menu scene. If I click now on the Escape key it will remove the main scene and load back the main menu scene but this time I can't click on any of the buttons in the main menu. I'm not sure if this is the right way to switch between the scenes but it's not working good. On the Newgame button I created and attached a new script. And then in the OnClick event of the button I'm calling the method LoadByIndex using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class LoadSceneOnClick MonoBehaviour public void LoadByIndex(int sceneIndex) SceneManager.LoadScene(sceneIndex) On the main scene I added a empty gameobject and attached to it another script using System.Collections using System.Collections.Generic using UnityEngine public class BackToMainMenu MonoBehaviour public int sceneIndex Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Escape)) UnityEngine.SceneManagement.SceneManager.LoadScene(sceneIndex) When the game start in the main menu when clicking on New Game button it's loading index 1 the main scene and removing the main menu. When clicking on escape key it's loading index 0 and removing the main scene. But then the main menu is not working.


Which is the better way to distribute server workload for MMO server? I'm making a server for MMO in Unity, which implies that I'll have a big world, split into maps which will be on different servers (to distribute the workload), managed by one master server. Now I can't decide weather I should use one executable per map and have few executables run on each server or have few maps on one executable, which will have it's own server. Second solution also would allow me to redistribute the workload by moving maps from one server to other (which shouldn't take long to do since servers don't need to load models). Btw servers need to be made in Unity for the physics simulation and collisions... The networking part can easily be multithreaded simply by using many threads to process the requests and generate response. But since Unity is single threaded adding more maps would slow down the physics engine (plus the same thread has to apply all actions of the players to the game), so the first solution helps here by using multiple executables. (Edit Note physics engine will take considerable amount of CPU time, even while the scene is empty) Which solution should I chose? EDIT On the end I decided to use both few executables on each server, with each executable being able to run multiple maps and being able to dynamically create dungeons when needed.


Using this.GameObject I once read (I actually don't remember where, I'm looking for it) that using this.GameObject to call the script owner is a very bad practice. I believe it has to do with some sort of information hiding, but I couldn't figure out why. What are the disadvantages with this? Is there a best practice to achieve the result?


Randomly instantiate avoiding overlapping in Unity 5 I'm starting a 2D game where I want all the letters A Z displayed in a random position and, then, the player collects them all in the correct order. I need to randomly instantiate the letters without overlapping. I use C .


How to put labels at a specific point on any resolution I am working on a project in Unity 4.6.1 and I put the label at the top But when I put the Scene in full view this happened I made a Development Build and when I select my resolution (1366x768) the label goes behind the buttons. Is there any way to put the label at a specific point no matter what resolution?


Unity C order of execution for multiple start functions? I have a scene in my project where a lot objects need to access different objects to share data with. Some objects have functions that need to be executed only once during the void Start function. These call a predefined function in a different class. So now you know a bit what is happening I am experiencing an issue. During the Start function they call a method that only works when the Start function of that class has already been progressed. Example Class A has certain values to calculate and set. Once this has happened function A will work. Class B, C and D have a function B that is called at the last line of the Start function. Function B does some magic and then calls function A from Class A. The problem here is however that the void Start from class B, C and D executes before the Start from Class A. This results in not all values being set properly. I only discovered this through debugging and tracking timings of when each function was executed. Is it possible for Class A to make the void Start execute before the void Start from the other classes? For example is the order of execution based on alphabetical values or something awake (per class) start (class A) start (class B) update (per class)? So that start A would happen before start B with a simple change of class name? If I put this code in the awake call I will have the same issues since the awake in other classes might happen before or after the current awake will be executed. To clarify, they all happen at the same time, but line 12 gets executed before line 13. Which is fairly logical, but how do you know which Start gets executed before the other Start? Or am I simply completely wrong? I do realize that this might be a confusing read so please don't hesitate to ask questions so that I can explain my issue better.


Normal mapping for Android and iOS I'm making a mobile game for Android and iOS on Unity. At the moment I am researching and designing the technical aspects of the game. Since it is not plausible to use highly detailed models for mobile platforms, should normal mapped models be used instead? Thus I have couple of questions about normal mapping. Are normal mapped models much more costly to make, in other words, do they take a lot longer to create? And are they much more expensive to render? At least there are no additional draw calls, but of course the shader is more complex.


Unity Set LightProbes to "Off" on Static objects Since I use Light Probes for Indoor Scenes only I only need them to work on Dynamic Objects. Objects in Indoor Scenes are all Lightmap Static and baked, objects in outdoor scenes rely on real time lighting. Most objects are not within range but sometimes the Lightprobes from inside interfere with Static objects outside and add light to them that should not be. It's really time consuming to disable LightProbes in every individual Mesh Renderer I sort all Prefabs amp Game Objects by Static, LightmapStatic and Dynamic. Turning Lightmapping on and off can be easily done in the hiearchy but turning off LightProbes needs to be done in every individual Mesh Renderer. Is that so, or am I overlooking something? If not this is really something that should get fixed. My Version is 2017.3.1f1


How to achieve 2D ski movements similar to Alto Adventure? I'm trying to achieve 2d movement similar to Alto's Adventure with Unity 2D. When grounded I want the character to slide alone the terrain parallel to the slope, but I want to be able to freely rotate the character in mid air. In my current failed implementation I tried using a 2d collider attached to an gameobject with a movement custom script. I'm using vertical and horizotal raycast to detect the slopes, and the object rotates based on the angle of the slope. Long story short I've given up on this implementation for now. Do you guys have any suggestions or pointers on achieving this type of movement?


HDRP project error unity i just created a new HDRP project and my scene is blank. Pls Help!!! Unity view Error RenderTexture.Create failed format unsupported for random writes RGBA16 SFloat


Hierachy organisational methodology in Unity I'm just getting into Unity, so I do not know if my system of organisation will have any negative consequences. I intend to store my project files and assets under an assets directory, then into scripts and such, as is commonplace. For the hierarchy I intend to have a top level empty object titled something like "Hierarchy", under which all objects will be children. I am also thinking that I will further subdivide into logical and physical objects, putting objects that do not have components on them but have a physical space in the game (not including transforms) under the former, and anything with a physical presence under the latter (lights, player etc). The main reason is so that I know where to look, based on functionality. I can also use alt click to close all objects at once. I find this helpful for navigating the hierarchy. Is this a bad plan?


WebGL game won't go into fullscreen mode on iOS devices I have built my game and hosted it on itch.io. it works well on PC browsers and on the mobile Android browser. The problem appears when I try to launch it on an iOS phone the game won't go into full screen (it's supposed to go into it automatically). I added a button that's supposed to switch to full screen but it doesn't respond (the button does work on PC and Android though).


LOD culled gameobject still interacts with raycast The camera is sort of top down and the player can move objects around, rotate them, delete them etc. I use a raycast to check what was hit when the player clicks. But some objects are culled by the LOD group when far away, but the LOD group only disables the renderer, not the colliders, so it still interacts with the raycast. This means a player can move or delete an object that they can't even see. I've tried looping through all the renderers in the lod group and using renderer.isVisible but it doesn't solve the problem of collision and raycasts. I'd really rather not poll isCulled every frame in update either because there are thousands of gameobjects, that would be horrible for performance. LODGroup lodGroup GetComponent lt LODGroup gt () LOD LODs lodGroup.GetLODs() for (int i 0 i lt LODs.Length i ) LODRenderers LODs i .renderers bool isCulled true for (int i 0 i lt LODRenderers.Length i ) if (LODRenderers i .isVisible) isCulled false


Unity C Spell System I couldn't find any proper tutorials in the internet how to make one so I tried it myself. I've written a base "Skill" class with methods like Cast(), DealFlatDamage(), ShootProjectile() and they all work so far. But I also wanted to implement trigger methods for passive spells OnDeath(), OnKilled(), OnProjectileHit(). First Question Is this a wrong way to go? Because I couldn't find anything like this in the internet. Second Question The idea was to create new classes inheriting from this base class and the base class calling all the "On..." methods of each derived class. How can I do this? Would appreciate help!


I've completed my mobile game now what? After months of development, I've finally finished my mobile app, but I have no idea what to do next. I want to publish my app to the Google Play Store and the App Store, yet I don't know how. I've done tons of research and every single website shows different methods and requirements. I've seen that I'm supposed to have some kind of license, a specific certificate, and all these other connections that I'm really confused on how I'm supposed to get them, and where to even start. I've gotten as far as getting Apple Developer and Google Developer, but that's basically it. I just want a simple step to step guide. I've already looked on StackExchange for an answer, but all have slightly different questions, such as marketing the app and updating the app, but nothing on how to get it out there. I'm using Unity as an engine and X Code via my Mac to test my app on my iPhone. I appreciate any help in advance. Thank you!


Is it possible to push real world, real time data into Unity? I'm pretty new to this, and I'm having trouble figuring out where to even look. If there's relevant terminology that'll be google able, that would be a great help. Suppose I want to have a monitor in game that displays the output from a camera that's in the same room as the player. Are there libraries for grabbing and rendering that data?


Unity won't compile project successfully I am trying to build the project into a Web GL, but it throws 3 errors when it reaches the quot Building additional assets quot stage. Error 1 Building Failed to write file resources.assets UnityEditor.HostView OnGUI() Error 2 An asset is marked with HideFlags.DontSave but is included in the build Asset 'Library unity editor resources' (You are probably referencing internal Unity data in your build.) UnityEditor.HostView OnGUI() Error 3 Error building Player Couldn't build player because of unsupported data on target platform. Things to note I do not use NGUI or any other third party GUI solution, but Unity's new UI system I have tried versions 5.2.3 and higher and it still has returned me errors I have one DLL LitJson that is used to parse JSON files Project includes StreamingAssets and Resources folders Error occurs even if I try building on other platforms such as Windows. Same errors are returned I am using a custom font downloaded online Blacksmith's Character quot Challenger quot is also included I thought the project folder has been corrupt so I decided to migrate all assets to a clean project. No changes Any idea how do I fix these? Thanks in advance!


Reduce emission of sphere object with HDRP material I have a material which I have assigned to be used on a sphere game object which acts as stars. This is what the settings are set to And this is what the Game View looks like I have also tried setting emission intensity to 0 nits and exposure weight to the minimum (0), but some stars still are far too bright, below is a screenshot of what it looks like with the altered emission intensity and exposure weight The bigger stars are far too emissive. I am trying to give each star a little glow. How do I reduce the emission?


How to stop jumping again when 3D character is in air (double jump)? I'm working on simple rpg and having some trouble with player jumping. I'm trying to use unity's raycast to check colliders under the player before jumping again. The problem appears that no matter how many tweaks I make to the distance or the validation of the canJump function, the raycast the player seems to at max jump twice. At lower levels the player can even hover if timed correctly. Could someone overlook my code since it appears that I might have a noob glitch somewhere? using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour public float speed public float jumpForce public float turningSpeed private bool canJump void Start() void Update() RaycastHit hit if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.01f)) canJump true ProcessInput() void ProcessInput() if (Input.GetKey("right") Input.GetKey("d")) transform.position Vector3.right speed Time.deltaTime if (Input.GetKey("left") Input.GetKey("a")) transform.position Vector3.left speed Time.deltaTime if (Input.GetKey("up") Input.GetKey("w")) transform.position Vector3.forward speed Time.deltaTime if (Input.GetKey("down") Input.GetKey("s")) transform.position Vector3.back speed Time.deltaTime if (Input.GetKeyDown("space") amp amp canJump) canJump false GetComponent lt Rigidbody gt ().AddForce(0, jumpForce, 0)


Unity2D Vector3.Lerp smooth movement I have a script that randomly chooses a position to move a game object every 5 seconds, however instead of moving my object smoothly, my script make my object jumps, which is not desirable! How would I make my object move to position smoothly! Thank you! public float timer public float speed public int newtarget public float xPos public Vector3 desiredPos void Start() void Update () timer Time.deltaTime if (timer gt newtarget) newTarget () timer 0 void newTarget() xPos Random.Range( 4.5f, 4.5f) desiredPos new Vector3(xPos, transform.position.y, transform.position.z) transform.position Vector3.Lerp (transform.position, desiredPos, Time.deltaTime speed) if (Vector3.Distance(transform.position, desiredPos) lt 0.01f) xPos Random.Range( 4.5f, 4.5f) desiredPos new Vector3(xPos, transform.position.y, transform.position.z)


Any way to combine instantiated sprite renderers into one texture so I can apply into a plane at runtime? So I am procedurally generating a tile set in Unity by instantiating different tiles that only have a transform and sprite renderer components. I managed to pack the sprites using unity sprite packer assigning them a packing tag so that I reduce the draw calls drastically. But Im still having to deal with a great amount of game objects in the scene when the camera zooms out, increasing the batching and giving me problems when I try to apply light to them for example. So I am trying to find a way to combine all these sprite renderers into a texture.So I can then apply this to a plane and Ill only have to deal with one plane gameObject for the map. But I cant figure out how to do this. I cant really use the combine meshes way as they are sprites only, not meshes. I tried taking a screenshot at run time but It comes up a bit blurry. Any idea how can accomplish this? Thank you for your help.


Throwing away inner faces of cubes of a transparent voxel structure in Unity3D? I want to create a "Building site is (not) obstructed." indicator for my building system. How can I throw away those faces which would be hidden if the material would be opaque?


Unity Is there a way to edit a Skin file? My project has multiple skins and sometimes we have to deal with skins with many custom styles. Editing them in the editor is difficult, for instance, I cannot delete one style that is not the last one without deleting the ones after it. Would there be a way to edit a file that represents this skin? Could I edit a skin file if I use Text in the Asset Serialization Mode (Unity Pro)? If not, is there something in the Unity Store to help me better edit skins?


New Input System Differs Between Editor and Runtime? I'm sure the problem is me. Here is a simple look script (from a tutorial, actually). I'm getting inconsistent results between editor and runtime. I'm guessing its a framerate thing. Code using UnityEngine using Mirror using Cinemachine public class PlayerCameraController NetworkBehaviour Header( quot Camera quot ) SerializeField private Vector2 maxFollowOffset new Vector2( 1f, 6f) SerializeField private Vector2 cameraVelocity new Vector2(4f, 0.25f) SerializeField private Transform playerTransform null SerializeField private CinemachineVirtualCamera virtualCamera null private Controls controls private Controls Controls get if (controls ! null) return controls return controls new Controls() private CinemachineTransposer transposer public override void OnStartAuthority() transposer virtualCamera.GetCinemachineComponent lt CinemachineTransposer gt () virtualCamera.gameObject.SetActive(true) Controls.Player.Look.performed ctx gt Look(ctx.ReadValue lt Vector2 gt ()) enabled true ClientCallback private void OnEnable() gt Controls.Enable() ClientCallback private void OnDisable() gt Controls.Disable() private void Look(Vector2 lookAxis) float deltaTime Time.deltaTime float followOffset Mathf.Clamp( transposer.m FollowOffset.y (lookAxis.y cameraVelocity.y deltaTime), maxFollowOffset.x, maxFollowOffset.y) transposer.m FollowOffset.y followOffset playerTransform.Rotate(0f, lookAxis.x cameraVelocity.x deltaTime, 0f) The code seems right. Watching the values of Vector2 lookAxis reveals that the numbers are slightly different coming into the function based on environment. Is there something wrong with this code that would give different results between editor and runtime?


How should I load change activate scenes? Scenes are confusing the hell out of me and I'm pretty sure they should be simple to understand. When the game loads, only the current scene has a buildIndex ! 1. In order give it a 'real' build index I need to load it by path or name (because there's no build index). The scenes are ten game scenes, one title scene and one persistent scene (which has the player and the status bar with the score etc.). Should I load a scene every time I change scene and then load additive afterwards or should I be using Set Active Scene? All the scenes are ticked in the Build Settings. I'm looking at the index with this private void Start() var sceneName "Persistent" var sceneBeforeLoading SceneManager.GetSceneByName(sceneName) Debug.Log( "Scene sceneBeforeLoading.name , BI sceneBeforeLoading.buildIndex ") SceneManager.LoadScene(sceneName) var sceneAfterLoading SceneManager.GetSceneByName(sceneName) Debug.Log( "Scene sceneAfterLoading.name , BI sceneBeforeLoading.buildIndex ") Which outputs Scene , BI 1 UnityEngine.Debug Log(Object) Title Start() (at Assets Scripts Title.cs 10) Scene Persistent, BI 1 UnityEngine.Debug Log(Object) Title Start() (at Assets Scripts Title.cs 13)


Particle system appear inside UI? How to make the particle system appear inside the Canvas ? No need for unity store assets. I'm using Unity 5.5.0


Unity3d change texture on terrain at specific vector3 at runtime I need the terrain texture to change at certain positions depending on where trees etc. are randomly positioned at runtime. I'm struggling to find any solid information about how to take a particular vector3 and tell the terrain to paint a different texture of size x at that location. So far I have found a lot of information about how to change textures based on height map information. As my map is flat, that information doesn't seem very relevant. EDIT using the following code when each tree was randomly instantiated public void ChangeTextureAtTreeLocation(Vector3 treePosition) int mapX (int)(((treePosition.x terrainPos.x) terrainData.size.x) terrainData.alphamapWidth) int mapZ (int)(((treePosition.z terrainPos.z) terrainData.size.z) terrainData.alphamapHeight) float ,, splatmapData terrainData.GetAlphamaps(1, 1, 4, 4) terrainData.SetAlphamaps( mapX, mapZ, splatmapData) terrain.Flush() got me this result As you can tell, the results aren't great. There are two main deficiencies I don't know how to access the terrain texture array directly so I paint a portion of the map first (see the bottom left of the image), sample that portion, and then set that sample at the location of the trees. This is not ideal as I cannot change the shape, size, or opacity of the added terrain texture. There is also no blending between textures, which gives the texture a rabbit burrow look. you cannot see it in the image, but the textures do not appear under the trees but are directly north east of them. Not sure why that is. I'm assuming it has something to do with how textures are drawn relative to their origin.


How to drag an object with mouse with collision? I want to drag a GameObject with the mouse but I need collision. The basic mouse dragging code simply sets the position of the object to the hit.point with an offset from the difference at the start of the drag. As for collision, I've tried using kinematic rigidbodies and setting the position with rigidbody.MovePosition(uh) but that allows the object to rotate while pushing it up against a corner on one side. With rotation constraints enabled, it flickers a lot and still intersects a lot. I also tried playing with collision detection and interpolation. None of the settings improved it. I also tried Physics.ComputePenetration but that is extremely messy because some of the objects I'm dragging, have several colliders. The distance it calculates is per collider so it doesn't calculate the offset required to separate the entire object. I tried disabling all the colliders and then adding a single box collider sized to fit the bounds of the object. That had bad flickering problems. The last thing I tried was box casts on each side that would find the closest point and offset the mesh in that direction. But if I moved the mouse too fast it would go inside the other mesh and would no longer register any colliders intersecting the box casts. It also suffered from flickering problems. Ideally, I want to have fairly accurate detection. I don't want to approximate the other colliders (not the ones on the object I'm dragging). Assume the other colliders could be any type (box capsule sphere mesh). The image below shows the problem I'm having. The green dot shows approximately where the cursor was (also the hit.point from the raycast on the surface of the red cube). What I expect is that the couch should be offset so that it was close to the cursor but prioritizes not intersecting other meshes over sticking to the mouse.


Coloring a Voronoi Graph Intro I want to convert a Voronoi Graph made with this awesome library by jceipek on GitHub into something I can work on. So far so good, this user provides with a demo to start with and shows how to generate the VG. Question How do I convert the VG (made by edges and that dot in the middle) into something that I can work with? Such as, after you generate some noise and apply to it (height), you colour the polygons based on it. Thoughts Something comes to my mind about instantiating meshes and tiles based on the edges and the position of the dot as a start, but it won't work if I can't "detect" the polygon. Expected result Image from this blog about Voronoi Mapping link What I have It is drawn with Gizmos (for visual debugging in Unity) I want to know how to color my polygons as in the expected image above. So I thought about doing a mesh or individual tile (and color it based on height afterwards but that is sauce for another question if needed) Edit of my progress To further explain this question I provide the next image. The image shows that I could use that position data somehow and turn that random polygon shape into a "tile" that will have a colour (mesh?) and possible data in it (script). I hope this helps otherwise let me know in the comments.


Unity3D Resources load to materials, how to? I think is a simple question, but I don't know nothing about it I have an created material in my materials folder, I just want to apply it to the GameObject by script. I am trying this.GetComponent lt Renderer gt ().materials 0 Resources.Load("Test", typeof(Material)) as Material The material name is Test and it is in materials folder, but the return is always the default material applied to the GameObject, so I think Unity didn't found it.


Unity objects not rotating around pivot point Suddenly, for some reason, objects in the unity editor started rotating around their center of gravity (at least that's what I think is going on) instead of their pivot point. I tried placing the object inside an empty object which would serve as the new pivot point, like usual, but this did not change anything. Is this some setting or some updated feature? How can I stop it?


Unity strange clones behavior I am setting up a grid of tiles (2d sprites) in Unity with this code public class Grid MonoBehaviour public GameObject slot public int gridW 9 public int gridH 9 private GameObject , grid new GameObject 9, 9 void Awake() for(int y 0 y lt gridW y ) for(int x 0 x lt gridH x ) GameObject gridSlot (GameObject)Instantiate(slot, new Vector3(x, y, 0), Quaternion.identity) gridSlot.transform.parent transform grid x,y gridSlot I then would like to have printed on the console the x,y coordinates of an individual tile when clicked on it. This is the script attached to the tile prefab public class Tile MonoBehaviour void Start () void Update () if(Input.GetMouseButtonDown(0)) Debug.Log(transform.position.x " " transform.position.y) Yet when I click on a tile I get printed the coordinates for ALL of the tiles on the grid. Why is this happening? Is there something very basic I am missing...? Thanks!


What am I suppose to use instead of Unity Resources if I have to load and unload sprites at runtime? I recently read this guide posted in the Unity website about Resources. It is clear from the get go that it is discouraged to use Resources unless you are prototyping something. My game is like a 2D RPG, and it has over five thousand monster sprites (yes, a lot). As far as I'm concerned, it makes perfect sense to put all the sprites in the Resources folder, and just load the ones that I need (using their name) when a battle starts and then unload them. The Unity article makes one point that might support my approach Generally required throughout a project's lifetime Well, I'm not so sure about it in a single game session it's entirely possible that thousands of those sprites will not be used at all as the player simply doesn't encounter those monsters. The article goes on to talk about why is it discouraged to use Resources This operation is unskippable and occurs at application startup time while the initial non interactive splash screen is displayed. Initializing a Resources system containing 10,000 assets has been observed to consume multiple seconds on low end mobile devices, even though most of the Objects contained in Resources folders are rarely actually needed to load into an application's first scene. And it is indeed true my game does in fact take several seconds to load on some low end devices, especially Android ones. It is also true that none of those sprites of mine need to be loaded at startup. So I am willing to stop using Resources but I am at a loss now the article doesn't mention a reasonable alternative to this. Here are the (unreasonable) approaches that I have thought of Create a component with a collection of all the sprites, that way they are all loaded without using Resources. Yeah but I have five thousand sprites. This sounds extremely tedious. Same as the previous suggestion, but use Texture Packer or something similar to pack lots of sprites into different sheets this way I have to do less work. My sprites are large and packing them won't be a huge help I'd still end up with a thousand or so sheets. My point is, I just can't have 5000 sprites preloaded. I need to load them at runtime via Resources, but Unity clearly discourages it. Is there a solution to this?


How do I properly change the value of a prefab'd instance variable? I am currently following a tutorial on how to make a 2D platformer in Unity. The tutorial explains how to make an enemy wave spawner, but it doesn't explain how to make enemies stronger after I have completed a certain amount of waves. So, to explain I have an Enemy class, which has an EnemyStats class in it public class Enemy MonoBehaviour System.Serializable public class EnemyStats public int damage 20 public int maxHealth 100 public int CurrentHealth get return currentHealth set currentHealth Mathf.Clamp(value, 0, maxHealth) private int currentHealth public void Init() CurrentHealth maxHealth public EnemyStats stats new EnemyStats() private StatusIndicator statusIndicator void Awake() stats.Init() statusIndicator transform.Find("StatusIndicator").GetComponent lt StatusIndicator gt () if (statusIndicator ! null) statusIndicator.SetHealth(stats.CurrentHealth, stats.maxHealth) And in the WaveSpawner class I have the method to spawn the enemy private void SpawnEnemy(Enemy enemy) Transform sp spawnPoints UnityEngine.Random.Range(0, spawnPoints.Length) if (CurrentWave 5 0) enemy.stats.maxHealth 20 Instantiate(enemy.transform, sp.position, sp.rotation) In the WaveSpawner you can set a certain number of waves (let's say 5), and after you complete all of the waves I've set them to repeat. So after I beat the 5 waves, I want the 5 waves to repeat and the enemies to be stronger (for example to have their max hp increased by 20). I do that with the line enemy.stats.maxHealth 20 But the problem here is that after this line is executed and I Instantiate the enemy prefab, the prefab changes its value in the inspector. So let's say that the initial value of the prefab was 120, after I beat the 5 enemy waves, the value of the prefab is set to 140. Then, after I reset the game, the initial value of the prefab is 140 and the max health of the first enemies is 140 and not 120. I have tried to not change the maxHealth variable of the EnemyStats class, but instead to have another variable tempMaxHealth and do the changes on it. This doesn't resolve my problem, as other problems arise and I don't know what to do anymore. I hope that you have an answer for me, I would be grateful if that's the case.


What is a "Projectile"? I don't know what a Projectile os. I'm not sure whether a Projectile is a spawn point which spawn a number of object or a number of multiple objects. I'm referring to this website. How do I use Projectiles and what does it mean?


Irregular Shaped Colliders For Unity Is it possible to create an irregular shaped collider? If so, how? Would I need to create a couple objects and group them up into one Game Object?


Unity, manual culling Is there a way to for example in vertex shader cull current vertex? I have my own grass system and I would like to cull straws that are further away than some distance but I can't use camera culling because grass is drawn in chunks and it hides a whole chunk.


How to instantiate GameObject on client without network? When I NetworkServer.Spawn(ob) a gameobject and make it a child of a transform.parent after it spawns on both the server and client it usually lags, meaning it takes some secs to align with the transform.parent which is the player Example Instantiating a GameObject containing a ParticleSystem which gives the parent somewhat an effect, smoke or something in that direction, in the host client every object usually has a smooth movement where as in the connected client it goes very rough and slow, like every gameobject having a low fps except the main client player prefab So i was thinking spawning the same effect on both clients so it wouldn't have to sync from the server to the client which uses it instead it only would have to sync inside the clients game, it might not have the same particle movements but it wouldn't make a difference Here's the child's prefab network identity and transform


Tags changing automatically on iOS build! First let me tell you that game runs fine in the editor. I check for hitting an enemy via a tag comparison and as I said it works correctly in the editor but when I deploy to my iPad and attach remotely with with MonoDevelop, I can see that the same object I'm checking against in Editor and had "Enemy" tag now has another tag, "Door". Even before character doing anything, their tag is changed to "Door". It's actually in the main menu and before running much code so I'm fairy certain it's not my code. I'm sure there is nowhere in the code that I'm changing the tags. And my specs Unity is 5.6.1, Xcode is 8.3.3 and my iPad iOS is 10.3.2 and my macOS (OS X) is 10.12.5 (Tried with both Append and Replace builds) Thanks


C Events in Unity to separate GameObject features into Components Broadly speaking, this is a question about how to separate my game object's code into distinct feature components that can be added and removed as needed. More specifically, I am trying to achieve this using C events in Unity. But I am open to other solutions. Scenario We have enemies that have health. When their health reaches zero, they die. Some enemies (think asteroids) may spawn a number of child enemies (think smaller astroid pieces) when they die. Others however, just die. I want to have two scripts EnemyHealth Tracks the enemy's health and kills the enemy when its health reaches zero. EnemyChildrenSpawner Spawns child enemies after the enemy's death This way, all enemies will have the EnemyHealth script, and some enemies will have the EnemyChildrenSpawner script in addition. My idea is to have the EnemyHealth script raise an event when the enemy dies, and have EnemyChildrenSpawner subscribe to said event to spawn the children. What would be the best way of achieving this? Here's my attempt. It works. Just not sure if this is good practice, especially using the GetComponent in the second script? EnemyHealth.cs public class EnemyHealth MonoBehaviour The event to invoke when this enemy died public event EventHandler OnDied Gets called when this enemy's health reached zero private void Die() Invoke the died event OnDied?.Invoke(this, EventArgs.Empty) Destroy this enemy EnemyChildrenSpawner.cs public class EnemyChildrenSpawner MonoBehaviour private void OnEnable() GetComponent lt EnemyHealth gt ().OnDied SpawnChildren private void OnDisable() GetComponent lt EnemyHealth gt ().OnDied SpawnChildren private void SpawnChildren(object sender, EventArgs e) Spawn children


How to create axes for a console controller What should I change in the input manager to enable me to use a joystick? I have a usb cable to connect the joystick to the computer but how do I set up the controls?


2d ParticleSystem batching problem I have multiple ParticleSystems with TextureSheetAnimation pointing to the same texture, using different offsets rows to choose different textures. They seem to batch with each other, but they're also being split by Unity into multiple batches in a strange manner. Here's a Frame Debugger view These 4 Draw Dynamic are on the same atlas, using Mobile ParticlesAdditive shader. The reason of breaking batching is Objects have different batching keys. This is usually caused by using different vertex streams on ParticleSystems or by mixing Lines and Trails, or by mixing lit and unlit geometry. All of the ParticleSystems have a simple setup, some Color Over Lifetime, some Velocity Over Lifetime etc. The strange thing is that Unity breaks batching like it makes one batch, puts half of the stars and half of the smokes into that, and then, makes another batch from these two. So they do batch, and the don't o.O I couldn't find and help on the web about this issue. I'd be glad for help.


Unity PNG sequence animation changing position in animation We are making frame by frame animation and we have a canvas size for animation. Attack animation is changing position in canvas. In Unity after the attack animation is completed it teleports back to the initial position. I tried setting animation event and updating parent position but it does not work. It teleports to nonsense locations like player is looking at x but it teleports to x. Anybody have solution for this? Since it is not rigged, root motion is not working. I tried to put animation event at the last frame and put this script to the character controller which is a child object of empty parent object public void animationFinished() animation finished true void LateUpdate () if(animation finished ) transform.parent.position transform.position transform.localPosition Vector3.zero I have 25 PNG as frames of animations. From idle animation I go to attack animation. Idle is stable as a position, but attack animation is changing position in canvas for example animation canvas is 1920x1080 canvas size and animation starts from the left size to right size. I can't move the character with a script because it has its own timing that I can't set up with script. So I am trying to get the last frame position and pass it to idle animation at that position but instead of that without code it teleports back to the initial position after attack is completed. This is a similar topic, but the solution did not work.


What is the correct way to authenticate a player with password from Unity to a php api server? So, I have a game in Unity for mobiles that gives you the possibility to sign up with username, email and password to unlock extra features. The datas are sent, through a POST request, to a PHP MYSQL server that expose an API. I'm developing both so I have complete freedom on how to implement it. My question is what is the correct way to save auth data on player mobile device so it can automatically login on subsequent runs of the game how to safely send username and password to my server for the authentication I want to protect data from man in the middle attacks and I don't want to send clear password because users tends to always use the same email password combination. Thank you


Particle spawn on collision spawns too many particles So i have the following code private void OnCollisionEnter(Collision collision) foreach (ContactPoint contact in collision.contacts) if (contact.otherCollider.CompareTag("Ground")) Instantiate your particle system here. Instantiate(Effect, contact.point, Quaternion.identity) Now this works great however it spawns way too many particles (as the animation I am doing with the item hits the ground a lot). Is there a way to limit the particles in a sensible way?


Unity Deactivating Keyboard Input Interpolation I'm working on a game in Unity, and it is a little jarring to use with keyboard controls. I'm using the built in Input Manager, where I have a set of axes mapped to the left and right keys. When the player is using the keyboard instead of a joystick, I'd like it to simply be 1 when hitting left, 1 when hitting right, and 0 otherwise, but this isn't the case. I've found that for the first few frames of the button being held, Unity automatically builds up to the value for example, if I'm holding right, the value wouldn't go straight from 0 to 1, but rather from 0, to 0.25, to 0.5 and so on, continuously up to 1. Can I deactivate this? If so, how? Thanks in advance.


How to rotate just the object being touched in Unity? For my first steps in Unity I am just trying to rotate some squares when I touch them. using UnityEngine using System.Collections public class testskript2 MonoBehaviour Use this for initialization void Start () transform.Rotate(Vector3.forward 2 100) Update is called once per frame void Update () if (Input.touchCount 1) Ray r camera.ScreenPointToRay(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y)) RaycastHit hit0 if (Physics.Raycast(r, out hit0, 100f)) transform.Rotate(Vector3.forward Time.deltaTime 100) It isn't working this way. Any tips?


How to make a one way trigger? In my game, there is a cat that jumps on pillars. When it lands on a pillar, force is applied and it jumps. There are three animation states which are just single image. The states are idle,up and down. When cat lands on the pillar, Collision is triggered where i set animation state to idle. Then, force is added and animation state is changed to up. But problem is, this collision and add force happens so fast, the cat switches between down and up without showing idle. To overcome this, i added an empty child object to pillar. Then added Edge collider set as trigger. This child was placed slightly above the pillar. So when cat hit this, animation state would switch to idle. Then the cat would land on pillar and jump. This worked except, the trigger is two way. When cat jumps from pillar, it collides with this trigger and state is changed from up to idle. I tried to add platform effector with one way, but the effector cannot be used on a trigger. So, is there a way i can add a collider to the empty child which will let it go through aftyer setting state to idle?


Why would I receive a NullReferenceException when the object is clearly set, and still works? I am getting the exception "NullReferenceException Object reference not set to an instance of an object" while changing text of a user interface text field, even though the text changes successfully, as you can see in the image. It still gives me a null reference exception if it was not set, then how can it change the text? I don't know what is happening, here. I have re imported the project, but the problem stays. using UnityEngine using System.Collections using UnityEngine.UI public class Menu MonoBehaviour public Text headingaccuracy public Text magneticheading public Text rawvector public Text trueheading private void Start() headingaccuracy.text "Heading Accuracy "


UI looks different between editor and in game I am very confused about Unity's UI system. This is how my inventory menu looks in the Editor And this is the view in game Settings Can someone please explain why this happens?


How to make enemies randomly choose a path and then come back if wrong one? So I'm making a 2D Tower Defense game in Unity with C where the enemy has to go to the base, but can go to the wrong path randomly and then turns around when the road ends. How can I achieve this?


Shake a tree on chop I have a top down RTS type of game where the player (God mode style) can click a tree to chop it. I'd like to shake the tree where the base of the tree (where the position marker is) moves the least and the top the most to simulate like it's being hit by an axe so it shows visual feedback. Any ideas on how to accomplish this? Not really sure where to start. This would be in 3D.


Retrieve the original prefab from a game object How would one proceed to retrieve the original prefab used for instantiating an object? In the editor these two functions work Debug.Log(PrefabUtility.GetPrefabParent(gameObject)) Debug.Log(PrefabUtility.GetPrefabObject(gameObject)) But I need something that works in the release version. I have objects that can be transported between scenes ands I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated. ie Game designers create new prefabs. Game designers create objects from prefabs and place them in scenes (50 to 150 scenes). Game is played and objects are moved across scenes. Game is saved and infos about objects which have moved are saved in the save streams (files or network). This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field). Maybe there is a better way to achieve proper save games without having to access to the original prefab name. But currently we keep the saves segmented on a per level basis (easier and safer to save load to files and transfer the save games to from servers)


Unity3D Upload a image from PC memory to WebGL app I need user to upload his(her) avatar picture from PC to game How can I create a file dialog and upload a image to WebGL game?


How to make an expanding radial search in Unity? I am currently working on a City Builder Game and I often come across the problem of having to decide wich location to use. Examples The citizen has a job and needs a home. There are several buildings with open slots. The citizen is at a positon and is hungry. There are several restaurants on the map. How can I choose the right building to go to? I don't really wan't to check the distance for each, because there could potentially be hundreds of buildings and that decision problem occurs quite often. I also don't care for the optimal solution, any nearby result is fine. Currently all buildings register them self in a LinkedList. When searching for something I'd start at the beginning and the first occurrence that was 'good enough' would be returned. Citizen now drive across the map for something that was right next to them if the one far away was built earlier in the game. Any suggestions?


Why is Raycast hitting masked layer? Many questions have been posted on this topic but I'm facing a weird behavior which I could not find an explaination for. I perform a raycast giving it a LayerMask parameter which is defined as public variable and set in the inspector with thick on layer "Wall" and "Enemy". At first glance it appeared to work fine because raycast rightly stops on GameObjects with that layer. But then I saw that it stopped also on GameObjects with default layer, like if the LayerMask was ignored. Is there something I'm missing? According to this answer I set up everything correctly and I expected it to work fine. Looking at the inspector at Runtime I can clearly see that my mask is set only to "Wall" and "Enemy", and that the GameObject the collider is attached to has default layer set. I'm then stating that the mask the way I'm using it does not exclude other layers. The only way I found to have this working is by setting that GameObject layer to Ignore Raycast but in this case the LayerMask is not necessary. I'm calling the function this way RaycastHit2D inSight Physics2D.Raycast(start, end, lm) Maybe is there something different using Physics2D? I would really enjoy touse LayerMasks instead of giving specifically Ignore Raycast to whatever I want to ignore. Any clue?


How to use the latest MongoDB C driver with Unity? I recently updated my Unity 2018 to the 2020 version then I created a new project to connect my game to a MongoDB database. My main goal is to be able to store not only common data in my collection but also files and images by using GridFS. I use Visual Studio 2019 Community so for my project. I installed the MongoDB drivers directly from NuGet. In Visual Studio everything is OK, I added a using for all required libraries and I have no errors but when I switch to Unity 2020 it seems that I can't start my project because my MongoDB driver is not correctly loaded there. I found some tutorials like this one where they had the same problem and fixing it by adding the DLLs directly in the Unity folders. That works for me, but only with the DLLs shared in the tutorial (you can access the working DLLs in the video description). What is a bit disturbing is that the DLLs' versions seem to be outdated, since the connections process is a bit different from the one in the MongoDB documentation. I cloned the latest MongoDB C driver repository from GitHub and tried to reproduce the same process with the latest DLLs, but once again it only works in VS 2019 but not in Unity, even though I have added the DLLs in the Unity folder. Is there is some kind of compatibility problem between Unity and the latest MongoDB? How can I fix this to work with the latest version?


Damping the Camera "lookAt" rotation I have created a very short piece of code to make the camera look at a transform object. I locked the rotation of the x and z axis as it is only supposed to rotate on the y axis. I would like to add some damping to this and make it rotate slowly, thanks. Here is my Code public Camera Camera public void lookAt (Transform target) Camera.main.transform.LookAt (target)


Storing wins and losses locally in Unity I am writing here as I have made a game in Unity where I want to store how many wins losses a player has. The way I am thinking to do it is by putting 2 counters One for every time a player wins, and one for every time a player loses. What I do when a player wins or loses is that he can shoot something and restart the game I load scene 0 here. I know that the counters will reset once the player closes the application, but that doesn't matter. Anyway, is there a better way to do it? The other thing I am thinking about is storing how many times a player has played the game in total, and this has to be stores locally too and must not get reset when the player closes the application. How is this done?


How to directly set a value to an UI Image's alpha channel(not the percentage of rendering) When you write the code bellow, it renders a percentage of an image's predefined alpha value (which you define in unity's inspector for example if you define the alpha value of an image to 100, the code bellow actually makes it 25, when the scene is being rendered) image.GetComponent lt CanvasRenderer gt .SetAlpha(.25f) How can i rewrite the code above, to directly set an alpha value? Thanks.


How do I stop my skeleton from playing the walking animation? I'm trying to get a Skeleton Model to go from its walking animation to its idle animation using a bool that checks for input. Currently, in game, the skeleton doesn't leave its walking animation and stays in it even when not walking. Here is the code I'm using public class SkeletonMove MonoBehaviour private float velocity 5f public bool isWalking false Vector2 input void Update() GetInput() if (Mathf.Abs(input.x) lt 1 amp amp Mathf.Abs(input.y) lt 1) return Rotate() Move() void GetInput() input.x Input.GetAxisRaw( quot Horizontal quot ) input.y Input.GetAxisRaw( quot Vertical quot ) void Move() controller.Move(transform.forward velocity Time.deltaTime) anim.SetBool( quot Walking quot , isWalking) if (input.x ! 0 input.y ! 0) isWalking true if (input.x 0 amp amp input.y 0) isWalking false


Quaternion.LookRotation with Joystick I am having an issue i cannot seem to figure out within my code. What this code does at the moment is that it rotates the 3D Model around the z axis but i need it to rotate around the y axis. Any help would be greatly appreciated. void Update () Vector3 moveVector (Vector3.up joystick.Horizontal Vector3.left joystick.Vertical) if (joystick.Horizontal ! 0 joystick.Vertical ! 0) transform.rotation Quaternion.LookRotation(Vector3.forward, moveVector)


Unity augmented reality app doesn't work on android I am pretty new to unity and augmented reality applications. I use unity 2019.4.4f1 and my project is very simple as you can see in the screenshot below I am using Wikitude plugin for image tracking and the image i am using as the marker is the Jack of Clubs card as you can see in the assets. The project works fine when i press play and use my laptop's webcam , but when i build the project for android (unity 2019 automatically uses Gradle to build the project) and install the .apk file in my android phone, all i see on my phone screen when i open the application is As you can see the phone camera doesn't work and it gets stuck in this screen. How should i fix it? Does it have to do something with Gradle? I haven't tried using unity version 2018 to build it using the quot Internal quot build option. Anyways that's just my own thought and i might be wrong, but the final question remains which is how this problem can be fixed? By the way i don't build the .apk file directly from the unity engine. I use the export option in unity to get a gradle project folder then i use that in Android Studio to build the final .apk file. The reason that i don't use unity to build .apk is that it gives errors and doesn't work for me so this is the solution i found for it. Update I debugged the application and it seems that the application needs camera permission to work, this is my debugging log 07 22 17 47 16.908 E Unity(32483) On Camera Error 07 22 17 47 16.908 E Unity(32483) Error Code 1000 07 22 17 47 16.908 E Unity(32483) Error Domain com.wikitude.camera.android 07 22 17 47 16.908 E Unity(32483) Error Message Permission denied. Make sure to have camera permissions before trying to access the camera. 07 22 17 47 16.908 E Unity(32483) 07 22 17 47 16.908 E Unity(32483) (Filename . Runtime Export Debug Debug.bindings.h Line 35) I'm pretty sure that it didn't ask for camera permission, how should i allow the permission if it's not asking?


How to optimize Floor Meshes with different material in unity I have several meshes (floor tiles) that consist of unique materials as they have different textures. I see that it is taking too many batches and it has around 100m vertexes. Is there any way to improve it through programming? The long way, it should be ported to 3d modeling and combine. I also see the mesh combine but it requires the same material. Edit Around 17k Floor tiles (LoD 9) with details around 5 or 6 large tiles (Floor LoD 7) with fewer details that are placed beneath the LoD 9 tiles lod9 tiles are display based camera culling otherwise LoD7 floor shows all the time. Here are some of the screenshots Lod 7 Tile example (there total 16 tiles)


Unity 2D Why does my character stutter if I add deltaTime to moveSpeed? So I'm following a tutorial on youtube, first time Unity user, but been making games in other frameweorks before. In the tutorial he does not use deltaTime for movement, which has always been the standard for me, so I added it my self, but it makes my character "stutter lag" really weirdly (does not stutter without deltaTime). Surely I must use deltaTime for movement in the Update()method? Script for Player movement void Update () playerMoving false if (!playerAttacking) Vector2 direction new Vector2() if (Mathf.Abs (Input.GetAxisRaw ("Horizontal")) gt 0.5f) Debug.Log ("Moving on X") playerMoving true direction.x Input.GetAxisRaw ("Horizontal") lastMove.x direction.x lastMove.y 0 if (Mathf.Abs (Input.GetAxisRaw ("Vertical")) gt 0.5f) Debug.Log ("Moving on Y") playerMoving true direction.y Input.GetAxisRaw ("Vertical") lastMove.y direction.y lastMove.x 0 if (playerMoving) myRigidBody.velocity direction.normalized moveSpeed Time.deltaTime else myRigidBody.velocity Vector2.zero My Camera (Stutters unless I use fixedUpdate) void FixedUpdate () targetPos new Vector3 (followTarget.transform.position.x, followTarget.transform.position.y, transform.position.z) transform.position Vector3.Lerp (transform.position, targetPos, moveSpeed)


Horizontal scrollview only I am using unity's scrollview. I want to disable the vertical scrollbar and i want the viewport to resize vertically depending on the content. Too confusing to explain with word so i have created the example picture below How do i achieve this properly ?


I've completed my mobile game now what? After months of development, I've finally finished my mobile app, but I have no idea what to do next. I want to publish my app to the Google Play Store and the App Store, yet I don't know how. I've done tons of research and every single website shows different methods and requirements. I've seen that I'm supposed to have some kind of license, a specific certificate, and all these other connections that I'm really confused on how I'm supposed to get them, and where to even start. I've gotten as far as getting Apple Developer and Google Developer, but that's basically it. I just want a simple step to step guide. I've already looked on StackExchange for an answer, but all have slightly different questions, such as marketing the app and updating the app, but nothing on how to get it out there. I'm using Unity as an engine and X Code via my Mac to test my app on my iPhone. I appreciate any help in advance. Thank you!


2D Skier physics looks very artificial I am creating a ski slalom game and I coded a new physics routine, because I was told the rigidbodies are pure "not overly good thing" to use by my boss. With my physics routine it indeed looks much better, but I have no idea how could I make the skier look less plastic. Which means I want to achieve similar level of control like in Skiing Yeti Mountain, because there the physics is quite enjoyable, though still arcade. Basically the requirements are that I need to set up acceleration, top speed and the amount of grip to use when turning, but it somehow bites me back SerializeField private Vector2 slopeDirection Vector2.up var dt Time.fixedDeltaTime var dirVector Vector2.zero dirVector.x Mathf.Cos( radianOrientation ) dirVector.y Mathf.Sin( radianOrientation ) float actualAcceleration Mathf.Abs(Vector2.Dot(dirVector, slopeDirection)) actualAcceleration Mathf.Lerp(maximumAcceleration, 0, actualAcceleration) Mathf.Pow(maximumAcceleration, accelerationSmoothing) velocity.x actualAcceleration dirVector.x dt velocity.y actualAcceleration dirVector.y dt Vector2 velocityDirection velocity velocityDirection.Normalize() float actualFriction Mathf.Abs(Vector2.Dot(dirVector, slopeDirection)) actualFriction Mathf.Lerp(minimumFriction, maximumFriction, actualFriction) Mathf.Pow(actualFriction, frictionSmoothing) Simulate friction velocity actualFriction Debug.Log(velocity) if(! isFinished) this.transform.position new Vector3(velocity.y, velocity.x, 0) why it is overly odd is that when I turn to the side it has a very abrupt power loss and when I turn the skis to 45 degrees to the slope. how could I achieve that the skier will slow down when he turns his skis, but after a little while it will accelerate again like in Skiing Yeti Mountain?


How do I load an asset bundle? I am trying to load a bunch of prefabs from an asset bundle. I am building the asset bundles for StandaloneWindows64 BuildPipeline.BuildAssetBundles(BuildPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64) I load my asset bundle using Unity's new web request system var www UnityWebRequest.GetAssetBundle(Url) yield return www.Send() if (www.isError) Debug.LogError(www.error) yield break var bundle ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle However, my bundle does not have my asset bundle in it. It only has the manifest Output "1 asset bundlemanifest" Debug.Log(bundle.GetAllAssetNames().Length " asset " bundle.GetAllAssetNames() 0 ) If I look at my manifest, I can see my asset bundle names "structures" does exist ManifestFileVersion 0 CRC 3317959940 AssetBundleManifest AssetBundleInfos Info 0 Name structures Dependencies I tried retrieving it from my AssetBundleManifest var manifest bundle.LoadAsset lt AssetBundleManifest gt ("assetbundlemanifest") But the AssetBundleManifest only has functions which return strings and Hash128s. How can I instantiate the prefabs in my asset bundle named "structures"?


"lerp" returning value (Shader)? I don't understand the lerp example in this code if(dot(WorldNormalVector(IN, o.Normal), SnowDirection.xyz) gt lerp(1, 1, Snow)) o.Albedo SnowColor.rgb else (Snow is in the range 0..1) The article says We then compare the dot value with a lerp if our Snow level is 0 (no snow) this returns 1 and if the Snow level is 1 it will return 1 (the entire rock is covered). It's quite normal to only vary the snow level between 0..0.5 when we use this shader so that we only have snow on surfaces that actually face the snow direction. Why does it return 1 (with Snow at 0) and 1 (with Snow at 1) ? (source http unitygems.com noobs guide shaders 2 ) Thanks


How do I organize and sync multiple animated sprites in Unity2D? I have a human with three parts legs, body and head, 2D, top down view (GTA 1 2 alike). Head does nothing, legs have walking animation and body has 2 animations walking animation (moving hands which match with legs animation) and some additional animation. I have 3 gameObjects with SpriteRenderer, for each part, stored in parent. How do I animate all parts synchronously so that if human walks, then does additional body animation while legs are walking and returns to body walking animation so that if e.g. legs play 5th frame of its animation, body also plays its 5th frame, not 1st. Is it possible and if yes, then how? Also, do I need separate Animators for each body part or only one?


How to mitigate when applying horizontal force to a rigidbody seems to overpower gravity? I've started testing movement using the example code in this answer of making a body accelerate to a target velocity private void FixedUpdate() Vector2 input GetInput() if (Mathf.Abs(input.x) gt float.Epsilon Mathf.Abs(input.y) gt float.Epsilon) Vector3 desiredVelocity new Vector3(input.x speed, 0f, input.y speed) Vector3 delta desiredVelocity body.velocity Vector3 acceleration delta Time.deltaTime if (acceleration.sqrMagnitude gt maxAccel maxAccel) acceleration acceleration.normalized maxAccel body.AddForce(acceleration, ForceMode.Acceleration) and I've encountered the following curious behavior https imgur.com snGyVYK When moving the body by applying force, the body seems to levitate as if gravity is not being applied. It actually is being applied but it seems as if the force being applied to the body is overriding the force of gravity because as soon as I let go of the movement keys the body suddenly drops. I am not applying any force on the y axis so I'm not sure what exactly is at play here. What is going on here and what can I do to mitigate this behavior?


Navigate UI with Dpad from Xbox controller on Mac Unity ? So, according to some documentation I found, the Xbox controller on Mac does not return Dpad presses as vertical horizontal axes As you can see, the Dpad is only recognized as buttons 5, 6, 7, and 8, and not as horizontal vertical axes. For my character's movement, I just created code that returns 1 or 1 for axis depending on the button pressed. It works perfectly fine. But then I found another problem UI navigation. I can't navigate my menus with the Dpad on Mac because the the EventSystem is expecting navigation via horizontal vertical axes, which the Dpad is not providing. Is there any way I can turn these Dpad button presses into real horizontal vertical axes in Unity's Input system? Or is there something else I can do to make UI navigation happen on a Mac, with the Dpad?


Smooth vector based jump I started working on Wolfire's mathematics tutorials. I got the jumping working well using a step by step system, where you press a button and the cube moves to the next point on the jumping curve. Then I tried making the jumping happen during a set time period e.g the jump starts and lands within 1.5 seconds. I tried the same system I used for the step by step implementation, but it happens instantly. After some googling I found that Time.deltatime should be used, but I could not figure how. Below is my current jumping code, which makes the jump happen instantly. while (transform.position.y gt 0) modifiedJumperVelocity jumperDrag transform.position new Vector3(modifiedJumperVelocity.x, modifiedJumperVelocity.y, 0) Where modifiedJumperVelocity is starting vector minus the jumper drag. JumperDrag is the value that is substracted from the modifiedJumperVelocity during each step of the jump. Below is an image of the jumping curve


Unity how to render to texture with VR distortion I've also asked the question here http answers.unity3d.com questions 1392099 how to set a render to texture camera to be a vr c.html (but it's currently "under moderation") So, I want to do some post processing effects in VR. I put a camera as a child of the Main Camera and set it to render to texture. Then, I take what is rendered, and display it (with my post proc shader) on a quad in front of the Main Camera (The main camera and the child camera render different layers, so I don't render the same thing twice). (Also worth noting I know that the depth will be collapsed out of the rendered to texture content this is intentional.) The problem is, in this process, the positional data (that was rendered to texture) gets misaligned. I've already fixed a problem where I have to manually set camera project.GetComponent lt Camera gt ().aspect main camera.GetComponent lt Camera gt ().aspect every frame. (Changing setting the screen size auto sets the aspect ratio of the main camera it does not automatically set the aspect ratio of the child camera. So, with just that, everything lines up great and looks fine when it isn't in VR. But, when it is in VR, it appears that maybe some distortion is happening to the main camera that isn't happening to the render to texture camera, and thus, the overlay (the post proc'd content) isn't lining up. So what can I do to emulate the VR distortion in the child camera? Are there other properties of the Main Camera that are getting auto set in VR that I can manually copy to the Main Camera? (I also noticed that aspect wasn't listed in the camera documentation https docs.unity3d.com Manual class Camera.html unless you knew to search for it explicitly, so I think it might be likely there is some other property I'm missing?)


Top Down Octree Generation of Procedural Terrain I'm trying to implement a voxel based terrain generation system in Unity3d (C ). I have successfully implemented a uniform 3d grid system, and have extracted the isosurface out using Marching Cubes and Surface Nets algorithms. I quickly bumped up against the inherent issues in representing all space with a 3d grid. Much of this space was either above or below the surface, and I turned to space partitioning with octrees, as it didn't seem too difficult. One of the great things about octrees is that octree nodes that that don't have edges intersected by the surface don't need to be split again. I researched, and found a couple resources to construct my code. One is Volume GFX, and another is the original Dual Contouring paper by Ju et al. My edge checking is done by the Marching Cube's checking from Paul Bourke's code. If the "cubeindex" is either 0 or 255, then no edge is intersected, and the octree node does not need to be split. My Octree generation code works for something like a quarter sphere, where the surface features are extremely normal As seen in the picture, only octree nodes containing the surface are subdivided. Working great. Now, however, when we move to something more complex, like Unity3d's PerlinNoise function GASP! What's that hole doing in the mesh at the lower right corner? Upon closer inspection, we see the octree didn't subdivide properly (red lines highlighting the offending node's dimensions) This turns out to be the same issue Jules Bloomenthal highlights in her paper on polygonization, page 10, Figure 10. Traditional methods at generating top down octrees ("Adaptive Subdivision"), are sensitive to fine surface features relative to the size of the octree node. The gist X X lt Node X X X's tested values, all outside of the surface! lt surface The surface breaks the surface, but comes back down before it goes over a vertex. Because we calculate edge intersections by looking at the signs at the two vertices, this does not flag the edge as crossed. Is there any method to determine if these anomalies exist? Preferably, the solution would work for more than just the Unity3d noise function, but for any 3d noise function (for cliffs overhangs floating islands, etc). UPDATE Thanks to Jason's awesome answer, I was able to answer my own questions I asked (in the comments under his answer). The issue I had was that I didn't understand how I could create a bounding function for trigonometric functions (sine,cosine,etc) due to their periodic nature. For these guys, the periodicity is the key to bounds functions. We know that sin cos reach their extrema values at a set interval, specifically every 2. So, if the interval we are checking contains any multiple (cos) or half multiple (sin) than 1 1 is the certain extrema. If it doesnt contain a multiple (i.e. the interval 0.1,0.2 ), then the range is simply the values of the function evaluated at its endpoints. UPDATE 2 If the above doesn't make sense, check Jason's answer to my comments.


collision detection and normals from rigidbody Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody? Here is a stripped down version of the script I'm using for collisions. Used in other scripts (Necessary) public GameObject ground null public Vector3 groundNormal public bool onGround Used internally public bool isColliding public float slopeLimit Character Controller public CharacterController controller void Start() controller GetComponent lt CharacterController gt () void Update() Check if the player is colliding with anything (Character Controller) if (controller.collisionFlags CollisionFlags.None) isColliding false else isColliding true Check if the player is standing on the ground if (isColliding amp amp groundNormal ! Vector3.zero) onGround true else onGround false void OnControllerColliderHit(ControllerColliderHit hit) Check for floor if (Vector3.Angle(transform.up, hit.normal) lt slopeLimit) Store floor object data ground hit.gameObject Store ground surface normal groundNormal Vector3.Normalize(hit.normal) else reset variables ground null groundNormal Vector3.zero slopeLimit is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later. Edit Currently I'm using controller.collisionFlags to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the isColliding bool to true using Rigidbody.OnCollisionStay would be simple, but setting it to false without use of another void function seems difficult. is that possible at all?


Encapsulating parameterised prefabs I'm currently using the following general pattern for most of my configurable components (i.e. MonoBehaviours) public class MyComponent MonoBehaviour Configurable fields SerializeField private bool someParameter SerializeField private int anotherParameter Fake constructor to act as a replacement for GameObject.AddComponent with additional parameters. public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter) var myComponent gameObject.AddComponent lt MyComponent gt () myComponent.someParameter someParameter myComponent.anotherParameter anotherParameter return myComponent Public properties and other methods ... This works around the lack of constructors for MonoBehaviours but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built). Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into AddComponent). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them. So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but without exposing them publicly and breaking encapsulation? (I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)


Why isn't my player moving? Why is my code not working? using UnityEngine using System.Collections public class NewBehaviourScript1 MonoBehaviour public float moveSpeed public Vector3 input public Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () void FixedUpdate () moveSpeed 2 input new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) rb.AddForce(input moveSpeed)


Why are my target following objects rotated the wrong way? I writing a script that would make my players reach a target destination. It looks like this so far private void MoveTowardsGoal() if (Vector3.Distance (reachGoalTarget.transform.position, transform.position) gt 2.0f) rDirection (reachGoalTarget.transform.position transform.position).normalized if (rAcceleration lt rMaxSpeed) rAcceleration 0.5f rVelocity rDirection Time.deltaTime rAcceleration transform.Translate (rVelocity,Space.World) It works fine The objects move towards the destination point. However, I want them to move looking at the target in the forward direction (forward z axis). Currently they move with their x axis facing front. I tried a simple rotation inside Start() like transform.LookAt(reachGoalTarget.transform). With this, they look in the forward direction but then they completely move off their initial positions by rotating themselves to reach the goal. What am I doing wrong?


How can I implement a revealing light beam? In SEARCHLIGHT, you control a ray of light that illuminates incoming enemies that are otherwise invisible in the night sky. Here is an illustration How would I go about doing this, preferably in Unity? I imagine this is less about lighting and more about shaders, but I'm not sure on details. The fact that I know very little about coding shaders makes it worse. If it is about shaders, what are the specifics? Is there a stretched quad that moves with said shader applied to it, or perhaps is using the Line Renderer a better option? As a beginner, may I try to achieve a similar effect, or should I leave it for when I'm better? (P.S. The game was made in Unity. Here is its itch.io page.)


Unity2D Repeating of code makes game lag (Spawnning script) does anyone knows how to shorten down this script and that I can edit the amount of enemies I want to spawn in, so that I don't have to keep on copying and pasting the same method below again and again, my code is also making my game a bit laggy. Which isn't a good sign. This is my code public bool fromTop false public GameObject enemy1 public float enemy1Time 2f public GameObject enemy2 public float enemy2Time 2f public GameObject enemy3 public float enemy3Time 2f public GameObject enemy4 public float enemy4Time 2f Variable to know how fast we should create new enemies void Start() InvokeRepeating ("Enemy1", enemy1Time, enemy1Time) InvokeRepeating ("Enemy2", enemy2Time, enemy2Time) InvokeRepeating ("Enemy3", enemy3Time, enemy3Time) InvokeRepeating ("Enemy4", enemy4Time, enemy4Time) void Enemy1() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy1, spawnPoint, Quaternion.identity) void Enemy2() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy2, spawnPoint, Quaternion.identity) void Enemy3() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy3, spawnPoint, Quaternion.identity) void Enemy4() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy4, spawnPoint, Quaternion.identity) Please and Thank you. )


How to pause audio playback when a breakpoint is hit or resume afterward? When my code hits a breakpoint, audio that was previously started (via an AudioSource) continues to play while the threads are paused. I'm using a coroutine to query the status of the AudioSource, and update my UI. Because the audio continues to play, then after I've spend some time stepping through code the next frame tick when Unity gets control back runs the next iteration of this coroutine, which updates the UI. I never get to see the in between states. Because it's a relativley short audio clip it's usually finished playing before I've finished stepping through the code. I'm using Unity 2018.4 with VSCode and the Debugger for Unity extension, if that helps. I'm quite lost at what to try here. Looking for issues with Unity's AudioSource and breakpoints yields a lot of varied information about audio issues in general in Unity. I've tried using Debug.Break(). It pauses the Unity editor, which can be useful but has the following caveats it requires extra effort on each breakpoint that requires enabling (if the call is not there already) it requires manual intervention to resume the editor once you've finished stepping through code because it is code, it cannot be added after Unity is playing, e.g. to additional breakpoints that are added once debugging has started Does Unity have a mechanism that enables this behaviour that I've just missed? If not, what's an appropriate alternative approach?


Unity built in Network Lobby How to move GUI? I'm using built in network manager HUD and I'm fine with it for now. But I can't move lobby GUI, only Network Manager HUD. Is there a way to move it down to make space for Title Art?


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