moving ball on spawn I'm working on some special pick ups on an arkanoid like game. Currently, I have one that should spawn several balls all in a row, right after the original ball hits the paddle. All the additional balls should spawn just above the paddle and then they are passed the vector from the original ball, in which case they should follow that vector, essentially causing a line of balls all traveling in the same direction. The problem I am having is the ball's spawn just above the paddle, but they are spawning in place. Gravity pulls them down, and when they hit the paddle, that seems to be when the vector becomes active and the ball takes off like it should have when it spawned. I'm not sure what I am doing wrong here to keep it from just taking off like that as soon as it spawns. Can anyone see anything here that could be causing this behavior? This is the code for spawning a ball and setting the vector. Instantiate(newBall, new Vector3(paddle.transform.position.x, (paddle.transform.position.y 1), 0), Quaternion.identity) newBall.GetComponent lt Ball gt ().hasStarted true GameManager.pickUpManager.allBalls.Add(newBall.GetComponent lt Ball gt ()) newBall.GetComponent lt Rigidbody2D gt ().AddForce(mainBallVector, ForceMode2D.Impulse) use the original ball's vector3 to follow it directly Here is where mainBallVector gets set, it is a vector3 mainBallVector mainBall.GetComponent lt Rigidbody2D gt ().velocity


Placing Zones in Cities Skylines I'm trying to build a mod that places zones on a keypress. How would I accomplish this? So far I've detected the keypress. But when I modify m blocks in ZoneManager by calling block.setZone(x,y,zone) The block appears to have changed, but only for the moment. When I run the keycommand again, the data appears to have been reset. I never see the zone change in game, only when I print it to the console. string outtext quot quot uint blockCount Singleton lt ZoneManager gt .instance.m blocks.m size outtext quot start n quot for (int index 0 index lt blockCount index ) var block Singleton lt ZoneManager gt .instance.m blocks.m buffer index if (block.m valid ! 0) block.SetZone(1, 1, ItemClass.Zone.Industrial) block.RefreshZoning(0) outtext quot valid quot block.m valid quot position quot block.m position.ToString() quot zone quot block.GetZone(1, 1) quot n quot outtext quot quot Debug.Log( quot OUTTEXT quot outtext) I've tried calling block.refreshZoning() as well, but I'm not sure how to calculate the blockid (.


How to use base.Function() in Unity I am using 3 classes EnemyBullet MonoBehavior EnemyBulletType1 EnemyBullet EnemyBullet Class void FixedUpdate() this.gameObject.transform.rotation Quaternion.Euler (new Vector3 (0,0,90)) EnemyBulletType1 Class override void FixedUpdate() base.FixedUpdate () Do something else here The reason is I'll have many EnemyBulletType classes and I want them all to do a common thing and then do something on their own. Question This code isn't working Error virtual or abstract members cannot be private How is FixedUpdate() defined in the MonoBehviour and how to change it to help my usecase?


Why I can't do a build for Linux? I'm using Unity 5.3.x (free version) on a Windows machine. I would like to build my simple desktop game either for Windows and Linux, but Linux (and Mac) build is disabled. Am i missing something ? Thanks


Using Lerp to zoom in on an object inside an if statement I'm trying to zoom in on an object once the raycast hits it in the Update method, I am using the Lerp method to make the camera movement smoother but it's not working properly. The object only lerps for a single frame. I also tried using a coroutine but the result is still the same. I can't simply just place it outside the if statement because I only need to change the field of view once the raycast hits an object. Here's a sample of my code if (Input.GetMouseButtonDown(0)) ray mainCam.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit)) if (hit.collider.tag.Equals("Building")) SetTarget(hit) mainCam.fieldOfView Mathf.Lerp(mainCam.fieldOfView, newFOV, Time.deltaTime smooth)


Launching projectile from a "canon" I'm working on "Scorched earth" like game just for learning purpose. I can't figure out how to launch the projectile from my tank's position, with a power of X ( 0,100 ),at an angle of Y ( 180,180 ).


Object doesn't instantiated right spot I have weird glitch in my game. When player shoot the gun, bullet is instantiated something called "ShootPoint" transform. This is the ShootPoint's position And this is the code of firing bullet RigidbodyProjectile CreateBullet() GameObject bullet Instantiate(bulletPrefab, shootPoint.position, shootPoint.rotation) RigidbodyProjectile projectile bullet.GetComponent lt RigidbodyProjectile gt () projectile.rigidbody.AddForce(shootPoint.forward.normalized bulletSpeed, ForceMode.VelocityChange) return projectile Simple script to just instantiate bullet prefab in ShootPoint.transform. However when I run the game, bullet generated totally wrong place That picture captured right after creation, even before push the bullet. Here's the updated code for capture that moment, I intentionally throw the error so that makes game stop RigidbodyProjectile CreateBullet() GameObject bullet Instantiate(PrefabManager.GetPrefab("bullet"), shootPoint.position, shootPoint.rotation) Throw the exception throw new System.Exception("DIE") So codes under here will not work RigidbodyProjectile projectile bullet.GetComponent lt RigidbodyProjectile gt () projectile.rigidbody.AddForce(shootPoint.forward.normalized bulletSpeed, ForceMode.VelocityChange) return projectile I don't get it, why my bullet doesn't generated in ShootPoint.transform? I literally removed all components in Bullet and tried again but still had same problem. Funny thing is that this is not always happening, it only happens in certain angles, especially looking down. I already checked hundreds that ShootPoint pointing something wrong direction or reference of ShootPoint was wrong, but no, there was no problem at all! What should I check in this case? It's really annoying issue, because when I shoot little lower angle, it always hit the ground almost instantly after fire. Anyone who knows about this issue, if could be great what should I check, thanks. Additional Info about Bullet I forgot to mention about bullet. It has parent and child, and parent has rigidbody and child has mesh to display. This is because basically bullet wasn't pointing forward so I rotated it to pointing forward and wrapped by empty game object so that eventually it pointing forward direction even mesh is rotated. Here's the screenshot to explain this


Unity3d Rotating a sphere so point lines up with the camera I'm trying to make a world map in Unity that contains a rotating globe with landing sites on the perimeter. What I want is that when a player clicks on the landing site the globe rotates so that the landing site is centered. I've been trying to find the right way to use the Quaternion class but not much luck. Here is my latest attempt which doesn't work. The landing sites are parented to the globe but the camera and globe are separate. void Update() if ( selectedLandingSite ! null) var rotation Quaternion.FromToRotation( selectedLandingSite.transform.localPosition, MainPlanet.transform.forward) var trans Game.Game.Instance.MainCamera.gameObject.transform var lookDirection new Vector3(trans.position.x, trans.position.y, trans.position.z) lookDirection rotation lookDirection var lookRotation Quaternion.LookRotation( selectedLandingSite.transform.localPosition) rotate us over time according to speed until we are in the required rotation MainPlanet.transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime 1) MainPlanet.transform.rotation Quaternion.RotateTowards(MainPlanet.transform.rotation, targetRotation, 1)


Unity Efficient way to get the average pixel color for a portion of the camera viewport At it's core, the problem I'm trying to solve is this I have a camera (not main) that I would like to project to a 2 pixel RenderTexture. I would like the first pixel to be the average color of all pixels in the left portion of the camera viewport (or a close approximation). And the second pixel to be the average color of all pixels in the right portion of the camera viewport. So far I've looked into doing this via OnRenderImage(src, dest) but I'm open to any suggestions. Same goes with camera resolutions, 256x256 seems like a good starting point but open to suggestions here too. It's worth mentioning that I just threw together a brute force non threaded approach that works but totally tanks FPS (nothing surprising) Any help would be greatly appreciated. This doesn't seem like an incredibly weird downscaling approach but I can't seem to find anything regarding it. There might be a clever way of dealing with this via a shader but I have yet to find it. Bilinear downscaling (which I think is what unity uses by default) sadly does not give the appropriate result. System compatibility is not an issue, Win 10, DX 12.


Color bands over tile when scaling texture in shader I want to have tiles with different sprites on the back. Initally I thought I will mix two textures together and then apply mixed texture to game object. I thought that should be easy, but google returned discussion about shaders and their superiority. After reading about shaders I decided to use shaders instead. Also I am using rather big sprites and I am scaling them down in shader. Kind of want to be sure that tiles look good on big screens also. Also to be sure that game works on smaller screens I change camera distance when game does not fit in the screen. Everything is working nice when tile is "near". But when tile is far away it starts to show artifacts over all surface of tile. It appears that scaling is done not pixel by pixel but in some chunks. Modified shader code (I commented out mainTex because it does not change anything from "bug" perspective) Shader "Custom TwoTextureShader3" Properties Color("Color", Color) (1,1,1,1) MainTex("Main Texture Color (RGB)", 2D) "white" MainTex2("Overlay Texture Color (RGB) Alpha (A)", 2D) "white" Glossiness("Smoothness", Range(0,1)) 1 Metallic("Metallic", Range(0,1)) 0.2 OffsX("Offset X", Range( 2, 2)) 0 OffsY("Offset Y", Range( 2, 2)) 0 Scale("Scale", Range(0, 10)) 1 SubShader Tags "RenderType" "Transparent" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard alpha fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex sampler2D MainTex2 fixed OffsX fixed OffsY fixed Scale struct Input float2 uv MainTex float2 MainTex2 half Glossiness half Metallic fixed4 Color void surf(Input IN, inout SurfaceOutputStandard o) float4 mainTex tex2D( MainTex, IN.uv MainTex) fixed2 offsetUV fixed2( OffsX, OffsY) float4 overlayTex tex2D( MainTex2, IN.uv MainTex Scale offsetUV) half3 mainTexVisible mainTex.rgb (1 overlayTex.a) half3 overlayTexVisible overlayTex.rgb (overlayTex.a) float3 finalColor (mainTexVisible overlayTexVisible) Color o.Albedo finalColor.rgb o.Albedo overlayTex.rgb o.Metallic Metallic o.Smoothness Glossiness o.Alpha max(mainTex.a,overlayTex.a) o.Alpha 1 ENDCG FallBack "Diffuse" Tiles looks good when they are near Tiles looks awfull when they are far away Currently I am thinking about using two Meshes for single tile, so that game never hints about what is on the back of the tile even when graphics hardware really want to.


Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help! i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set This is rotation of character my script is attached to And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions. this is the script public class ScreenCharacterController MonoBehaviour private Camera mainCamera private CharacterController character private int leftFingerID 1 private int rightFingerID 1 private Vector2 leftFingerInput private Vector2 rightFingerInput private float xAxisRotation private float yAxisRotation SerializeField private float minXRotation SerializeField private float maxXRotation SerializeField private float minYRotation 25f SerializeField private float maxYRotation 25f SerializeField private float cameraRotationSpeed 20f void Start() mainCamera Camera.main void Update() for touch TouchInput() for calculating rotation vaues CalculateAndClampRotation() RotateCamera() void TouchInput() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) Left Touch if (touch.position.x lt Screen.width 2) leftFingerID touch.fingerId Right touch else rightFingerID touch.fingerId else if (touch.phase TouchPhase.Moved) Left Touch if (touch.position.x lt Screen.width 2) if (leftFingerID touch.fingerId) Right touch else if (rightFingerID touch.fingerId) rightFingerInput touch.deltaPosition Time.smoothDeltaTime else if (touch.phase TouchPhase.Ended touch.phase TouchPhase.Canceled) if (touch.fingerId leftFingerID) leftFingerID 1 else if (touch.fingerId rightFingerID) rightFingerID 1 rightFingerInput new Vector2(0, 0) void RotateCamera() Quaternion currentRotation mainCamera.transform.localRotation Quaternion targetRotation Quaternion.identity targetRotation Quaternion.Euler((mainCamera.transform.localRotation.x yAxisRotation), (mainCamera.transform.localRotation.y xAxisRotation), 0f) mainCamera.transform.localRotation Quaternion.Slerp(currentRotation, targetRotation, 0.5f) void CalculateAndClampRotation() xAxisRotation rightFingerInput.x cameraRotationSpeed yAxisRotation rightFingerInput.y cameraRotationSpeed xAxisRotation Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation) yAxisRotation Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation)


How unity works on Web How Unity can work on Web if the code is written in C ? I understand that you can compile the C code to a shared library and use it in Java (for Android) in ObjectiveC (for iOS) to enable Unity on multiple platforms, but you cant use shared library on JS. Does Unity do language to language translation from C to JS to enable Unity on Web? As I understand now starting from Unity 5.0 it even doesn't use Unity Web Player.


View individual UI Rect boxes when multiple UI elements are selected? I have 2D UI layout with multiple text boxes over the canvas, I need to easily be able to see where the Rect boxes for each are positioned, so that I can see where the safe areas are for placing buttons etc. Selecting each individual item shows its own individual Rect box, but selecting multiple items just shows one big box around all of them. Is there a way of selecting multiple items and see each individual Rect box? It's extremely time consuming having to go and check each one individually.


Unity Render an animated texture to a screen I'm looking for a way to write a typed text on a texture, and then render it on a screen in the game it's just the screen of a computer where a scientist is typing text on. The texture will be already generated it will have several textures in it. I can't find any obvious way to do a simple render to texture with unity, how could I do that ?


SSAO in my unity games has flickering lines at the top and right side of the screen I've tried both the built in unity ambient occlusion that comes with the post processing stack, as well as another one ported from the Microsoft MiniEngine by someone https github.com keijiro MiniEngineAO. Both of them have the same issue pictured below with these dark lines and the occlusion on the faces around the lines seem to flicker as the camera moves. I've been trying to solve this issue by using the Microsoft MiniEngine AO and changing the compute shader. In one of my attempts, I changed the output of the shader from the calculated occlusion Occlusion OutPixel lerp(1, ao, gIntensity) to the depth texture UV to be sampled Occlusion OutPixel QuadCenterUV.x (QuadCenterUV probably being the center of the UV to sample for the 4 depth texture samples ) Fetch four depths and store them in LDS ifdef INTERLEAVE RESULT float4 depths DepthTex.Gather(samplerDepthTex, float3(QuadCenterUV, DTid.z)) else float4 depths DepthTex.Gather(samplerDepthTex, QuadCenterUV) and this was the output With a similar effect on the Y axis. I think that may be the cause, as the distortion of the UVs matches the distortion of the effect. I don't know how to fix this, because I don't have enough knowledge about RWBuffers or compute shaders. My terrain is generated by a noise function as a 2D array, constructed into a mesh, the mesh runs Mesh.RecalculateNormals(), and then is sent to the Mesh Filter. What is the issue here, and how can I fix it, or can anyone fix it for me?


Instantiate a prefab on button press and keep it dragged So far the gameObject is created, but I need to click on the object a second time, in order to start the Drag event. Here's the script where I use the button to spawn a prefab public void SpawnPrefab(Transform prefab) clicked false Vector3 mousePosition, targetPosition mousePosition Input.mousePosition targetPosition Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,distance)) prefab.position targetPosition if(isAlreadyClicked false) Instantiate(prefab, prefab.transform.position, prefab.transform.rotation) isAlreadyClicked true Debug.Log(clicked) I call this Drag event from another script inside the spawned gameObject though void OnMouseDrag() cursor.setGrab() if(this.transform.parent null this.transform.parent ! null) drag the component Vector3 curScreenPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) Vector3 curPosition Camera.main.ScreenToWorldPoint(curScreenPoint) offset transform.position curPosition if(this.gameObject.CompareTag("Component")) mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(false) if(this.gameObject.CompareTag("NewComponent")) mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(true) Hope it's clear enough. Any ideas? Thanks in advance! EDIT So I found out that the SpawnPrefab() only works when mouse button is released. Is there any way I can make the buttons work on mouse pressed?


How to handle global Data within a state machine setup? (C ) I am currently building a turn based framework (Unity,C ) I was tired of my former tight coupled systems and opted for a state machine this time, basically all components subscribe to the state Enter and state Exit event. I am aiming for scalability and structure. But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states? Example The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board. The Unit creation logic is and should(?) be handled inside the level script. How does it know where to create which unit? Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state. While leaving the state the level scripts scans the clipboard and creates any assigned units. But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process. Is there a better way?


Serialize ScriptableObject without creating an asset out of it? Is it possible to do something like this? public class SomeScriptable ScriptableObject public MyScriptable myScriptable public void OnValidate() if (myScriptable null) myScriptable ScriptableObject.CreateInstance lt MyScriptable gt () public class MyScriptable ScriptableObject public int MyVar1 public string MyVar2 I tried this but am getting a "Type Mismatch" error in Unity.


How to stop all character movement when jumping against the side of a platform? My Sprite is Moving against a platform. I have a script and an unusual one (that's what one of the member said.) My isGrounded isn't using any rayCasting. I didn't have any problem with it but when I created a platform and jump against it My character would fall down slowly. If I try to move against the platform, I would be able to move and it would appear as if the character was flying. So question is, how can I stop all my movements, jumping everything, when I collide like this with a platform? My Code is using System.Collections using System.Collections.Generic using UnityEngine public class pScript MonoBehaviour public Rigidbody2D rb SerializeField public Transform Points SerializeField public float radius SerializeField public LayerMask layer public bool jump public bool isgrounded false SerializeField public float MoveSpeed SerializeField public float jumpHigh public bool facingRight public Animator animator public Object CallfPanel public Object CallfText public float Move 8f public Vector3 Dir public Vector3 tart Use this for initialization void Start () rb GetComponent lt Rigidbody2D gt () animator GetComponent lt Animator gt () CallfPanel GameObject.Find ("Panel") CallfText GameObject.Find ("Text") Update is called once per frame void Update () RaycastHit hit Debug.DrawRay (transform.position, Vector3.right, Color.white, Move) tart new Vector3 (200, 300, transform.position.z) Dir Vector3.right if (jump true) if (Physics.Raycast (tart, Dir, out hit, Move)) jump false float horizontal Input.GetAxis ("Horizontal") animator.SetFloat ("speed", Mathf.Abs (horizontal)) isgrounded isGrounded () rb.velocity new Vector2 (horizontal MoveSpeed, rb.velocity.y) if (Input.GetKeyDown (KeyCode.Space)) jump true if (isgrounded amp amp jump true) isgrounded false rb.velocity new Vector2 (0, jumpHigh) if (isgrounded false) jump false changeDirections () private bool isGrounded() if (rb.velocity.y lt 0) foreach (Transform points in Points) Collider2D collider Physics2D.OverlapCircleAll (points.position, radius, layer) for (int i 0 i lt collider.Length i ) if (collider i .gameObject ! gameObject) return true return false public void changeDirections() float horizontal Input.GetAxis("Horizontal") Vector3 theScale transform.localScale if (theScale.x 1) facingRight true else facingRight false if (horizontal gt 0 amp amp !facingRight horizontal lt 0 amp amp facingRight) theScale.x 1 transform.localScale theScale public void showTextDuration() float lifetime 4.0f Destroy (CallfPanel, lifetime)


How can I provide an instance of a certain script to all scripts that need it? Problem Whenever a player is added to the game (in the form of the server instantiating a player Game Object with a Player component), I want to provide it to every script that needs a reference in other words, dependency injection. Potential Solutions I thought I'd create an IPlayerRequester interface and have the Player script look up all implementing scripts on the client when it's created, but Unity has no interface searching equivalent of FindObjectsOfType lt gt (). More Info The game is multiplayer, where 1 player is the host a client and the server that is joined by other clients. I'm using Mirror. When a new client is added, the Player script's (that was just spawned) callback OnStartLocalPlayer() is invoked, and so far, that's the only way I've found to access the local environment. But because this is the same Player that I'm trying to inject into requesting scripts, I can't just raise an event in that method, so that's out. What would be a good solution here?


Unity3D Creating Sharing light baked levels without updating the game I want to give myself freedom to add more levels after releasing the game. For creating levels I broke down structure and created a tilemap like a structure. here's an example I will add them up to create a level and send it to server from where I can download the JSON in game and read it at run time to place things around. The problem is I want to also use Global Illumination. What I can do is send lightmap data with created level to server and download and use it for lighting after generating level. But what If my map is huge?? I don't want to have lightmap size. The other thing I can do is create light baked prefabs, suggested by this article, https unity3d.com how to light baked prefabs on mobile. But every single object has to be attached to a surface and baked because of shadows. Is there a better approach? Thank you.


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


Dynamic frame rate in Unity I'm developing a 3D visualization tool based on Unity, targeting WebGL. The user rarely interacts with the 3D scene and when he does it's only about adjusting the camera like rotating or zooming the view. I disabled vSync (QualitySettings.vSyncCount) and locked the frame rate to 30 (Application.targetFrameRate) to reduce the CPU usage at least a bit while still having an acceptable level of responsiveness when the user moves the camera around. With 30 fps I get a CPU usage of around 30 . Considering lower end hardware this seems still too high. In order to further decrease CPU usage, I introduced two 'modes' Interactive runs with 30 fps Idle runs with 10 fps I wrote some lines of code to switch between those modes depending on user interaction. So when an input is detected, the application uses more fps and after a certain amount of time without any interaction, the application uses less fps again. It works pretty well so far The app uses 30 in interactive mode and 8 to 10 of the CPU while in idle mode. Setting the idle frame rate to 1, CPU usage is reduced to 1.5 while in idle mode. This is really great. But as expected there's a problem. Basically I locked all the Update() methods to be called only once per second. When the user interacts with the camera, the event will be processed with an expected delay of something around one second. Now the question How can I detect user input immediately while having the application run with a low frame rate and also immediately apply a new frame rate (say 30) without any noticeable delay? Originally I wanted to have some sort of on demand rendering. I've read some posts about how people render to a texture to reduce rendering cost in less interactive scenes. But setting the frame rate dynamically seems like a cleaner solution in my opinion. I also tried to use the FixedUpdate() method to check for inputs and switch to interactive mode, but that didn't work either. Note Also worth mentioning, this approach produces errors in the browser, indicating that the application frame rate should be 0 (not in terms of Unity's target frame rate but as in 'let the browser handle the frame rate'). While this might be a different question it's still related to this topic. Maybe someone has an answer for that as well! Edit 1 As mentioned in the comments below, Unity provides the callbacks MonoBehaviour.OnApplicationPause and MonoBehaviour.OnApplicationFocus to detect whether the application is about to receive or lose focus. However, the problem is this My application nearly never loses focus. While this is a nice additional optimization it doesn't really help me too much. My problem is that the app is idle most of the time while also having focus. It's really just the user staring at the window most of the time. Just to make some more sense I'm targeting WebGL. Unity's sole purpose is to visualize some stuff while the user mainly interacts with some HTML controls. In the rare case he wants to interact with the 3D scene, I want to set the frame rate to say 30. The idea is quot I don't re render the scene too often as long as you don't interact quot . To emphasize In my most relevant use case the application never loses focus. This means, the only reliable indicator to determine when to switch between frame rate profiles is based on user input. Sorry if I wasn't too clear about that ) Edit 2 I posted this topic on the Unity Feedback Page. If you're interested, check it out and leave a vote. Maybe this request gets enough attention to get supported by the Unity developers.


How to disable script component while in game? I'm trying to make a C script to disable the First person controller script component for my character. I'm doing this so that while I'm controlling something else such as a vehicle, the only control script enabled at the time is the vehicle, and vice versa for when I'm not in the vehicle. I did find a tutorial on the Unity Web site for Enabling and Disabling components but it uses a light component as an example, and I have no idea of how to do the same thing with a script component. I really appreciate any help I can get to solve this problem. Thank you This is the code in C provided by the tutorial public class EnableComponents MonoBehaviour private Light myLight void Start () myLight GetComponent lt Light gt () void Update () if(Input.GetKeyUp(KeyCode.Space)) myLight.enabled !myLight.enabled


Managing Unity Scenes during refactoring? Most of my Unity project code is in a visual studio project, and I use Unity for UI Rendering wiring things together. I renamed some fields in an object and suddenly the game, when run in unity, became unrunnably buggy. It turned out that a field I had set in the unity frontend had been unset when I renamed it. What's a good way to avoid these sorts of problems when working with unity? I was using version control and could have reverted to an old build in the worst case, but I couldn't find any human readable Unity Scene files that could have just shown me what I changed.


Visual Studio IntelliSense syntax highlighting not recognizing Unity types Frequently when I open a Unity C script in Visual Studio, the built in Unity Engine types aren't recognized, so I don't get syntax highlighting or code completion hints for things like MonoBehaviour. Sometimes if I delete the script and create a new one it works, but lately nothing I do solves the problem. Is there something I can do?


Push Notification to start a scene I was wondering whether I can use APNs in iOS to trigger an event in my game, like start a scene without user clicking the notification. Is it possible to use remote push notifications for events like this?


Stop animation from playing while waiting to destroy object I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object? C void Die() GetComponent lt Animation gt ().CrossFade(die.name) If the current animation time is greater than 90 of the entire animation length, destroy the object. if(GetComponent lt Animation gt () die.name .time gt GetComponent lt Animation gt () die.name .length 0.9) StartCoroutine(RemoveBody()) IEnumerator RemoveBody() yield return new WaitForSeconds(5) Destroy(gameObject)


How can I fill the white color image to fill within that border in a shape of a glass? I'm using this in 2D canvas. Because I'm doing a health bar and it suppose to fill from the bottom to up but I don't know where to start from here.


In Unity3D, how do I create an efficient scratch card effect? I want to create a scratch card like effect in new Unity UI's new Image tag. I know it's possible with setPixels, but that's prohibitively expensive on mobile devices. Something like this I'd like the user to be able to drag on any part of the image to "scratch off" the top layer and reveal the content underneath it. How can I do this?


Raycast will not hit generated box colliders at initialization In my map class I have an algorithm that is generating and merging box colliders together. These belong to the layer "Ground". After that, in some places on my map I'm generating some new cubes on the fly, and some of these cubes I don't want to generate at all. So, I'm doing a raycast to determine if they should be added or not. I'm doing these raycasts to check if the position they should be generated at have free space to the left and right. For both rays I'm checking if they hit a collider beloning to the layer "Ground". But I don't get a hit at all! I've tried to create two cubes in the editor and assign them to the layer "Ground". If I run the game then I get a hit between these two cubes. But I will never get a hit checking against my generated colliders. I do this logic in the Start method, is there any certain method in the life cycle when I can start to use my generated box colliders?


Bullet physics C script Is imparting force on rigidbody objects I have recently made the simplest gun and bullet script that I could and it works amazingly, except for one problem that I've found. When I attach it to a game object with a rigid body the force of the bullets move the object back with quit a bit of force. But what I can't seem to figure out is why the bullets are imparting force on the object at all. The bullets do not have a rigid body component. The way my guns work is with two scripts, one which acts as a simple spawning point when a key down event is given and what ever object you give it to spawn. The second script is applied to the bullet itself which causes the bullet to have motion through transform.Translate with a speed variable. The best example I can give of this is when I attached two guns to the default unity jet and when I fired, it had enough force to move the jet back against its thrust speed. I really would appreciate any help with this so I can move on with my project. I will provide the code bellow for the two scripts. Thank you public class Shoot MonoBehaviour public GameObject bullet void Update () if (Input.GetKey (KeyCode.Mouse0)) Instantiate(bullet, transform.position, transform.rotation) public class MoveBullet MonoBehaviour public float speed 1f void Update () transform.Translate (0, 0, speed)


In Depth Lockstep Explanation I'm making a multiplayer game built upon a lockstep system and I'd just like a better grasp on the concept. My main question is on how to get every command to simulate at the same time on every client, or rather, on the same points in each client's timeline. I'm using a fixed update of 10 frames per second for simulating every object's position from movement commands (Click and move style) the same way. How do I tell all clients to execute all commands at the same relative time to the first command? Note I'm using Unity3D and a sufficiently accurate physics implementation. I just need to get across every command at the correct time.


Animating two characters (like a fighting game) whose animations are tied together? So, say one character grabs another and throws him against a wall. Are these two separate animations that get attached to each character? Or is this really one animation that somehow involves each character model to itself? I'm using the Unity game engine.


How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?


How to know when the cameras change? I'm working on a script that uses raycasting from the camera's perspective to see what the player is looking at. Pretty standard stuff. The only question is, how to reliably find the camera? Everything I've seen says you don't want to use Camera.main in Update() because performance, so instead you should call it once in Start() and cache it in a field. And that's great, as long as you can guarantee that the main camera will never change. But what if it does? What I'd like is to have some sort of OnCameraUpdated event I can subscribe to that will let me know when the main camera has changed, but I don't see anything like that on the Camera class. Is there any good way to find this out without polling for it?


Rotating UI element using touch for mobile Unity 2D I want to create the above object that will rotate on z axis following the direction of a finger. Like a dial. I have written the following code and attached it to that element private float rotationRate 3.0f void Update() get the user touch input foreach (Touch touch in Input.touches) Debug.Log("Touching at " touch.position) if (touch.phase TouchPhase.Began) Debug.Log("Touch phase began at " touch.position) else if (touch.phase TouchPhase.Moved) Debug.Log("Touch phase Moved") transform.Rotate(touch.deltaPosition.y rotationRate, touch.deltaPosition.x rotationRate, 0, Space.World) else if (touch.phase TouchPhase.Ended) Debug.Log("Touch phase Ended") But the element does not move at all. Any ideas? EDIT Here is a gif for better understanding


How do you set the target location for a navmesh using a GameObject? I am trying to get a GameObject to navigate through a map and get to the exit. I have created a navmesh for the map and given the player GameObject a navmesh agent. The exit is marked with a empty GameObject. Using the unity manual I made this script and atached it to the player function Start () var agent NavMeshAgent GetComponent. lt NavMeshAgent gt () agent.SetDestination(GameObject.Find("exit")) The porblem is that this script gives the error "Assets Scripts enemy.js(4,29) BCE0017 The best overload for the method 'UnityEngine.NavMeshAgent.SetDestination(UnityEngine.Vector3)' is not compatible with the argument list '(UnityEngine.GameObject)'." I think is is because unity wants a vector3 but I have given it a GameObject. How can I get this to work with a game object?


Calculating t value to use with Hermite interpolation I'm developing an FPS in Unity using Photon for networking. The Photon provided interpolation is very basic so I decided to roll out my own using the Hermite spline. It works good and is significantly better than the provided interpolation. However, I was wondering what's the correct way to choose the t value. In a perfect world, it should be incremented by deltaTime timeBetweenPositionUpdates. However, that doesn't work since even if the tickRate is set to 10 for example, sometimes the client sends it at 9.5, and then at 10.2 and so on and so forth. This means that we can't have a constant increment rate for the t value since it'll either lag behind or move too fast and we'll run out of buffered frames. What I decided to do is to send the time between frame updates as well and interpolate using that. But, this also isn't perfect by any stretch of the imagination and the receiving client will soon lag very much behind. What I'm doing now is using a multiplier on the t value such that if there is more frames in the buffer than we want to have then it'll speed the interpolation up, and if there's less than how many we want in the buffer then it'll slow the interpolation down. This works pretty well, but it's a hack I believe. Is there a better way, or a proper way to do this?


Why does my Unity animator state "finish" before the visible motion does? Example The TopAppearing motion boost the alpha of the sprite from 0 to 1 for total of 2 seconds After TopAppearing state has been finished The TopAppearing's transition settings Question Why is the Top's sprite alpha 235 after the TopAppearing animatior state has been finished?


What's the best way to make a game launcher? I am a new game dev, and would like to make a launcher for my games. All my games would be in ONE launcher, and it'd be similar to the Minecraft Launcher. I wanna do it for free too. The main reason I wanna do it is to update my games. I don't have a file server, so the files would be on Google Drive. Thanks!


Unity post processing Bloom lags on mobile I made my (first) game today and noticed, that it looked kind of boring, so I decided to add some bloom to my camera and it was looking waaay better. The only problem was the performance, it dropped down from constant 60 fps to like 20 30, I looked it up in the profiler to be sure and yep, it was the post processing, I saw mobile games which had post processing including bloom, but these games never lagged on my phone. My phone has pretty good specs for a phone (Samsung Galaxy M20) so how do I make my post processing performant, are there some special settings I have to make or is it just my phone?


Unity test Play mode window problem I tried to find an answer to his problem but i wasn't successful. When i press play to test my game, instead of the play mode going to the Game tab and play the game there, with all the unity tabs and options still on the screen, it goes almost full screen, all of the unity window goes to the game mode and i can't see anything but the game, to see the scene, options, etc.. again i need to stop the play mode. For example, if i want to test triggers in play mode, i can't because all i see is the game window. How can i test the game just in the Game tab? Perhaps i changed some setting. I'm not sure if im explaining my problem correctly. Thank you


NullReferenceException Object reference not set to an instance of an object on boolean variable from separate class I'm trying to develop game scenario that able to trigger the alarm with alarm light and siren audio to play. For the testing purpose I set it that to boolean value as "alarmOn" in AlarmLight class. AlarmLight.cs public class AlarmLight MonoBehaviour public float fadeSpeed 2f public float highIntensity 2f public float lowIntensity 0.5f public float changeMargin 0.2f public bool alarmOn false private float targetIntensity public Light light add alarm lights tag as siren void Awake() light.intensity 0f targetIntensity highIntensity void Update() if (alarmOn true) light.intensity Mathf.Lerp(light.intensity, targetIntensity,fadeSpeed Time.deltaTime) ChecktargetIntensity() else light.intensity Mathf.Lerp(light.intensity, 0f, fadeSpeed Time.deltaTime) void ChecktargetIntensity() if (Mathf.Abs(targetIntensity light.intensity) lt changeMargin) if (targetIntensity highIntensity) targetIntensity lowIntensity else targetIntensity highIntensity Then I tried to access that value with LastPlayerSight class and for the testing purpose i was trying to return false as below. alarm.alarmOn (playerPosition ! resetPlayerPosition) Then I tried to play my scene, and I got the error which is the problem with above line of code. This is my LastPlayerSight.cs class public class LastPlayerSight MonoBehaviour public Vector3 playerPosition new Vector3(1000f, 1000f, 1000f) public Vector3 resetPlayerPosition new Vector3(1000f, 1000f, 1000f) public float lightHighIntensity 0.25f public float lightLowIntensity 0f public float fadeSpeed 7f public float musicFadeSpeed 1f directional alarmlight ref private AlarmLight alarm main directional light ref private Light mainLight private AudioSource panicAudio siren audio private AudioSource sirens void Awake() alarm GameObject.FindGameObjectWithTag(Tags.alarms).GetComponent lt AlarmLight gt () mainLight GameObject.FindGameObjectWithTag(Tags.mainLight).GetComponent lt Light gt () GameObject sirenAttachedGameObjects GameObject.FindGameObjectsWithTag(Tags.siren) sirens new AudioSource sirenAttachedGameObjects.Length for(int i 0 i lt sirens.Length i ) sirens i sirenAttachedGameObjects i .GetComponent lt AudioSource gt () void Update() SwitchAlarms() MusicFading() void SwitchAlarms() alarm.alarmOn (playerPosition ! resetPlayerPosition) float newIntensity if(playerPosition ! resetPlayerPosition) newIntensity lightLowIntensity else newIntensity lightHighIntensity mainLight.intensity Mathf.Lerp(mainLight.intensity, newIntensity,fadeSpeed Time.deltaTime) for (int i 0 i lt sirens.Length i ) if (playerPosition ! resetPlayerPosition) sirens i .Play() else sirens i .Stop() void MusicFading() AudioSource audioTemp audio.GetComponent lt AudioSource gt () if (playerPosition ! resetPlayerPosition) audio.GetComponent lt AudioSource gt ().volume Mathf.Lerp(audio.volume, 0f, musicFadeSpeed Time.deltaTime) panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.8f, musicFadeSpeed Time.deltaTime) else panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.0f, musicFadeSpeed Time.deltaTime) I'm beginner of developing such things and can anyone guide me to correct the problem?


Build pipleine between 2 points take rotation into account Given a start point and start rotation and end point and end rotation, how can i find a path from start to end, that takes rotation into account and moves only on the axis. I currently have a code that can handle straight line and a L turn. I want it to be able to handle also S or U turn (like on this image), but i cant figure out how to do it. Below is my current code for handling the pipleine building. How do different games handle that? Like satisfactory fluid pipes on vertical mode. Vector3 endPos endPosition Vector3 startPos startPosition Vector3 dir startRotation Vector3.forward Vector3 diff endPos startPos Conveior prev startTarget int dist1 Mathf.RoundToInt(Vector3.Scale(diff, dir).magnitude) BuildStraight(dist1, ref startPos, dir, startRotation, ref prev) Vector3 endDir endRotation Vector3.forward GameObject temp if (dir ! endDir) temp GameObject.Instantiate(turnRight, startPos, Quaternion.AngleAxis(Vector3.Angle(prev.transform.right, endDir), dir) startRotation) else temp GameObject.Instantiate(straight, startPos, startRotation) temp.GetComponent lt RaycastController gt ().dontIgnoreRaycast() temp.transform.Find( quot DirectionGuides quot ).gameObject.SetActive(false) Conveior t temp.GetComponent lt Conveior gt () if (prev ! null) prev.SetNext(t) prev t diff endPos startPos int dist2 Mathf.RoundToInt(Vector3.Scale(diff, endDir).magnitude) startPos endDir BuildStraight(dist2, ref startPos, endDir, endRotation, ref prev) if (endTarget) prev.SetNext(endTarget) private void BuildStraight(int distance, ref Vector3 startPos, Vector3 dir, Quaternion rotation, ref Conveior prev) for (int i 0 i lt distance i , startPos dir) GameObject go GameObject.Instantiate(straight, startPos, rotation) go.GetComponent lt RaycastController gt ().dontIgnoreRaycast() go.transform.Find( quot DirectionGuides quot ).gameObject.SetActive(false) Conveior c go.GetComponent lt Conveior gt () if (prev ! null) prev.SetNext(c) prev c


Interpolation UNITY taking longer than expected I'm trying to do multiplayer interpolations with the lidgren network (UDP) but the interpolation is taking longer than expected and the message queue is getting full. It's been a week and I still can't find the issue. Here's an approximate code private void Update() if (networkUpdates.Count gt 0 amp amp CurrentUpdate.Finished) var update networkUpdates.Dequeue() CurrentUpdate NextVesselUpdate NextVesselUpdate update StartupInterpolation() private void StartupInterpolation() CurrentVesselUpdate.NextUpdate NextVesselUpdate StartCoroutine(CurrentVesselUpdate.ApplyUpdate()) In the CurrentVesselUpdate class.... public IEnumerator ApplyUpdate() InterpolationDuration NextUpdate.SentTime SentTime for (float p 0 p lt 1 p (Time.delta InterpolationDuration)) ApplyInterpolations(p) Several lerps here yield return null Finished true ApplyInterpolations(1) Several lerps here


Travel over step angle http www.gamasutra.com blogs AdamWinkels 20140220 211306 DevLog 7 Learning How to Walk.php Following the link above I have been able to get my character to move and rotate very smoothly over angled surfaces up to 80 degrees. Anything over that and it begins to clip and wobble when traveling down the surface. The spiders rotation only reaches half of the desired angle. So at 85 degrees it only rotates to 42.5. Going up is a mess, but I have not implemented the fix for that from the link above, so I am less worried about that. Any suggestions? private float RayDuration 0 private float RayAngle 5f private float RayLength Vector2 MovementDirection float OffSetY 5 float OffSetX .5f int GroundMask 1 lt lt 8 void Start() SpiderRect GetComponent lt RectTransform gt () RayLength SpiderRect.rect.height private void TouchHeld(CustomEvent customEvent) if (Input.mousePosition.x gt 400) MovementDirection transform.right else MovementDirection transform.right Vector2 transformUp transform.up Vector2 position transform.position Vector2 rightRayPosition new Vector2(transform.position.x OffSetX, transform.position.y OffSetY) Quaternion rightOffSetAngle Quaternion.AngleAxis( RayAngle, new Vector3(0, 0, 1)) Vector2 rightRayAngle rightOffSetAngle Vector2.down Vector2 leftRayPosition new Vector2(transform.position.x OffSetX, transform.position.y OffSetY) Quaternion leftOffSetAngle Quaternion.AngleAxis(RayAngle, new Vector3(0, 0, 1)) Vector2 leftRayAngle leftOffSetAngle Vector2.down RaycastHit2D rightHit Physics2D.Raycast(rightRayPosition, rightRayAngle, RayLength, GroundMask) RaycastHit2D leftHit Physics2D.Raycast(leftRayPosition, leftRayAngle, RayLength, GroundMask) region move if (rightHit amp amp leftHit) Debug.DrawRay(rightRayPosition, rightRayAngle, Color.red, RayDuration) Debug.DrawRay(rightRayPosition, rightHit.normal, Color.green, RayDuration) Debug.DrawRay(leftRayPosition, leftRayAngle, Color.yellow, RayDuration) Debug.DrawRay(leftRayPosition, leftHit.normal, Color.magenta, RayDuration) Vector2 averagePoint (leftHit.point rightHit.point) 2 Debug.DrawRay(averagePoint, transform.up, Color.cyan, RayDuration) Vector2 averageNormal (leftHit.normal rightHit.normal) 2 Debug.DrawRay(averagePoint, averageNormal, Color.cyan, RayDuration) Quaternion targetRotation Quaternion.FromToRotation(Vector3.up, averageNormal) Quaternion finalRotation Quaternion.RotateTowards(transform.rotation, targetRotation, 10) transform.rotation Quaternion.Euler(0, 0, finalRotation.eulerAngles.z) transform.position Vector2.MoveTowards(transform.position, averagePoint MovementDirection, .15f) else Debug.Log("What")


3 hit combo system plays first attack animation every time So the new input system is out, and we're using it for our game. The next hurdle I'm trying to get over is implementing a melee combo ( E E E). Not 100 sure how to get the new system to execute something like that. Right now my trigger isn't resetting. Images of the animator graph at the bottom public class PlayerController MonoBehaviour Rigidbody2D rigidbody SpriteRenderer renderer Animator animator public float fallMultiplier 2.5f public float lowJumpMultiplier 2f PlayerInputActions inputActions Vector2 movementInput public bool inInteractionZone public int attackCount 0 public float attackTimeout 0.5f bool touchingWall private void Awake() HRHEventHub.OnPlayerDeath HRHEventHub OnPlayerDeath inputActions new PlayerInputActions() inputActions.Player.Move.performed ctx gt movementInput ctx.ReadValue lt Vector2 gt () inputActions.Player.Interact.performed InteractPressed private void InteractPressed(InputAction.CallbackContext obj) TODO add attack timeout Check if we are inside a interaction zone if (inInteractionZone) TODO implement return if (attackCount 0 amp amp grounded) attackCount animator.SetTrigger("Attack") animator.SetBool("ATK1", true) else if (attackCount 1 amp amp grounded) attackCount animator.ResetTrigger("Attack") animator.SetTrigger("Attack") else if (attackCount 2 amp amp grounded) attackCount 0 animator.ResetTrigger("Attack") animator.SetTrigger("Attack")


Combining cubes Issue in Marching Cubes I was trying to implement the marching cubes and combine every little cube this way I get a cube of vertices depending on their surfaceLevel I look for the ones that are below the surfaceLevel and get the edges that relates to them get a vertice out of the edge using the formula on http paulbourke.net geometry polygonise I put every vertex i created based on the edges on mesh.vertices I make the order on mesh.triangles based of the edge number on triTable i combine everything but i get this Here's my code https pastebin.com jqetCk8r. My guess was that the combine order of every marched little cube is not good. I've got no idea know how to solve this. ps the triTable doesn't show in the pastebin, i copied it from the same link above.


Coroutine problem, I don't know what's happening Calling function. private const int deathHangTime 2 private void Die() Debug.Log("1 " Time.time) StartCoroutine(DelayForTime(deathHangTime)) Debug.Log("4 " Time.time) Coroutine IEnumerator DelayForTime(float time) Debug.Log("2 " Time.time) yield return new WaitForSeconds(time) Debug.Log("3 " Time.time) Why doesn't it wait for 2 seconds? Why doesn't it print the 3rd Debug line?


Improve appearance of neon LineRenderer at sharp corners I followed the answer given in how to make 2d neon using linerender and get neon effect nicely, but when I draw a line with a tight circle or overlap nearby lines, I get unsightly triangle artifacts and discolouration I'm using this alpha image And I apply this shader on the LineRender Shader quot Trail Neon quot Properties PerRendererData MainTex( quot Sprite Texture quot , 2D) quot white quot Color( quot Tint quot , Color) (1,1,1,1) MainTexture( quot Sprite quot , 2D) quot white quot MaterialToggle PixelSnap( quot Pixel snap quot , Float) 0 SubShader Tags quot Queue quot quot Transparent quot quot IgnoreProjector quot quot True quot quot RenderType quot quot Transparent quot quot PreviewType quot quot Plane quot quot CanUseSpriteAtlas quot quot True quot Cull Off Lighting Off ZWrite Off Blend One OneMinusSrcAlpha Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma target 2.0 pragma multi compile PIXELSNAP ON pragma multi compile ETC1 EXTERNAL ALPHA include quot UnityCG.cginc quot struct appdata t float4 vertex POSITION float4 color COLOR float2 texcoord TEXCOORD0 UNITY VERTEX INPUT INSTANCE ID struct v2f float4 vertex SV POSITION fixed4 color COLOR float2 texcoord TEXCOORD0 UNITY VERTEX OUTPUT STEREO fixed4 Color v2f vert(appdata t IN) v2f OUT UNITY SETUP INSTANCE ID(IN) UNITY INITIALIZE VERTEX OUTPUT STEREO(OUT) OUT.vertex UnityObjectToClipPos(IN.vertex) OUT.texcoord IN.texcoord OUT.color IN.color Color ifdef PIXELSNAP ON OUT.vertex UnityPixelSnap(OUT.vertex) endif return OUT sampler2D MainTexture sampler2D AlphaTex fixed4 SampleSpriteTexture(float2 uv) fixed4 color tex2D( MainTexture, uv) if ETC1 EXTERNAL ALPHA get the color from an external texture (usecase Alpha support for ETC1 on android) color.a tex2D( AlphaTex, uv).r endif ETC1 EXTERNAL ALPHA return color fixed4 frag(v2f IN) SV Target standard sprite shader, only this part is different. takes the sprite in fixed4 s SampleSpriteTexture(IN.texcoord) makes a colored version of the sprite fixed4 c s IN.color makes the grayscale version fixed n (s.g s.r s.b) 3 So, I've scrapped the previous calculation in favor of this I'll leave the previous one in too, just for reference c (c 3 n c.a) c.a Adds the grayscale version on top of the colored version The alpha multiplications give the neon effect feeling c.g (c.g n c.a) c.a c.r (c.r n c.a) c.a c.b (c.b n c.a) c.a You can add c.a multiplications of colors (i.e. turn c.g to c.g c.a) for less color in your effect this saturates the insides a bit too much for my liking return c ENDCG How can I improve the appearance of these corners, so they look smooth?


How can I scroll animate up lines reading from a string to ui text? This is the reading lines code if (primaryTarget ! null) var lines primaryTarget.description.Split(' n') text.text quot Item found quot primaryTarget.description else text.text quot quot And this is the script of the description The script is attached to each interactable target(item) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class InteractableItem MonoBehaviour public enum InteractableMode your custom enumeration Description, Action public InteractableMode interactableMode InteractableMode.Description public float distance private bool action true TextArea(1, 10) public string description quot quot public void ActionOnItem() if(interactableMode InteractableMode.Action amp amp distance lt 5f amp amp action true) action false Depending on the amount of text in the string I want to show it in the ui Text. If there is one line then just show the text or even if there are two lines. but if there is a lot of text then split the lines and scroll the lines smooth up so the first line will be disappear or pushed up and bottom lines will come up. In the screenshot you can see on the left the text that show in the ui text on the right the text of the description. The ui text can't show all the text and I don't want the text to overlap other ui's or objects so the idea is to make the text slowly smooth scrolling up.


Create fog (smoke) on Unity3D? I'm creating a game where you are inside a boiler room, the problem is I want to create the fog (smoke) to make this more realistic.


Unity 2D Player Shoots at my joystick position Hi I am new to unity and have only a little coding knowledge. Right now I have made my character shoot at my touch position on mobile but when ever I touch the joystick, whick I use to move my character, he shoots there, what should I do to make him not shoot at the joystick when i hold the joystick, any suggestion... heres my code. Shooting code public class Shooting MonoBehaviour public GameObject shot private Transform playerPos void Start() playerPos GetComponent lt Transform gt () void Update() if (Input.GetTouch(0).phase TouchPhase.Began) Instantiate(shot, playerPos.position, Quaternion.identity) else if (Input.GetTouch(1).phase TouchPhase.Began) Instantiate(shot, playerPos.position, Quaternion.identity) else if (Input.GetTouch(2).phase TouchPhase.Began) Instantiate(shot, playerPos.position, Quaternion.identity) Projectile Code public class Projectile MonoBehaviour private Vector2 target public float speed private Shake shake void Start() shake GameObject.FindGameObjectWithTag( quot ScreenShake quot ).GetComponent lt Shake gt () target Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) target Camera.main.ScreenToWorldPoint(Input.GetTouch(1).position) target Camera.main.ScreenToWorldPoint(Input.GetTouch(2).position) Update is called once per frame void Update() transform.position Vector2.MoveTowards(transform.position, target, speed Time.deltaTime) if(Vector2.Distance(transform.position, target) lt 0.2f) Destroy(gameObject) void OnTriggerEnter2D(Collider2D other) shake.CamShake() Thanks in advance


On key press, spawn a collider where my player is facing? I'm trying to create an attack mechanic to my player hero in my 2D Tower Defense game. When I press the Q button I want my hero to do an animation and spawn a temporary collider shaped as a cone at where the hero is looking at. If this collider collides with a GameObject called "Stone" it will decrease its hpValue with a script I made. If there is multiple Stones in the cone I want it to only effect one Stone, chosen either by random or and closest to the hero. How would I go about doing this and how can I detect the direction of where my hero is facing? This is my movement script public float speed Movementspeed Rigidbody2D rbody void Start () rbody GetComponentInChildren lt Rigidbody2D gt () rbody.freezeRotation true void FixedUpdate () Vector2 movement vector new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) rbody.MovePosition (rbody.position movement vector speed Time.deltaTime) A picture visualising what I mean


The camera does not capture movements in z axis I want to make a simple drag and drop card in Unity, where the card pops up a bit towards the screen when the drag begins (lifting effect), and then drops down back on the table when the drag ends. My script looks like this public class Draggable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) public void OnDrag(PointerEventData eventData) this.transform.position new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10) public void OnEndDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) The card is an image, and it is child of the canvas. The render mode for the canvas is Screen Space Overlay. The drag works correctly, but I cannot capture the movements in the z axis. It does capture the movements in the z axis when I change the render mode. However, then the card is too far away in the z axis, and it moves with an offset with respect to the mouse pointer. As far as I understood, I need to do something about realtive distances, but I how can I force the mouse pointer to be on z 0 plane.


Why the update function only call once I asked about this question How to efficiently implement a 7 segment display? in previous post. Now I just add an update function to the last part of the code to display the time(I don't bother the exact time at the moment just want to make sure the number change regularly). However,I'm not sure why the update only run once, I checked the answer in this website, mentioned the root cause is gameobject deactivated(Update function only running once) but this is not my case. I tried with void OnMouseDown() Display(DateTime.Now.Second) , the number does change according to my mouse button so I'm not sure what wrong with Update function. In addition, I assigned all the variable but it still pop out message unassigned reference exception, not sure where the problem. using System using UnityEngine public class ClockDigit MonoBehaviour Assuming you number your segments as follows 0 5 1 6 4 2 3 Store a lookup table for which segments should be active when displaying each digit. static readonly bool , SEGMENT IS ACTIVE new bool , true, true, true, true, true, true, false , 0 false, true, true, false, false, false, false , 1 true, true, false, true, true, false, true , 2 true, true, true, true, false, false, true , 3 false, true, true, false, false, true, true , 4 true, false, true, true, false, true, true , 5 true, false, true, true, true, true, true , 6 true, true, true, false, false, false, false , 7 true, true, true, true, true, true, true , 8 true, true, true, true, false, true, true 9 public Color32 activeColour Color.red public Color32 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) var digit number 10 if (digit lt 0) digit 1 for (int i 0 i lt 7 i ) if (SEGMENT IS ACTIVE digit, i ) segments i .color activeColour else segments i .color inactiveColour public void Update() Display(DateTime.Now.Second) I tried this command also, the infinite loop freeze the Unity and FixedUpdate() command also update the frame only one time. void Update() while(true) Display(DateTime.Now.Second)


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


Why does Unity think my RectTransform has changed? I am working with UI. I want to know when my RectTransform changes its position. I am using transform.hasChanged void Update() if (transform.hasChanged) Debug.Log("Updated Position") transform.hasChanged false However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky. I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property. How can I check to see if my RectTransform has changed its position efficiently and elegantly?


How to create an animation clip that changes whatever color a RawImage has to a certain destination color? I created an animation clip that turns a certain RawImage's color from white to red. I'd like to know how I could change that clip to turn any color that the RawImage might have into red with other words, I don't want to have a specific starting color. Instead the current color shall be used and faded to red.


Space to Switch to Hand Tool in Tile Palette? Hi I just download a Utility called Hold Spacebar for Hand (drag) Tool I read the code and I can understand it, but now I wondering how can I modify this to support the same functionality but works in Tile Palette tab, thanks!


How to solve conflicting OnValidate() functions I have two OnValidate() functions in two scripts, one attached to the Enemy (EnemyScript) game object and the other to the Enemies(EnemiesScript) game object. In OnValidate() in EnemyScript I have the following void PrepareEnemyType(EnemyType enType) by default hasHibernated false if (!hasHibernated) if (enType EnemyType.Green) gameObject.GetComponent lt SpriteRenderer gt ().sprite Resources.Load lt Sprite gt ("Sprites greenEnemy") else if (enType EnemyType.Red) gameObject.GetComponent lt SpriteRenderer gt ().sprite Resources.Load lt Sprite gt ("Sprites redEnemy") else if (hasHibernated) gameObject.GetComponent lt SpriteRenderer gt ().sprite Resources.Load lt Sprite gt ("Sprites greyEnemy") In OnValidate() in EnemiesScript I have the following for (int i 0 i lt enemies.Length i ) if (!enemies i . hasHibernated) enemies i . hasHibernated true based on the above all the enemies should change sprite to greyEnemy sprite, but that doesn't happen. Before I run the application all of them change to greyEnemy sprite initially, then after I run the application some of them change back to their original sprites, and when I stop running the application they sprites remain the same as when the application was running (different sprites). At this point, the only time that they all become grey again is when I make some other edit to either one of the scripts and save it. Then the above transition repeats. I suspect there could be some conflict with the two OnValidate() functions, not certain though. How can I resolve this?


How can I customize scrollbar sensitivity in editor property drawers in Unity3D? A custom property drawer, in my Unity 2017.3 project, has code like this in its OnGUI implementation public void OnGUI(Rect position, SerializedProperty property, GUIContent label) ... EditorGUI.BeginDisabledGroup(maxX 0) scrollX (uint)GUI.HorizontalScrollbar(new Rect(xyPos new Vector2(slHeight, normalizedSize), new Vector2(normalizedSize, slHeight)), scrollX, 1, 0, maxX 1, GUI.skin.horizontalScrollbar) EditorGUI.EndDisabledGroup() EditorGUI.BeginDisabledGroup(maxY 0) scrollY (uint)GUI.VerticalScrollbar(new Rect(xyPos, new Vector2(slHeight, normalizedSize)), scrollY, 1, maxY 1, 0, GUI.skin.verticalScrollbar) EditorGUI.EndDisabledGroup() ... But these scrollbars have a sensitivity of 10 (pressing the up down, or left right, buttons will change the current value by 10 in the respective direction). I need them to have a sensitivity of 1. How can I do it?


In Unity, is there a way to Set a new MeshRenderer? Here is what I want to do in Unity for a given GameObject go new GameObject(). I want to create a MeshRenderer, change its properties and only in the end set it as the component of go. For instance MeshRenderer newmeshrenderer (...) do stuff with newmeshrenderer go.AddComponent lt MeshRenderer gt () newmeshrenderer (or) go.GetComponent lt MeshRenderer gt (newmeshrenderer) But both way fail. What is the correct way of setting a MeshRenderer previously created to be the MeshRenderer of an object?


How do I make a MoveToward() GameObject jump without Rigidbody, CharacterController or Raycast? I have a prefab that is moving from one point to another thanks to MoveTowards(). Currently, I am having trouble with a functionality where the player can press a button and make the object jump, affecting only the Y coordinate. I tried doing the following before putting the MoveTowards() code down void Start() playerInstance Instantiate(playerPrefab, startPos.position, Quaternion.LookRotation(endPos.position), null) speed Random.Range(2f, 8f) currentPlayerInstancePositionY playerInstance.transform.position.y isGrounded true void Update() if (isGrounded) if (Input.anyKeyDown) playerInstancePositionY jumpForce else playerInstancePositionY currentPlayerInstancePositionY else playerInstancePositionY gravity Time.deltaTime currentPlayerInstancePositionY playerInstancePositionY playerInstance.transform.position Vector3.MoveTowards(playerInstance.transform.position, endPos.position, speed Time.deltaTime) I just used custom gravity to decide when the object falls. But the problem I found was that MoveTowards() takes a Start Position, an End Position and a Float in its method. But it cannot change individual coordinate values. As the only control you have over the object is making it jump, I was wondering if there was another way to implement this since the Y value is not being inserted into the prefab before it is given the MoveTowards() function. I am trying to implement the jump mechanic without any RigidBodies, CharacterControllers or Raycasts. Any help would be appreciated.


Best way to create icon for UI , based on 3d model player can use in game I'm trying to figure the best way to create icon (for UI) from my 3d model (object) that player can use in the game. Maybe this is a silly question, but how do you create icon ? Do you create a new scene, place object and use a "shift print" to take screenshots ? Others way ? Thanks


Single Letter Alphabet recognition in AR I am developing an AR game with unity where I need to recognize alphabets in runtime. I have tried vuforia but it does not support single letter recognition. OpenCV is an alternative solution, but I don't understand how to detect text in Runtime with OpenCV. I have also tried object recognition, NFT and markerless tracking. But all of these failed because a single letter does not have enough feature to get detected. I am really new in Augmented reality and image processing. Can anyone give me a guideline or plan what I should do? I am using this letter blocks from amazon https www.amazon.ca gp product B0006MU23W ref s9u simh gw i1?ie UTF8 amp pd rd i B0006MU23W amp pd rd r 22ef1e20 b08e 11e7 91cc bbe5f37c0d0f amp pd rd w wCg3M amp pd rd wg NG8Lg amp pf rd m A3DWYIK6Y9EEQB amp pf rd s amp pf rd r TH85A9MZFVDZPD8YYR5P amp pf rd t 36701 amp pf rd p 09a46553 65cf 45b2 8aaa e9bb559981ab amp pf rd i desktop


Why should I always consider creating and using object pools instead of instantiating the new object on the fly? I have read about this pattern several times (from a best practices perspective) Memory Allocation Instead of instantiating the new object on the fly, always consider creating and using object pools. It will help to less memory fragmentation and make the garbage collector work less. However, I don t know what it actually means. How can I implement it? For example, I can instantiate a GameObject using the Instantiate method of Unity? Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity) Is this use discouraged? What else can it mean?


How to check whether an angle lies within a specific negative to positive range? I'm trying to develop a script that detects if an object's angles are tilting too much. I am new to Unity, and I am sure this is not the best way to test an object's angles, but I am trying to learn C so I'd rather figure that out myself. All I want to know is how to check whether a value is between 101 and 101. I have tried this so many different ways, and even though it is working fine for positive integers, the if statement is not applying the moment that my z angle becomes negative. Here is what I have tried so far (maxangle 101, minangle 101) if(Player.transform.rotation.eulerAngles.z gt Mathf.Sign( 101) amp amp Player.transform.rotation.eulerAngles.z lt maxangle), if(Player.transform.rotation.eulerAngles.z gt minangle amp amp Player.transform.rotation.eulerAngles.z lt maxangle)


Find grandchildren with specific tag I have an empty object that contains multiple children each containing their own child objects. I want to get a list of all the objects containing a specific tag but i don't know the depth of each child object. The following solution only returns the children that have the tag. foreach (Transform child in city) if (child.CompareTag("Zone")) buildings.Add(child)


Mesh does not translate accordingly to WheelCollider So I am trying to implement a car controller script in Unity were the WheelTransform position and rotation is set with every update as the same as the WheelCollider position and rotation, it all works fine except for one thing when translating the WheelTransform, if the car goes slowly, WheelTransform translates as expected, but when the car goes faster, there's a clear offset between the WheelTransform position and the actual position of WheelCollider. Here's the code were WheelTransform position and rotation is set as the same as the WheelCollider position and rotation private void UpdateWheels() UpdateWheelPos(frontLeftWheelCollider, frontLeftWheelTransform) UpdateWheelPos(frontRightWheelCollider, frontRightWheelTransform) UpdateWheelPos(rearLeftWheelCollider, rearLeftWheelTransform) UpdateWheelPos(rearRightWheelCollider, rearRightWheelTransform) private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans) Vector3 pos Quaternion rot wheelCollider.GetWorldPose(out pos, out rot) trans.rotation rot trans.position pos Every single one of the car controller scripts I've found and tried use the same code for this section, I have also tried with 2d sprites without any colliders as WheelTransform but neither the scripts or changing WheelTransform solved the problem. Thanks in advance for the help.


Unity3D Smooth rotation for seek steering behavior I am trying to implement Reynolds' seek steering behaviour, but I am having problems on the rotation part. This is what I have void FixedUpdate() get position of current waypoint Vector3 targetPos new Vector3(path currentWaypoint .x, transform.position.y, path currentWaypoint .z) velocity vector towards target Vector3 desiredVelocity targetPos transform.position calculate the steerforce required for the desired velocity based on current velocity Vector3 steerForce desiredVelocity currentVelocity steerForce new Vector3(steerForce.x, 0, steerForce.z) steerForce Vector3.ClampMagnitude(steerForce, maxSteer) create a move vector to be added to agent's current position Then normalize it so it can be scaled according to the agent's max speed Vector3 moveVector steerForce.normalized moveSpeed Time.fixedDeltaTime transform.Translate(moveVector) How would I do it so my agent will be rotated smoothly based only on the code above? I tried rotating based on the current velocity, but the agents is rapidly rotated in one frame towards the target waypoint. I am not working with rigidbodies. Am I doing something wrong? What am I missing? Thanks, Jack


How can I load a scene when starting a new game if the loading scene have a Main Camera? The problem is that if I turn the camera on enabled in the editor it will show part of the scene mixed with the main menu scene. And if the loading scene main camera is enabled off I will get error Display 1 No cameras rendering. I have two scenes in the Hierarchy. The first is Main Menu. The main menu have a camera. Now I did that when I click on the button START A NEW GAME It will load another scene using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class NewGame MonoBehaviour public void StartNewGame(int SceneIndex) SceneManager.LoadScene(SceneIndex) In this screenshot you can see in the Inspector I'm calling the method StartNewGame and the index 1. Index 1 present the second scene that should be load The Space Station Now in the scene The Space Station I have also a MainCamera under Player. The MainCamera is turned off in the editor. And I need somehow to switch between the Main Menu scene camera and the The Space Station scene camera. If I will turn on the MainCamera in the inspector I will see some objects of the first scene and the second scene and then the game will start without the main menu and the player will fall down. If I start the game when the MainCamera is turned off I will the Main Menu but then when I click on START A NEW GAME it will show me the message Display 1 No cameras rendering. The last screenshot is of the Build Settings Edit Build Settings... I added the two scenes to the build. The first scene at index 0 is the Main Menu the second scene at index 1 is The Space Station


Why I cant change the GUILayout.Button color to green when click on a button? I used a break point and it's getting to the line style.normal.textColor Color.green But not changing the color of the clicked button. And there are no any errors or exceptions. using System.Collections using System.Collections.Generic using System.Diagnostics using System.Linq using UnityEditor using UnityEngine using System.IO public class Manager EditorWindow MenuItem("Tools Manager") static void Manage() EditorWindow.GetWindow lt Manager gt () private void OnGUI() var style new GUIStyle(GUI.skin.button) style.normal.textColor Color.red style.fontSize 18 string assetPaths new string 2 string 0 "Test" string 1 "Test1" foreach (string assetPath in assetPaths) if (assetPath.Contains(".test") var i assetPath.LastIndexOf(" ") var t assetPath.Substring(i 1) if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50))) style.normal.textColor Color.green


Sending position to .net server unity I'm working on a multiplayer game, I created a custom C server using TCPListner. I can't figure out how to send a players position to the server from the client side. I also couldn't figure out how to broadcast the position received from the client side to the rest of the players. Can someone help me with this?


Isometric coords to cartesian coords I'm new to the tilemap feature of Unity, and I'm having a hard time with all those coords. I created a new project, added an isometric tilemap and left all values to their default. In the Unity Editor (and in game at runtime as well), the coordinates of the cells are like this This is pretty disturbing to me and it will be to most players (not programmers) too I guess. I would like something like this However, I can't figure out how to do the transformation. I tried this Vector3 currentWorldPos Camera.main.ScreenToWorldPoint(Input.mousePosition) Vector3Int currentCellPos grid.WorldToCell(currentWorldPos) This gives the coordinates as in the Unity Editor except for z currentCellPos.z 0 Set z to 0 so the coordinates of the cell are exactly as in the Unity Editor Vector3 cartesianCellPos new Vector3((2 currentCellPos.y currentCellPos.x) 2, (2 currentCellPos.y currentCellPos.x) 2, 0) Try to transform the Unity coordinates into cartesian coordinates WRONG RESULT But this calculation gives weird results, not what I expect at all. Do you know how I could transform the Unity coordinates shown in the first screenshot into the coordinates shown in the second screenshot?


Why is my button script not working? Okay so i'm new to C and i made this script. The goal i have in mind is that when the player is on the button and presses a button ( W in this case ) the button is switched from on to off ( or vice versa). The problem i have is that when the character stands on the button and presses W it doesn't always switch its state and i have no idea why. Any info would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class Button MonoBehaviour public bool Pressed false Animator Anim Use this for initialization void Start () Anim GetComponent lt Animator gt () Update is called once per frame void Update () Anim.SetBool ("Pressed", Pressed) void OnTriggerStay2D(Collider2D other) if (Input.GetKey(KeyCode.W)) if (Pressed) Pressed false else Pressed true


Why isn't occlusion culling working correctly? Occlusion culling doesn't seem to be behaving the way I was expecting. I've set the yellow wall as static and have baked an occlusion map using the occlusion window in unity. However when visualising the occlusion the red cylinder behind the wall is still visible despite not being seen in the camera preview. Any clue what I'm doing wrong?


What happens with associated animation clips when I copy a gameobject in Unity? I have a gameObjectOne that has two animation clips move into the screen and move out of the screen. This gameObjectOne has an animator that checks when each clip has to be played. Now I duplicated this gameObjectOne via the edit menu and named the copy gameObjectTwo, and to my surprise the animator and the animations still work. I expected that the animation clips were associated with gameObjectOne but this is not the case.... The animation clips are not duplicated. There are still only two clips and one animator in the project window. But when I click on gameObjectTwo in the animation window, you can see that there are two animation clips associated with gameObjectTwo as well. So my question is how is this possible? And is there a way to see what is "inside" an animation clip file? If I click in the project window on an .anim file, it doesn't say which gameObject it belongs to.


Unity "Convert To Entity" does not work (Render) with "Skinned Mesh Renderer" for Animations I'm trying to make a game with Unity's ECS and Job System. I came across the issue where, Convert To Entity does not support Skinned Mesh Renderer. It does not render the mesh. I need it for animations. On the bright side, Game Object Entity does render Skinned Mesh Renderer. The downside is that, it does not support Physics Shape and Physics Body. Convert To Entity does. I am using Physics Shape and Physics Body for physics. Would anyone mind telling me what options are open to me?


Correct the rotation of a car gun? This script for drive a car by arrows. I added a gun above it to aim at target. My issue here is the rotating of my gun effected by my drive when I turn left or right. How to stop the rotation of my gun to be effected by car turns ? using UnityEngine using System.Collections public class RearWheelDrive MonoBehaviour private WheelCollider wheels public float maxAngle 30 public float maxTorque 300 public GameObject wheelShape public Transform target public Transform gun car here we find all the WheelColliders down in the hierarchy public void Start() wheels GetComponentsInChildren lt WheelCollider gt () for (int i 0 i lt wheels.Length i) var wheel wheels i create wheel shapes only when needed if (wheelShape ! null) var ws GameObject.Instantiate (wheelShape) ws.transform.parent wheel.transform public void Update() Gun rotation Vector3 dir target.position gun car.transform.position Quaternion lookr Quaternion.LookRotation(dir) Vector3 rotationy Quaternion.Lerp(gun car.localRotation,lookr, Time.deltaTime 7).eulerAngles gun car.localRotation Quaternion.Euler (0f,rotationy.y,0f) Drive float angle maxAngle Input.GetAxis("Horizontal") float torque maxTorque Input.GetAxis("Vertical") foreach (WheelCollider wheel in wheels) a simple car where front wheels steer while rear ones drive if (wheel.transform.localPosition.z gt 0) wheel.steerAngle angle if (wheel.transform.localPosition.z lt 0) wheel.motorTorque torque update visual wheels if any if (wheelShape) Quaternion q Vector3 p wheel.GetWorldPose (out p, out q) assume that the only child of the wheelcollider is the wheel shape Transform shapeTransform wheel.transform.GetChild (0) shapeTransform.position p shapeTransform.rotation q


Change rigidbodys default height from floor? I am new to unity and I have a few questions There is a mesh that has a rigidbody and a box collider that I placed on the scene. I also added a generic terrain to the scene from the 3D objects menu. When I put the mesh at a certain height and it drops I notice that it always stops at Y 0.500000. How do I change this default value? What controls this? For example, does unity have it so that when any other type of collider hits the terraincollider the other collider automatically updates the rigidbody to be 0.50000 above it and this only happens when it hits a terrain collider? If this is the case, Is this causing a collision every frame and adjusting it to 0.50000 every frame so it doesnt fall through? Finally, assuming that the Y 0.50000 value above the ground cannot be changed, if I wanted something to quot hoover quot above the ground, would I always need to take that the maximum amount that I can get to the ground is Y 0.500000?


Why players who join late can't see other people data? I want to show the name of the players above their head but I have a problem where people joining late doesn't get other players' name. For example Player 1 joins to the server with the name Peter. Player 2 joins to the server with the name Josh. Peter (Player 1) sees Josh's name perfectly, but when Josh joins Peter's name is not synchronized correctly. My sync code looks something like this SyncVar private string NAME public override void OnStartClient() if(networkPlayerData is null) networkPlayerData BTNetworkController.Controller.playerData NAME BTNetworkController.Controller.playerData.Name SendPlayerNameToServer(NAME) Command private void SendPlayerNameToServer(string name) RpcSetPlayerName(name) ClientRpc void RpcSetPlayerName(string name) gameObject.GetComponentInChildren lt TMP Text gt ().text name So my question is how can I sync data to newly joined players and refresh player names accordingly.


How to control which path a unit will take? This might be a really easy solution that I probably just do not know due to lack of experience so thanks for any and all the help. TLDR at bottom of post. I'm still learning Unity C and I am following Brackey's Tower Defense tutorial series while adding my own twist. The tutorials use levels with only 1 available path for units to walk along. However, the game I am currently developing has 3 separate paths that units can walk along. Essentially, the game is similar to the mobile game Clash Royale with 3 lanes except it is also a tower defense. Here is the current layout The different lanes are empty gameObject labeled as Path1 (red), Path2 (blue), and Path3 (green). The nodes laid out in each path are all children objects of their respective path. Each of the parent path objects contain the following script public class Waypoints MonoBehaviour public static Transform points private void Awake() points new Transform transform.childCount for (int i 0 i lt points.Length i ) points i transform.GetChild(i) Now, following the tutorial, I have also successfully added an enemy that contains this EnemyMovement script public class EnemyMovement MonoBehaviour public float speed 10f private Transform target private int waypointIndex 7 void Start() target Waypoints.points 7 void Update() Vector3 dir target.position transform.position transform.Translate(dir.normalized speed Time.deltaTime) if(Vector3.Distance(transform.position, target.position) lt 0.2f) GetNextWaypoint() void GetNextWaypoint() if(waypointIndex lt 0) Destroy(gameObject) return waypointIndex target Waypoints.points waypointIndex Now, as it currently stands, whenever I have an enemy present on the field, it will successfully run down path2 (blue nodes). However, it will ONLY run down path2. I would like to be able to decide which path the enemy will take. Eventually, the enemy's actions will be decided by an Enemy AI. The player will also be able to spawn units and will be able to decide which path the unit will travel. So to reiterate TL DR Following Brackey's Tower Defense tutorial. Currently, enemy will always default to path2. I need to figure out how to have control over which path, out of 3 options, an enemy or friendly unit will take.


Increment grid by rotation I'm currently working on a grid for snapping objects side by side. My current script is working fine, but only for game objects which haven't been rotated. Here is an example video of the problem https vid.me jN6D The cube at the right has a rotation of Vector3.zero, the left one has been rotated on the Y axis. As you can see snapping works perfectly for the right one, but at 0 15 you can see that the snapping doesn't work well for the rotated cube, that's because I've currently no idea how I can add the rotation in my current script. Here is a snippet of the most important part of code I'm currently using to calculate the grid Vector3 pivotToPoint hit.point nearestGameObject.transform.position float positionX nearestGameObject.transform.position.x Mathf.Round(pivotToPoint.x nearestGameObject.transform.renderer.bounds.size.x) nearestGameObject.transform.renderer.bounds.size.x float positionZ nearestGameObject.transform.position.z Mathf.Round(pivotToPoint.z nearestGameObject.transform.renderer.bounds.size.z) nearestGameObject.transform.renderer.bounds.size.z Vector3 origin new Vector3(positionX, 0, positionZ) Vector3.up 100 if (Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity, layerMask)) previewGameObject.transform.position new Vector3(positionX, hit.point.y, positionZ) previewGameObject.transform.rotation nearestGameObject.transform.rotation Maybe some of you guys have an idea how to solve this, it's driving me crazy. p.s. Here is some guy with a similar problem, but I'm very lost when in comes to adding the solution into my code.


Is it efficient to have a only data MonoBehaviours on lots of game objects? I'm working on a voxel based game and this solution would make the implementation of networking and other features a lot more easier, it is less error prone, easier to edit in the Editor, etc. So the question is How bad is it performance wise to have lots of MonoBehaviours in the scene, if they don't implement any of the MonoBehaviour methods? (So they only have primitive data stored in them)


Coroutine problem, I don't know what's happening Calling function. private const int deathHangTime 2 private void Die() Debug.Log("1 " Time.time) StartCoroutine(DelayForTime(deathHangTime)) Debug.Log("4 " Time.time) Coroutine IEnumerator DelayForTime(float time) Debug.Log("2 " Time.time) yield return new WaitForSeconds(time) Debug.Log("3 " Time.time) Why doesn't it wait for 2 seconds? Why doesn't it print the 3rd Debug line?


Passing properties as arguments such that the resulting class can modify the original I'm really not experienced with c so maybe my whole methodology is wrong but here goes. I'm trying to build a GUI that allows many many parameters to be modified in real time and have a central repository for all those variables. So I am trying to build a wrapper class around the slider so I don't have to explicitly link it to each property in the parameters class manually, and make it easier to add other generic functionalities like events or whatever. So right now I have a UI class that holds the sliders, a slider wrapper class that holds some extra functionality, and a central parameters class. The central class shouldn't have any dependencies of the other two classes. The UI class instantiates the slider wrapper class, and passes a Unity slider object. That part works fine. It also passes the property from the central parameter class to which it should be linked. That's the part I'm stuck on. UI class public class UIParams MonoBehaviour private GeneralParams centralParams reference to central parameters class private Transform mainUI reference to main UI panel private Transform panel1 reference to sub panel private MySlider mySlider1 instance of my slider wrapper class more sliders go here void Start() init centralParams GameObject.FindObjectOfType lt GeneralParams gt () var Panel1 GameObject.Find( quot MainUI quot ).transform.Find( quot Panel1 quot ) sliders mySlider1 new MySlider( Panel1.Find( quot Slider1 quot ).GetComponent lt Slider gt (), pass the actual slider to the wrapper centralParams.Parameter 1) pass the central parameters property to the wrapper more sliders go here Slider wrapper class Code (CSharp) class MySlider private Slider slider object to hold the slider private float sliderValue value of the slider public MySlider(Slider Slider, float CentralParameterProperty) slider Slider reference to Slider slider.onValueChanged.AddListener(delegate update() ) listen for changes to slider, don't want to be checking all the time sliderValue CentralParameterProperty set slider to default value in CentralParams. How do I modify that value??? private void update() sliderValue slider.value how do I change the original value from Central Params without explicitly linking each property manually? Central parameter class Code (CSharp) public class CentralParams MonoBehaviour public Action GeneralUpdateEvent tell other classes when an update has occured SerializeField private float parameter 1 public float Parameter 1 get gt parameter 1 set parameter 1 value GeneralUpdate() more parameters go here void GeneralUpdate() GeneralUpdateEvent?.Invoke() Passing the float CentralParameterProperty into the MySlider instance works to set the default value of the slider. But obviously from that point onwards the slider only modifies the internal variable sliderValue, not the property of the central class. Can I set it up so I pass some object from the UI class into the MySlider on instantiation such that the MySlider instance can both get and set the values of the CentralParams property, without explicitly linking to central class within the MySlider class? Or is this just Wong? Hope that made sense...