How to calculate acceleration distance(frictionless, massless) Object A is moving via. 2D rigidbody by velocity V and in script is defined breaking power P. Every frame of breaking (P Time.deltaTime) is subtracted from velocity V (in other words, ignoring mass). How i can calculate distance D required to slow down to target velocity tV ? I'm not actually using force power but i setting velocity directly with this line of code Vector3 dir transform.TransformDirection(Vector3.up) ship.rb.velocity Vector2.MoveTowards(ship.rb.velocity, (dir maximalSpeed) ship.massModifier, speedGain ship.massModifier) (Don't worry about ship.massModifier, Basically heavier ship hulls are slower) I'm self learning Indie developer and i need this for AI to my game. Enemy in space ship have nothing like space breaks so only way how to slow down is to turn ship by 180 degrees and thrust forward in counter direction.I need to know this to calculate distance from target required to slow down and prevent possible collision with target.


Unity animations threading As one cannot play around with threads themselves, the user made code that uses unity's API is executed on the main thread. I'm sure unity uses some sort of thread management on its own though. Thing is, I wrote some basic UI animation toolkit (rotate, scale, lerp alpha, move and tie events etc) that as being user code runs on the main thread, taking up CPU power, even if they are not vital to be completely synchronized with the logic. (Event connected to them only start other animations). I would like to know if Unity uses another thread for animations as well and if so, is it possible to mark this UI toolkit to be executed on that thread or as I said user code with unity api can be only ever executed on the main thread?


Unity LWRP alternatives for camera stacking I am working on upgrading a project in unity from a 2018 version to the latest 2019. One of the mechanics of the game is an AR (augmented reality) system. Some of the UI elements appear in the 3D world, but clearly as part of the hud. They need to be transformed as the camera moves, but should always be drawn on top of the 3d scene. The old project achieved this via camera stacking. All the AR elements were drawn on a different camera which rendered on top of the 3D camera. The clear flags were set to "depth only" and it removed all other elements from that camera. In the 2019 version of Unity with the Lightweight Render Pipeline (LWRP), the clear flags feature on the camera is missing. To the best of my research, camera stacking has been removed from LWRP. What are my alternatives? How can I now achieve this effect? I would like to stick to LWRP as I am using Shader Graph for many of the effects in the game.


Unity Improvements to skinnedMeshRender.BakeMesh performance or alternatives? I'm running to a situation where I need to do some manual deformation to a skinnedMeshRenderer's mesh vertices after applying some blendskinning. I'm finding that the following code takes 15ms to run. I've calculated the time both by running it 100 times and measuring time difference, and by using the Unity Profiler. Mesh bakedMesh new Mesh() skinnedMeshRenderer.BakeMesh(bakedMesh) The mesh has 7000 vertices. I just need loop through each vertex to get its current (blendskinned) position relative to its gameObject's local origin. The goal is to calculate the amount of deformation it experienced. so something like (pseudocode) for i in vertices deformation i originalVerticies i bakedCertices i It's the call to BakeMesh that is slowing things down, which is required to get bakedVertices i . Is there another way to get backedVerticies i without actually baking the mesh? Maybe some kind of manual calculation to simulate baking but only on the vertices? or perhaps some way to speed up the baking process? Additional info The reason i'm calculating the deformation is to undo unity's automatic linear blend skinning, since at runtime I want to move some bones without affecting the mesh. However, when I move the bones, unity's automatic linear blend skinning kicks in and deforms the mesh, so this is a way to calculate how much it was deformed so I can "Undo" this blend skinnning by adding the deformation back on to the vertices. Perhaps there is a more elegant solution, but I can't find any way to temporarily turn off the automatic linear blend skinning. Note that I need to do this every single frame. I'm currently at 15ms for this script, which is really pushing the 16ms limit to maintain 60fps. When I add other scripts etc into the scene it will for sure be laggy. I would also like it to run at at least 90fps since i hope to use this script in VR in the future.


Unity2D Collision Issue I have a crate setup (in pic below) with a rigid body component, box collider and 3 circle colliders(they allow me to push the crate most of the time without getting stuck on the floor textures which are normal box colliders) As you can see in the pic there are collisions detected between the crate and floor even though they are not physically touching. How can i make the collisions more precise as my crate gets snagged on the floor textures when there is minuscule difference between the floor box colliders?


Is this Possible to force gameobjects (coliders etc) to get stretched based on the aspect ratio of the screen? Well with unity3D, I am in big trouble whenever I use sprites. As for textures I compensate for a evener look by Stretching it (Screen.width amp Screen.height that's fine for low end 2D games). Now If I have an Image and based on content of Image (Let's say I want to add BoxCollider for the walls in image). It works, but for only one aspect ratio. As I am making game for Android. I am having bunch of different resolution amp Aspect ratios. Is this possible to stretch my coliders or other game objects so that I can Work easily???? please help me. I am in a rush (


Moving a GameObject to a position, waiting, and then moving it again Hello hello ) Ive been attemping to move a platform (a door basically), and it has partually worked. What works so far is i can move an object from A to B and wait, however it will not move it towards C afterwards, here is my code (note that all of the Debug.Logs work). Here is my code. public class OpenDoor MonoBehaviour public Transform origPos public Transform targetPos public float speed public GameObject button private ButtonScript bs private void Start() bs button.GetComponent lt ButtonScript gt () void Update() if (bs.buttonActive) Debug.Log("Button Active 2") StartCoroutine(MovePlatform()) bs.buttonActive false IEnumerator MovePlatform() float step speed Time.deltaTime bool arrived false while (!arrived) transform.position Vector3.MoveTowards(transform.position, targetPos.position, step) if (Vector3.Distance(transform.position, targetPos.position) 0) Debug.Log("DISTANCE 0") arrived true yield return null if (arrived) Debug.Log("Arrived") yield return new WaitForSeconds(1) Debug.Log("Waited") transform.position Vector3.MoveTowards(transform.position, origPos.position, step) Any assisstance would be greatly appreciated )


Physics2D.Raycast not hitting any colliders I am making a topdown 2d game and want to get the x,y of mouse clicks so I can move the character to that location. I am writing a CharacterController script which performs the mouse click check and raycast in the Update function void Update () if (Input.GetMouseButtonDown (0)) RaycastHit2D hit Physics2D.Raycast(Input.mousePosition, Vector2.up) if (hit.collider ! null) Debug.Log (hit.point) This runs whenever I click the mouse, but the if(hit.collider ! null) condition is never met. I've looked around for other solutions, such as Unity Raycast not hitting to BoxCollider2D objects, but when I change my code to the one used in that answer RaycastHit2D hit Physics2D.Raycast( Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.back ) then the if(hit.collider ! null) block is always true, even if I click on empty space, and it always returns the same coordinate. To illustrate this, here is a video of me clicking the game view. The green area has a 2d box collider that is very closely mapped to its boundaries. You can see that the logged hit.point is always the same. video is here https i.imgur.com uhNp8wC.gifv screenshot


Why Does unity LightPosition 0 Seem to Depend on Camera Position? I'm trying to write a fairly basic shader but I keep running into lighting issues with Unity. My first problem was trying to figure out which variable stored the light's position in world space. (I'm only working with one light, at least at the moment). I finally found something that responds to movement of my light source unity LightPosition 0 . However the shader still didn't do what I wanted it to do, so I did some debugging I have a basic vertex and fragment shader and what I'm currently doing in the fragment shader is float4 c float4(0, 0, 0, 1) float3 lp normalize(unity LightPosition 0 ) c.rgb lp return c This should just set the color of my object to the normalized position of the light source, correct? What I see in my scene is my object changes colors when I move my camera around it (I'm not moving the light source at all, it is a separate entity). The color also seems to increase in strength as I zoom in. To me, it seems as if unity LightPosition 0 is related to my camera's position, as well as orientation and zoom level, yet the documentation I've found says it should represent the position of the light in world space. I tried switching to using the following float3 lp float4( unity 4LightPosX0 0 , unity 4LightPosY0 0 , unity 4LightPosZ0 0 , 1.0 ) ...but that only colors my object red regardless of the light's actual position. Additionally, I've set the LightMode tag to Vertex. It seems like simply getting the world position of the light source shouldn't be this difficult. What am I not doing correctly? EDIT I've been playing around with the camera and light position and I think that unity LightPosition 0 actually puts out position in the projection space. If I place the light source in the lower left corner of the screen, the object is black. Upper left the object is green (0, 1), upper right is orange (1, 1), and lower right is red (1, 0). When I place it in the lower left (0, 0) and move the camera in front of it, it becomes blue. This is consistent with the depth value behavior. (0, 0, 0) would appear as blue. Now, how to get it from projection back to world?...or should I use a different variable?


Rotate object always at same speed on screen, no matter camera distance? I am rotating a globe like XCOM's hologlobe, I rotate it using Quaternion.RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta). I found a good value for maxDegreesDelta, in my case it is 5.0f. There is a limit on how close or far the camera can be, let's assume clos is 1.0f and far is 2.0f. I want to be able to zoom into the globe, but obviously when I do, it rotates a bit too fast then. When zoomed out, rotation speed is satisfying When zoomed in, rotation is too fast, making it more difficult to manipulate And the problem is even more evident as game view size gets bigger, i.e. fullscreen. Using Mathf.Lerp and Mathf.InverseLerp, I've tried to make maxDegreesDelta and mouse delta proportional to the distance the camera is but it's hardly convincing. Note I rotate the globe, not the camera. Question How can I ensure object rotates at same speed on screen, no matter how close or far camera is ? Code (assumes there is a sphere of radius 0.5 at Vector3.zero and camera is positioned at Vector3.back) using UnityEngine using UnityEngine.InputSystem namespace Test2 public class GeoScapeController MonoBehaviour region Public public Transform TargetObject public Camera TargetCamera Range(0.01f, 1.0f) public float Sensitivity public bool Smooth public float ZoomDistanceMin public float ZoomDistanceMax endregion region Private SerializeField HideInInspector private Quaternion TargetRotation SerializeField HideInInspector private int ZoomLevel SerializeField HideInInspector private int ZoomLevels SerializeField HideInInspector private Vector3 ZoomVector SerializeField HideInInspector private Vector3 ZoomVelocity private void Reset() Sensitivity 0.05f Smooth true ZoomDistanceMin 0.625F ZoomDistanceMax 1.25F ZoomLevels 10 private void Start() TargetRotation Quaternion.LookRotation(TargetObject.forward, TargetObject.up) ZoomVector TargetCamera.transform.position private void Update() var mouse Mouse.current var delta mouse.delta.ReadValue() var scale new Vector4( 1.0f, 1.0f, 1.0f) var x mouse.leftButton.isPressed ? delta.y scale.y Sensitivity 0.0f var y mouse.leftButton.isPressed ? delta.x scale.x Sensitivity 0.0f var z mouse.middleButton.isPressed ? delta.x scale.z Sensitivity 0.0f var r Quaternion.AngleAxis(x, Vector3.right) Quaternion.AngleAxis(y, Vector3.up) Quaternion.AngleAxis(z, Vector3.forward) if (Smooth) hopefully, quaternion limits won't be crossed ! TargetRotation Quaternion.RotateTowards(TargetRotation, r TargetRotation, 2.5f) TargetObject.rotation Quaternion.Slerp(TargetObject.rotation, TargetRotation, Time.deltaTime 5.0f) else TargetObject.rotation TargetRotation r TargetRotation var wheel (int) mouse.scroll.ReadValue().y 120 if (wheel ! 0) ZoomLevel Mathf.Clamp(ZoomLevel wheel, 0, ZoomLevels) var lerp1 Mathf.InverseLerp(ZoomLevels, 0, ZoomLevel) var lerp2 Mathf.Lerp(ZoomDistanceMin, ZoomDistanceMax, lerp1) ZoomVector Vector3.back lerp2 TargetCamera.transform.position Smooth ? Vector3.SmoothDamp(TargetCamera.transform.position, ZoomVector, ref ZoomVelocity, 0.3f) ZoomVector endregion


How to instantiate cubes at every given positions I have a list of coordinates in 3D (XYZ) list 226.29, 485.28, 345.396 , 298.292, 108.226, 551.422 , 452.987, 164.874, 416.242 , 562.8, 29.4951, 297.651 , 610.087, 99.9056, 156.377 , 470.804, 12.3284, 428.671 , 590.609, 197.615, 137.146 I want to instantiate cubes at every given positions, how to define given list correctly in C and use it as a vector3 ? I tried something like that.. for (int i 0 i lt 7 i ) Instantiate(prefab, new Vector3(list i ), Quaternion.identity)


In unity, how do I rotate a vector in relation to the player? I am making a radar script in a unity FPS game project I am making for class. I already have a working example of a radar script that works in relation to the player's position. However the rotation is in relation within the world map, not the player's view. In code I have it kinda like this (not actually my code, as I don't have it with me right now, but basically the same algorithm) if (isPlayerInViewRange(otherPlayer i ) these are both normalized Vector dir getDirectionFromPosition(player, otherPlayer) dir rotateDirectionInRelationshipToPlayer(player, dir) problem here dir new Vector3(dir.x, dir.z, 0) dir.Scale(MapToRadarPosition, 0, MapToRadarPosition) radarDot i dir radarDot i .setActive(true) else radarDot i .setActive(false) Any ideas what I am missing, I feel like I am missing some obvious function to do it.


Rotating UVs by X degrees I would like to make a tileable texture with UV noise in Unity Shader Graph only, but I have a problem. After creating simple noise from UV, I want to rotate it by 90 degrees, but the node Rotate (as well as Rotate About Axis) doesn't rotate my UV (like a picture in PS), instead it changes the colors in it from black amp white to red (yellow, green, ...) amp black. Could you tell me please, how to fix it? Some context Based on the answer https gamedev.stackexchange.com a 23631 , I want to rotate the noise three times (so 0 90 180 270 ), multiply them and thus normalize the edges to make the texture tileable. Instead of it, even at 0 rotation the color of noise is changed to yellow somehow and the multiplication is everything but not the result I want. That's how I wanted to do it


Unity Failed to build APK. See console for details i am getting this error whenever i am trying to build a project. i looked at so many solutions but this one just doesn't go away. This is the error CommandInvokationFailure Failed to build apk. C Program Files Java jdk 9 bin java.exe Xmx2048M Dcom.android.sdkmanager.toolsdir "C Users Mohit AppData Local Android sdk tools" Dfile.encoding UTF8 jar "C Program Files Unity Editor Data PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Exception in thread "main" java.lang.reflect.InvocationTargetException at java.base jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java 62) at java.base jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java 43) at java.base java.lang.reflect.Method.invoke(Method.java 564) at SDKMain.main(SDKMain.java 130) Caused by java.lang.NoClassDefFoundError sun misc BASE64Encoder at com.android.sdklib.internal.build.SignedJarBuilder. lt init gt (SignedJarBuilder.java 177) at com.android.sdklib.build.ApkBuilder.init(ApkBuilder.java 446) at com.android.sdklib.build.ApkBuilder. lt init gt (ApkBuilder.java 422) at com.android.sdklib.build.ApkBuilder. lt init gt (ApkBuilder.java 362) at UnityApkBuilder. lt init gt (UnityApkBuilder.java 214) at UnityApkBuilder.main(UnityApkBuilder.java 34) ... 5 more Caused by java.lang.ClassNotFoundException sun.misc.BASE64Encoder at java.base java.net.URLClassLoader.findClass(URLClassLoader.java 466) at java.base java.lang.ClassLoader.loadClass(ClassLoader.java 563) at java.base java.lang.ClassLoader.loadClass(ClassLoader.java 496) ... 11 more stdout exit code 1 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.HostView OnGUI() what i have tried so far 1) downgrading android sdk 2) moving zipalign file from build tools to tools folder 3) setting up keystore


Can I create realtime textures with text? I have a large number of items in my game, that will eventually have a texture associated with them. The problem is, for right now, I have nothing. I would really like to do something with, say, the first 2 letters of the object's name. As my main system will be pure textures, I really don't want to add a text object to the texture, I would really like to just create a texture with the object's first two letters. Is there a way I can create a texture, realtime, with font rendered on that texture? Preferably without a camera render texture, unless I can create them once. I really want to create a unique default texture for each item at runtime, preferably with some kind of font. Can I do this?


Unity vr device support I have been looking for a list of VR devices that unity supports (or that you can use to develop VR games with). However i have been unable to find a list. Currently im looking at BOBO VR Z4 But to make sure i do not make any incorrect purchases so it would be really helpful to know supported devices. Also it is worth noting i'm going to be using the newest version of Unity. (which is currently version 5.6)


Will my huge sprites for a 2d game create performance issues? I'm new to Unity, and have been confused about this issue for a while. Some people say that for 2D games you don't need to worry about performance (I'm making the game for PC, not mobile) while others report bad performance with larger sized sprites I have a long scene with some large background sprites, measuring about 14552x3308 (weird resolution I know, would that also cause issues?) All methods of scaling it down and resizing in Unity lead to jagged edges (these are basically hills so I need them to be significantly bigger than the player character) I always keep the image size in the inspector similar to the resolution of the actual file, and set the filter mode to Point, so the jagged edges are not due to that, but only because of me scaling up a smaller file size to fit the scene. If I use the original sprites of 14552x3308, it's perfectly smooth (image size set to 8192 in inspector) but each file takes about 120mb in the profiler. All combined, my assets are showing a usage of 1.25 GB for this scene. How bad is this? Should I be trying to keep it under 1GB? I don't really know what the best practices are in this situation, so I don't know what to aim for. I'd ideally like to keep the sprites at this large size so that I don't have to redraw anything.


My runtime mesh is not being created where it's vertices are located, need help I'm trying to create a quad at runtime and I'm encountering an issue where the mesh does not show up in the scene where it's vertices where set. In the following picture you can see the ship, and to the far right the mesh. The 4 white dots around the ship where drawn after the mesh was made using the 4 vertices of the mesh. My Code Handles the method calls for the mesh creation private void BoundingMeshCreation() Quaternion currentRotation ResetPosition(new Quaternion(0, 0, 0, 0)) BoundingPointsType boundingPoints DetermineBounds() Mesh boundingMesh CreateBoundingMesh(boundingPoints) AssignMesh(boundingMesh) ResetPosition(currentRotation) Creates the mesh filter and assigns the mesh private void AssignMesh(Mesh boundingMesh) MeshFilter newMeshFilter gameObject.AddComponent lt MeshFilter gt () newMeshFilter.mesh boundingMesh VectorLine testPoint new VectorPoints("testPoint", boundingMesh.vertices, null, 5) testPoint.Draw3D() Creates a bounding mesh for the unit private Mesh CreateBoundingMesh(BoundingPointsType boundingPoints) Mesh boundingMesh new Mesh() boundingMesh.name "Bounding Quad" Vector3 vertices new Vector3 4 boundingPoints.LowerLeftPoint, boundingPoints.LowerRightPoint, boundingPoints.UpperRightPoint, boundingPoints.UpperLeftPoint int triangles new int 6 0, 2, 1, 0, 3, 2 boundingMesh.vertices vertices boundingMesh.triangles triangles return boundingMesh Resets the units rotation to the specific quaternion and returns the quaterion from before the reset. Bit of a hack for now to make sure that the original box is the proper size. private Quaternion ResetPosition(Quaternion toResetTo) Quaternion currentRotation transformV.rotation transformV.rotation toResetTo return currentRotation Determines and returns the bounding box points private BoundingPointsType DetermineBounds() Vector3 maxBounds childSprite.GetComponent lt Renderer gt ().bounds.max Vector3 minBounds childSprite.GetComponent lt Renderer gt ().bounds.min BoundingPointsType boundingPoints new BoundingPointsType(new Vector3(maxBounds.x, 1, maxBounds.z), new Vector3(minBounds.x, 1, maxBounds.z), new Vector3(maxBounds.x, 1, minBounds.z), new Vector3(minBounds.x, 1, minBounds.z)) return boundingPoints I've even tried manually setting the vertices like the following Vector3 UpRight transformV.position Vector3 UpLeft transformV.position Vector3 LowRight transformV.position Vector3 LowLeft transformV.position UpRight.z 1 UpRight.x 1 UpLeft.z 1 UpLeft.x 1 LowRight.z 1 LowRight.x 1 LowLeft.z 1 LowLeft.x 1 Vector3 vertices new Vector3 4 LowLeft, LowRight, UpRight, UpLeft boundingPoints.LowerLeftPoint, boundingPoints.LowerRightPoint, boundingPoints.UpperRightPoint, boundingPoints.UpperLeftPoint I'm at a loss, and have no idea what I'm doing wrong. My dynamic meshes seem to work perfectly fine for everything else in the game. Thanks.


Cannot open a package from the Unity Asset Store website Yesterday I found an asset on the Unity Asset Store website, clicked the button "Open in Unity", and it was opened in Unity. Today, when I did the same thing, I got the error message below I opened the Defaults Apps page in Windows 10 Settings. But what do I do from here?


Model mesh overlapping while animating in Unity but not in Blender I made an FPS model in blender and created reload animation when I imported that model in Unity I saw that while the magazine ejecting from the rifle it overlapped some of the gun parts. Then I went back to the blender and changed some keyframes and positions in the blender but in Unity, it showed me the same problem. I tried many times it looks fine in the blender but in the Unity, it has the same problem.


Why does my Outlined Diffuse 3 shader seem "detached" at a distance? I'm using the Outlined Diffuse 3 shader from Unity and I'm having a problem with it the outline looks great when the camera is near the object, but at a distance, it looks detached. From nearby (looks good) From afar (looks bad see the shelf and books) How can I fix this graphical anomaly?


Migrate from NGUI to Unity UI I used NGUI 2 and NGUI 3 for our UI. Now want to upgrade to Unity 4.6 and migrate all NGUI to Unity UI. Is there any tools? What's the best practice?


Turning the camera when the player turns I have a 3rd person view of the player character, and I wish my camera to follow the player both when he moves and when he rotates. So far I have the movement correct public class CameraController MonoBehaviour public GameObject player private Vector3 offset Use this for initialization void Start() offset transform.position player.transform.position Update is called once per frame void LateUpdate() transform.position player.transform.position offset However the rotation of the camera does not change when the player looks in either direction. How can this be done?


Unity Animation (2D) Cannot drag sprite into animation I am trying to create animations for my sprite which are configured to the quot Multiple quot option. When I try to drag the sprite into the timeline for the animation it won't do anything. It will just go back into the folder like nothing happened. I don't know if this is normal or there is a problem. Thank You. EDIT First I created a 2D animation, I gave it a name, docked and locked the animation then tried to drag the sprite into the timeline and didn't let add components nor drag the sprite i spliced.


Unity Kinect Current, and active wrapper options? What are some current wrapper solutions for using the Kinect with Unity? The initial primesense one seems not to be in active development. I'm aware of the Zigfu one, however are there any open source alternatives?


How to make a script on a prefab act on a particular scene instance? I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it. Actionables are prefabs, which have an Actionable component, with the same setup (at the moment). Once the player is happy with the location of their Actionable, they click LMB, which activates onClick callback, which is supposed to call Planet.Build(), which adds the Actionable on the Planet permanently (saves it into an internal array). I also have a quot Turn Off quot Button, which calls stopBuilding() when clicked, disabling the preview placement. When stopBuilding() is invoked by the button click, everything works as expected. I also want to be able to call Planet.stopBuilding() (which, by removing the actionableModel, disables hover preview on the Planet) from Planet.Build(), such that the player does not need to click the Turn Off button described above after building an Actionable. Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly. How do I access the scene object Planet from Actionable prefab? Here is my Planet and its stopBuilding method so far public class Planet MonoBehaviour private GameObject actionableModel ... public void stopBuilding() For debugging only Planet planet GameObject.Find( quot Planet quot ).GetComponent lt Planet gt () Debug.Log(planet.actionableModel) Debug.Log(this.actionableModel) And here is the Actionable component which has a UnityEvent property onClick, which calls stopBuilding() on a click event. public class Actionable MonoBehaviour public class OnClick UnityEvent lt GameObject gt public OnClick onClick new OnClick() ... void OnMouseDown() onClick.Invoke(gameObject)


Send post request with content type I used a php server to communicate with my unity application . I want to send post data with content type so that my php server can use the approriate variable for the content type , for example if i send post request with content type quot file quot , my php server can use FILES instead of POST , and i am a beginner and i'm too skeptical to use POST to handle upload request from unity application to server . My best guess is that i must use something from WWWForm to achieve it , but in my opinion the documentation isn't friendly enough for beginner like me . Can someone here lend me a hand to achieve this ? (sending post request with content type) Oh , also , i'm sorry for too much using php in my example , below is how i achieve it in html, i can achieve it in html by using something similar to this code (this html send POST request to upload a pictures with quot file quot as it content type) lt form method "POST" enctype "multipart form data" gt lt label gt Browse Image lt input type "file" name "pictures" style "display none" gt lt label gt lt br gt lt button name "upload" gt Upload Now lt button gt lt form gt Please forgive me if my english is too bad , thank you .


Panel gets transparent when accessing the offsetMin of RectTransform I need to place 3 panels side by side in my application. It was working fine with Render mode Screen space Overlay. Now due to some other requirement, I had to change the Render mode to Screen space Camera. Now when I access the offsetMin of RectTransform of the panels so that it shifts to the right, the panel gets transparent. I commented the code where I'm accessing and the Panel doesnt get transparent then. I'm not sure why it is happening. The requirement is place a 3D model in canvas, so I had to change the Render mode. If there is a way to place 3D model in canvas with Screen space Overlay. That would be great as well.


Unity soft blur effect for dark void edges I'm a former Flash dev working in Unity (or in 3D for that matter) for the first time. For the game I'm working on, I've designed an interior room like so To represent void space outside the bounds of the current room, there's just black. In order to hide the back faces of the exterior facing walls, I've created a snug fitting mesh cutout which sits just below the lip of the wall. If I moved the camera below the surface, you would clearly see that. I'm quite new to Unity, and have very little experience with shaders. Anyway, I figured this would be a good place to try for creating my first shader, but I'll need some help. I'd like to blur soften the edges where the wall lip meets the void, like so The only way I could achieve this effect would be by hacky means, like by using a gradient texture ( 00000000 FF000000) UVed around the edges of the wall lips, but I suspect there is a more elegant solution by rendering the black surface with a shader. Currently, even with a basic understanding of fragment shaders and the rendering process, I would have no idea where to start if I tried to write my own. When I read shader script I can only stare in wonder at the sheer etherealness of it. I just don't know how to craft a solution in such basic terms, but I'd love to learn. I understand the answer is probably as simple as 'use a gaussian blur', but i would appreciate some more input to steer me on the right path, and maybe some examples to help me understand.


Send a Push Notification from a device to another device (Unity, Firebase) I have setup Firebase authentication in my game for Android. I need to implement a feature in my Android game, where a user can challenge another player. I need to implement it this way The user is shown the list of all users registered on Firebase on the Game. To any user, he can tap on a button for respective user to send a challenge. When, he taps, a push notification is to be recieved by that user. When he taps on the notification, he is redirected to a specific part of the game. Maybe a specifc scene for now and he is shown there the Challenger's name. I have explored the Firebase documentation, but it does not provide information for client client push notifications. Maybe there are other options available like GameSparks and OneSignal. But I don't know if there is a requirement of own Server for implementing it.


How to move rotate different parts of an entity indepently from each other? Background I am playing around with a simple isomorphic 3D shooter where a player controls a character which can shoot other players. Here's an example scene where you can also see the hierarchy for the game objects and the controlling script As you can see, I have created a simple turret which consists of three parts Guns Torso Bottom Just to be more clear, here's a screenshot of the turret close up with its armature In Unity, I have already created a simple PlayerController.cs script (see beloc) which allows a player to move the entire game object around using W, A, S, D and look using the mouse. However, I want to rotate the Bottom independently. So if the Player moves left, the bottom should rotate towards that direction but the torso should still focus on the mouse position. Now the first question is how I can do that. I don't know how to get access to the game objects and rotate them independently. The second question is how I can or should design the player game object s.t. I can exchange models more easily. What I mean by that is Imagine the player switches the weapon. Obviously, only the guns should change but e.g. not the entire character. Only the mesh etc. should change dynamically. I am sure this isn't that hard to accomplish but I couldn't find a simple example that kind of explains how to do it. PlayerController.cs public class PlayerController MonoBehaviour SerializeField public float moveSpeed 1f private Vector3 forward private Vector3 right public LayerMask layerMask Start is called before the first frame update void Start() this. forward Camera.main.transform.forward this. forward.y 0 this. forward Vector3.Normalize(this. forward) this. right Quaternion.Euler(new Vector3(0, 90, 0)) this. forward Update is called once per frame void Update() if (Input.anyKey) this.Move() this.MouseLook() public void Move() var rightMovement this. right Input.GetAxis("HorizontalKey") var upMovement this. forward Input.GetAxis("VerticalKey") transform.position (Time.deltaTime this.moveSpeed Vector3.Normalize(rightMovement upMovement)) var heading Vector3.Normalize(rightMovement upMovement) if (Vector3.Magnitude(heading) gt 0.0) transform.forward heading void MouseLook() Ray castPoint Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(castPoint, out hit, float.MaxValue, layerMask)) Vector3 direction hit.point transform.position direction.y 0.0f transform.forward Vector3.Normalize(direction)


Why is FindObjectOfType(MyType) not finding anything? Why would I get the following log? Start OpponentMotionReceiver motion receiver not found true public class ScoreAnimation MonoBehaviour private OpponentMotionReceiver cachedObject private void Start() cachedObject FindObjectOfType lt OpponentMotionReceiver gt () private void OnDestroy() var motionReceiver FindObjectOfType lt OpponentMotionReceiver gt () if (motionReceiver null) Debug.Log("motion receiver not found") if(cachedObject ! null) prints true, another proof that the gameObject is active Debug.Log(cachedObject.gameObject.activeInHierarchy) public class OpponentMotionReceiver MonoBehaviour private void Start() Debug.Log("Start OpponentMotionReceiver") private void OnDisable() never enters Debug.Log("OnDisable OpponentMotionReceiver") private void OnDestroy() never enters Debug.Log("OnDestroy OpponentMotionReceiver") P.S. This is extremely simplified version of the code so that the rest brings no confusion. If you need more details, I'd be pleased to answer you!


Add Atten property in Unity Shaderlab In Unity Shaderlab shader, Is there any way to apply Atten value? Using surface shader, and vertex fragment shader I can do it easily. But, I didn't find any reference to do that in Shaderlab syntax. Shader "Diffuse" Properties Atten ("Light Attenuation Power", Float) 1.0 lt how to apply? Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Transparency (A)", 2D) "" SubShader Pass SetTexture MainTex constantColor Color combine texture constant, texture constant this makes syntax error. constantColor Atten Color


Sort buttons in unity 2D I've a list of buttons that I create using XML stored data. To achieve it, I've created a Prefab. These buttons are created correctly, and now I want them to be sorted for the user. public List lt GameObject gt myButtons As I said, now I want to sort them. I've found out that sorting the List itself, buttons are sorted in the UI. myButtons.Sort((x, y) gt ...) The problem is, that I don't have the necessary data to sort them within them. This leaves the .Sort() method unavailable for use. I've tried to sort them adding an script to each one, which contains the data that I need to use to sort them. However, it doesn't work correctly and I seem unable to find out why, so I'm wondering about other more direct methods to sort them. Notice that I'm referring to simple buttons in a 2D game, and that they're all inside the same parent gameobject. Technical Details Let's start by the basics I want to order the buttons taking into account if the user has reached a point in which the item it represents should be available. This is stored in an instance of a class that represents the items related to the buttons of the question. public class myItemClass Here there are other properties public bool available Therefore, we've a correspondence between two lists public List lt myItemClass gt myItems public List lt GameObject gt myButtons Where myItems 0 is related represented by myButtons 0 ... NOTICE that this relation exist at the initialization of the game, so i need to keep it at any moment (meaning, having to sort both lists). What I tried To be able to order my buttons depending on if the items are available or not, what I've done is Creating an script myItemScript, which has a reference to my original items from the other list. Sorted the items using Sort function over them. public class myItemScript MonoBehaviour public OtherClass.myItemClass dataObject And then sorting them like myButtons.Sort((x, y) gt y.GetComponent lt myItemScript gt ().dataObject.available.CompareTo(x.GetComponent lt myItemScript gt ().dataObject.available)) As I said before, both list need to be following the same order, so just after it, I order the item list as well myItems.Sort((x, y) gt y.available.CompareTo(x.available)) Checking Debug As result, I found that items were in fact sorting different. However Items inside myItems List were sorted as expected. Buttons in UI (and hence, myButtons List were not sorted as expected. Mixed items (available true false) were mixed and not ordered in two blocks, one first and then the other one. This was checked using breakpoints within VS2017 and pausing the game in Unity interface.


How to interpolate colors around the spectrum of hues? I wanted to generate a 7 segment display whose color brightness varies with time, this can be done by just using linear relationship. Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) So in 1 complete second, it produce color in the range of (1,0,0) to (1,1,1) as in the code below using System using UnityEngine public class ClockDigit2 MonoBehaviour 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 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) 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 activeColour2 else segments i .color inactiveColour void Update() Display(DateTime.Now.Second) However, now I want to interpolate through all the colors in the circle above over 1 second. I don't know how to express this as a formula for R, G, and B. The RGB value is not linear relationship as you spin the selected color in the chart, you can notice the RGBA components vary together in a nonlinear form. I considered using Lagrangian interpolation. However, this will not be accurate or might fail greatly because if you take a reference point at the circle and assume in 1sec, it made a complete revolution, you will notice there is a certain period of time where the RGB value is constant along the path either 0 and 1. So is there any method to get a formula that perfectly fits the color chart with respect to time?


How can I handle ball interaction with lanes in a pinball game? In a pinball game, how can I handle collision or constraints on the ball for convincing movement on those highway rails tracks? I assume using physics and a mesh collider would not work, even when the poly count is really high the ball still bashes into all those faces instead of hugging a smooth, round wall. I could constrain the ball to a spline but I foresee problems with the balls speed and proper physics. I'm wondering if it is possible to tell the ball that mesh corners below a certain degree should be treated as round. Perhaps only when coming from a certain angle?


How do mobile games implement time gates unhackably? Is it possible in offline games? I'm thinking about porting my game to Google Play, and it would be free to play with time gates which are skippable if you watch an ad. What are the ways of implementing an unhackable time gating? Is it possible without internet connection? If yes, how? If no, is there a way to implement it without custom backend, using Google Play's services? Or should I care about this at all? Because... It doesn't affect other players... Most of the audience couldn't do it anyway, and if the game stays small, hacks couldn't really spread. Then maybe I should just let them hack those time gates, it's a marginal revenue loss. What do you think?


Get world position of random point inside bounds I am trying to get a random world position inside my targets collider, so that I can fire an arrow at it. I have tried a bunch of different solution but can't seem to get it right, for example (this code is on my target) Inside Awake colliders GetComponentsInChildren lt Collider gt () I want this to work on a unit with a single capsule collider and a building with 8 different box colliders public Vector3 GetRandomPoint() Bounds b new Bounds() for (int i 0 i lt colliders.Length i ) b.Encapsulate(colliders i .bounds) float minX gameObject.transform.position.x gameObject.transform.localScale.x bounds.size.x 0.5f float minZ gameObject.transform.position.z gameObject.transform.localScale.z bounds.size.z 0.5f return new Vector3(Random.Range (minX, minX), gameObject.transform.position.y, Random.Range (minZ, minZ)) In the scenario I'm having issues with right now, the trageet simply has a single capsule collider. This return a point quite far away from my target, but I cant find the issue. EDIT Here is another one I tried without success public Vector3 GetRandomPoint() Bounds b new Bounds() for (int i 0 i lt colliders.Length i ) b.Encapsulate(colliders i .bounds) var target new Vector3( UnityEngine.Random.Range(b.min.x, b.max.x), UnityEngine.Random.Range(b.min.y, b.max.y), UnityEngine.Random.Range(b.min.z, b.max.z) ) return b.ClosestPoint(target)


Why even use coroutines in Unity? I have been thinking about the use of Unity's coroutines recently, and while I've used them in the past, and am already aware of their bad reputation (although I've also seen posts on the unity forums of people who seem to absolutely swear by them), the more I think about it, I'm kind of struggling to see any compelling reasons to use them at all instead of simply creating a new component and simply performing the logic of the coroutine in said new component's Update method. By using a IEnumerator coroutine inside of another component, it seems to me like all it accomplishes is decreasing the cohesiveness of individual components and the re usability of the component using them. Is there any convincing argument to actually use coroutines in Unity and would I be missing out by simply not using them? Are there any scenarios I'm overlooking where their use would either be required or prove incredibly useful?


Starting Couroutine in newly activated gameObject I'm working on a UI system that animates an element's properties using coroutines. Every element that should be animated has a component called AnimatedUIElement which provides the function Enter(). The function Enter() is basically starting coroutines depending on the chosen animation settings, but only after calling Enable(), which sets the gameObject active with gameObject.SetActive(true) , updates its component references and makes the element interactable. AnimatedUIElement also defines an Exit() function acting similar, but disabling the element after the animation. public class AnimatedUIElement MonoBehaviour private CanvasGroup canvasGroup ... public void Enter() ... TriggerEntry() private void TriggerEntry() PlayChildrenEntry() Calls Enter() on all animated Children Enable() StartCoroutine(SomeAnimation(...)) private void Enable() gameObject.SetActive(true) Init() canvasGroup.interactable true canvasGroup.blocksRaycasts true private void Init() canvasGroup GetComponent lt CanvasGroup gt () ... private IEnumerator SomeAnimation(...) ... public void Exit() Similar to Enter, but disabling the element Now I want to open the options panel by clicking a button in the game's UI. The panel is inactive (unticked) in the beginning, while the AnimatedUIElement component is enabled. UI Hierarchy Options Button calls Enter() on Options Panel. The desired setup in the Button Component calling OptionsPanel.Enter() and MainPanel.Exit() But clicking the button throws the following exception Coroutine couldn't be started because the the game object 'Main Menu Button' is inactive! UnityEngine.MonoBehaviour StartCoroutine(IEnumerator) AnimatedUIElement AnimatePosition(Vector2, Vector2, Single, AnimationCurve) (at Assets Animated UI Elements AnimatedUIElement.cs 265) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 93) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) AnimatedUIElement PlayChildrenEntry(Transform) (at Assets Animated UI Elements AnimatedUIElement.cs 219) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 79) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) UnityEngine.EventSystems.EventSystem Update() In this stack trace you can see that the Options Panel did not start coroutines as no animation was defined in its component, but called Enter() on its children, which are animated. Using debug logs I found out that, while Init() is called immediately after Enter(), Awake() is called after the coroutines (which happen later in the program flow) throw errors. This makes it seem like the object is not available instantly after calling setActive(true). Is there an explanation and possibly a fix for this behavior?


How to write a unit test in Unity? is there a tutorial and patterns to write unit tests in Unity ? Should we use the classical c way and test the code or should we test the interactions in UI ? If so how?


Unity Particle System Shuriken Setting particles in code with random row in texture animation? Good day, I'm attempting to randomly generate a space scene (quite large actually) in Unity through C code mainly. So far, I've gotten stunning results up to what image 2 will show you. However, now I'm looking to expand the look with more random particles. So, I've made a texture atlas of 8 in a vertical row, which works on the random setting if you have an emitter and the particle system is called with PS.Play() Assigning different materials would only work on a per particle system basis(which would be new texture PER cloud, so to speak) which is not what I want. So, my question How can I use the Shuriken Particle System's Texture Sheet Animation functionality through code, without having an "active" particle system? More precisely, I wish to use the 'Random Row' feature of it to assign random textures to each particle. Since I can't share my code (due to policies), here is a bit more info on how I do it I create an array with coordinates for each cloud. Assign a particle system to that cloud. Randomly generate all the particles for the cloud with relative offsets. Use PS.setParticles(particlesArray) Using a Texture Atlas consisting of the letters A to H to test, only B showing on all particles. Using a Texture Atlas consisting of the fog particles to test, only 2nd showing on all particles. Thank you DMGregory for the help, I've tested it multiple times and it works perfectly now, I've also went ahead and tweaked a few of my settings just to get a more "clear" space


How to stop 3D model from reflecting light like plastic I was browsing SketchFab and found a 3D model I decided to try in Unity. This is how the model looks in SketchFab's viewer When I put it in Unity, I used a Directional Light object As you can see, it looks like plastic. I have been playing with the light's intensity, but the model seems to always reflect light as if it were some sort of plastic (unlike SketchFab's viewer). How can I make it look like the above image? The model is https sketchfab.com models 1ee9b44352c840bda4202895948c30bb


How to setup a public github unity repo with paid assets? From what I gathered (like in this thread or here) I am allowed to push my own game code on github and choose a license, as long as I avoid putting assets I do not own. I want to make it public to be able to show it (to potential employers for instance) but I cannot make it open source as I plan to use paid assets (like DoozyUI). I can avoid pushing the asset itself on the repo (with .gitignore for instance). Should I prevent gameobjects created with this package to be pushed as well ? That would make the game unusable, even with the rights to use the package... Once that is settled, Is it ok to push it to github without license ? Specifically, I do not know if objects generated by a paid asset are still considered that asset or not... Edit I asked the question directly to DoozyUI support, which quickly responded You can upload your project, without the Doozy folder. Thus excluding our source code from being shared. Also, unsert a disclaimer letting anyone know that DoozyUI is required to be installed (before getting your files) for the project to work. You can share any GameObject (or prefabs) you create, but they will not work if DoozyUI is not installed due to missing references (scripts). Once Doozy is installed, they will work as expected. Thus anyone who has the system will be able to see use your project.


Unity Player Gets Stuck Between Tiles I am creating an endless game, which constantly spawns tiles. The problem is that after a few tiles the player gets stuck on random tile and stops moving. I noticed this problem even when i was designing a level, where when I align two tiles side by side, the player gets stuck on the junction of these two tiles. I am including a video link to my problem. Please help me and please try to be in detail because i very very new to Unity. Video for the problem im facing. https photos.app.goo.gl JrCPWkGclUA2UiMy1 using System.Collections using System.Collections.Generic using UnityEngine public class TileManager MonoBehaviour public GameObject tiles private Transform player private float SpawnLocationZ 30.0f private float tileLength 36 private float amountOfTilesOnScreen 5 private float SafeZone 45 private List lt GameObject gt activeTiles private int lastPrefabIndex 0 private bool StartCompleted false Use this for initialization void Start () activeTiles new List lt GameObject gt () player GameObject.FindGameObjectWithTag("Player").transform for(int i 0 i lt amountOfTilesOnScreen i ) Debug.Log("Start Method") SpawnTile( 1) Update is called once per frame void Update () if((player.transform.position.z SafeZone gt (SpawnLocationZ amountOfTilesOnScreen tileLength))) Debug.Log("started") SpawnTile(0) DeleteTile() void SpawnTile( int prefabIndex) if(prefabIndex 1) GameObject gor gor Instantiate(tiles 0 ) as GameObject gor.transform.SetParent(transform) gor.transform.position Vector3.forward SpawnLocationZ SpawnLocationZ tileLength activeTiles.Add(gor) else GameObject go go Instantiate(tiles Randome() ) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward SpawnLocationZ SpawnLocationZ tileLength activeTiles.Add(go) void DeleteTile() Destroy(activeTiles 0 ) activeTiles.RemoveAt(0) private int Randome() if(tiles.Length lt 1) return 0 int randomIndex lastPrefabIndex while(randomIndex lastPrefabIndex) randomIndex Random.Range(0, tiles.Length) lastPrefabIndex randomIndex return randomIndex


How can I make a chest that can be opened and shut in SteamVR? I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want. I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic. I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions. I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this.


Networking player input, UI, and ability use I am currently working on a project to learn more about networking, specifically authoritative network architecture. In most authoritative systems you capture a player's input queue them up then send them to the server after a certain count or time has passed. The input is "copied" to the local(client) loop and run as prediction while it waits for the server to return the authoritative state back to the local(client) for correction. The states are also sent to all connected players to recreate the observed behavior of remote players. This system works well for things like player movement and shooting(raycasts). This gets more complicated as we start to integrate UI and player skill ability bars. In most MOBA or MMO games there is UI that can also create "input". In these cases there isn't a truely 100 right way to accomplish the goal of networking these pieces. You wouldn't need or want the UI to be run on the server in most cases. I have come up with a few concepts of sending the input for these to the server and would like to know if I am close to conventions that are used in professional system or if I am even thinking about it in the right way. Case 1 Mapped config agreement In this model the player can assign abilities to a skill bar that is both clickable and correspond to the number keys on the keyboard. This "mapping" of abilities to bar slots is stored in a player config and is sent to the server. When the player presses a number key or clicks on an icon an input is generated and added to the input sent to the server that looks something like this BarId 1,BarIndex 1,KeyId 1 When this is received by the server the server looks up the player UI config that was sent to the server and see what abilityId was stored on that place in the bar, check if it is a valid move then update the server state. Case 2 Server Command In this case the player class has a UseAbility(abilityId,target) method that can be called from the client player instance but is executed on the server instance, this bypasses the normal input gathering loop by executing the command on the server immediately so incorporating this into the client server step systems isn't clean. Borrowing the use case from Case 1 The player presses the button on the keyboard or clicks the UI button. This is "mapped" locally to a specific skill. The button keypress calls UseAbility(0x00012,self) and is run on the client and server immediately it is checked for validity and then a state is sent to all connected players. Those are the two cases I have right now. One works well with how input is gathered and sent to the server for processing. The other makes more sense in that the code can be more explicit but it appears to break the server authoritative structure. Would you guys please tell me what you think and maybe we can have a conversation about best practices. Thanks for reading my post.


Free Look Camera Like Arma 2 while pressing ALT I'm trying to create a simple script that give me the possibility to rotate the camera while pressing a key. So, in a pseudo code way, how I can intercept the Input event and limit the player's movements to hold the character direction? I should tweak the MouseLook script? Or completely create a new one?


How come changing the speed of an animation isnt making the animation speed up? I made an animation of a bow string being pulled and another animation of the string being released but my issue is that I need the string to snap back quickly. I changed the speed of the release animation which is what makes the string go back to being straight (as if you had just released it). However, changing the speed isn't making the animation happen any faster... Any ideas why this might be happening?


Simple Water surface simulation problems (GDC2008 Matthias Muller Hello World) Im attempting to implement a simple height field water surface simulation outlined in Matthias Muller's GDC 2008 talk. "http www.matthiasmueller.info talks gdc2008.pdf" I can't seem to see why it my implementation doesnt work. Could anyone help? Any advice or help would be much appreciated. The main processing loop is below The obstruction array is initialized as 1. And the source just adds 0.1f to a point. void wave() for( int i 0 i lt size i ) height i source i height i obstruction i for (int i 1 i lt iwidth 1 i ) for(int j 1 j lt iheight 1 j ) velocityField indexFind(i,j) (height indexFind(i 1,j) height indexFind(i 1,j) height indexFind(i,j 1) height indexFind(i,j 1) ) 4 height indexFind(i,j) velocityField indexFind(i,j) dampening height indexFind(i,j) velocityField indexFind(i,j) int indexFind(int x, int y) return (x iwidth y) This is what happens (height field rendered as a texture on a plane) This is the page from the link that outlines the algorithm


Why is my enemy object shaking in my AI code? My script here is attached to an 'enemy' object. My enemy walks to certain "points" if the player is far away from him. If the player gets close to him, the enemy follows the player. The problem is that after chasing the player, when he escapes, the enemy should walk back to the "points". Now I see the enemy object shaking and walking far away from the expected direction?! public class enemyscript MonoBehaviour public Transform target public Transform waypoint points NavMeshAgent ePath private int farPoint 0 public float elife 100f,distance,look range 20.0f Use this for initialization void Start () ePath GetComponent lt NavMeshAgent gt () ePath.speed 2 Update is called once per frame void Update () distance Vector3.Distance(gameObject.transform.position, target.transform.position) if (ePath.remainingDistance lt 0.5f) nextpoint() if (distance lt look range) attack() void attack() ePath.SetDestination(target.position) ePath.speed 6 void nextpoint() if (waypoint.Length 0) return ePath.destination waypoint farPoint .position farPoint Random.Range(0, waypoint.Length) ePath.speed 2


What is the speed difference between cross platform HTML5 games and native mobile games? Microsoft is advertising and promoting cross platform HTML5 game development. I am thinking of creating a simple 2D side scroller game and I am trying to decide what engine should I use for creating it. I am trying to understand if there is a big difference between developping once in Unity and exporting to different platforms or simply develop it once in HTML5 in Visual Studio and publish it everywhere. What are the drawbacks and benefits for each? Is there any speed lag difference? any tips are useful


button thumbnail slider effect unity3D I am trying to make this effect for buttons. i.e the middle one is bigger and is selected. the buttons can be moved left or right by swapping with finger. Does anyone have any idea how to do it?


Shoot projectile same direction weapon faces I want to be able to shoot a projectile from a weapon mounted on a vehicle. Right now I am able to do it but only in front of the vehicle. I managed to rotate the weapon to the direction the mouse is facing, but the projectile still goes straight. I believe that the issue is that the velocity of the projectile is the problem here. Right now I have it like this if (playerShooting NPCShooting) if ((timer gt cooldown) amp amp hasEnergyAvailable()) timer 0 GameObject intantiatedProjectileContainer Instantiate(projectileContainer, transform.position, transform.rotation) as GameObject Rigidbody instantiatedProjectile intantiatedProjectileContainer.GetComponentInChildren lt Rigidbody gt () if (playerController) instantiatedProjectile.velocity transform.TransformDirection(new Vector3(0, 0, speed transform.root.GetComponent lt PlayerController gt ().getZSpeed())) Where speed is the projectile speed and it's added to the vehicle speed. I thought that this should shoot forward but with the parent rotation, can someone tell me what I'm missing here? Thanks!


How can I make a 2D Sprite bleed glow colors at a particular spot? I am trying to make a gauge glow over the color it is at. For example, in the image below, when the needle is pointing at the red, the red is glowing. When it is pointing at the green, then the green is glowing. I want to replicate this My gauge will be on a gradient, so I cannot just color a particular segment. (There are no segments.) I am working with 2D sprites. I have looked into the Bloom asset as suggested here, but I have been met with nothing but failures. (Probably because that guide is for 3D.) How can I take the color at a particular position and make it bleed glow like in the images above?


Unity networking, make player disappear for all clients As title says I need to make the player disappear when he gets in car. Right now, it works as a single player, but since I am new to unet I don't really know how to achieve this, I tried some ways, but they didn't work. Here is script Client void OnControllerColliderHit(ControllerColliderHit hit) so if we hit car if(hit.collider.tag "Vehicle") if we pressed "E" if (Input.GetKeyDown(KeyCode.E)) call method to disable some stuff taht should be disabled, like controller, shoot, weapons etc. if (isServer) CmdCall(inVehicle, hit) else RpcCall(inVehicle, hit) Command void CmdCall(bool invehicle, ControllerColliderHit hit) RpcCall(inVehicle, hit) ClientRpc void RpcCall(bool invehicle, ControllerColliderHit hit) disable(inVehicle, hit) I can't see any errors in console but I cant enter play mode cause there are some compiler errors, which again i cant see in console. thank you for any tip, comment, downvote, upvote, or hint ) Nick.


Unity Failed to create decoder for ScreenSelector.png My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not. How it should look and how it looks I checked the logs and this is the error I am served Failed to create decoder for 'C Users Hamuel The First Documents Jetplatformer Builds Builds Data ScreenSelector.png' 0x80070002 Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity. Any help would be much appreciated!


Vuforia AR VR sample with Google Cardboard SDK I cannot switch from augmented reality to virtual reality I have followed the Integrating Cardboard to the AR VR Sample latest tutorial. I have configured the provided scene sample according to that tutorial. I have compiled it to Android without any problem. The game load an AR scene with a yellow pointer in the center. If I understood well, if a glaze at the ImageTargetStones GameObject, it will switch to VR. Unfortunately I cannot find that GameObject anywhere. I only see the AR scene with nothing than the yellow pointer. I don't find what I'm missing. Why is not that ImageTargetStones GameObject in the AR scene? UPDATE 1 I think I want to use Vuforia for an uncommon use. I think that's a reason of a possible misunderstanding. I don't want to use its image recognition possibilities. I want to switch between AR to VR when glazing to a button. I have tried to duplicate the VRButton to move it to an independent place of the scene with no parent. I have checked its IsTrigger checkbox. I have added a PointerEnter EventTrigger that set Focused to true. I have added a PhysicsRaycaster to both AR Camera and MainCamera (child of CardboardMain Head). Nothing happens when I gaze at the button. I have to compile everytime I want to try it by the way. I did not manage to make it work in the editor. UPDATE 2 I haven't been able to do it with vuforia yet. I have done it with WebCamTexture. Specifically, I have used the scripts of this answer http answers.unity3d.com answers 687987 view.html . The result is not nice because the image from camera seems closer than it actually is (with Vuforia, there is not that problem)


How to get neigbor pixel coordinates in Unity HLSL shader I am writing Mandelbrot set shader for Unity. I wrote an Image Effect shader and it works. Unfortunately, each point quot shimmers quot on translate scale. This is because, for each shader call I compute value for only one mathematical point, which is infinitesimal. On even small translation, the value can change drastically. So, I would like to compute math value not for one point, but for several. But for this I need to know, which aother points belong to my pixel, and for this I need to know the distance to neighbor pixel. Unfortunately, my incoming values are float and I don't know, how to step to next pixel. How to accomplish?


Unity3d Access the OnClick parameters of Button in a script I have a button and I have attached another script "PlaySound" for this button, which plays audio on button click. As soon as the audio gets completed, I want to stop the animation which I am triggering here in OnClick of Button. How do I access the Ellen gameObject and 0 parameter which I set in the Inspector window (check the picture) in the PlaySound script


Shader that draws just vertex points The game I am developing is in unity and I want to make a shader which can be put on a mesh that only 'draws' color on each vertex point. I am not proficient with shaders, and out of all my searching I have come up empty handed I unfortunately don't even know how to look up this question (I seem to only find results about point clouds, which only serves to confuse and scare me more P). Any help or if you can point me in the right direction on what to search, I would be very much greatful.


do i need a deterministic game engine for ball physics multiplayer game? I want to create a simple soccer game but where the ball physics is accurately rendered across the network. I looked at Photon's Quantum engine and it is too expensive for indie devs at 1k month for only 500 CCU. Is there an alternative approach? Basically I need the ball physics to be as accurate as possible.


Unity DontDestroyOnLoad FindObjectsOfType(GetType()).Length is always returning 1 I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs. This answer suggests the following code public void Awake() DontDestroyOnLoad(this) if (FindObjectsOfType(GetType()).Length gt 1) Destroy(gameObject) Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy. I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out FindObjectsOfType(GetType()).Length.


Transform.Rotate micro stutter? Hey all I have a quick question. I am new and obviously still learning the basics of programming scripting. However I am confused by the result of a simple script. The goal is to have a Start Menu with a 3d background.The camera is attached to an Empty Object, which has a script that is meant to constantly rotate. My confusion, is whether I am live testing in Unity, or a built executable. When the empty object is rotating, it will have a pause or a few milliseconds, and then continue with its rotation. Almost like a planned micro stutter. Regardless of where it is in its cycle. How can I make the rotation as perfectly smooth as possible? Below is the script for rotating the empty object that the camera is attached to. public class cameraAnchor MonoBehaviour public float speed 5f Update is called once per frame void Update () rotate camera anchor around y axis transform.Rotate(Vector3.down, speed Time.deltaTime)


Unity Mobile project, button problem "CrossPlatformInputManager.GetButton" not working Good afternoon, I have a problem with an input in my code Before testing it on mobile I tried on PC and the code to make my player sprint was like this var sprintPressed Input.GetKey(KeyCode.LeftShift) var targetSpeed maxSpeed if (attacking) targetSpeed attackMoveSpeedMultiplier else if (sprintPressed) targetSpeed sprintMultiplier And everything was working fine. My player increases the movement speed as soon as I press "Left Shift" button. Then I changed the code to make it work with a mobile button var sprintPressed CrossPlatformInputManager.GetButton("Sprint") var targetSpeed maxSpeed if (attacking) targetSpeed attackMoveSpeedMultiplier else if (sprintPressed) Debug.Log(sprintPressed ? sprintMultiplier 1) just to see if it take a button targetSpeed sprintMultiplier I also make a change for a controller so instead, to press WASD I use a screen joystick. That's work fine. But when I press a button to make a sprint, nothing happens. I insert a debug log line and when I press a button it just return 1 single value (sprintMultiplier) and not 1 per frame as it should be because this function is in the Fixed Update. I check in Google and I found this tutorial https www.youtube.com watch?v nGYObojmkO4 amp t 851s amp list PLXVRS21ln3JIbFLPwf9bdH3thHmmYRJGi amp index 16 Pretty much what I did but in his video, it's working. In my project doesn't. Can someone help me, please? Many thanks beforehand


How do you animate collide against a tessellated mesh? Now that I have a implemented tessellation for my mesh, I am trying to understand how I can leverage the generated primitives. Example I have the following track mesh generated procedurally, it consists of quads, in the first picture you can see one of them I am highlighting using the mouse. In the following picture, the shader applies some tessellation, you can see that now a quad has generated 16 quads. Question (two folded) Now that I have more control points for each of my quad, suppose I want to deform one of them, for instance, to look like the following How is one supposed to apply such transformation ? basically, what in terms of code behind shader code infrastructure is required to achieve such thing. How can collisions be checked for against that deformed mesh ? from what I've understood, a mesh collider would be unpractical since it's a heavy operation that just forbids real time updates


When an object is launched off screen, is there any way to know if it's coming back? In this scene, the object becomes invisible and then comes back In this scene, the object becomes invisible but does not come back Is there any way I can tell if an object will come back when it becomes invisible? Edit Thank you to S. Tar k etin for the solution private void Update() if (isInvisible) if (IsNotComingBack()) OnInvisible?.Invoke() private void OnBecameInvisible() isInvisible true private bool IsNotComingBack() var pos cam.WorldToViewportPoint( rb.position) var extents cam.WorldToViewportPoint( spriteRenderer.sprite.bounds.extents) var isNotComingBack pos.x extents.x lt 1 pos.x extents.x gt 0 return isNotComingBack


Room lighting in Unity I am trying to make a plain white room in Unity. I used six planes for the walls, but I can't figure out how to get the lighting to not look so harsh and uneven. The top picture is my best attempt using two directional lights, and the bottom picture is the look that I am trying to replicate. It is from a demo scene in the Google VR SDK 1.50 for Unity. It uses only a single point light, but when I turn it off in the scene view, it doesn't change the appearance of the room at all. How can I make my room look more like the Google VR demo? EDIT I made a big improvement by changing all my walls to be static so that they receive indirect lighting, and adding a single point light above the roof.


How can I recreate the camera used in Swordigo game? What sort of camera does the Android game (2.5D) Swordigo uses? Is it an orthogrpahic camera? I think it is an angled orthographic projection. How can I recreate that sort of camera in Unity?


Synchronize objects' movements moved by coroutine function I'm using Unity version 5.3.5. I'm having problems to synchronize the movement of three different objects from point A to point B and vice versa. To move the objects I use the following code public float time public Vector3 endPos private Vector3 startPos void Start() startPos transform.position void FixedUpdate() if(transform.position startPos) StartCoroutine(Move(gameObject.transform, startPos, endPos, time)) if(transform.position endPos) StartCoroutine(Move(gameObject.transform, endPos, startPos, time)) public IEnumerator Move(Transform thisTransform, Vector3 startPosition, Vector3 endPosition, float time) float i 0f float rate 1 (time) while(i lt 1) i Time.deltaTime rate thisTransform.position Vector3.Lerp(startPosition, endPosition, i) yield return null As long as all of the objects have the same "time" value, their movements is correctly synchronized regardless the distance that they have to cover. The problems arises when they all have different "time" value. For example, if they have to move backwards and forwards from startPos(0,0,0) and endPos(5,0,0) with the following "time" value Object A time 1 second Object B time 2 second Object C time 4 second After 4 second, they should all be again at the same start position. However, what happen is that the fastest object (Object A) has a delay over the other two and this delay increase over time. How can i fix this problem?


Is it possible to use true Blinn Phong lighting on Unity Android IOS? I've noticed that the Unity's Legacy Shaders Specular shader does not work on mobiles due to the lighting model being incompatible. I then tried using the Mobile Bumped Specular shader, but this shader does not support non directional lights. So I tweaked the mobile specular shader to remove the noforwardadd argument, but I noticed that specular highlights are improperly positioned for non directional lights, even after removing the halfasview interpolateview argument. Does Unity even support non directional specular highlights on mobile devices?


Input.GetAxis returns wrong sign only for 1 and 1 I'm using an Xbox 360 controller on Windows 10 with Unity, and the maximum values have the opposite sign as the rest of that side. For example, if I tilt the stick up, I get values from 0.1 to 0.99, but then I get a 1 when the stick is at maximum. Have I configured it to be this way by mistake? I have reproduced the issue in a clean project and using another controller. void Update () float pitch Input.GetAxis("Vertical") Debug.Log (pitch) I have discovered that if the axis is inverted (i.e. not as shown in the image) then returned values have expected signs. I will add this workaround as an answer for anyone else who may encounter this problem, but I will refrain from accepting it to allow for answers addressing the root cause.


How do you turn off all scene lighting in the game view like you would with the scene view button? In the scene view, there's a control bar with a 'lighting' button that lets you toggle scene view lighting. This turns off all shadows and all light sources, i.e. makes it so that all objects are seen as fully bright on all sides. How do I do the same for the game view?


Create Script from custom templates issue They are created with the default name and cannot been named on creation I was just being introduced to the AssetDatabase class, and I was curious of creating Script Templates, such as Interfaces, pure C classes, and a MonoBehaviour template more suitable for my work style. I tried to emulate a solution I found on Unity Forums, and the template creation goes well, except that the name gets setted once it is created, and it doesn't let you name the created asset, as the Unity Scripts let you once you create them. The fact that the name is not changed by the user, makes the script on its default state, with the exact code the template has, without changing the SCRIPTNAME s declared, throwing errors, and being counterproductive with the time optimization goals I had in mind. using UnityEditor using UnityEngine using System.IO public class CustomScriptsCreator public const string CONTEXT MENU PATH "Assets Create Custom Scripts" lt summary gt Custom Scripts default Path. lt summary gt public const string CONTEXT MENU CUSTOM C SHARP " C MonoBehaviour" public const string CUSTOM TEMPLATE FOLDER PATH "Assets Custom Script Templates" public const string CUSTOM C SHARP TEMPLATE PATH "C Script CustomMonoBehaviourScript.cs.txt" public const string PATH NOT FOUND MESSAGE "Script Template Not Found" public const string WINDOW ERROR MESSAGE "There is no Template at path n n" public const string WINDOW OK ANSWER "Ok" MenuItem(CONTEXT MENU PATH CONTEXT MENU CUSTOM C SHARP) public static void Create(MenuCommand cmd) Object selection Selection.activeObject if (selection ! null) string path AssetDatabase.GetAssetPath(selection) if (File.Exists(path)) path Path.GetDirectoryName(path) if (string.IsNullOrEmpty(path)) path "Assets " THIS WAS JUST A FAILED TEST... Object obj Resources.Load("ScriptTemplates " CUSTOM C SHARP TEMPLATE PATH) if(obj ! null) AssetDatabase.CreateAsset(obj, Path.Combine(path, "NewScript.cs")) else EditorUtility.DisplayDialog ( PATH NOT FOUND MESSAGE, WINDOW ERROR MESSAGE (CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH), WINDOW OK ANSWER ) string newName EditorUtility.SaveFilePanelInProject("Save Your Prefab", "NewScript.cs", "cs", "Please select file name to save prefab to ") File.Copy((CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH), Path.Combine(path, "NewScript.cs")) if(AssetDatabase.CopyAsset((CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH), Path.Combine(path, "NewName.cs"))) IT CHANGES THE FILE NAME SUCCESSFULLY, BUT NOT ON THE SCRIPT. AssetDatabase.RenameAsset(Path.Combine(path, "NewName.cs"), "KillMePlease.cs") AssetDatabase.Refresh() else EditorUtility.DisplayDialog ( PATH NOT FOUND MESSAGE, WINDOW ERROR MESSAGE ((CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH)), WINDOW OK ANSWER ) The paths are ok, since the script is being created. If there is more information you need, let me know. Thanks in advance.


How to activate GearVR Menu in my own Unity Apps? So in normal GearVr Apps, which you can download from the marketplace, you can activate the GearVr Menu to control brightness etc. with a long click on the back button. But this does not work for all of my apps which I made with Unity for the GearVr, is there something special I have to import into my project?


ArgumentNullException Parameter name format I have made a simple game using Unity with Vuforia and exported for Android and iOS. It works fine on Android, but on iOS it crashed and gave the error ArgumentNullException Argument cannot be null. Parameter name format at System.Type.GetTypeFromHandle (RuntimeTypeHandle handle) 0x00000 in 0 at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object args) 0x00000 in 0 at System.String.Format (IFormatProvider provider, System.String format, System.Object args) 0x00000 in 0 at System.String.Format (System.String format, System.Object args) 0x00000 in 0 at UnityEngine.Debug.LogFormat (System.String format, System.Object args) 0x00000 in 0 at Vuforia.TrackerManager.InitTracker T () 0x00000 in 0 at Vuforia.TrackerManager.InitTracker T () 0x00000 in 0 at Vuforia.TrackerManager.InitTracker T () 0x00000 in 0 (Filename currently not available on il2cpp Line 1)


Failed to load QCARWrapper.dll I am using unity 5.1.0f(64 bit) and Vuforia SDK Version vuforia unity 5 0 5 The web cam is operating normally in windows but in unity in Play Mode not. I am getting an error message "failed to load QCARWrapper.dll expected 64bit architecture..." Can anybody help out solving this issue?


convert view space normal to world normal Im writing a shader that uses Unity's CameraDepthNormalsTexture to get both the view normal and depth values. I return a color from my fragment shader equal to the normal values sampled. I am having problems converting the view normal into a world normal so that when my camera tilts around, the fragment colors shouldnt change. How can turn my view normal world normal in my fragment shader? Relevant code is marked with TODO below Shader "Custom DepthNormal" Properties MainTex ("", 2D) "white" HighlightDirection ("Highlight Direction", Vector) (1, 0,0) SubShader Tags "RenderType" "Opaque" Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D CameraDepthNormalsTexture sampler2D CameraDepthTexture struct vertexOutput float4 position in clip space SV POSITION float2 depth TEXCOORD0 float4 scrPos TEXCOORD1 float4 position in world space TEXCOORD2 vertexOutput vert(appdata full v) vertexOutput output output.position in clip space UnityObjectToClipPos(v.vertex) use the helper function instead of MATRIX MVP as per documentation mul(UNITY MATRIX MVP,float4(v.vertex,1.0)) output.position in world space mul(unity ObjectToWorld,v.vertex) recall computeScreenPos does not divide by w, but because this is not an image effect, diving by w here will WARP things unless we are completely parallel to viewing camera output.scrPos ComputeScreenPos(output.position in clip space) return output float4 frag(vertexOutput input) COLOR float3 normalValues float depthValue extract depth value and normal values recall computeScreenPos does not divide by w, so if you want proper screenUV for use in tex2D divide xy by w https forum.unity3d.com threads what does the function computescreenpos in unitycg cginc do.294470 float2 screenUV input.scrPos.xy input.scrPos.w DecodeDepthNormal(tex2Dproj( CameraDepthNormalsTexture, input.scrPos), depthValue, normalValues) Alternatively DecodeDepthNormal(tex2D( CameraDepthNormalsTexture,screenUV), depthValue, normalValues) TODO CONVERT TO WORLD NORMAL? float4 worldNormalValues mul(unity ObjectToWorld,mul(UNITY MATRIX IT MV, float4(normalValues,1.))) THIS ISNT RIGHT ( float d pow(depthValue,2) return float4(normalValues.x,normalValues.y,normalValues.z,d) ENDCG fallback "Diffuse"


Shader intersection radiate outwards I've been working on a water shader for a project I'm currently working on and have been trying to work on the intersections between objects in the water to create a foam effect that radiates outwards. I'm very new to shaders so my code is probably horribly inefficient! But here it is Shader "Unlit WaterShader" Properties Color("Color", Color) (1,1,1,1) IntersectColor("Intersection Color", Color) (0,0,0,0) MinIntensity("Minimum intensity", Float) 0.04 MaxIntensity("Max Intensity", Float) 0.4 SubShader Tags "Queue" "Transparent" "RenderType" "Transparent" LOD 100 Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D cameraDepthTexture struct appdata float4 vertex POSITION float4 uv TEXCOORD0 struct v2f float4 screenPos TEXCOORD2 float4 vertex SV POSITION float4 Color float4 IntersectColor float MinIntensity float MaxIntensity v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.screenPos ComputeScreenPos(o.vertex) return o sampler2D CameraDepthTexture fixed4 frag (v2f i) SV Target float currentDepth tex2Dproj( CameraDepthTexture, UNITY PROJ COORD(i.screenPos)).r float linearDepth LinearEyeDepth(currentDepth) float depthDifference linearDepth i.screenPos.w if(depthDifference lt MinIntensity) Color IntersectColor return Color ENDCG It works well enough But now Id like to maybe try increase the intensity of the intersection. I know increasing MinIntensity doesn't really do what I want it to do, as it only shows more and more of the image submerged in water, which removes the effect of shoreline foam. I'd also like the outline of the objects in the water to spread out and fade out over time, I've tried using a sin wave for this but haven't been able to achieve the desired look.


What is a proper way to handle player inputs based on different states? So, I have two ideas how to do that Use enum to define current state and check current state value before running certain method group in Update. Code void Update() switch(currentState) case 1 InputGroup1() break case 2 InputGroup2() break lt ... gt And so on. I don't think that this is a good idea because of possible performance drops. Same concept about current state, but instead of checking it and running method groups, "head" script will check current state and activate corresponding script, disabling others. For me it looks like best way in terms of performance and usability. And also, is it better to keep all input checks in one giant script component and call functions you need from it? Essentially creating centralized Input Manager.


Ways to move a character in Unity I am studying Unity, and so far I encountered three different ways to move a character. As far as I understand Directly changing the transform ignores both physics and colliders Using a CharacterController component ignores physics but considers colliders Using a RigidBody component considers both physics and colliders. Are these descriptions correct? Which one should I use?


Should a wall be created as a plane or as a box? What are the benefits of a wall being as a plane or as a box? Should I use a plane with a box collider instead of mesh collider?


Should I avoid using object inheritance as possible to develop a game? I prefer OOP features when developing games with Unity. I usually create a base class (mostly abstracted) and use object inheritance to share the same functionality to the various other objects. However, I recently heard from someone that using inheritance must be avoided, and we should use interfaces instead. So I asked why, and he said that "Object inheritance is important of course, but if there are lots of extended objects, relationship between classes are deep coupled. I'm using an abstract base class, something like WeaponBase and creating specific weapon classes like Shotgun, AssaultRifle, Machinegun something like that. There are so many advantages, and one pattern I really enjoy is polymorphism. I can treat the object created by subclasses as though they were the base class, so that the logic can be drastically reduced and made more reusable. If I need to access the fields or methods of the sub class, I cast back to the sub class. I don't want to define same fields, commonly used in different classes, like AudioSource Rigidbody Animator and lots of member fields I defined like fireRate, damage, range, spread and so on. Also in some cases, some of methods could be overwritten. So I'm using virtual methods in that case, so that basically I can invoke that method using the method from parent class, but if the logic should be different in child, I have manually overridden them. So, should all these thing be abandoned as bad practices? Should I use interfaces instead?


Camera Movement Smoothing I am trying to smooth a camera I create in my game, but I can't seem to find a way to actually do this correctly. What I have Calculate the "current" Forward vector var cameraForward Vector3.Cross( Self.forward, target.up) .normalized.Cross(target.up).normalized Rotate the camera on the Y axis of the current target, and X Axis based on delta.y and CurrentVerticalLook cameraForward Quaternion.AngleAxis(delta.y, ViewTarget.transform.up) Quaternion.AngleAxis(CurrentVerticalLook, Self.right) cameraForward var offset cameraForward CameraDistance var pos LookAt offset Self.Position pos Self.transform.LookAt(ViewTarget.position) So what I ahve tried I tried Lerping the Vector Position, I tried smoothing the delta.y based on the last N frames. The Camera I need is something like this Rotate on the Around UP Axis of the target and Rotate on Right Axis of the Camera, Camera Up is always to Target UP. So this is sort of Orbital Camera, but I am having trouble finding the correct rotation operations. The way its set right works, but the camera movement is jaggy, but I can't seem to find a way to add Slerp in there without messing everything. Thanks! Edit lt


Rigidbody2D without pushing eachother on collision TLDR How to stop movement if two Rigidbodies collides? Also, here's a potato video of the problem https gfycat.com ComposedArcticBetafish Say I have three objects in a scene Player Enemy Rock The player and enemies is moving freely, but the rock is static. So I attached a Rigidbody2D on player and enemy to move them around with script. All of them has a Box Collider 2D. Now, if I (Player) move into an Enemy, I will start to push it (changing its position). I don't want this. I can set the Enemy's mass to something large, but then two enemies can still push eachother. I don't want this. If I try kinematic solutions I've found, but then they can move through the rock. I want Player can not move enemies Enemies can not move players Enemies can not move each other Nothing can move or go through the rock Enemies can not move through player Player can not move through enemies I keep reading that if I'm moving colliders, I should also use Rigidbodies for performance. But I can't see how I get this to work with Rigidbodies. How do I set it up? Or should I move away from rigidbodies and set it up myself?


IOS Keyboard as Gamepad in unity So I ve been messing around in unity lately, and I got a vr headset to mess around as as well(google cardboard). I also want to make my own controller to use with this. To achieve this, I want to use a HID complient chip with a arduino. Basicly, this sends usb keyboard input. I was wondering, will Input.getkey(keycode.whateverkey) work with this? I m not sure if that will even register on ios, because iOS keyboard is usually separate from the app because it covers the screen.


How to put trees on procedural generated world created using Perlin noise I have been new to game programming but I knew little bit about Perlin noise. So I have created a infinite world using Perlin noise but I don't be able to understand how I put trees in my world like it is put in game Factorio. My game is a 2d top down.


Have a particle system's particles obey transparency sort mode individually Background In a top down game, I have particles that spawn animated textures. I have my 2D renderer settings set up so that it orders sprites based on their position on th Y axis via "Transparency Sort Mode Custom Axis Y". The Problem But instead of sorting for each particle spawned, what happens is the particle system obeys the setting as a whole so that the sort order is only based on the particle's system's center. Is there a way to have each particle obey Transparency Sort Mode individually? What I want for each particle What actually happens Other Solutions Other people seem to have an old workaround to use GetParticles and setting their "order in layer" individually. See this thread from 2015 https forum.unity.com threads particle systems with sprites order in layer.464533 But I'm trying to find if there's a cleaner solution for Unity 2019 without having to fudge with "order in layer".


Unity Logic for saving and loading objects with both static and dynamic data I need help to get some structure for my save and load. I am making a city builder, so I have Buildings thats need to be saved. Each building has a lot of static Data, for example name, description, etc. However it also has a lot of dynamic Data, for example worldPosition, id, etc. My current structure looks like this On each Building GameObject I keep a reference to a ScriptableObject that stores all the static data. I also store a reference to an Object that stores all the dynamic data. This means I need 2 classes for storing Building data, which I already don't like (BuildingStaticData amp BuildingDynamicData) When I Save Load my game I only need to store the Dynamic data, so for saving I just save the DynamicData. For Loading I load the DynamicData, and instantiate a Building GameObject that is associated with it, then the GameObject has the reference to the StaticData. While this works, I would prefer to have a structure where I only have a single class for BuildingData, but I also don't want to lose the power of a ScriptableObject where I can reference other Prefabs etc. I need some help with this logic.


Unity InputSystem using Unity Events not maintaining values I am testing out using the new Input System and cannot get the values from context.ReadValue lt Vector2 gt () to pass into a private variable. The simple setup is below using UnityEngine using UnityEngine.InputSystem public class PlayerController MonoBehaviour Vector2 leftThumbstickValues void Start() leftThumbstickValues Vector2.zero void FixedUpdate() Debug.Log( quot FixedUpdate quot leftThumbstickValues) Always displays quot FixedUpdate (0.0, 0.0) quot public void Move(InputAction.CallbackContext context) leftThumbstickValues context.ReadValue lt Vector2 gt () Debug.Log( quot Move quot leftThumbstickValues) Displays correct values As you can see, in the Move function it correctly pulls the values from the thumbstick, but when it tries to use the values in FixedUpdate it always equals Vector2.zero. It seems like it should just work, but I think I must have overlooked something very simple. Player Input Settings Input Action Move Properties Input Action Left Stick Properties EDIT I decided to remove the Player Input component and subscribe to the events in code controls.Player.Move.performed cntxt gt Move(cntxt) controls.Player.Move.canceled cntxt gt leftThumbstickValues Vector2.zero This now works as expected. I'm not sure I should mark this as the answer though as it doesn't explain why it doesn't work with the original setup, just offers an alternative solution.


How to setup a public github unity repo with paid assets? From what I gathered (like in this thread or here) I am allowed to push my own game code on github and choose a license, as long as I avoid putting assets I do not own. I want to make it public to be able to show it (to potential employers for instance) but I cannot make it open source as I plan to use paid assets (like DoozyUI). I can avoid pushing the asset itself on the repo (with .gitignore for instance). Should I prevent gameobjects created with this package to be pushed as well ? That would make the game unusable, even with the rights to use the package... Once that is settled, Is it ok to push it to github without license ? Specifically, I do not know if objects generated by a paid asset are still considered that asset or not... Edit I asked the question directly to DoozyUI support, which quickly responded You can upload your project, without the Doozy folder. Thus excluding our source code from being shared. Also, unsert a disclaimer letting anyone know that DoozyUI is required to be installed (before getting your files) for the project to work. You can share any GameObject (or prefabs) you create, but they will not work if DoozyUI is not installed due to missing references (scripts). Once Doozy is installed, they will work as expected. Thus anyone who has the system will be able to see use your project.