stop previous audio from playing when starting a new one I created a dialogue system with audio it works perfectly fine unless you start skipping the voice lines so then it all becomes a mess with all of the voice lines overlapping is there a way to make it so when you go to the next audio line the previous one stops playing? Example of what is happening as you can see in the video you can switch the text just fine and it doesn't show the previous one but for the audio, it just transforms into a jumbled mess, is there a way to fix this or to at least make it so people cant go to the next line until they finish hearing the current one? DialogueManager Script public class DialogueManager MonoBehaviour public Door1Animation doorAnimation public Text nameText public Text dialogueText public Text changeText public AudioManager Sound public Animator textBoxAnimation public Queue lt string gt sentences public Queue lt string gt voiceLines void Start() sentences new Queue lt string gt () voiceLines new Queue lt string gt () public void StartDialogue (Dialogue dialogue) textBoxAnimation.SetBool( quot Open quot , true) changeText.text ( quot Aperte R para continuar quot ) nameText.text dialogue.name sentences.Clear() voiceLines.Clear() foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() foreach (string voiceLine in dialogue.voiceLines) voiceLines.Enqueue(voiceLine) PlayNextLine() public void DisplayNextSentence() if (sentences.Count 1) changeText.text ( quot Aperte R para fechar quot ) if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() dialogueText.text sentence public void PlayNextLine() if (voiceLines.Count 0) return string voiceLine voiceLines.Dequeue() Sound.Play(voiceLine) public void EndDialogue() Debug.Log( quot End of conversation quot ) doorAnimation.openDoor true textBoxAnimation.SetBool( quot Open quot , false) AudioManager Script using UnityEngine.Audio using System using UnityEngine public class AudioManager MonoBehaviour public Sound sounds void Awake() foreach (Sound s in sounds) s.source gameObject.AddComponent lt AudioSource gt () s.source.clip s.clip s.source.volume s.volume s.source.pitch s.pitch s.source.loop s.loop private void Start() Play( quot BackgroundMusic quot ) public void Play (string name) Sound s Array.Find(sounds, sound gt sound.name name) s.source.Play() Just the part of the interaction code so you can go to the next line audio public void Update() if (Input.GetKeyDown(KeyCode.E)) PersonInteract() buttonInteract() if (Input.GetKeyDown(KeyCode.R)) FindObjectOfType lt DialogueManager gt ().DisplayNextSentence() FindObjectOfType lt DialogueManager gt ().PlayNextLine() Inspector view of the dialogue manager


How to express and verify euler rotation limits in Unity I need to find a way to set min and max angles for each Euler component and check whether transform.localEulerAngles falls within those limits. My current code looks like this class JointLimit MonoBehaviour SerializeField Range( 180f, 180f) private float minX 180f SerializeField Range( 180f, 180f) private float maxX 180f SerializeField Range( 180f, 180f) private float minY 180f SerializeField Range( 180f, 180f) private float maxY 180f SerializeField Range( 180f, 180f) private float minZ 180f SerializeField Range( 180f, 180f) private float maxZ 180f public float Error get Vector3 localEuler transform.localEulerAngles Vector3 signedLocalEuler new Vector3(Mathf.DeltaAngle(localEuler.x, 0), Mathf.DeltaAngle(localEuler.y, 0), Mathf.DeltaAngle(localEuler.z, 0)) float error 0 error Mathf.Max(0, minX signedLocalEuler.x) error Mathf.Max(0, signedLocalEuler.x maxX) error Mathf.Max(0, minY signedLocalEuler.y) error Mathf.Max(0, signedLocalEuler.y maxY) error Mathf.Max(0, minZ signedLocalEuler.z) error Mathf.Max(0, signedLocalEuler.z maxZ) return error This basically checks whether the Euler components fall within the specified range and sums the exceeding angles up to an error. The problem is that Unity internally stores rotations as Quaternions and that there can be several euler representations for a single Quaternion, like Euler 123f, 17f, 235f and Euler 57f, 197f, 55f are the same thing. Is there any way I can bring an Euler representation into some kind of normalized form that allows me to reliably check it against my limits?


Unity profiler spikes with vsync vs smooth no vsync I'm trying to profile my game, this is a webgl game, and the browser forces vsync. My problem is, when I disable vsync in unity I get a pretty smooth profiler, while with vsync I get huge spikes. I cant tell if this is an editor issue or this spikes exist in the webgl version as well (I do have stuttering when playing in the browser, but cant tell if these spikes are the same ones) I don't display the WaitForTargetFPS in profiler as it is not interesing. no vsync with vsync Any ideas friends?


How to Make Organic Fade to Black in Unity I'm working a retro old style video game, and I was wondering whether or not there is a way to create an organic fade to black, similar to what is found in the original NES console. I am aware of how to create a traditional fade to black screen, but it doesn't really fit the theme of my game. I'm using Unity 2019.4 LTS. Here s a example of a character about to exit the area and cause a fade to black Here s what the organic fade looks like at 75 completion And here s what a traditional fade looks like at 75 completion


Limit mouse movement within 2 points I have a circle sprite that i only want to move between 2 empty game objects (points). Using Vector3.Lerp() I'm able to move the circle between those points void FixedUpdate() float speed 10 Time.deltaTime float current Mathf.PingPong(Time.time speed, 1.0f) transform.position Vector3.Lerp(startPoint.position, endPoint.position, current) The output The problem I want to move that circle using a mouse drag (basically like a UI slider from point a to point b) and as soon as the mouse leaves the circle to stop moving it I can currently move the circle anywhere on the screen using the mouse. I've set a circleCollider2D around the circle sprite and I have this code that moves the circle bool Selected false void Update() if (Selected) Vector2 cursorPos Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position cursorPos if (Input.GetMouseButtonUp(0)) Selected false void OnMouseOver() if (Input.GetMouseButton(0)) Selected true What I've tried I have tried adding a gameobject with a box collider between the two points and using triggers to detect when the circle exits the trigger (OnTriggerExit2D), but this solution only works when the circle fully leaves the collider (which i don't want). I want a way for the circle to move just like its moving currently with Vector3.Lerp but with mouse control I tried locking the circle to only one axis and moving it. While this worked, it failed when i rotated the whole slider as its only locked on one axis and rotation doesn't change that I have also tried to implement the mouse position into the Vector3.Lerp function with no luck Vector3.Lerp(startPoint.position, endPoint.position, mousePosition.x) I tried with y and z, all of it failed. And this way wouldn't work when i go to rotate the slider


Rotate bone on 1 axis to look at another object Unity 3D I'm new to game development and I'm trying to create a basic 3D Tower Defence game as my first project. I've created a basic turret in Blender and I'm now trying to rotate 2 different bones to make the turret follow the enemy. The first bone (which I have working) rotates the turret to face the direction of the enemy. The second which I can't get right needs to rotate the gun at the top of the turret to look down at the enemy. I need it to keep facing the same direction as the rest of the turret and don't want it to tilt to either side. So it needs to move on 1 axis only. I have tried various things, including examples from the Internet but I can't figure it out. So far I've managed to get it to look down at its base, up at the sky and spin like a wheel. Basically everything except where it's supposed to be looking. Here is the code I have at the moment if (enemiesInRange.Count gt 0) Rotate Platform This section works fine Transform platform transform.root.Find("Armature BaseBone PlatformBone") Quaternion targetRotation Final rotation (I.e. facing the enemy) Vector3 turretPosition platform.position Store the turrets current position turretPosition.y 0 0 the Y axis to stop the turret tilting up or down Vector3 targetPosition enemyManager.activeEnemies enemiesInRange 0 .transform.position targetRotation Quaternion.LookRotation(targetPosition turretPosition) float rotateSpeed 2.0f Time.deltaTime platform.transform.rotation Quaternion.Lerp(platform.transform.rotation, targetRotation, rotateSpeed) Rotate GunBox TO DO This part is not working Transform gunBox transform.root.FindChild("Armature BaseBone PlatformBone LowerArmBone UpperArmBone GunBoxBone") Vector3 gunBoxPosition gunBox.position float angle Vector3.Angle(gunBoxPosition, targetPosition) gunBox.RotateAround(gunBox.position, Vector3.left, angle) Debug.Log(angle) Here's a picture of the turret to give you an idea what I'm working with. You can see in the screenshot that the bone's default X rotation is roughly 50. Enemies walk through the trench around the turret. The PlatformBone rotates everything from the silver platform upwards. I also don't understand why the line below makes the turret rotate instead of tilting it. I would expect to rotate the turret around the Y axis to keep it flat on the floor and face another direction. Yet I seem to have to do the opposite (If I select the PlatformBone its Y axis is facing up as expected) turretPosition.y 0 0 the Y axis to stop the turret tilting up or down


Projector making the scene objects grey in Unity Everytime I enable my projector, it makes all the overlapping elements look entirely grey. The shadows also disapear. I tryed a couple of other shaders found on the internet but the issue still persists.


Show hide soft keyboard on demand I'm writing simple chat app using Unity. The problem with Unity's default implementation of soft keyboard visibility is that it hides itself when i'm clicking outside of keyboard panel. What i want is that keyboard stays always shown until i explicitly tells otherwise. For a couple of days i tried to find similar questions but none of them helped me. I have very little experience in "native" android development (i.e. Java). So far i managed to create simple native plugin for Unity. I tried to manually open keyboard with this code imm (InputMethodManager)context.getSystemService(Context.INPUT METHOD SERVICE) imm.toggleSoftInput(InputMethodManager.SHOW FORCED, InputMethodManager.HIDE IMPLICIT ONLY) The result was fine, except the keyboard had InputType set to TYPE CLASS NUMBER. For my app i needed TYPE CLASS TEXT. So i tried to research how to set InputType and stumbled on fact that this property can only be changed inside EditText object. As i'm writing my app in Unity, i had no way of finding my InputField's inside native code. So i tried to create EditText inside my native plugin. I followed the logic that if i create custom EditText, place it inside main layout and set visibility to NONE or make background transparent, then i can set focus to that element and be fine FrameLayout myLayout activity.findViewById(android.R.id.content) focusedText new EditText(context) focusedText.setFocusable(true) focusedText.setInputType(InputType.TYPE CLASS TEXT InputType.TYPE TEXT VARIATION NORMAL) myLayout.addView(focusedText) focusedText.setFocusableInTouchMode(true) focusedText.requestFocus() focusedText.setBackgroundColor(activity.getResources().getColor(android.R.color.transparent)) imm.showSoftInput(focusedText, InputMethodManager.SHOW FORCED) The end result was a mess. Soft keyboard behaviour became undesirable. In order for keyboard to show, i first needed to select InputField, then i would see transparent EditText be created in the middle of my layout with all input characters visible. Even if all worked fine, it still looks like a wacky hack. Does anyone stumbled across similar issues?


Unity Graphics.DrawMesh lags behind rotation? I have a setup in unity using Graphics.DrawMesh() to draw a mesh on my players camera location in the update loop, Graphics.DrawMesh(viewModel, matrix, material, layer, null, 0) matrix Matrix4x4.TRS(cam.transform.position, cam.transform.rotation, scaleFps) when I use my mouse to move around the camera, it lags behind where the camera is, as can be seen in the video. I have no idea how to fix this. I've tried not using the matrix, and it doesn't change anything. https youtu.be eWFFYcOX 4Q Here's the script I use for moving the camera Get the current mouse input. yaw Input.GetAxis("Mouse X") mouseSensitivity pitch Input.GetAxis("Mouse Y") mouseSensitivity Clamp the camera rotation. pitch Mathf.Clamp(pitch, maxLookAngle, maxLookAngle) Calculate and rotate the camera. currentRotation Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, mouseSmoothScale) Rotating the player. Vector3 bodyRotation new Vector3(0, currentRotation.y, 0) transform.localEulerAngles bodyRotation Rotating the camera. Vector3 cameraRotation new Vector3(currentRotation.x, 0, currentRotation.z) playerCamera.transform.localEulerAngles cameraRotation '


Can we measure the distance between and AR marker and camera? I'm in the middle of developing a game in Augmented Reality using Unity and ARToolkit plugin. I wanted to measure the approximate distance between the AR marker and the position of camera. Can anyone help me with a solution to this problem? Thanks in advance.


How can I display a 3d object and my player on a canvas? The main goal is to animate my player with animator on a canvas. The problem is that any 3d object (my player, a cube) I drag over the canvas is transparent not seen. The main camera is set to Clear Flags Depth Only and Culling Mask to Everything. The Main Menu Canvas is set render mode to Screen Space Camera and I selected the main camera. The Main Menu Background Material is set to New Material I created and on the new material I added a shader I created that make this image to be blur. The main camera settings screenshot And the Canvas settings And the Main Menu Background settings You can see in all the screenshots in the scene view top left that my player and the cube both are transparent on the canvas. Now if I change the Main Camera Clear Flags to SkyBox then I see my player and the cube but also they are not looking like they should be with the texture materials and also I don't want the Main Camera to be the clear flags on SkyBox I want the objects to be over the blur image so the Main Camera should be clear flags depth only. The main goal again is to put my player on the canvas with the blur image and animate my player. This is for my main menu. The canvas that will display the player if the player will be on his own canvas should be transparent and only display the player so the canvas will not overlap the other cnavas with the blur image. I want to animate using animator the player not only to display it as static object. This is a screenshot of what I mean I used paint to cut my player and put it on but the player canvas should be transparent or without a canvas the player should be on like the ui button on the left Another screenshot. On the top it's the scene view window the player the ui button and the blur image. On the bottom the game view window the ui button is on the blur image. I want the player to be the same as the ui button on the blur image and then to animate the player. Not like in my other screenshot the player should not have a skybox background or something it should be like the ui button on the blur image


How can I get a raycast to hit navmesh only? In Unity, I'm trying to get the raycast to hit the navmesh only, but I cannot find an option to place navmesh on a specific layer. Is there a way to raycast to the navmesh itself?


Instantiate player prefab using player data When my scene loads, I want to add my prefab to it along with its components. Here is what I mean scene loads player gender is determined via playerprefs or playfab sdk player prefab is loaded and displayed using said gender The prefab would have a script components attached for the current data etc. I might be approaching this wrong, but I want this to work with multiplayer in the future, so that's why I didn't just add the prefab directly to the hierarchy. What is the correct way of doing this?


How can I prevent a latitude longitude based chunk system from Mercator projection stretching? I'm working on an little mapbox based game and I'm currently working on an latitude longitude based chunk system. The distance between each of them should be the same. As you can see in the example the width and height of each chunk are equal. The little grey square is just the chunk middle. Those chunks were created near latitude longitude zero, where they aren't effected by the Mercator projection. But due to the Mercator projection the distances between the chunks are increasing as more as they move away from the middle (they look kinda stretched). As you can see the distances between each one aren't equal anymore. The height of each of those chunks did increase. Here's another picture of the Mercator projection to visualize what I mean The chunks of the first picture were created near the middle of the word map (where the big black upper arrow points towards). The chunks from the second pictures were created near the bottom of the world map, where the other arrow points towards. The type of game I'm developing requires equal chunk sizes and also it doesn't look that good when at some point the chunks look different due to the stretching. I want to achieve a chunk system like this on the mercator projection I calculate the chunks as follows First we need the player latitude longitude coordinates 3.0146683, 5.3046076 One latitude is about 110.57 km gt 110570 meters. One longitude is about 111.32 km gt 111320 meters. One chunk should be about 750 meters on the map. Because latitude and longitude got different ranges we need to adjust the chunk size. One latitude factor 110570 750 147,43. One longitude factor 111320 750 148,42. One latitude chunk size 110570 147 750 meters. One longitude chunk size 111320 148,42 750 meters. (Maybe this step is unnecessary) Now we convert the Lat Lng to meters. Latitude in Meter 3.0146683 110570 meters 333 331.873931 Meters. Longitude in Meter 5.3046076 111320 meters 590 508.918032 Meters. Now we need to calculate the meters till the last chunk by using modulo. Latitude Modulo gt 333 331.873931 modulo 750 331 meter. Longitude Modulo gt 590 508.918032 modulo 750 258 meter. After that we are able to calculate the Latitude and Longitude chunks. Latitude chunk position 333 331.873931 331 333 000.873931. Longitude chunk position 590 508.918032 258 590 250.918032. When we didive that now through the chunk size we get the actual chunk position. Chunk X 333 000.873931 750 444,0011. Chunk Y 590 250.918032 750 787,001. Rounded Chunk X 444 Chunk Y 787. Now we know that the player stands right in this chunk 444 787 . In the next step I just calculate the Chunk X and Y back to latitude and longitude and convert them via transform.AsUnityPosition to 3D coordinates, where I place those grey objects then. So basically I need a way to have the same visual distance between each of those chunks. Or either a way to change the projection from Mercator to a square projection, where nothing is stretched. I never worked with mapbox Google Maps before... so I'm a newbie. Or is there maybe a formula I can use to prevent my chunks from being stretched by the projection? Thanks for your time and attention! )


Unity inconsistent memory profiling when running same scene I'm in the making of a 2D silhouette style game where I'm trying basically 2 setups One where it consists only of sprites, One where it consists of a mix of sprites and meshes with NO texture. Now, I'm experimenting with the two as I wish to want the scenes to take up the least memory. I have these weird outcomes SPRITE SETUP Total 280 MB, Textures 155.5 MB, Meshes 1.7 MB Total 249 MB, Textures 151 MB, Meshes 4.1 MB Total 279 MB, Textures 151.0 MB, Meshes 10.8 MB SPRITE amp MESH SETUP Total 334.4 MB, Textures 188.2 MB, Meshes 1.8 MB Total 241 MB, Textures 148,0 MB, Meshes 2,3 MB Total 253.1 MB, Textures 157.7 MB, Meshes 4.2 MB Total 301.8 MB, Textures 157.7 MB, Meshes 8.4 MB Total 234.8 MB, Textures 145.3 MB, Meshes 1.9 MB Now, I find these result strange because It was checked on the exact same scene (the mesh setup had same amount of objects, just swapped the sprites for meshes) and the data is inconsistent, meaning there is about 100MB difference between the same mesh scene A scene of mostly mesh with zero textures uses more, or at least not less, textures than a sprite only scene?? By taking a look at the data above, I would require someone skilled to guide me through this. Shall I keep using those meshes or just go for sprites? What is really goind on here with this data?


Importing audiofile into Unity3d gets shown after ending playmode I am working on a game where the user has the possibility to import custom audio tracks that can be listened to during the game. For this I am making use of System.IO.File.Copy method. This works, there are no issues or flaws here. When I inspect the target and destination folder the file(s) get copied properly and show up in the folder. The issue however is that the Unity Editor doesn't show the file despite it actually being there. During play mode in the Unity editor the new file isn't shown in the resources folder (which I use as destination for now). When I use windows file explorer I can clearly see the file in the corresponding folder. Using debugs (in Unity) also state that the folder is empty, however when I use debugs outside of Unity it shows that the folder contains the copied item. Keep in mind that these both debugs are called roughly at the same time. I have tested this in many ways to be 100 certain that Unity doesn't see the file, while it is there. So once I stop playmode it starts loading importing processing the new file and then it shows up in the folder in unity as well. When I launch playmode after this the file is indeed loaded and included in the game as well. I however need this to happen without having to stop playmode. So there is probably some type of processing that I haven't called for Unity to process the addition of the new file and for it to be visible. So in a nutshell basically copying a file from folder to folder isn't enough for Unity to directly utilized in the same play session (and all after). How can I make the audio file directly showable and accessable? There aren't any errors or warnings. The file plays correctly after it has been processed. I am at a loss with this issue bug.


Using a Wii remote as main controller? I would like to use a Wii remote to control my player in my 3D game. So far I have the arrow keys and mouse to move and look but I want the Wii d pad to move and accelerometer data to look around. I have downloaded Unity Wiimote 1.1 and the demo works fine. In my game I have imported the Unity package for the Wii remote but I'm not sure what script goes where, attached to what, how to call particular functions. They are mostly C scripts. There is no documentation with the Unity Wiimote 1.1 and as I'm a newbie, I'm clueless on what to do. Or is there a simpler method to getting the Wii remote to be the main controller?


object reference not set to an instance of an object hello i have a error "object reference not set to an instance of an object" when my ball collide with the spikes.its supose to remove one heart but it doesnt. health code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Health MonoBehaviour public int health public int numOfHearts public Image hearts public Sprite fullHeart Use this for initialization void Start () Update is called once per frame void Update () if (health gt numOfHearts) health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt health) hearts i .sprite fullHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false public void Damage(int dmg) numOfHearts dmg spikes code using System.Collections using System.Collections.Generic using UnityEngine public class Spikes MonoBehaviour private Health Player Use this for initialization void Start () Player GameObject.FindGameObjectWithTag("Player").GetComponent lt Health gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) if (col.CompareTag("Player")) Player.Damage(1) here i have the error.


Unity LWRP Sprite Renderer Sorting incorrectly after upgrading I'm making a project where every tile is a sprite renderer, this would work fine in the old unity system (from the fact that it used it until recently), but upgrading to the LWRP broke the sorting of the sprite renderers. Previously, I didn't have to change the order at all, but now they phase in and out of each other based on the position of the camera, like the picture shown below. They all use LWRP 2d Sprite Lit Default, as any other of the LWRP materials do not use the texture from the sprite renderer and instead make it all black. I do not want to use sorting layers because I have meshes sprinkled in, and what i have seen there is no way to control if the mesh is on anything but order 0, besides some hacky way. Even using a box mesh it gets cut off when the floor is closer to the camera. Here is what it looks like far away, the floor should be there the entire time and not have the darkness of the walls seeping down into them. I don't think I can use mesh renderers either, as I want a way to control the texture from each individual object, and share a material through all of them. I think if I used a mesh renderer I would have to use a material for each different tile, and I would not be able to tile them like I am doing now.


How can I reduce Unity's package size? I've been experimenting with Unity3D 4.3's 2D features. I've created a simple prototype game to learn how Unity works, how to create sprite animations, collisions and all the basic things. My project compiled for PC was approximately 23MB. The game includes one larger bitmap for a background (originally 1MB JPEG). The player spritesheet was black and white with almost no details. So all the assets had (in their original, compressed form) no more than 2 3 MB. I ended up with one large executable file (about 10MB) and a folder with .dll files and assets (5 6MB). Can that be reduced? My experience with C WinForms code makes me believe that executables and DLLs grow that big only when binary data was involved (images, sound, etc). Is that the case with Unity? I am interested in developing 2D applications for Android and iOS, where low total app size is a priority.


Referencing a Text in Unity Error I am working on trying to add a coin system to my game. I have it setup right now so that when the player hits a coin the score text goes up by 1. I have setup a reference in the script, which is attached to the coin, to the score text in my scene. In the game the player can click a button that will switch between two lanes to avoid enemies. These lanes are infinte and in these lanes is where I put the coins. And when a new lane is created the reference to the text disappears from the coin and teh tect does not change. I am not sure why the reference is disappearing. Here is the coin script that is on the coin public int scoreToGive 1 public Text coinText void OnTriggerEnter2D(Collider2D other) if(other.gameObject.tag "Player") AddScore() public void AddScore() TheScore.theScore if(coinText ! null) coinText.text TheScore.theScore.ToString() Destroy(gameObject) void Update() coinText.text GameObject.FindGameObjectWithTag("Ui").ToString() Thanks to anyone who can help!


Client not executing commands in Unet Edit Okay, so I partially solved the problem by adding a rigid body component to the capsule. I read somewhere that apparently you have to have one in order to move on the server. Problem 2 The next problem I have is that I can now move a capsule that is spawned by the client fine and the host can move it as well as many times as they like. The problem I am getting now is that when the host spawns a capsule the client cannot move it at all and I get a sort of glitch effect on the client side and the capsule still doesn't move on the host side. Is there a reason why it would only work one way and not the other way around? I thought at first it might have to do with Spawn vs SpawnWithClientAuthority but that doesn't seem to make a difference. Project Summary I have a pretty simple multiplayer project, all I want to do is have one player host and the other join as a client. Once they are joined together the two players can spawn a capsule and then when the user clicks on a capsule. They should be able to pick it up and move it around the scene and the other player should be able to see this action. I can get both players to connect to the server and spawn their own capsule and both players can see this. The movement script is done as well. However, it is only transmitted on the host side. When the client picks up the object it does not update on the server. Problem I have done a bit of debugging and have found that when I call the command on the client it is not being executed at all through line breaks and simple debug statements. Code public void OnInputClicked(InputClickedEventData eventData) Debug.Log("clicked") if (isLocalPlayer) if (Physics.Raycast(transform.position, direction transform.forward, hitInfo out hit, maxDistance range)) Debug.Log("Hit capsule") objectID GameObject.Find(hit.transform.name) objNetId objectID.GetComponent lt NetworkIdentity gt () playerIDThatClicked player.GetComponent lt NetworkIdentity gt () CmdAssignAuthority(objNetId, playerIDThatClicked) Debug.Log("grabbed") else if we are releasing the object we want to unassign our authority if (objNetId ! null) CmdAssignAuthority(objNetId, playerIDThatClicked) objNetId null Debug.Log("released") Command void CmdAssignAuthority(NetworkIdentity target, NetworkIdentity player) Debug.Log("inside cmd") current target.clientAuthorityOwner playerconn player.connectionToClient if (current ! null amp amp current ! playerconn) Debug.Log("Had authority now removing and replacing") target.RemoveClientAuthority(current) target.AssignClientAuthority(playerconn) else if (current ! null) Debug.Log("removing authority") target.RemoveClientAuthority(current) else if (current null) Debug.Log("No authority, adding one now") target.AssignClientAuthority(playerconn) else Debug.Log("CmdAuthority error") target.RemoveClientAuthority(playerconn) Question Am I calling this command correctly? The script is attached to a player prefab and the capsule prefab contains a network id and a network transform. I am pretty new to Unet and this feels like a noob mistake.


Unity Proximity Warning System Trigger issues I'm trying to set up a proximity warning system but I'm having some trouble. To simplify things as much as possible I have two game objects in a scene (Object1 and Object2). Object1 has a large child object (twice as large as Object1 or Object2) which has no mesh renderer, but has a box collider (with the Is Trigger box ticked). Object 2 has a rigidbody component. When Object1 gets close enough that it's child's Box Collider overlaps with Object2's rigidbody, a script on Object1 should Debug.Log the name of the object it's close to once a frame until Object1 moves away. My code is as follows public Collider objectCollidedWith void OnTriggerStay(Collider other) objectCollidedWith other.transform.GetComponent lt Collider gt () void Update() Debug.Log(objectCollidedWith) Unfortunately, something about my setup isn't working. The console just shows "null" once a frame and the objects getting close doesn't change this. Can you tell me what I'm doing wrong? Many thanks for your time.


Why does duplicating my object cause its vertex animation shader to distort it? I used a vertex shader (based on this example) to animate a flag waving. When I have a single flag in my scene, it works correctly. When I duplicate the flag, all of the copies become wildly distorted after I hit play. Here is the shader code I'm using Shader "Custom Flag" Properties MainTex ("Albedo (RGB)", 2D) "white" Speed ("Speed", Range(0, 5.0)) 1 Frequency ("Frequency", Range(0, 1.3)) 1 Amplitude ("Amplitude", Range(0, 5.0)) 1 SubShader Tags "RenderType" "Opaque" Cull off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 float Speed float Frequency float Amplitude v2f vert(appdata base v) v2f o v.vertex.y cos((v.vertex.x Time.y Speed) Frequency) Amplitude (v.vertex.x 5) o.pos mul(UNITY MATRIX MVP, v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o fixed4 frag(v2f i) SV Target return tex2D( MainTex, i.uv) ENDCG FallBack "Diffuse" How can I make this work with multiple flags using the same material? Should I use a new material instance for each object like this? It doesn't seem optimal material new Material (Shader) Create new material material.SetFloat (" Speed", Speed) material.SetFloat (" Frequency", Frequency) material.SetFloat (" Amplitude", Amplitude) material.SetTexture (" MainTex", MainTex) flagObj.GetComponent lt MeshRenderer gt ().sharedMaterial material Set values


Camera relative movement is pushing into off the ground instead of parallel I'm building upon roll a ball tutorial in unity, and I have managed to rotate the camera around the ball just fine with the code below. But there's one problem. In this code, when I add force to the ball, with W for example, the force will be added in the exact direction the camera is looking at the ball, meaning pushing the ball onto the ground, increasing friction and lowering speed. And if I press S the force will push the ball to the air, lowering friction and making the ball move fast. So my question is, how can I achieve rotation without this issue? Code for Camera (CameraController) public GameObject Player private Vector3 offset public float cameraSpeed private Vector3 point static public Vector3 finalMovement void Start () offset transform.position Player.transform.position point Player.transform.position transform.LookAt(point) void LateUpdate() point Player.transform.position offset Quaternion.AngleAxis(Input.GetAxis("Mouse X") cameraSpeed, Vector3.up) offset transform.position point offset transform.LookAt(point) Vector3 movement void FixedUpdate() movement new Vector3() float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") movement new Vector3(moveHorizontal, 0f, moveVertical) finalMovement GetComponent lt Camera gt ().transform.TransformDirection(movement) Code for ball public float speed void FixedUpdate() rb.AddForce((CameraController.finalMovement) speed)


1 kb swf file created when building to flash in unity I am trying to build a project in flash that I have made. It goes through its building process, but when it is done the swf file that it creates is 1 kb in size. I am not sure what I am doing wrong or what is going on. I have built to flash before and never ran into this problem until recently.


Particle system on sphere surface I would like that particle system travels only on sphere surface. I have set sphere and particle system as it's child. How to constraint particle system ? How to make trails follow along sphere surface? On sphere it would look something like this with trails without trails


Issues with 3dsmax and Unity3d scale I changed the units in Blender so they are identical to Unity 3d. If I make a 1m 3 box in Blender, it will import into unity as exactly the same size as the standard cube. With 3ds max, I changed the unit setup to metric and made sure it was centimeters in the system unit setup tab. However, when I import an obj file made in Blender and used in Unity, it is absolutely tiny. I have to convert the model to meters on import and then, when exporting, I have to set the model scale to .01 otherwise it is enormous in the unity scene. I've tried changing the max units to meters and nothing changed. How do you change the max unit grid setup so one grid unit is 1m 2 and exactly equivalent to unity's grid?


How to share Unity High Scores on social media (Facebook , Google and Twitter)? This may be a common question but as a n00b I have some confusion on achieving this . I am on a small game project and I want the user to share his her scores on social media after completing the game . When they post , it should be something like "Hurrayyyy ! I Scored 12345 on My Game App Name , Can you beat my score ? Try it ." where ' My Game App Name ' and 'Try it' should be a link directing to Google Play Windows Store etc . My Idea is like this Here Share This on Facebook , Share This on Google and Share This on Twitter are 3 UI Images with Button component attached to them . So when the player clicks on those buttons , they should post on social media . So how to achieve this ? I got something here , but I don't know how to use that . I will prefer not to use Facebook Unity Plugin . So can I achieve this ? I need code in c , not in JavaScript ) I hope you will help me to figure this out . Regards , NB )


Raycasting against my plane does not detect collisions in Unity I'm trying to keep the camera above a plane which acts as the ground, so I wrote this bit of code RaycastHit hit if (!Physics.Raycast (transform.position, new Vector3 (0, 50, 0), out hit, 5)) transform.position new Vector3 (0, 20, 0) Debug.Log ("No ground found when raycasting down!") Debug.DrawRay (transform.position, new Vector3 (0, 50, 0), Color.red, 0, true) else if (hit.distance lt 1) transform.position new Vector3 (transform.position.x, 1, transform.position.z) The camera is clearly over the plane on position 0, 20, 0 while the plane is at 1, 1, 1, with scale 50, 1, 50, but it never detects a hit. The ray drawn by DrawRay() does intersect the plane. The plane is oriented upwards, but just to be sure I tried raycasting from below as well, without success. I have also tried replacing the mesh collider with a box collider using size 10, 1, 10 (I'm not sure why, this seems to be the same size as my scaled plane) and 10, 10, 10. Neither worked. What Am I missing?


Enemy shake vibrate when following character I am using the arongranberg A path finding project to create way points for one enemy to follow the player. However, the enemy vibrates back and forward by about 0.1 0.2 unit distance when moving. I have done a lot of research regarding this problem in the past few days but to no avail I could not find a solution that solves it. This is link to a gif to show what I mean. I have tried, changing Application.targetFrameRate 30 changing fixed update to update and vice versa using rigidbody2d and turn interpolate on plus using velocity to move turning iskinematic on and off using translate to move. none of the above solution works. Below is the script I have for my enemy. Any advice would be appreciated. using UnityEngine using System.Collections Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors This line should always be present at the top of scripts which use pathfinding using Pathfinding public class AstarAI MonoBehaviour The point to move to public Transform target private Seeker seeker The calculated path public Path path The AI's speed per second public float speed 200 The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance 0.02f The waypoint we are currently moving towards private int currentWaypoint 0 Rigidbody2D rb public void Start () rb this.GetComponent lt Rigidbody2D gt () seeker GetComponent lt Seeker gt () Start a new path to the targetPosition, return the result to the OnPathComplete function seeker.StartPath( transform.position, target.position, OnPathComplete ) public void GoToNewTarget(Transform newTarget) path null currentWaypoint 0 nextWaypointDistance 0.02f target newTarget seeker GetComponent lt Seeker gt () seeker.StartPath( transform.position, target.position, OnPathComplete ) public void OnPathComplete ( Path p ) Debug.Log( "Yay, we got a path back. Did it have an error? " p.error ) if (!p.error) path p Reset the waypoint counter currentWaypoint 0 public void Update () if (path null) We have no path to move after yet return if (currentWaypoint gt path.vectorPath.Count) Debug.Log( "End Of Path Reached" ) return this.GetComponent lt Rigidbody2D gt ().MovePosition (path.vectorPath currentWaypoint ) Debug.Log (path.vectorPath currentWaypoint ) Direction to the next waypoint Vector3 dir ( path.vectorPath currentWaypoint transform.position ).normalized GetComponent lt Rigidbody2D gt ().velocity new Vector2 (dir.x 3, dir.y 3) Vector3.MoveTowards(transform.position, path.vectorPath currentWaypoint , 2 Time.fixedDeltaTime) dir speed Time.deltaTime rb.velocity dir this.gameObject.transform.Translate( dir ) Check if we are close enough to the next waypoint If we are, proceed to follow the next waypoint if (Vector3.Distance (transform.position, path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint return


How can I add velocity to the standard CharacterController? I have FPS controller from standard asset. After a long trial and error I figured that CharacterController doesn't respond to AddForce. So, I have this trigger in the scene which I would like to throw FPS controller upwards. Now, I know that I need to replace AddForce with adding velocity to the player. How to do that? I need to use FPS controller component for velocity and add Vector3.up. So, every game object other which will enter the trigger, will get upwards velocity. void OnTriggerEnter(Collider other) other.attachedRigidbody.AddForce(Vector3.up 100, ForceMode.Impulse)


How to avoid movement speed stacking when multiple keys are pressed? I've started a new game which requires no mouse, thus leaving the movement up to the keyboard. I have tried to incorporate 8 directions up, left, right, up right and so on. However when I press more than one arrow key, the movement speed stacks (http gfycat.com CircularBewitchedBarebirdbat). How could I counteract this? Here is relevant part of my code var speed int 5 function Update () if (Input.GetKey(KeyCode.UpArrow)) transform.Translate(Vector3.forward speed Time.deltaTime) else if (Input.GetKey(KeyCode.UpArrow) amp amp Input.GetKey(KeyCode.RightArrow)) transform.Translate(Vector3.forward speed Time.deltaTime) else if (Input.GetKey(KeyCode.UpArrow) amp amp Input.GetKey(KeyCode.LeftArrow)) transform.rotation Quaternion.AngleAxis(315, Vector3.up) if (Input.GetKey(KeyCode.DownArrow)) transform.Translate(Vector3.forward speed Time.deltaTime)


Camera to the right from the character I'm trying to create a camera like in Fortnite or Gears of War. It's focus must be to the right side from the character But when I rotate the camera, the character slightly shivers. Lerping and multiplying by Time.deltatTime doesn't help. This is my code using UnityEngine RequireComponent(typeof(Camera)) public class ThirdPersonCamera MonoBehaviour Header("Sensitivity") SerializeField private float xSensitivity SerializeField private float ySensitivity Header("Limit angles") SerializeField private float upLimit SerializeField private float downLimit Header("Positioning") SerializeField private Vector3 offset SerializeField private float maxDistanceFromPlayer SerializeField private Transform player private float rotationAboutX private float rotationAboutY Start is called before the first frame update void Start() rotationAboutX transform.localEulerAngles.x rotationAboutY transform.localEulerAngles.y void Update() rotationAboutX Input.GetAxis("Mouse Y") ySensitivity rotationAboutY Input.GetAxis("Mouse X") xSensitivity rotationAboutX Mathf.Clamp(rotationAboutX, downLimit, upLimit) Adjust camera position. void LateUpdate() Vector3 direction new Vector3(0.0f, 0.0f, maxDistanceFromPlayer) Quaternion rotation Quaternion.Euler(rotationAboutX, rotationAboutY, 0) Point to look at in the runitme. Vector3 focus player.position transform.TransformDirection(offset) Rotate vector according to mouse inputs. transform.position focus rotation direction transform.LookAt(focus) It shivers only if offset is not zero. Otherwise it's ok.


Problems with gravity and box colliders in Unity 3D I have a game character that can jump or roll in order to avoid obstacles. He is able to roll while on the ground and he can also roll while he is in the air after jumping. Everything was working fine when I made him roll. I want to make it so that when he rolls while he's in the air after jumping, he would fall at a faster pace than if he was just falling normally. So I did this in my c script IEnumerator IncGravAcc() Physics.gravity new Vector3(0, 50f, 0) yield return new WaitForSeconds(2f) Physics.gravity new Vector3(0, 9.8f, 0) I call this coroutine in the function that runs when the down arrow is clicked. Everything is working fine. When he rolls while in the air, he falls at a faster than normal rate. However he doesn't land properly and he just falls right through the platform like it's not even there. Here's a video to show what I mean https youtu.be sirc4L3MnqM I have a box collider, not set to isTrigger, on the player (you can see it, the green box, right underneath him in the video) and the player's also a rigidbody. The platforms don't have rigidbodies on them but they do have box colliders set to trigger. You can see the platform's box collider in the relation to player's box collider in the picture provided (the platform's box collider is the larger one of course) How do I get it so that the character doesn't fall through? Please let me know if there's anything else you need to know about the project. Thank you for helping me!


Is it possible to load asset bundle dependencies manually in Unity 5.0? Is it possible to tell Unity to not load asset bundle dependencies automatically so they can be loaded manually. If so, how can this be done?


Creating an object in javascript with unity (unityscript) So I have a ton of experience with JavaScript (its what I do for a living) but I am new to unity. I have built a game engine in javascript but now want to move it over to unity. I have been trying to implement my player class but am running into this error. I have a getter function for my level up stats. and inside of my level up function I call that getter function and store it now I know this would work in normal javascript but its not in unity and I have having a heck of a time googling any information on objects in unityscript. Here is the relevant code function level getter() return base level exp float , lvl exp modifier float , current level int function level up() var level object new Object() level object level getter() level object.current level 1 level object.base level exp level object.base level exp level object.lvl exp modifier level setter(level object.base level exp, level object.lvl exp modifier, level object.current level) I guess my first question is, is it even valid to return an object like that in unityscript?(in the level getter() function). If its not valid what do people suggest I do instead. Set a getter function for each var? My second is how do I declare level object so that it can accept the return if it is valid, and so that I can access the members of the object. I have been looking around at tutorials and google for several hours now and have found nothing to clear up my confusion over objects in unityscript. So any help would be appreciated.


pre load new scene in unity async but don't show it I have a top down dungeon crawler in 3D where I show one room at a time. Each room is it's own unity scene. Each room has an exit point that when clicked I fade the screen, load a new scene and then fade in the screen. What I'd like to do, but not sure how, is to pre load the next possible scenes (note the S, there will be 2 but could be more. 2 because it's the next room or the previous if the player decides to go back) while in one scene. I know the scenes that are possible to get to, but how can I pre load but not show them and because there is more than 2, I assume if they go in one direction, there is a pre loaded one that I need to unload. Overall I want to do this to make a faster smoother transition between rooms, but I want the one room at a time for artistic style.


Unity build does not launch and leaves no logs errors I have released my first title Audio Infection ( https store.steampowered.com app 911580 Audio Infection ) for a bit over a year ago. Recently 1 user has so far encountered an issue where the game does not launch. He is the only user that encounters this problem. He has this issue on both Win 7 and Win 10. His system specs are fine and his drivers are up to date. The game does not leave a log file, rather it looks like it is unable to boot. There are no Windows error reports on it either. I watched it through Discord screenshare because I could not properly understand his issue. I had asked a few other random people to test my game and demo (he has the issue with both, the demo and full version) however no one else (including me) is able to reproduce this behavior. At this point I have tried updating Unity from 2018 to 2019 (no change in behavior) added manual logging (with no results) updating drivers (on his system) installing Visual C (on his system) empty project with Unity sample scene (he was able to load the sample scene!) deleting crashhandler.exe (used to fix similar issue in the past based on older threads) modifying files deleting and downloading the files What else can I try in order to figure out what is causing the issue? I am honestly clueless. Since the sample project was able to boot on his system there is definitely something wrong with the build on my end. However he is the first person with this issue. It doesn't even get to the point of launching on his system and it can't be found in the memory either. It is almost as if Windows is blocking it from launching, however that is not the case. But the result is very similar to that. There is a free demo on the store page available in case you want to see if it boots on your system. It works for both VR and non VR systems. When no VR devices are detected all VR related contents are disabled. This has been thoroughly tested and worked on loads of different Windows systems with different specs, with VR and no VR. Once again, there are no errors, no logs, the build doesn't even make it to that point, yet that exact same build works for literally everyone else on various systems. I am absolutely clueless about what to do in order to resolve this issue. Any help advice or pointers towards the right direction are greatly appreciated! PS he is not a troll, I have known this guy for a long time now and he genuinely wants to support me.


FindObjectsOfType returns null array I am making the game in this tutorial https www.youtube.com watch?v OR0e 1UBEOU and at 2 53 23 he is coding a LevelController script. I noticed that mine wasn't working the way his was and so I went to try and debug the error. I found that the error was in the function FindObjectsOfType() You can find my code below. using System.Collections using System.Collections.Generic using UnityEngine public class LevelController MonoBehaviour private Enemy enemies private void onEnable() enemies FindObjectsOfType lt Enemy gt () Update is called once per frame void Update() Debug.Log( enemies) When I run this my debug log returns null values which is confusing because I have 3 objects (Monster, Monster (1) and Monster (2)) which have the Enemy script assigned to them. What could be going wrong?


How can I roll up a plane with a vertex shader? I have plane that I want to roll up using a vertex shader, like this I found a math demo that shows the kind of curve I want my mesh to follow. I tried implementing this in my shader code, but the results don't form a roll as expected Shader " Custom Rolling " Properties MainTex ("Base (RGB)", 2D) "white" Bend("Bend",Float) 1 Strength("Strength",Float) 1 SubShader Tags "Queue" "Geometry" "IgnoreProjector" "true" "RenderType" "Opaque" Cull Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct v2f half2 texcoord TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float Bend float Strength v2f vert(appdata full v) v2f o I don't know what should I write here for rolling ,please help me. v.vertex.y ??? v.vertex.y exp( Bend (v.vertex.x Strength)) something like this but this hasn't twist effect o.vertex UnityObjectToClipPos(v.vertex) o.texcoord v.texcoord return o float4 frag (v2f i) COLOR float2 uv i.texcoord.xy float4 tex tex2D( MainTex, uv) return tex ENDCG Fallback Off Instead of a neat roll, the end of my plane shoots up into the sky!


objects are keep falling I added some screenshots above. When I run the game obstacle are falling rapidly through y axis. So, there's no more obstacle in that ground. If there's ground than those obstacle should stopped. I tried by freezing them. But, when another object hit them they are froze. So, I want ground to stop them. I have another question also. I have player movement. When I will run the program. The Player should be go through z axis. But, The object(player) don't move. PlayerMovement.cs using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 2000f void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(!Input.touchSupported) Still support PC keys if(Input.GetKey(KeyCode.D)) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey(KeyCode.A)) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) else For touch devices if(Input.touchCount 1) var touch Input.GetTouch(0) var touchPos touch.position var isRight touchPos.x gt Screen.width 2f if(isRight) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(Physics.Raycast(transform.position,Vector3.down,0.5f) false) rb.velocity new Vector3(0, rb.velocity.y, 0) rb.constraints RigidbodyConstraints.FreezePositionZ else rb.constraints RigidbodyConstraints.None if(rb.position.y lt 1f) FindObjectOfType lt GameManager gt ().EndGame() PlayerCollision.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame() else if(collisionInfo.collider.name quot END quot ) FindObjectOfType lt GameManager gt ().CompleteLevel() void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) If you look at above source code clearly. So, you might see that I have a Debug.Log right there. But, when I run the game. I don't get any message to console. As a new game developer(learning) I don't know what's happening, what's wrong with this.


Playing an animation all the way through with one quick keypress with Mechanim Unity I have an if statement inside of the Update function that is only called if three other conditions are met. The problem is that right now the function sets a boolean to true which causes the animation to play inside of unity Mechanim. This boolean is only true when I hold down the button, but I would like it to play the whole animation or keep this boolean true for a certain amount of time, thanks and here is my Code. Running and jumping animation if (Input.GetKey (KeyCode.W) amp amp (Input.GetKey (KeyCode.Space)) amp amp otherAnimation false) anim.SetBool ("isRunningAndJumping", true) else anim.SetBool ("isRunningAndJumping", false)


Unity frame rate drops stall I have an issue where my game suddenly stops for a second and then continues. And I think it has something to do with my performance so I took at look at the profiler I tried to take a screenshot as soon as the crack happened However, since I am a bit new to optimization could anyone give me a helping hand on what might be the problem here?


In Unity, is there a difference between Vector3.down and Vector3.up? I've noticed numerous tutorials and examples using something like "transform.up 1" or " Vector3.up" instead of simply saying "transform.down" and "Vector3.down". Is there a good reason for this, or is it simply a style difference? I'm specifically thinking about downward raycasts, if that matters at all.


When I shoot from a gun while walking, the bullet is off the center, but when stand still it's fine. (Video Included) I am making a small project in Unity, and whenever I walk with the gun and shoot at the same time, the bullets seem to curve and shoot off 2 3 CMs from the center. When I stand still this doesn't happen. This is my main Javascript code script RequireComponent(AudioSource) var projectile Rigidbody var speed 500 var ammo 30 var fireRate 0.1 private var nextFire 0.0 function Update() if(Input.GetButton ( quot Fire1 quot ) amp amp Time.time gt nextFire) if(ammo ! 0) nextFire Time.time fireRate var clone Instantiate(projectile, transform.position, transform.root.rotation) clone.velocity transform.TransformDirection(Vector3 (0, 0, speed)) ammo ammo 1 audio.Play() else I assume that these two lines need to be tweaked var clone Instantiate(projectile, transform.position, transform.root.rotation) clone.velocity transform.TransformDirection(Vector3 (0, 0, speed)) I just started Unity, and I might have a difficult time understanding some things. EDIT Here is a video http www.screenr.com 2pxH (If there are any more mistakes in my code, feel free to edit it.)


Creating multiple levels in Unity without duplicating scripts I'm trying to create a falling word typing game like z type. I have used the code provided here I want to create multiple levels in the game, and it seems like I need to make some changes in the code for each level. For example, in the word display file, I want the active word to be changed to red for level 1 and blue for level 2. So I created a copy of my level 1 scene, created a duplicate WordDisplay script file, changed the code for active word to blue.... public class WordDisplay MonoBehaviour public Text text public float fallSpeed 1f public void SetWord (string word) text.text word public void RemoveLetter () text.text text.text.Remove(0, 1) text.color Color.red ... Here's the duplicate script I made public class WordDisplay1 MonoBehaviour public Text text public float fallSpeed 1f public void SetWord (string word) text.text word public void RemoveLetter () text.text text.text.Remove(0, 1) text.color Color.blue ... Then I made a copy of the WordSpawner as well because I was getting an error I had to change the method's return type to to WordDisplay1 and then got one more error which was in the Word file, leading to more changes... public class WordSpawner MonoBehaviour public GameObject wordPrefab public Transform wordCanvas public WordDisplay SpawnWord() ... public class WordSpawner1 MonoBehaviour public GameObject wordPrefab public Transform wordCanvas public WordDisplay1 SpawnWord1() ... Then I created a duplicate of the word prefab and selected the appropriate word spawner file... All of this seems like too many changes for a simple colour. Is there a better way to have multiple levels without having to create a duplicate of all these files and the word prefab?


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.


Unity how do I make an input only available to the code? I have a simple function attached to a button. I then decided to change it by adding an input. The problem is that the function won t run unless I specify the input in Unity via the inspector. I don t want to do that because it will affect the function and I have already changed it inside. I already set the input when I run the function so there s no need to set it again in Unity this is a problem because the input is going to be different depending on different scenarios. How can I overcome this? public void Eruption(string biome) if (biome sea ) do something


Framerate drop from 160 to 56 59 when upgrading Unity to 2020 I just updated to Unity 2020.2 from Unity 2019.4. I use Ubuntu 2020.10. Everything is super fast but the framerate is less than 60 FPS, precisely between 56 and 59 FPS, for all my Android project. With Unity 2019.4, it was more than 160 FPS. Even Unity Sample scene has this framerate. Is this bug on my laptop or a configuration set by Unity? How can I edit it to get my previous framerate?


How do I stop gyroscope controlled camera from jittering when holding phone still? I have here a simplified version of my gyro controlled camera with a sensitivity modification (a side effect of increasing sensitivity is that the jitteriness is exacerbated). public class GyroControl MonoBehaviour private Transform rawGyroRotation Vector3 gyroAdjust SerializeField private float smoothing 0.1f void Start() Input.gyro.enabled true Application.targetFrameRate 60 rawGyroRotation new GameObject( quot GyroRaw quot ).transform rawGyroRotation.position transform.position rawGyroRotation.rotation transform.rotation private void Update() rawGyroRotation.rotation Input.gyro.attitude gyroAdjust rawGyroRotation.rotation.eulerAngles 2 increase rotation sensitivity transform.rotation Quaternion.Euler(gyroAdjust) transform.rotation Quaternion.Slerp(transform.rotation, rawGyroRotation.rotation, smoothing) When in motion, the jittering isn't noticeable. But when you hold the phone still, there's what I assume to be just analogue noise that causes jittering. I would really appreciate any help or advice on how to add a filter or something to reduce the jittering for this kind of controller. Thanks.


Unity Build Failed Duplicate Class I'm here struggling for hours to build my game (android) and 'Execution failed for task checkReleaseDuplicateClasses' Duplicate class androidx.annotation.AnimatorRes found in modules androidx.annotation.annotation 1.0.0.jar (androidx.annotation.annotation 1.0.0.jar) and androidx.annotation.annotation 1.1.0.jar (androidx.annotation.annotation 1.1.0.jar) Duplicate class com.google.android.gms.auth.api.signin.zaa found in modules classes.jar ( com.google.android.gms.play services base 17.0.0 ) and classes.jar ( com.google.android.gms.play services base 17.1.0 ) ... are just two examples of the 486 warnings I'm getting. Can anyone help a noob out? Thanks so much for your time!


Instantiated object not tracking collision I have an issue, and I'm not sure why it's happening. I have a prefab that I've built in a colour changing game. It has the following Four 2D objects that if they collide with the player (2D collider attached to all), they cause the player to die. One 2D object that if the player strikes, it generates a duplicate of itself with the Instantiate function. All 2D objects are created The four objects that cause the player to die are being created as normal and continue to cause the player to die. However, the object that instantiates the prefab and increments the score can no longer be collided with. The player appears to pass behind it. I'm pasting my code below. I would really appreciate if anyone can offer advice on this void Update () if (Input.GetButtonDown("Jump") Input.GetMouseButtonDown(0)) thing.velocity Vector2.up bounciness scoreText.text score.ToString() private void OnTriggerEnter2D(Collider2D collision) if (collision.tag "plusScore") score Destroy(collision.gameObject) Instantiate(barrier, new Vector2(transform.position.x, transform.position.y 7f), transform.rotation) return if(collision.tag ! currentColour) Debug.Log("You DIED!") SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) score 0


How to properly create a handle for setting moving platform's target position in Unity? As the title suggests, I am trying to set up a handle for setting target position of a moving platform. I have an empty GameObject(targetPos) and this is what I want to use for setting target position of the moving platform. Here is the code I have for it so far but it does not seem to work correctly and I am not sure what is wrong. The problem is, the empty gameobject's transform is not using correct position for moving platform to go to. Not that I put the empty gameobject as the child of the moving platform. using System.Collections using System.Collections.Generic using UnityEngine public class MovePlatform MonoBehaviour public Transform targetPos private Vector3 initialPosition, targetPosition, targetPosDebug public float speed 3 public bool loop void Start() initialPosition transform.position SetTargetPosition(targetPos.position) void Update() transform.position Vector3.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) if (transform.position targetPosition) if (loop) SwitchDirection() public void SwitchDirection() if (transform.position initialPosition) SetTargetPosition(targetPos.position) else targetPosition initialPosition private void SetTargetPosition(Vector3 localPosition) targetPosition initialPosition localPosition targetPosDebug targetPosition void OnDrawGizmos() if (Application.isPlaying) Debug.DrawLine(initialPosition, targetPosDebug, Color.red) else Debug.DrawRay(transform.position, targetPos.position, Color.red) Gizmos.DrawSphere(targetPos.position, 1.0f)


Storing stats for multiple tiers of upgrades on an item I have one script for all my weapons (I have 3 weapons in total) and each of these 3 weapons has 3 different tiers. I'm currently using a method to set the values, like this public void SetTier1Value() if (weapon1IsActive true) damage 6 fireRate 18 etc... if (weapon2IsActive true) damage 5 fireRate 20 etc... and like this for the rest of the weapons and tiers All the weapons and all the tiers will have the same variables, the only difference between them are the values of their stats. I know that the way that I'm doing stuff is over complicating a lot. I want to fix so in the future it's easier to add new weapons and the code in general isn't that bad to change. What I want from this script is to be able to change the values of the weapon easily by code. What ways can I do this?


Batch Combine multiple Graphics.DrawProcedural Calls in Unity I have multiple calls to Graphics.DrawProcedural in my Unity project. E.g. I'm drawing 1000 procedural geometries that share the same material and get their positions meshes from a ComputeBuffer. At some place in my code I'm doing something like this foreach(ProceduralGeometry pG in proceduralGeometries) pG.Draw() Where draw sets the Materials buffer accordingly and calls Graphics.DrawProcedural. Is there anything I can do to batch all these geometries together? Currently I perform over 1000 DrawCalls (seen in the frame inspector) which happen to be very expensive performancewise. Thanks in advance!


is mvc design pattern good for developing video games? how mvc design structure works in game development and specially in unity game development. I know what mvc is and how it works but in coding structure for game development specially in unity I don't know how it really works. as you may know is it a good structure for developing video games? if its a yes, why and how it should be used? thank you for helping


Unity how to put a target under a character's feet that follows ground model contours? In my current projects, one of the power ups needs to place a target marker centered on the position of the player triggering it the actual design for this is TBC, but will be a circle with a radius of 10 units. The ground for the playing arena is a model, and not flat. Assuming that I use a texture to show this target area, how can I have this texture render following the contours of the ground? Alternatively, any other approach to solving this would be appreciated. Thank!


unity3d AI terrain detection My goal is to have my animals walk around within a certain range. Everything works except for when it comes to the y axis. I can choose a position for it to walk and it will go there but I have no way of telling the height of the terrain at the selected point, or at the points all along the way. Im wondering how I can have my npc's always walk on the ground rather than walking through the ground. My code is here if it helps, but my problem is pretty straight forward. if(timer 0) Look at target myTransform.rotation Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (walkToPosition myTransform.position), rotationSpeed Time.deltaTime) if(Vector3.Distance (walkToPosition, myTransform.position) gt 1) Move towards target myTransform.position myTransform.forward walkSpeed Time.deltaTime anim.CrossFade("walk") else walkToPosition.x Random.Range(initialSpawn.x walkDistance, initialSpawn.x walkDistance) walkToPosition.z Random.Range(initialSpawn.z walkDistance, initialSpawn.z walkDistance) timer walkCooldown anim.CrossFade("idle") Debug.Log (walkToPosition) EDIT I am doing this project in Unity3d. I do not need to know how to render this, all I am looking for is some kind of function or something that I can use to tell the character to walk along the ground rather than walking through it. At the moment when I set a new walk to position, the Y coord is 0, which means the character is going to forcibly go to the 0 axis without even considering the terrain.


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


How do I draw a context menu next to my object? I want to show a menu next to an item in an inventory. This is what I try to rebuild I do this by placing a canvas in 3D world space next to the inventory As I don't want the menu to be rotated, I rotated the menu the opposite X value as the camera. The camera has an X rotation of 11, so I rotate the menu by 11 to make it look straight Since I don't want the menu to get stuck in the case, I move it closer to the camera One can see that the menu is now offset to the left and to the top because of the camera perspective. How could I offset the menu in such a way that it still aligns with the right top corner of the item? Thank you!


Unity Nav mesh lading data each frame Hey all I had a question, I was looking into my game's performance and noticed this in the profiler Is there any way to optimize this such as pre generating tiles so it doesn't have to do it each update ) ?


How can I flip a coin? I am working in unity and have flattened out a cylinder object to make a coin for a 3d coin flipping game, but I am not sure how to get the coin to flip when the player swipes across it and allow for a double flip if the player swipes over it a second time while in mid air. here is what I have tried using System.Collections using System.Collections.Generic using UnityEngine public class CoinFlip MonoBehaviour private Vector3 start private void Start() start gameObject.transform.position void Update() transform.position transform.right Mathf.Sin(Time.time 0.45f) 0.025f void OnEnable() gameObject.transform.position start


Unity 2109.3.4 apk fails to install on to quest Hello's I was able to successfully sideload APK's on to the quest for a while now however when I updated to unity 2019.3.4 side quest is now unable to successfully load a built APK onto the oculus quest. Here is the error I receive, INSTALL FAILED NO MATCHING ABIS Failed to extract native libraries, res 113 I have tried numerous things and am a bit stuck. Any help is appreciated List of attempts Tried with SDK included in unity Tried custom android studio location Tried switching from MONO backend and enabling Arm 64 Tried lowering min to the lowest API level Tried updating all SDK tools in android studio Tried custom ndk, unable to get one unity is happy with Tried clearing cache and uninstalling prev install


Unity Facebook WebGL build... Does this work or not?!?! Getting conflicting answers So here is the facebook documentation.. It seems to be saying you can output a Facebook WebGL build from Unity and upload it. It does not work for me, I get this message when I upload. "Games must reference one of our supported SDKs via our CDN." Theres also this thread, with people saying it is not supported. https forum.unity.com threads facebook instant games support html5.499198 Yet the latest version of Unity has a WebGL option when building to Facebook platform. What is going on? Does or doesn't this work?


Effects of collisons broken glass, damaged cars, how are they created? My question is related in particular to achieving the effects of collision in game engine, how is this done? I have searched a bit, read from the internet and went through a few tutorials, and saw that one way to create one of the effects, explosion, or something breaking is to create the model in pieces, and apply force (in a game engine such as Unity 3D) to make the pieces fly off. It seems to be a solution, but it doesn't address the problem of items that are vaporized in a big explosion, with so many pieces. How is this done? Basic methods and tricks etc would be helpful. Secondly, the problem of things bending and getting damaged on impact, such as a car's front end destroyed when it hits a wall? How is this done? One thing that comes into my mind is to create each component of a car in a different state as an animation in 3Ds Max or Maya, and then in the engine, according to the collision, switch the model state in the time bar. Is this how it is done? Finally, what about materials, such as net of a basketball net, or a soccer goal net for example? Effects of ball hitting it can be calculated and applied in a script, but how to make the net bend and stretch with it? Is it done through models or materials? Also what about a flag fluttering in the wind? My questions are specific to game engines, particularly Unity3D. Some good links on the subject would also be helpful.


Building a game project in C for Unity in VS? Say that a project needs to be created from scratch for later use in Unity, for scripts. What is the ideal way to setup this without using a template in Visual Studio? Can this be created in C with some simple classes and one or two game loops?


LeanTween How to check if gameObject is destroyed? I am trying to animate a gameObject using LeanTween which has got destroyed already. The MissingReferenceException occurs in LeanTween.setOnUpdate() The null check doesn't work either (gameObject ! null) I have used LeanTween.cancel(gameObject,false) but it still throws an exception.


The type or namespace name OpenCVForUnity' could not be found I am working on face traching in unity3D I have downloaded and imported the sample project on "FaceTracker Sample using OpenCV for Unity". But when I tried to runned the project,its showing me the error.Below is the screen shot of the error What will be the issue?can anybody help out please? I am using unity(5.0.0f4(64 bit))


Why does Unity not follow the z value when drawing text? I'm currently working on the credits of our game. For this I'm using multiple elements in a canvas I want the order that these elements are drawn in to be as follows, I gave them a z value based on this Z Object Object type 0 Text (The actual credits) Text 1 Hider (Green for demonstration) Sprite 2 Divider (The grey line) Sprite 2 Gametitle Text The camera has a z value of 10. The canvas is in "Screen Space Camera" render mode. But for some reason Unity is not drawing these items based on these Z values As you can see, the Divider is drawn over Text, but Text is above Hider and Gametitle. Why is this happening and what can I do so the credits get properly drawn?


Unity Photon Networking Cant understand OnPhotonSerializeView In all tutorials I see that an object sends data over the network and receives the data. For sync in the same method Code void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.isWriting) stream.SendNext (transform.position) stream.SendNext (transform.rotation) else Debug.Log("never gets called ") never gets called... transform.position (Vector3)stream.ReceiveNext () transform.rotation (Quaternion)stream.ReceiveNext () But when I test my code, the lower part, where the data gets received, is never executed! I never see the logs. But the object is SYNCHED because it is set in the inspector But the problem is that the object is not interpolated so it looks kind of funny. So, I need to know how can I make the upper method to work so I can do some interpolation stuff.


How to move the player while also allowing forces to affect it For now, that's how I move the player rb.velocity Vector2.right input.x And I affect him a force while he is damaged by an entity rb.AddForce(Vector2.right force) It works fine, until I try to move while I'm damaged by an entity. Since my velocity input.x while I move, I can't affect any forces to it. I've tried to summarize velocity rb.velocity Vector2.right input.x But then I need to clamp the speed and if I clamp it, my force which is affected to player is also clamped. How can I resolve this problem?


How to share some elements of array with different players on Photon in the same Room? Unity3d I want to assign cards to different players in the room. I've a Class "Cards" that contains an array of 52 cards like this "2 of spades","3 of spades"....... and so on. All i want is to assign random indexes or values to different players on the basis of which I'll instantiate Cards Sprites. How can I do that? I've heard that there are RPC calls but how do I manage to make a "Middle Man" script that would deal with different players?


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.)


Unity mailchimp Klaviyo subscription form Hey everyone so i want to add a subscription form on my game. so far i can send data to a database and display them on a leaderboard, i found a similar question here but its a bit outdated. Ideally i would like to use klaviyo but since this is the only lead i have i might want to get familiar with how it works! using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class MailingScript MonoBehaviour public InputField emailField public InputField nameField public void onClick() StartCoroutine(SendToMailChimp()) private IEnumerator SendToMailChimp() WWWForm form new WWWForm() form.AddField( quot EMAIL quot , emailField.text) form.AddField( quot b 0f079b7af1cef143021ff4236 6cd74c0a6a quot , nameField.text) form.AddField( quot subscribe quot , quot Subscribe quot ) UnityWebRequest www UnityWebRequest.Post( quot https slaga games.us1.list manage.com subscribe post?u 0f079b7af1cef143021ff4236 amp amp id 6cd74c0a6a quot , form) yield return www.SendWebRequest() if (www.isNetworkError www.isHttpError) Debug.Log(www.error) else Debug.Log( quot Registered quot ) this is my code so far but it wont do anything. i have a same code for the database which works!


Unable to move GameObject? This simulates a GameObject swinging between two positions. I am unable to manually move a GameObject on the Y axis using the Unity editor (in scene view) when the following script is attached and running, it's like a solid animation Vector3 min, max void Update() min wall1.position new Vector3(4,0,0) max wall2.position new Vector3(4,0,0) transform.position Vector3.Lerp (min, max, (Mathf.Sin(2 Time.time) 1.0f) 2.0f)


Limit rotation angles for Quaternion I have a short snippet that's rotating the meshes of the wheels as I'm driving forward, but it's also rotating wheels to match the direction I'm turning, and I wish to turn this off completely. Quaternion quat Vector3 position m WheelColliders i .GetWorldPose(out position, out quat) m WheelMeshes i .transform.position position m WheelMeshes i .transform.rotation quat How would I lock what angles I don't want the wheel meshes rotating?


Right way to dispose of a WWW IEnumerator after it has completed Unity What is the quot right quot way to dispose of an Ienumerator coroutine after it has completed?


Lightning not hitting an object? I was following this tutorial, but the lightning is not hitting the other object as the video shows. private LineRenderer lRend private Vector3 points new Vector3 5 private readonly int point Begin 0 private readonly int point Middle Left 1 private readonly int point Center 2 private readonly int point Middle Right 3 private readonly int point End 4 public Transform line private readonly float randomPosOffset 0.3f private readonly float randomWithOffsetMax 2f private readonly float randomWithOffsetMin 1f private readonly WaitForSeconds customFrame new WaitForSeconds(0.05f) void Start () lRend GetComponent lt LineRenderer gt () StartCoroutine(Beam()) private IEnumerator Beam() yield return customFrame points point Begin transform.position points point End line.position CalculateMiddle() lRend.SetPositions(points) lRend.SetWidth(RandomWidthOffset(), RandomWidthOffset()) StartCoroutine(Beam()) private float RandomWidthOffset() return Random.Range(randomWithOffsetMin, randomWithOffsetMax) private void CalculateMiddle() Vector3 center GetMiddleWithRandomness(transform.position, line.position) points point Center center points point Middle Left GetMiddleWithRandomness(transform.position, center) points point Middle Right GetMiddleWithRandomness(center, line.position) private Vector3 GetMiddleWithRandomness (Vector3 point1, Vector3 point2) float x (point1.x point2.x) point Center float finalX Random.Range(x randomPosOffset, x randomPosOffset) float y (point1.y point2.y) point Center float finalY Random.Range(y randomPosOffset, y randomPosOffset) return new Vector3(finalX, finalY, 0) Everything is good except that the lightning is not hitting the other object. What am I missing?


Timer as part of a condition I am using a sensor as the input to my game. When a certain level of force is exerted on the sensor, for a certain amount of time, I want the next level to be reached. How would I do this? I have attached both the timer code and the game code, but I don't know how to use them together. Timer code using UnityEngine using System.Collections using UnityEngine.UI using UnityEngine.SceneManagement public class Timer MonoBehaviour public int timeLeft 5 public Text countdownText Use this for initialization void Start() StartCoroutine("LoseTime") Update is called once per frame void Update() countdownText.text ("Time Left " timeLeft) if (timeLeft lt 0) StopCoroutine("LoseTime") countdownText.text "Times Up!" Invoke("ChangeLevel", 0.1f) IEnumerator LoseTime() while (true) yield return new WaitForSeconds(1) timeLeft void ChangeLevel() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1) Game code using System.Collections using System.Collections.Generic using UnityEngine using System.IO.Ports public class arduino MonoBehaviour SerialPort sp new SerialPort(" . COM6", 9600) Com port and the baud rate of the arduino Material m Material GameObject Sphere void Awake() Sphere GameObject.FindWithTag ("Player") m Material GameObject.FindWithTag ("Player").GetComponent lt Renderer gt ().material void Start () if (!sp.IsOpen) If the serial port is not open sp.Open() Open sp.ReadTimeout 250 Timeout for reading Update is called once per frame void Update () if (sp.IsOpen) Check to see if the serial port is open try string portreading sp.ReadLine() get the string output of the serial port float amount int.Parse(portreading) if ((amount gt 10f) amp amp (amount lt 100f)) m Material.color Color.grey Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) if ((amount gt 101f) amp amp (amount lt 150f)) m Material.color Color.blue Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) if ((amount gt 151f) amp amp (amount lt 201f)) m Material.color Color.yellow Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) if ((amount gt 201f)) m Material.color Color.red Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) catch (System.Exception)


Character Action Sprite Framelength of Late 90's Something, Industry Standards of that Era? I'm making a 3d character that emulates a sprite. The game as a whole emulates the feel of a classic RPG game. Old games like Ultima Online, or Diablo...or similar late 90's generation... For an average run sequence, they must have had general targets for "smoothness". I'm curious if there was an old industry standard of that time for "sprite frames for this action" in game design. Example. A walk sequence in Diablo. How many frames would they have targeted in those years? I'm looking for a general guideline to emulate "that cool 90's RPG". I'd love some advice. If there was no such standard, and designers of old were as hacky as they tended to be, I'll also take a good educated opinion on the matter.


Unity 2D UI Scrollview Stretch settings not staying So I'm trying to make a Scrollviewer and inside that will be aload of boxes stacked on top of each other (the boxes have information in them like the boxes in this screenshot here but they will always be the same size). My problem is that whenever (in Unity's UI) I set where the Text UIs (in game) should be, they will revert to some random place whenever I start the game. For example I set the X 0 Y 50, start the game changes are made and it looks right. But when I exit game mode the X Some random number between 0 1000 Y Also the same, some random number between 0 100. Anyone know why this is happening?


Aim prediction along a parabola How to make a Tower Defence Mortar aim accurately I am building a very basic tower defence game in Unity3D where one tower is your standard long range mortar artillery. I want the projectile it fires to follow a parabola curve to make its movement seem like a mortar. This movement is not dependant on any physics (as I can make a projectile follow a curve but I could implement the Unity3D physics if the method used would benefit from it. My question is What technique should I use to ensure the projectile hits the locked unit whilst taking into account that the unit is moving along a possibly non linear path (defined with my A implementation.) I have not implemented any code as of yet as I wanted to consult the masses for any wisdom you can provide! My initial idea was to fix the time the projectile would take along its parabola curve (regardless of distance) and try and track the position the unit would be at after this time delay. Is this along the right lines or are there alternative methods to consider when aiming a projectile that follows a curved path instead of a linear one? Thank you for your time.


My FollowPlayer script runs AWAY from the player? With the script I'm using, it would make whatever model it was attached to, follow the player when they were close enough. Even though I have NOT updated to the newer version of Unity, the script isn't working how it used to. While it does make the model face towards the player, it no longer follows chases then and I have a suspicion that it may be because I am using rigidbody for the player controls instead of character controller (due to Character Controller no longer working after the latest Unity, which I did NOT update to) Below is a copy of the script I'm using, which is super simple using System.Collections using System.Collections.Generic using UnityEngine public class FollowPlayer MonoBehaviour The target player public Transform Player At what distance will the enemy walk towards the player? public float walkingDistance 10.0f In what time will the enemy complete the journey between its position and the players position public float smoothTime 10.0f Vector3 used to store the velocity of the enemy private Vector3 smoothVelocity Vector3.zero Call every frame void Update() Look at the player transform.LookAt(Player) Calculate distance between player float distance Vector3.Distance(transform.position, Player.position) If the distance is smaller than the walkingDistance if (distance lt walkingDistance) Move the enemy towards the player with smoothdamp transform.position Vector3.SmoothDamp( transform.position, Player.position, ref smoothVelocity, smoothTime) Any ideas why the model isn't chasing the player? I keep changing the settings to see if it's anything silly like that, but no matter what I put it, or what I do, the model just wants to stare but not follow or chase the player Here's a screenshot of the hierarchy And the player model does have the player tag. No matter what values I put into the inspector for the FollowPlayer script, the model with the attached script will not move towards the player. UPDATE I figured out it was because the model with the script attached didn't have a rigidbody component. The problem now is, the model runs away from the player.


Unity in c errors with "the type does not contain a constructor that takes 0 arguments" This is the problematic line datosAguardar datos new datosAguardar () Here is my code public class estadoJuego MonoBehaviour public int puntuacionMaxima 0 public static estadoJuego estadojuego private string rutaArchivo void Awake () rutaArchivo Application.persistentDataPath " datos.dat" if (estadojuego null) estadojuego this DontDestroyOnLoad (gameObject) else if (estadojuego ! this) Destroy (gameObject) Use this for initialization void Start () cargar () Update is called once per frame void Update () public void guardar () BinaryFormatter bf new BinaryFormatter () FileStream file File.Create (rutaArchivo) datosAguardar datos new datosAguardar () datos.puntuacionMaxima puntuacionMaxima bf.Serialize (file, datos) file.Close () void cargar () if (File.Exists (rutaArchivo)) BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (rutaArchivo,FileMode.Open) datosAguardar datos (datosAguardar)bf.Deserialize (file) puntuacionMaxima datos.puntuacionMaxima file.Close () else puntuacionMaxima 0 Serializable definiendo la clase class datosAguardar ISerializable propiedades de la clase public int puntuacionMaxima metodo de la clase constructor de la clase public datosAguardar (int puntuacionMaxima) base (puntuacionMaxima) this.puntuacionMaxima puntuacionMaxima This is the constructor Serializable definiendo la clase class datosAguardar ISerializable propiedades de la clase public int puntuacionMaxima metodo de la clase constructor de la clase public datosAguardar (int puntuacionMaxima) base (puntuacionMaxima) this.puntuacionMaxima puntuacionMaxima


How can I replicate Quantum Break's distortion particle effect? Quantum Break has this fantastic particle effect, it's a distortion effect like broken glass. I want know how I can replicate this effect? You can see it below, and a full video is available on YouTube


Transparent image changing color to very light when used on light background in Unity I'm trying to use this transparent image (transparent brown, with a transparent white shadow) over this background in Unity UI. But the end result is not similar to what I see in photoshop at all. What I expect and what I have inPhotoshop What I get in Unity How can I fix this?


In Unity (2017) is there a way to set the buttons used by Input.GetAxis() programatically? The buttons used for keyboard axis inputs can be set manually via Negative and Positive Button fields for the axis at Edit Project Settings Input Manager. However I'd like to make this a user configurable option which I think means needing to set the button values from a script. I've been looking for a method along the lines of Input.SetAxis("Vertical").positveButton But so far I'm striking out. Is there a way to do this?


Optimizing data structure for my text adventure? In my text adventure I'm making, I store the story data in a hashtable (I'm using unity's javascript unity script since I'm more comfortable with the syntax than C ). The problem is, the way I structure the hashtable means that it gets incredibly bloated very quickly (I've used the same structure in all of my text adventures across multiple languages. It quickly grows to nearly 1k lines long) which makes it hard to edit in the future (especially if I need to go back to edit certain parts later on) Here's the hashtable as it's currently structured public static var story "0" "text" "", "choices" "response1" "text" "", "nextPart" "1" , "response2" "text" "", "nextPart" "2" , "response3" "text" "", "nextPart" "3" , "1" "text" "", "lastPart" "0" , "2" "text" "", "lastPart" "0" If anyone could help me optimize the structure of the hashtable that'll make it so it's more easier for me to edit it in the future, that would be great Quick information for parts that may not be self explanatory "lastPart" indicates to the hashtable parser that the player has died and the number refers to the part where they chose the response choice. "nextPart" refers to the part of the story the response leads to.


Reading from Streaming Assets in WebGL I'm trying to set up my Unity game for WebGL, but I quickly found out that you can't access your streaming assets as you would in a standalone build. For example, I have a code snippet below of how I load in all of my game's text for localization (i.e. get english translations of all text in my UI). public void LoadLocalizedText(string fileName) localizedText new Dictionary lt string, string gt () StreamingAssetsPath will always be known to unity, regardless of hardware string filePath Path.Combine(Application.streamingAssetsPath, fileName) if (File.Exists(filePath)) string dataAsJson File.ReadAllText(filePath) deserialize text from text to a LocalizationData object LocalizationData loadedData JsonUtility.FromJson lt LocalizationData gt (dataAsJson) for(int i 0 i lt loadedData.texts.Length i ) localizedText.Add(loadedData.texts i .key, loadedData.texts i .value) else ideally would handle this more gracefully, than just throwing an error (e.g. a pop up) Debug.LogError( quot Cannot find file quot ) isReady true I've been looking at online examples, and there's a lot of obsolete examples regarding the use of unity's WWW class and php. From what I understand the UnityWebRequest is now the way to go, but I'm confused how to use it with regards to the example above. I'm also trying to figure out how to connect to my SQLite database which is also stored in streamingAssets. public SqliteHelper(string databaseFileName) if (Application.platform RuntimePlatform.WebGLPlayer) ???????? else tag databaseFileName quot t quot string dbPath Path.Combine(Application.streamingAssetsPath, databaseFileName) if (System.IO.File.Exists(dbPath)) dbConnectionString quot URI file quot dbPath else Debug.Log ( quot ERROR the file DB named quot databaseFileName quot doesn't exist anywhere quot ) Now that I can't just open an SqliteConnection, I have no idea if there's a c only solution, or if I have to learn php as suggested from tutorials such as this one. If someone could walk me through how to solve either of these problems I would greatly appreciate it.


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