Going up and down stairs by Unity3d's NavMesh Purpose I want to create a navigation mesh that is optimized for going up and down stairs and stopping. Question I'm making a nav mesh to make a character go up and down stairs. I'm making a nav mesh that makes a character go up and down stairs, but when the character stops in the middle of a step, his foot floats or his foot gets stuck in the stairs. I'm having a hard time creating a good path for the nav mesh. I'm wondering if you have any knowledge on how to bake a nav mesh for ascending and descending stairs. Please let me know what you know about baking navmeshes for stair climbing and descending, and what pages or ideas I should refer to when implementing stair climbing. Please let me know what you know about baking a nav mesh for stair climbing. Preparation Create the stairs and the ground in Probuilder so that the nav mesh can be baked. Case 1 Bake the nav mesh of the stairs. Test result. When ascending and descending the stairs, my feet sink into the ground. Every time I ascend or descend a flight of stairs, the surrounding scenery wobbles up and down. Case 2 Make a board to accompany the stairs. Bake the nav mesh with the stairs hidden and the slope displayed. Test result. When ascending and descending the stairs, the feet do not sink in. But when I stop at the step, my foot floats away. The scenery does not wobble because you are running on a board. Case 3 I made a board to accompany the stairs. I want to make the nav mesh of the step part flat. I want to make the nav mesh of the step part flat, so I'll edit the step part with the Probuilder function. Instead of a straight slope, lower the knot to create a slope and bake it. Test result. There is not much change in the shape of the nav mesh from Case 2. The phenomenon that the foot lifts off the ground when stopping at the step was not improved. The scenery is not wobbly because you are running on a board. Navigation mesh we want to achieve Development environment Unity2019.4.9f1 Package used ProBuilder4.2.3


How to achieve this kind of look of a cube in a most efficient way? It might be a trivial question, but I couldn't come up with a simple solution. I need to create a cube like on the image below in Unity. As always, I target mobile so it would be nice if it was made on a mobile diffuse shader. I was playing with lights a little bit, but in order to achieve this kind of look, I'd need to stack multiple lights because one shadow is not enough. Also, I tried adjusting the angles of the lighting with no luck. Do you have any tips, how could I make one in a most efficient way?


Help to Code Bowling Like Feature in Unity for Mobile I need Code or Guidelines for Touch Feature. When We Drag ball back and Send it Forward. I am Making feature like bowling, and I need Player to add force while dragging back and also curve the path of the Ball Anybody, Please Help


Unity Texture Problem http www.gfycat.com FlawedLimpingGrizzlybear http www.gfycat.com UnawareQuerulousHawk Every texture and shader has the same problem. It seems like the problem has nothing to do with either. Tried all the things my friends suggested I should, reimported everything, restarted my machine, nothing seems to work.


How to write properly shader with gradient based on vertex color? I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient. fixed4 frag (v2f i) SV Target fixed4 mainTex tex2D( MainTex, i.uv) fixed4 overTex tex2D( OverTex, i.uv3) fixed4 final fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) i.color, 1.0) final lerp(float4(0, 0, 0, 1.0), final, i.color.a) shadows return final How can i make the same gradients as bottom left and top right? In game this is faces of blocks (like minecraft) and gradients is smooth shadow light. So I cannot change tris


Unity shaders best way of handling data structures I'm working on a shader in Unity that uses a Binary Tree to store some precomputed values, this binary tree should be available to the shaders and would ideally also be constructed on the graphics card (each node in this tree is based on 1 pixel) is there a good way of doing this?


Camera Transition between 2 position rotation, and follow a 3rd target I have setup a transition of camera between 2 transform, here the result in video https youtu.be rcwQ6KuEfMw I have the information of the 2 transform position (vector3) rotation (Quaternion) And I do a Lerp, from Position1 to Position 2, and from Rotation1 to Rotation2 Vector3 finalPosition Vector3.Lerp(previousPosition, nextPosition, evaluateValueLerp) Quaternion finalRotation Quaternion.Slerp(previousRotation, nextRotation, evaluateValueLerp) Now the problem is, as you can see in the video the player target (the car) is lost durring the transition, I would like to keep it always in the view. How can I manage to do it ? Thanks you !


shader tutorial for unity I would like to start developing my own shaders within unity. For starters I would like to do a screen spaced blur. Are there any good tutorials to learn shader development besides the official unity documentation, which i find a bit hard to understand?


AddForce not moving imported model in Unity I've got a Unity project with an imported .fbx model I'm attempting to add movement to. As a test, I've added a sphere primitive with a sphere collider, a rigid body, and the following script public class ball test MonoBehaviour private Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () void FixedUpdate () Vector3 movement new Vector3 (1f, 0.0f, 1f) rb.AddForce (movement) This is partly copied from the Roll A Ball tutorial, and this works fine. The ball slowly rolls with no problem. I've imported a custom model, added a box collider, a rigid body, and assigned to it the same script. It doesn't move. Here's how they're set up


How to avoid game starting before start button is clicked? I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game before the user presses start. Is there a way to make the GameObjects only appear after the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right. This is my first game ever, so hope the code provided is relevant. Enemy.cs void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") GameManager.cs public void StartGame() powerup.transform.rotation) score 0 UpdateScore(0) isGameActive true titleScreen.gameObject.SetActive(false) void Update() enemyCount FindObjectsOfType lt Enemy gt ().Length if (enemyCount 0) roundNumber SpawnEnemyIntruders(roundNumber) Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation) void SpawnEnemyIntruders(int enemiesToSpawn) for (int i 0 i lt enemiesToSpawn i ) int enemyIndex Random.Range(0, enemies.Length) Instantiate(enemies enemyIndex , GenerateSpawnPosition(), enemies enemyIndex .gameObject.transform.rotation) public void GameOver() restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) isGameActive false PlayerController.cs void Start() playerRb GetComponent lt Rigidbody gt () playerAudio GetComponent lt AudioSource gt () StartButton.cs void Start() button GetComponent lt Button gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () button.onClick.AddListener(StartThis)


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.


Having player names over models in 3d space I wanted to have in my multiplayer game, the players name's over their models, however I am faced with the question of how? Should I create a new Canvas object for each game model or just use 1 main canvas and move their names around relative to position in 3D world space? My aim is to have an open world game.


Unity Animation Curve to change value over time I am trying to learn how to use AnimationCurve to change a float value over time. However i am not really sure how to do it Say i have the following class public class SpiritAway MonoBehaviour public List lt SkinnedMeshRenderer gt MeshList public List lt Material gt DissolveList public float percentage 0.0f public bool IsDissolveing public AnimationCurve Curve private void Start() percentage 0.0f for (int i 0 i lt MeshList.Count i ) for (int j 0 j lt MeshList i .materials.Length j ) if (MeshList i .materials j .shader.name "Dissolve") DissolveList.Add(MeshList i .materials j ) Update is called once per frame void Update() if (IsDissolveing) if (percentage lt 1) percentage 0.01f for (int i 0 i lt DissolveList.Count i ) DissolveList i .SetFloat(" alphaClipDissolve", percentage) Now i wish to incrase the percentage value with the percentage of the animation curve to get a more smooth and controlled transition of the value. Could anyone explain how this is possible?


Discarding triangles in Unity I have about 2 years of experience in computer gaming development and I just started writing my own shaders to help me utilize performance. I have this problem that I'm trying to work around but after several tries nothing seems to work. Basically, I have a plane that's made of 16641 vertices thats 32768 triangles and I know that is pretty much. The plain has a texture on it with some colors. Now, what I am trying to do is placing units on that plane. Where they stand, the vertex under them will have a certain color but all other vertexes on the plain will have the color white. The idea is to discard and don't draw vertexes that aren't white. Now in the shader, I tried two things. 1 In the vertex input I check if the vertex, called o, had the o.color.b value ! 0. If so it was given the alpha value of 0 and would not be seen when rendering. 2 In the vertex output, I checked the same thing ( if(i.color.b ! 0) discard ) and discarded the fragment so it would not be rendered. That way I thought Unity should not count these triangles and thus wouldn't waste performance. Now when I run my game and open the stats, with the plane active I have 85.8k triangles and only 28 draw calls. With the plane un active I have 20.2k triangles and 26 draw calls (Note there are some units, interface, skies etc around that counts up to 26 draw calls, thus the plane is just 2 draw calls). I thought this solution would be clever to save draw calls (developing for mobile games) by treating this plane and the colors under the units as one instead of making them all a separate gameobject. Turns out, I'm way over budget on the triangles. Does anyone know if this is possible and if so, give a good answer or explenation? Here is the following shader. Shader "Custom Ottar VertexBasic" Properties MainTex ("Particle Texture", 2D) "white" Transparency("Transparency", Range(0,1)) 1 SubShader Tags "Queue" "Transparent" Blend SrcAlpha OneMinusSrcAlpha AlphaTest Greater .01 ColorMask RGB Lighting Off ZWrite Off Fog Color (0,0,0,0) Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma multi compile builtin pragma fragmentoption ARB precision hint fastest include "UnityCG.cginc" uniform float4 MainTex ST float Transparency VertexInput struct vI float4 vertex POSITION float4 texcoord TEXCOORD0 float4 color COLOR uniform sampler2D MainTex VertexOutput struct vO float4 pos SV POSITION float2 uv float4 color vO vert (vI v) vO o o.pos mul (UNITY MATRIX MVP, v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) float4 viewPos mul(UNITY MATRIX MV, v.vertex) o.color float4(v.color.rgb, v.color.a 1) if(o.color.b ! 0) o.color.a 0 else o.color.a 1 return o float4 frag (vO i) COLOR if(i.color.b ! 0) discard else half4 texcol tex2D( MainTex, i.uv ) return texcol i.color Transparency ENDCG Fallback "Particles Alpha Blended"


In Unity how can I know which direction is the screen auto rotated? From the Screen.orientation description I get If the value is set to ScreenOrientation.AutoRotation then the screen will select ... automatically as the device orientation changes. This seems to imply that if the screen does auto rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation. If that's so, how can I know in which direction it has been auto rotated? Disabling the auto rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either. This should be cross platform, without including any kind of non C plugin. (the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)


Player going out of boundaries So, I been following up the Space shooter tutorial on Unity, I had an issue where the project was acting up with an alpha version, so I was able to get a version that worked on a old release and applied all the new things I developed But suddenly, my ship is acting up when getting closer to the boundary of its movement This is the player movement code public class playerMovement MonoBehaviour public float speed 0.0f public float tilt public Boundary boundary void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") var movement new Vector3(moveHorizontal, 0.0f, moveVertical) var rigidBody GetComponent lt Rigidbody gt () rigidBody.velocity movement speed rigidBody.position new Vector3 ( Mathf.Clamp(rigidBody.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rigidBody.position.z, boundary.zMin, boundary.zMax) ) rigidBody.rotation Quaternion.Euler(0.0f, 0.0f, rigidBody.velocity.x tilt) System.Serializable public class Boundary public float xMin, xMax, zMin, zMax And this is the player boundary properties It used to work previously moving forward to the alpha, now I'm working on 2019.2.0f1, but since working on the alpha this is the behaviour I'm having As you can see, getting closer to the player boundary, takes the player out of the play area, and I can't determine why this might be happening. I already tried removing the Math.Clamp, as I though there migth be bug with the function in this version, but even without it, the problem is present.


Frequent stuttering, high FPS spikes with VSync option turned on in Unity standalone build I'm experiencing an issue using Unity 4.3.2 and standalone builds. If I turn on VSync in the project's Quality settings, running the game at the native monitor resolution, I'll frequently get high framerate spikes (over 100FPS), and a strong stutter for a few frames, and then it drops back down to 60FPS and runs normally. If I run the game at a lower resolution (800x600 for example), the framerate stays at around 500FPS and the stuttering is consistent. However, if I turn off VSync in the Quality settings, and force it on in the Nvidia Control Panel, I don't experience any stuttering or framerate spikes, nor when I turn off VSync completely (but lots of screen tearing, which is very ugly and distracting). Can anyone explain this behavior? Is there anything that can be done to circumvent it? I'd imagine other Unity developers have used the built in Unity VSync with success before (or maybe not?!) so I'm hoping I'm just doing something wrong on my end.


Lightmapped prefabs for procedural content I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the scene instead of objects when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps. Is there a way to get lightmaps for dynamically created prefabs with Unity's built in lightmapper?


How to draw texture with unlit effect on surface base texture I am writing a shader to my Unity game and I want to have effect this type of effect Base texture, for example, skin of character is a texture that will use shadows, lighting. Second texture, unlit, it will not be using shadows, it will be moving and changing alpha intensity. Second texture will be drawn after base texture. Only unlit or surface shader looks bad, I think I must connect those two shaders, to make nice looking effect. I wrote something this and I am stuck Shader "My SurfaceUnlitBlend" Properties MainTex("Base", 2D) "white" MainColor("Main Texture Color", Color) (1,1,1,1) SecTex("Second Texture", 2D) "white" SecColor("Second Texture Color", Color) (1,1,1,1) SecTexAnimHSpeed("Second Texture Animation Horizontal Speed", Float) 0 SecTexAnimVSpeed("Second Texture Animation Vertical Speed", Float) 0 BlendValueModifier("Blend Value Modifier", Range(0.5, 2.0)) 1 Glossiness("Smoothness", Range(0,1)) 0.5 Metallic("Metallic", Range(0,1)) 0.0 SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Standard fullforwardshadows pragma target 3.0 struct Input float2 uv MainTex float2 uv SecTex sampler2D MainTex sampler2D SecTex fixed4 MainColor fixed4 SecColor fixed SecTexAnimHSpeed fixed SecTexAnimVSpeed fixed BlendValueModifier half Glossiness half Metallic UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf(Input IN, inout SurfaceOutputStandard o) Albedo comes from a texture tinted by color fixed2 moveVector fixed2( SecTexAnimHSpeed, SecTexAnimVSpeed) moveVector Time 1 set blend modifier according to time float blendLevel (cos( Time 1 ) 1.5) BlendValueModifier set colors fixed4 col1 tex2D( MainTex, IN.uv MainTex) MainColor 2 fixed4 col2 tex2D( SecTex, (IN.uv SecTex moveVector) 15) SecColor blendLevel blend colors fixed4 result col1 col2 o.Albedo result ENDCG FallBack "Diffuse" Because I don't know what to do, to have unlit effect in second texture.


Unity how to change runtime code for different platforms? In Unity, how can I programmatically control what source code is compiled? I have a script with various BuildPipeline.BuildPlayer calls, allowing me to build all versions of my game. However, I'm using the AVPro Video asset to play video, and it doesn't support 32bit Mac. As such, I need to fall back other video playing code on 32bit Mac. There's no preprocessor directive to differentiate 32bit OSX (like you can do for other platforms https docs.unity3d.com Manual PlatformDependentCompilation.html ). However, since I'm building each version in sequence, it seems like I should be able to set some state so that during compilation, the right code is used. I tried this VersionHandler.onMac32 true BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneOSXIntel, BuildOptions.None) VersionHandler.onMac32 false And then checking that static variable in game. However, that static is "never set", presumably because the the state of the variable during compilation doesn't affect the value at runtime. Is there any other way I can "get at" the compiled code and set a flag for certain builds? As a fallback, I can manually swap code in every time I build for OSX 32 bit, but I'd prefer not to do that.


Why doesn't my orbit form an ellipse? I'm playing around and trying to build an orbit simulator. Unfortunately, it isn't working out to well. Instead of forming some sort of elliptical orbit, I get this Here is the code I'm using to generate the orbits public class OrbitBehaviour MonoBehaviour public Double Mass private List lt GameObject gt bodies new List lt GameObject gt () private float gravConstant 6.673f Mathf.Pow(10.0f, 11.0f) Units m3 kg 1 s 2 private int delay 0 private float distanceConversion 6.68458712f Mathf.Pow(10.0f, 12.0f) m gt AU (Astronomical Units) private float massConversion 1.67403241f Mathf.Pow(10.0f, 25.0f) kg gt E (Earth masses) private float timeConversion 1.1574074074074074074074074074074e 5f s gt D (Days) Use this for initialization void Start() bodies GameObject.FindGameObjectsWithTag("mass").ToList() gravConstant Mathf.Pow( distanceConversion, 3.0f) gravConstant massConversion gravConstant Mathf.Pow( timeConversion, 2.0f) gameObject.GetComponent lt Rigidbody gt ().AddForce(Vector3.left 10f) Mass Mass massConversion Time.timeScale 99.0f Update is called once per frame void FixedUpdate() StepSimulation() private void StepSimulation() Walk each body in the system foreach (GameObject body in bodies) if (gameObject body) continue skip self Vector3 tSeparationVector body.transform.position gameObject.transform.position tSeparationVector tSeparationVector.normalized OrbitBehaviour bodyBehaviour body.GetComponent lt OrbitBehaviour gt () Double tForceValue gravConstant (this.Mass bodyBehaviour.Mass tSeparationVector.sqrMagnitude) gameObject.GetComponent lt Rigidbody gt ().AddForce(tSeparationVector.normalized (float)tForceValue) Does anyone know what I am doing wrong here?


Unity Profiler What would cause PlayerEndOfFrame to have 10 16MB in GC Alloc? I can't find much documentation on what "PlayerEndOfFrame" does. Sure it is the end of a frame but what would cause the GC Alloc to go so high? This is the profiler results from a debug build on a remote machine using the IP connect to unity profiler.


Why does my AI Enemy slide towards its target when it is supposed to be idle? So using Unity standard assets to get a stage rolling, Ive built a simple terrain and used FPSController as the player and AI ThirdPersonController (Ethan) as the enamy. Ive built the navmesh and everything was working in its default state, but then I changed the AI script slightly as I wanted Ethan to follow me only if I come within a certain range, so I changed it to the following public float dangerRadius 5f private void Start() get the components on the object we need ( should not be null due to require component so no need to check ) agent GetComponentInChildren lt UnityEngine.AI.NavMeshAgent gt () character GetComponent lt ThirdPersonCharacter gt () agent.updateRotation false agent.updatePosition true private void Update() if (target ! null) agent.SetDestination(target.position) if (agent.remainingDistance lt dangerRadius) character.Move(agent.desiredVelocity, false, false) else character.Move(Vector3.zero, false, false) public void SetTarget(Transform target) this.target target But the problem is that when the remainingDistance is greater than dangerRadius or when I am out of range, Ethan just slides slowly towards the target in idle state and as the distance becomes lower than the threshold he starts running as expected. Ive tried adding friction materials to the terrain and the collider on Ethan but he still slides. Help thanks


Select a button without calling click i have a grid layout group containing buttons. My game must be playable with a joystick and so I have to navigate the buttons using horizontal vertical input. My problem right now is when the layout group first becomes visible. Once I click on a button (with my mouse), it becomes "selected" and I can navigate through the layout group with my keyboard and 'click' with spacebar. This functionality is all fine, except for the need to click the button with a mouse to set the first selection. I've tried both of the following void buttonClicked() Debug.Log("clicked") void Start () this button is actually instantiated from a prefab, not shown here Button btn inventorySlot.button btn.onClick.AddListener(buttonClicked) attempt 1 btn.Select() attempt 2 eventSystem.SetSelectedGameObject( btn.gameObject, new BaseEventData(eventSystem) ) both these commands do select the button, but they also inadvertently call the onClick, and the button is clearly being clicked because it changes color (I have configured this through button opts in the inspector). My question is how can I "select" the button without clicking it? I perhaps should also note, I am populating the layout group with buttons at runtime. Each button is intantiated from a prefab in Start() (not showing that here). I only add the event listeners and try to select the button after it's already added to actual game objects in my scene.


How can I make a trail renderer flat with the normal of the nearest face? I'm making a basic skid system for a car model using a trail renderer. I have everything setup and working properly except that the trail renderer always faces the camera. I want the trails to be perfectly flat with the ground. So I thought if unity can make the faces all rotate towards the camera, then would it be able to rotate towards the normals of the nearest faces?


Unity3d Transform rotation(angle) help Im trying to rotate an object 90 degrees to the left but instead of rotating straight left it rotates 270 degrees to the right. Here's the part of the code which controls the rotation rotationDestination new Vector3(60, 270, 0) if (Vector3.Distance(transform.eulerAngles, rotationDestination) gt 0.2f) transform.eulerAngles Vector3.Lerp(transform.rotation.eulerAngles, rotationDestination, rotationSpeed Time.deltaTime) If I try to make the Y axis 90 a.k.a (60, 90, 0) then it rotates constantly to the left. How do I make it rotate straight to the left (90 degrees) ? Thank you.


Which collider to use on "island" situation? I have a 2d top down unity game where the player is on an island. The shape of the island is random generated and he is not able to "escape" from the island. So which Collider should I use for realizing this? Is there some form of an "inverted" collider? Are colliders able to have a hole in them? Or should I create a polygon collider with a small gap (This could be quite difficult if the polygon bends the wrong way)?


How to set keys for emission on off for a prefab? I am making a prototype for a Mario game and am having difficulty completing a canned animation for a prefab. There is an item box asset that has 3 materials and an "ItemGet" animation. One of these materials has an active emission property that is supposed to turn off during a specific frame of the "ItemGet" animation. These boxes will have an "Active" and "Inactive" state. While "Active", the item box just bobs up and down and IF Mario hits the trigger, the "ItemGet" animation plays (and the player gets a unique item). The box then becomes "Inactive". While "Inactive", no animations play, the emission effect is gone and the trigger cannot be reactivated. Challenges finding the correct property to set a keyframe for in the Animations panel. Making sure Active versions of the prefab remain Active after any ItemBox becomes Inactive and that all materials don't change when GetItem plays. Ideas Instead of keying the emission on off property (assuming that exists and does what I think it does trouble finding it), swap the materials. ( . . . ), swap the mesh. Can somebody please help me find a viable way to finish this animation that fits this object's intended use case?


Character Controller and Reverse Gravity So I have a Game object with Rigid Body, a Character controller and my Movement script. On a specific condition I am reversing gravity. The problem is that the velocity.Y when the gravity is reversed, keeps increasing to the infinity. If I try to reset it like in the first if statement (which works for normal gravity) the object keeps bouncing from the ground. Gravity scale is either 1 or 1 in order to reverse gravity and movement. This is the code void Update() isGrounded Physics.CheckSphere(groundCheck.position, 0.4f, whatIsGround) Move() void Move() Reseting States for new cycle , unless the object is falling if (( isGrounded amp amp velocity.y lt 0)) velocity.y 2f isRunning false isJumping false isFalling false else if (velocity.y lt 0 amp amp ! isGrounded) isFalling true Moving on X axis float x Input.GetAxis(KeyInputMove) if (x ! 0) isRunning true moveDirection gravityScale transform.right x controller.Move(moveDirection moveSpeed Time.deltaTime) Perfoming jump if (Input.GetButtonDown(KeyInputJump) amp amp isGrounded) velocity.y (float) Math.Sqrt(1 2f globalGravity) isJumping true velocity.y gravityScale globalGravity Time.deltaTime controller.Move(velocity Time.deltaTime) Updating animation states animator.SetBool( quot Grounded quot , isGrounded) This is the idle state animator.SetBool( quot Running quot , isRunning) animator.SetBool( quot Jumping quot , isJumping) animator.SetBool( quot Falling quot , isFalling) private void OnTriggerExit(Collider other) Reverse Gravity and Model Rotation if (other.gameObject.tag quot Portal quot ) transform.Rotate(0,0,gravityScale 180) gravityScale 1


Unity C Using Linecast with collider bounds I'm trying to to detect when two 3D objects overlap each other 'visually' without actually touching. For example, if I have two spheres in a scene that are 1 meter apart and I rotate my camera around the objects so that one sphere is blocked by the sphere in front of it, I want to detect when this occurs. After many searches in this forum, I patched together the solution below. However, it only partially works it only detects overlap when the center of the occluded object is reached (i.e., "bounds.center"). I read that there is a way to use the bounds in this scenario so that it samples multiple rays from around the object. This way, overlap is detected at the objects visual boundary and not just it's center. Unfortunately, my coding abilities are meager and I can't figure out how to do it. Any help would be greatly appreciated. using UnityEngine using System.Collections public class OverlapCheck MonoBehaviour public Transform myCamera private Color mouseOverColor Color.green private Color originalColor private Vector3 objectExtents Use this for initialization void Start () originalColor gameObject.GetComponent lt Renderer gt ().material.color objectExtents gameObject.GetComponent lt Collider gt ().bounds.center Update is called once per frame void Update () if (Physics.Linecast (objectExtents, myCamera.position)) gameObject.GetComponent lt Renderer gt ().material.color Color.yellow else gameObject.GetComponent lt Renderer gt ().material.color originalColor


How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object? I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have void Start () Color newShirtColor shirtColor Random.Range(0, shirtColor.Length) MaterialPropertyBlock props new MaterialPropertyBlock() props.AddColor(" Color", newShirtColor) GetComponent lt SkinnedMeshRenderer gt ().SetPropertyBlock(props) It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section?


What to use instead of UNet? If you look at this Link you'll see UNet is deprecated and will be removed in the future. I'm developing a mobile multiplayer game, i've red official advise about it but they say "You can publish it with 2018.4 (LTS)" and I can't use 2018.4 version because in my project i use LWRP which is not in the 2018.X versions. I've found the alpha version of the new system right here My questions are 1 Should i use the alpha version of the new system? And can i publish my game with it? 2 Should i wait for the new system came out? (I can't wait for months) 3 Should i try to use other third party systems like Photon? Or is there any way to publish my game with nice multiplayer system? Note I can't pay for multiplayer matchmaking system. Because of that i want to make Hosting multiplayer game.


How to change pre splash image for iOS? When I launched my game on my iPad, the screen first displayed a faulty splash image with a black lower half momentarily, before displaying the normal splash image. No matter what I tried, I couldn't get rid of this faulty 'pre splash image'. I have tried the following Entered my Plus package serial number and updated my seat in Unity. Deleted and left all splash images blank in Unity. Checked all the LaunchScreen XXX.png images in Xcode. Checked the files referenced by Images.xcassets in Xcode. Changed all the above images to a completely black image. Still, the old faulty picture would appear. Cleared all the data and installation files on my iPad. Deleted General Launch Images Source. I wonder where Xcode kept the faulty image. I am using Unity 5.5.1 and Xcode 9.2. Could someone please help?


How do I override a SteamVR Controller's transforms in Unity? I'm trying to provide an illusion to the user by rotating the controller about an arbitrary axis in the LateUpdate() method. But this doesn't seem to be having any effect as the controller probably is constantly getting updated by its real world location. Is there any way to override its real world position and orientation with a transformation in script?


Unity How can I control a Shadergraph effect on multiple enemies with the same prefab? So I made a simple White Flash Dissolve effect with shader graph 2D, it's my 1st time using shaders. I'm controlling the effect using a float inside the shader, with Material.SetFloat("FLOAT NAME", 0 1f) And I'm wandering how can a control only a single instance of my Shader without affecting all my enemies. Example I have 20 enemies, all from the same prefab with the same material. I want to be able to make 1 enemy dissolve whenever I shoot at him.


Unity Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY Unity How does one debug this Xcode error on an iOS device? Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY


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


In Unity displaying long lists of information to screen? Tables? Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers) But I cannot seem to find a way to display all these infos in a table with columns such as Name Age Company etc I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also. Any ideas for this in Unity specifically? EDIT I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject. EDIT 2 D i've found this https docs.microsoft.com en us aspnet mvc overview older versions 1 models data displaying a table of database data cs would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)? Thanks for any help


How do I hide an Input field? I have in my hierarchy tab a Canvas. Inside the canvas I have an Input Field that holds a placeholder and a text. I read the documentations and didn't find how to hide the Input field. I want that if a if statement is true, then it will show the input field. Else you won't see it. How can I implement it? EDIT I thought about an idea to test If I press the O key on the keyboard it disappears, and if I press again it appears and so on. This is what I tried bool shown true Use this for initialization void Start () Update is called once per frame void Update () GameObject inputField GameObject.Find("InputField") if (Input.GetKeyDown (KeyCode.O)) shown !shown inputField.SetActive (shown) I play the scene and when I press the O key I get NullReferenceException Object reference not set to an instance of an object If I double click on the console message it highlights me the if (Input.GetKeyDown (KeyCode.O)) line. Something not good does the SetActive(bool) method, I suppose.


Why can't I sample a texture in a vertex shader? I'm old in Game Development but very new in shader writing. I just want a shader that transform from 1 texture to another. So I did start learning shader writing and wrote my desired shader. But during writing one thing I cannot understand as I am very dumb in shader writing that if I assign fixed4 color with COLOR semantic in vertex method then compiler gives the following error. Shader error in 'Hamza TwoTextures' cannot map expression to vs 4 0 instruction set at line 39 (on glcore) Compiling Vertex program Platform defines UNITY ENABLE REFLECTION BUFFERS UNITY PBS USE BRDF1 UNITY SPECCUBE BOX PROJECTION UNITY SPECCUBE BLENDING SHADER API DESKTOP UNITY TEXTURE ALPHASPLIT ALLOWED Here is the not working shader code, Shader "Hamza TwoTextures" Properties NoScaleOffset Texture1 ("Texture 1",2D) "white" NoScaleOffset Texture2 ("Texture 2",2D) "white" Mixer ("Mixer", Range(0,1)) 0 SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag sampler2D Texture1 sampler2D Texture2 float Mixer struct appdata fixed4 vertex POSITION fixed2 tex TEXCOORD0 struct v2f fixed4 pos SV POSITION fixed2 tex TEXCOORD0 fixed4 col COLOR v2f vert(appdata i) v2f o o.pos mul(UNITY MATRIX MVP,i.vertex) o.tex i.tex Giving error on this line o.col (tex2D( Texture1,i.tex) Mixer) (tex2D( Texture2,i.tex) (1 Mixer)) return o fixed4 frag(v2f v) COLOR return v.col ENDCG And if I write same expression to throw it as return fixed4 value in fragment method then everything is working fine. Here is working shader code, Shader "Hamza TwoTextures" Properties NoScaleOffset Texture1 ("Texture 1",2D) "white" NoScaleOffset Texture2 ("Texture 2",2D) "white" Mixer ("Mixer", Range(0,1)) 0 SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag sampler2D Texture1 sampler2D Texture2 float Mixer struct appdata fixed4 vertex POSITION fixed2 tex TEXCOORD0 struct v2f fixed4 pos SV POSITION fixed2 tex TEXCOORD0 v2f vert(appdata i) v2f o o.pos mul(UNITY MATRIX MVP,i.vertex) o.tex i.tex return o fixed4 frag(v2f i) COLOR It is giving me no error return (tex2D( Texture1,i.tex) Mixer) (tex2D( Texture2,i.tex) (1 Mixer)) ENDCG Can anyone explain me that why it is happening? And what is the difference between them? As I mentioned that I did start learning only two days before. I'm sort of noob in this.


Unity3D) Is there a way not to draw line renderer if vertex pos is zero? I make a curved line with line renderer. and a sphere move along it. i want to draw a line only behind the sphere. so i do something like this. lr.positionCount 256 while (delta lt time) lr.SetPosition(i , curPos) yield return new WaitForFixedUpdate() and the problem is, because of i set the size of Positions 256, if time is short, there are zero vectors in position. so line renderer draw meaningless line. is there a way to set PositionCount dynamically like List? or any good way to not draw if positions are zero?


How to make Scriptable Objects derive from other Gameobejcts? I encountered a problem where I want to make a Scriptable Object that derives from another class, but C does not support multiple inheritance. Further, I do not think it would not make sense to make interfaces for this example. There is a lot of duplicate code within methods that only an abstract class could contain implementations of. Basically, I want an abstract class that models "anything that can take a turn." I call it a TurnTakeable. But I also want the TurnTakeable to be split into friend and foe derived types, as the two are slightly different. Yet they mostly have the same behavior. Is there a workaround, or do I have to make an interface? (


Why is my A object resetting to (0, 0, 0), instead of following its path? I'm working on an RTS project, and I'd like to use the A Project by Aron Granberg to navigate around obstacles. The problem is that the correct path is displayed in the scene, the unit is still walking forwards, but the unit just jumps to (0, 0, 0). As is, this as a workaround to have some progress in my build script. Why is my A object resetting to (0, 0, 0), instead of following its path? I don't know where I made the mistake that leads to this behavior. Here is script responsible for the movement using UnityEngine using Pathfinding using RTS public class Unit WorldObject public float moveSpeed public Path path public float nextWaypointDistance 3 private int currentWaypoint 0 protected override void Update() Vector3 dir (path.vectorPath currentWaypoint transform.position).normalized MakeMove(dir) if (Vector3.Distance(transform.position, path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint return private void MakeMove(Vector3 dir) transform.position Vector3.MoveTowards(transform.position, dir, Time.deltaTime moveSpeed)


How can I attract repel the mouse cursor from particular UI controls? This question came from some of my students. I wanted to share it here so others can find amp improve on the solutions we've found so far. In particular, my answer below doesn't behave as well as I'd like in windowed editor mode UI buttons no longer respond to hovering the cursor. I welcome alternative answers that solve this more completely. We're making a visual novel game using the Fungus asset for Unity. We want to add a twist where some dialogue options are easier or harder to press, because they attract or repulse your mouse cursor. Unfortunately, we haven't been able to identify a cross platform way to manipulate the mouse's position, nor a way to create a "Fake" mouse cursor image that can still interact with Fungus's UI buttons. How can we pull this off?


Problem with Raycasting in a 2D Game I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have, function calculateWalk() yield WaitForSeconds(0.3) var hit RaycastHit if(Physics.Raycast (transform.position, Vector3.down, 100.0)) Never evaluates to being true var distanceToGround hit.distance Debug.Log("Hit") if(hit.collider.gameObject.tag "tallGrass") walkCounter Debug.Log("Tall Grass") END if END if END calculateWalk() I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles.


Inheritance accessing child class values I want to use the same variable for five different child classes. It is basically a boolean that is true when a player purchases an item(represented by a child class) and false when the player is yet to purchase that item. Then save the bool status. Can someone tell me how to do just that? Do I create five different bool variables each on their respective classes(the child classes), then access them individually when a player wants to buy the item? If I change the bool value of a parent class, it'll change it across all of it's child class.


How can I rotate an object with random speed with some delays? using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World Use this for initialization void Start () Update is called once per frame void Update () if (World true) transform.Rotate(TurnX Time.deltaTime,TurnY Time.deltaTime,TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime,Random.Range(3,300) Time.deltaTime,TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) This is the random part Random.Range(3,300) but sine it's changing the random numbers too quick the changes are almost not visible. I want somehow to make that if for example the next random will stay for example 5 seconds at this speed number then move to the next random number and again stay at this number 5 seconds and so on. Tried this using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World private bool IsGameRunning false Use this for initialization void Start () IsGameRunning true StartCoroutine(SpeedWaitForSeconds()) Update is called once per frame void Update () IEnumerator SpeedWaitForSeconds() var delay new WaitForSeconds(3) define ONCE to avoid memory leak while (IsGameRunning) if (World true) transform.Rotate(TurnX Time.deltaTime, TurnY Time.deltaTime, TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime, Random.Range(3, 300) Time.deltaTime, TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) yield return delay wait but that just rotate the object once each 3 seconds. and not rotating it all the time with speed changing every 3 seconds. but now it's not rotating for 3 seconds it rotating every 3 seconds. better to describe what I want is like intervals. The object should spin all the time nonstop like i Update but then each 3 seconds to change for a random speed. for example spin at speed 5 ....after 3 seconds spin at speed 77 ....after 3 second spin at speed 199


Gradient Input in Game view I want to develop a little tool to help visualize fireworks before using them in a show in Unity where the user can set several parameters and gets a preview of the firework effect in a preview window. To allow the user to customize color over time like I can currently statically do in the visual effects graph, I wanted to add a Gradient input field to my UI. After fiddling around with manually trying to make things work, I stumbled upon the new UIElements UI Toolkit and following this Medium post was able to render a simple text UI in a Panel Renderer. However the Gradient Field I added won't show up (which is quite reasonable because in the UI Builder it said something about quot Editor only quot ). Just to make sure, the box on the left is what I mean I was strolling around in the Asset Store for a while but couldn't find anything like what I was looking for (just shaders and stuff to apply a gradient to UI elements amongst other things). Other searches led to tutorials on how to completely custom build a single color selection tool which both seemed like a larger effort and didn't allow creating a full gradient. The question is Is there some sort of library, package or tool I could use to add an input like that to my quot game quot ? Or am I taking a completely wrong approach with this?


pass by reference a transformation I create a C script in which I declare a transformation public Transform Origin When I put this script on an object of the hierarchy, in the Inspector a field Origin appears at the level of the script in which I have to drag and drop a transformation of a GameObject or a GameObject. How does the Origin transformation deal with the GameObject transformation to move in this field? Thank you for your help


Unity Autoscroll when selecting buttons out of viewport I have a ScrollView element, that contains many buttons. I want that when I select buttons (via arrow keys), the panel scrolls so that the selected button is contained within the viewport. How could I achieve this? UPDATE This is example of my structure (with 2 buttons only, but you get the gist...)


GameObjects deleted before scene loads I am trying to persist objects on scene loading, but the objects always get deleted when the scene does load. LevelManager.CS public void LoadLevel(string name) if (name "Main") SceneManager.LoadSceneAsync(name) GameManager.LoadState() else GameManager.SaveState() SceneManager.LoadScene(name) Debug.Log("the scene is " name) I placed the LoadScene method ontop in the hopes it would complete loading the scene before moving onto the next method call. In the next method call, I restore objects to their state. GameManager.CS public static void LoadState() ES3.Load lt Dictionary lt Vector2, Building gt gt ("Buildings") foreach(Vector2 v2 in buildingPositions.Keys) Building b buildingPositions v2 if(b.GetType() typeof(Farm)) newFarm Instantiate(farmPrefab) as Farm Debug.Log("Build " newFarm) newFarm.transform.position v2 Debug.Log(newFarm.transform.position) newFarm.level b.level newFarm.name b.name newFarm.levelText newFarm.GetComponentInChildren lt Text gt () CheckTheCall() What actually happens is when the scene is changed, the LoadState code is run at the same time, which then causes my object to be deleted after the scene has finished loading, because its created before the scene changes. The third last line "newFarm.name b.name" gives me an error that newFarm was destroyed. The last line "CheckTheCall()" calls newFarm (which I declare at the top of the script to ensure scope wasn't the issue) and that shows newFarm exists as a farm. THEN after all this, the scene changes, so my instantiated object is deleted. I'm so confused I tried with just SceneManager.LoadScene(name) but the result is still the same. It's like the entire function completes and then the scene loads. Any ideas on how to get around this one? I need the objects to spawn back into the main scene in the same state they were.


Hold button down by mouse? When I hold down a button by mouse for 5 seconds, print a message. How to do this ? I wrote this script but is not working. I don't know if there other methods. Public float clock Public Button out public void quit out mouse() clock Time.time if(Time.time clock gt 3.0f ) Debug.Log (" gone !! ")


Why when using editor script with handles with DrawSolidArc it's not drawing any arc over the object? This is the editor script is in the Assets Editor using UnityEngine using UnityEditor CustomEditor(typeof(DrawSolidArc)) public class DrawSolidArcEditor Editor public float arrowSize 1 void OnSceneGUI() DrawSolidArc t target as DrawSolidArc Handles.color Color.blue Handles.Label(t.transform.position Vector3.up 2, t.transform.position.ToString() quot nShieldArea quot t.shieldArea.ToString()) Handles.BeginGUI() GUILayout.BeginArea(new Rect(Screen.width 100, Screen.height 80, 90, 50)) if (GUILayout.Button( quot Reset Area quot )) t.shieldArea 5 GUILayout.EndArea() Handles.EndGUI() Handles.color new Color(1, 1, 1, 0.2f) Handles.DrawSolidArc(t.transform.position, t.transform.up, t.transform.right, 180, t.shieldArea) Handles.color Color.white t.shieldArea Handles.ScaleValueHandle(t.shieldArea, t.transform.position t.transform.forward t.shieldArea, t.transform.rotation, 1, Handles.ConeHandleCap, 1) And the mono script for example this script is attached to a simple 3d cube using UnityEngine ExecuteInEditMode public class DrawSolidArc MonoBehaviour public float shieldArea 5 but there is nothing around the cube. not also near it nothing. it should draw arch in the editor. Later I want to be able to use the mouse with a click down and drag to be able to change the arc size but for not it's not drawing any arc. I took the example from the unity official docs https docs.unity3d.com 540 Documentation ScriptReference Handles.DrawSolidArc.html I noticed now also for example that I don't see the gui button in the inspector of the object that the mono script is attached to if (GUILayout.Button( quot Reset Area quot )) not sure what's wrong with the editor script. This is working. I still wonder why the unity docs example didn't work but this is working and I don't need the editor script. The problem with this script is that I must to turn on the Gizmos in the editor and I don't want to make it turned on all the time. So it's working but not as I wanted. I want to draw the arc without the gizmos. using UnityEngine ExecuteInEditMode public class DrawSolidArc MonoBehaviour public Vector3 offset Vector3.one public float fieldOfViewAngle 20 public float viewDistance 4 public bool usePhysics2D false public void OnDrawGizmos() DrawLineOfSight(this.transform, offset, fieldOfViewAngle, viewDistance, usePhysics2D) public static void DrawLineOfSight(Transform transform, Vector3 positionOffset, float fieldOfViewAngle, float viewDistance, bool usePhysics2D) if UNITY EDITOR var oldColor UnityEditor.Handles.color var color Color.yellow color.a 0.1f UnityEditor.Handles.color color var halfFOV fieldOfViewAngle 0.5f var beginDirection Quaternion.AngleAxis( halfFOV, (usePhysics2D ? Vector3.forward Vector3.up)) (usePhysics2D ? transform.up transform.forward) UnityEditor.Handles.DrawSolidArc(transform.TransformPoint(positionOffset), (usePhysics2D ? transform.forward transform.up), beginDirection, fieldOfViewAngle, viewDistance) UnityEditor.Handles.color oldColor endif


How do I deal with scale of the universe when generating a simulated universe? I have a dataset of 100,000 actual stars. I wish to create a game where I can fly between the stars and fly up to them and click on them etc. How do I go about dealing with the problem of the scaling of the universe, even If I were to allow fast as light travel it would be too vast. Should I cluster my data and then implement a subtle sort of scaling to move around? Sorry for the broad question but I'm rather stuck at the moment.


In Unity C , how can I change weapon a few frames later? I have this Input code to change weapon if (d left) if (!p d left) states.inventoryManager.ChangeWeaponToNextWeapon(true) p d left true if (d right) if (!p d right) states.inventoryManager.ChangeWeaponToNextWeapon(false) p d right true And in the InventoryManager I have the weapon changed by this public void ChangeWeaponToNextWeapon(bool isLeft) if (isLeft) if (l index lt r l weapons.Count 1) l index else l index 0 EquipWeapon(r l weapons l index , true) else if (r index lt r r weapons.Count 1) r index else r index 0 EquipWeapon(r r weapons r index ) states.actionManager.UpdateActionsOneHanded() Then equip the weapon along with animation and other stuff public void EquipWeapon(RuntimeWeapon w, bool isLeft false) if (isLeft) if (leftHandWeapon ! null) leftHandWeapon.weaponModel.SetActive(false) leftHandWeapon w else if (rightHandWeapon ! null) rightHandWeapon.weaponModel.SetActive(false) rightHandWeapon w string targetIdle w.instance.oh idle targetIdle (isLeft) ? " l" " r" states.anim.SetBool(StaticStrings.mirror, isLeft) states.anim.Play(StaticStrings.changeWeapon) states.anim.Play(targetIdle) UI.Slot uiSlot UI.Slot.singleton uiSlot.UpdateSlot( (isLeft) ? UI.QSlotType.lh UI.QSlotType.rh, w.instance.icon) w.weaponModel.SetActive(true) But the problem is the weapon changes immediately after pressing the button. How can I switch my weapon a few frames later while playing the animation?


How to generate objects at specific intervals and make them move with same speed? I'm creating an infinite runner where character has to jump on randomly generated pillars. The pillars are positioned with a gap between each of them. The gaps are dmin and dmax. In addition to this, i want the pillars to move to the left of screen with increasing velocity. But they all need to move with same velocity so that the gap in between them is maintained. I have the script as follows pillar is a prefab.go is an empty gameobject which will later be used to Instantiate pillars. first is the first pillar, manually positioned in the scene. using UnityEngine using System.Collections public class GM MonoBehaviour float tempx,dmin 1.3f,dmax 3.5f GameObject bins Vector2 speed,pos,tempvel public GameObject pillar,go public Transform first Use this for initialization void Start () speed new Vector2 ( 0.005f,0) tempx first.transform.position.x tempvel new Vector2 (0, 0) void Update () if ((Vector3.Distance (go.transform.position,transform.position) lt 40f)) tempx Random.Range(dmin,dmax) pos new Vector2(tempx, 2.22f) go Instantiate(pillar,pos,Quaternion.identity) as GameObject bins GameObject.FindGameObjectsWithTag("trash") tempvel new Vector2 ( 0.0005f, 0) foreach (GameObject bin in bins) bin.GetComponent lt Rigidbody2D gt ().velocity new Vector2(Random.Range( 0.005f, 0.05f),0) bin.GetComponent lt Rigidbody2D gt ().velocity tempvel Problem is, the speed of pillars increases way too fast. They move to the left at nearly invisible speeds. Also, after a certain speed, the gap between the pillars increases. They become so far apart, one is in camera view, another is somewhere far away. Is there a way to accomplish this?


Spawning random items to drop from the top of the screen I'm wondering how to make specific random objects drop. In my case, from the top of the screen. I have 16 objects, named recycle items 0 through recycle items 15. IEnumerator CreateRoutine() while (true) yield return new WaitForSeconds(3) CreateItems0() private void CreateItems0() Vector3 pos Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0)) pos.z 0.0f Instantiate(recycle items 0, pos, Quaternion.identity)


Unity uNet Low Level API which values should I snyc? I am using unitys unet low level api TransportLayer. I send my own message by converting strings to byte arrays. I want a server authoritive setting, so that I can try to implement my own client side prediction. I am also using unitys physics2d, rigidbodies and so on. I thought about to move the rigidbodies with it's velocity. I wonder which values I should send from client to server and backwards, to avoid the rigidbody jittering. I know that I cannot simply send the clients position to the server, because that will cause the jittering "effect". Would be nice, if anyone can give me guidance. Thanks )


Unity 2D Cinemachine weird behavior for non rectangular confiner I have been trying to emulate a sort of Megaman X4 way of following the player around platforming levels, where the camera is confined to certain boundaries of such levels. However, all the tutorials and guides out there only show rectangular or square shaped confiners for the virtual cameras, and not odd shapes like an L shaped confiner, when using a weirdly shaped confiner the camera just tends to snap from one position to another and the game ends up feeling bad when that happens. I have tried solving this problem by using dolly tracks, which work nicely... But I end up having tons of virtual cameras to change to on sections that are weirdly shaped since the camera ends up also suddenly snapping on to weird positions on sharp turns and it also tends to get way off track, even when the settings of the virtual camera are configured to have very little damping and if there's no damping the camera just stutters all the time. Is there a way to have this kind of behavior to confine a virtual camera to oddly shaped level boundaries?


My unity game fails to open in my mobile I'm new to Unity, and want to make a android game. I made a very simple scene A sphere A cube (floor) A simple script that moves the sphere by touch. I tried it with unity remote and it works fine. But the problem manifests when I build it to test it. When I run it on my mobile, it opens and suddenly gets closed. I don't know what is the actual problem. what should i do?


How to zoom image on Unity UI to particular point where mouse cursor is located? I have some RectTransform on Unity UI. I have already implemented some Zoom functionality but now I need it to zoom to the area where the mouse cursor is located. Currently, it zooms to the anchor point. How can I zoom to the mouse cursor? Here are some screenshots from a hierarchy. I have already implemented zoom itself. public class ZoomableRect MonoBehaviour SerializeField private RectTransform rectToZoom SerializeField private ZoomConfigs zoomConfigs private bool onObj false SerializeField private ScrollRect scrollRect public ScrollRect ScrollRect get return scrollRect set scrollRect value private bool isZoomAllowed public bool IsZoomAllowed get return isZoomAllowed set isZoomAllowed value private bool isFullScreen public bool IsFullScreen get return isFullScreen set isFullScreen value void Start() if (!rectToZoom) rectToZoom GetComponent lt RectTransform gt () void Update() float scrollWheel Input.GetAxis("Mouse ScrollWheel") if (isZoomAllowed amp amp scrollWheel ! 0) ChangeZoom(scrollWheel) SetPosition(Input.mousePosition) private void ChangeZoom(float scrollWheel) float rate 1 zoomConfigs.zoomRate Time.unscaledDeltaTime if (scrollWheel gt 0) SetZoom(Mathf.Clamp(transform.localScale.y rate, zoomConfigs.minSize, zoomConfigs.maxSize)) else SetZoom(Mathf.Clamp(transform.localScale.y rate, zoomConfigs.minSize, zoomConfigs.maxSize)) private void SetZoom(float targetSize) transform.localScale new Vector3(targetSize, targetSize, 1) public void SetPosition(Vector2 mouseInput) float rectWidth rectToZoom.rect.width float rectHeight rectToZoom.rect.height float mousePosX mouseInput.x float mousePosY mouseInput.y float widthPivot mousePosX rectWidth float heightPivot mousePosY rectHeight Debug.Log("widthPivot " widthPivot " heightPivot " heightPivot) rectToZoom.anchorMin new Vector2(widthPivot, heightPivot) rectToZoom.anchorMax new Vector2(widthPivot, heightPivot) rectToZoom.transform.position new Vector2(mousePosX, mousePosY) Debug.Log("MousePosX " mousePosX " MousePosY " mousePosY) public void SetAnchors(bool isFullScreen) if (!isFullScreen) rectToZoom.anchorMin new Vector2(1, 1) rectToZoom.anchorMax new Vector2(1, 1) But anchors always snap to the bottom left corner. And widthPivot and heigtPivot values are always bigger than 1. Actually, after testing, I see that anchors are less than 1 when the cursor is located in the bottom left part of the screen. And bigger than 1 when the cursor is in the top right part of the screen. When zooming it always snaps to the bottom left corner. It seems that mouse position connected to the current resolution at the same time canvas on which zoomableRect is potisioned has reference resolution of 1920 x 1080. Changing a pivot in the same way instead of anchors doesn't have any effect. Same result.


Dual touch controls turning on one axis I wanted a swift look around functionality to be put in the middle of a room and just look around. So obviously I imported the standard assets and put the FPS controller in the middle and then dragged in the Dual touch controls and build it to android. The problem is that it only rotates horizontally and not vertically. I tried playing around with the values a bit but nothing seems to be working.


How to adjust the width of a LineRenderer I wrote a code that draws a line by mouse movement. I am searching for some way to give it pencil style and head and end of the line have thinner width. As we know the LineRenderer draws the line between points. How can I access first and last point elements to set the width of them and how can I do that?


Game build crashes on scene load I built out my project to Android to do some testing and stuff, but I can't get any further than the main menu scene. I built it out previously and it was running fine. Now as I try loading level0 it crashes with no error messages from adb logcat. Just exits the game and that's it. It works fine in the editor. I tried several things. I changed the color space back and forth, I built my addressables, tried development built and non development one, and the Split application binary checkbox is false as well... Unity 2019.2 My adb catlog output


How to add user created data to drop down menu options So I'm trying to make it that I can have a dropdown that will have user created info appear in it. List lt engines gt engineList new List lt engines gt () public Dropdown engineSelect public class engines public string engineName public int featureNumber public int totalDevPoints public string optimizedGenre public engines(string name, int feature, int totalPoints, string opt) engineName name featureNumber feature totalDevPoints totalPoints optimizedGenre opt engines playerEngine new engines(engineName, numFeature, 0, whatGenre) Pretend player set engineName, numFeature, and whatGenre with text fields. I wanted to have it that the drop down would add in whatever new engines the player makes. How would I do that? I want to have it say select engine and then the player would pick from dropdown from engines they made(only saying engine names).


How can I make alternate fragments drop (or make them black) based on a checkerboard texture? How can I make alternate fragments drop(or make them black) based on a checkerboard texture in a Unity fragment shader? I am using forward path rendering in my shader passes for lighting and shadows for every object in the scene. Now,I need a shader (or something) that drops alternate pixels from the overall screen space after everything is rendered. How can I achieve this effect?


Setting up sequential animation clips in Unity I'm trying to play two animation clips sequentially using Unity 2D. I've been using Mecanim for this so I've imported the two clips in a newly created controller and connected the first one to the next one. I also want the last clip to be looping so I set that toggle in the settings of the clip. Now for some reason the first clip is played just fine but the second one doesn't animate at runtime. It loops fine in the Animator window and the clip itself works in the preview window but not at runtime. I've also tried setting it up using the Animation Component and use the PlayQueued method but this doesn't give any animation. I'm kind of lost on what to try next EDIT This is to be used on a Canvas UI Image


Make gameObject stick to another gameObject after it has collided with it? Currently, I am using the following code to make objects stick to other gameObjects. rb GetComponent lt Rigidbody gt () rb.isKinematic true gameObject.transform.SetParent (col.gameObject.transform) It works perfectly, but it causes many other problems... For example, after colliding, it can no longer detect collisions... Is there an alternative to this code (which makes a gameObject stick to another one after collision)?


Why does my Unity Android game get a small amount of lag when not being touched for some time? I have made a 3d version of space invaders. I made all the assets myself in Blender. I feel that it's a very basic game and my Galaxy Note 3 test device should handle it no problem. (Although it's a few years old now so perhaps some kind of shader issue or something that my phone not updated enough for ?) There are 55 enemies all with one mesh each. There's the flying saucer model and the player model. Then there's a plane for a background, and 4 defensive meshes (although I've tested without these and the result is the same). Basically, it all runs superbly (I have turned down much of the lighting and graphics quality etc, but have left basic shadows in). However I notice that if the player just lets the phone sit there in game without touching it, there is very slight (but noticeable) frame lag. All the enemies have a very short animation which moves its arms a small amount. I could post the code but its massively unorganized and really quite an embarrassment (HAHA!). Also I'm not sure what parts are relevant so it would be a huge post. Is there any known issues that can cause the lag only when not being touched? As I feel like some of my old projects might have had this happening too but they've been deleted now unfortunately so I can't really dabble with it. It works smooth as silk in the Unity Editor Android 'emulator' and as I say, if I actually play the game on my phone it's smooth too.


Why is there a discrepancy between these two transform.up vectors? I was trying to implement a feature which required transform.up, the result didn't match the green axis gizmo displayed in the editor so I assumed it was being put off by the rotation of the object despite expecting the gizmo to adapt to that. I then modified the prefab such that everything was now child to an empty object and the secondary objects were child to that instead of the rotating model, and wrote a script that simply copies the transform so that it tracks. This still didn't show the values expected from what the gizmo in the editor showed. I then did a Debug.LogError in the track script and this time the result was as expected. Why is transform.up showing the value expected from the local y axis gizmo but when passing a reference to the original script and checking tracked.transform.up gives off results? To reproduce in a simpler environment I set up a simple test scene. Simple default cube with the hierarchy structure shown in the screenshot. The transform values are as follows parent zeroed x 0, y 90, z 0 for cube x 0, y 90, z 90 for TrackPoint Scripts are as follows test.cs attached to trackpoint private void Update() Debug.LogError(transform.up) Track.cs attached to tracker public Transform transformToTrack private void Update() transform.position transformToTrack.position transform.rotation transformToTrack.rotation Debug.LogError(transform.up) byref.cs attached to cube public GameObject refObj private void Update() Debug.LogError(refObj.transform.up) When run, if you clear the console then click pause you'll see that one of them differs from the others. I don't understand why. My project and this sample scene differ in which it is that is giving unexpected results but the results are inconsistent with what I would expect. But wouldn't they all give the same result?


World space coords for 2d images How can I make an 2d image using World space coords with a shape? Like a circle instead of a quad.In 3d you can modify the vertices but if I want a smooth circle there will be too much vertices. What I want to achieve is something like a cirle mask that will be move over the global texture at runtime. So has anyone done something similar? I've tried combining some shaders with two uv's one for world space and one for alpha uv mesh but it gives some weird artifacts. This is the how the shader looks on the right Shader "Unlit WorldspaceTiling" Properties MainTex ("Texture", 2D) "white" SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" LOD 100 ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off Lighting Off ZWrite Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert (appdata v) v2f o o.vertex mul(UNITY MATRIX MVP, v.vertex) Gets the xy position of the vertex in worldspace. float2 worldXY mul( Object2World, v.vertex).xy Use the worldspace coords instead of the mesh's UVs. o.uv TRANSFORM TEX(worldXY, MainTex) return o fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) return col ENDCG


How to share microgame with WebGL Publisher? (Unity) I did unity lego microgame tutorials and now I want to publish it with WebGL publisher. I created build files but I can't publish. I get this error I rebuild again to solve this problem. (3 more times..) And clicked quot locate existing building quot again but I still get this error. What should I do?


How to efficiently keep the player from moving outside the gameobject he is colliding with? I am developing a game with Unity 2017. The game mechanics are as follow Classic top down RPG Movements are UP, DOWN, LEFT and RIGHT Player evolves in a 16 16 map He can dig in the direction he wants to make his way through the map one tile at a time At first I was using a very classical approach using tilemaps, RigidBody2D and BoxCollider2D on tiles and the player GameObjects. Collision detections went fine and my tilemap looked pretty much like that (red being the walls and white the empty spaces) The problem with this approach is that I have to keep in memory the state of 256 tiles in a List lt Vector2f gt and to create the 256 expected GameObjects representing either my walls (which a totally black), or my floor (the empty space). Creating a black GameObject with its own BoxCollider2D for each of the tile seems a little bit overkill. And this brings me to the second iteration of my game to keep in memory only the tiles the player digged. What I would like to achieve efficiently, is to let the player evolve as long as he is colliding with an underlying tile, but stop moving as soon as he doesn't. This is ok This isn't, and player should be placed to previous state. I could take advantage of OnTriggerEnter2d and handle custom collision and response, but I have the feeling that something more simple and more optimized may exists somehwhere in the wild! Thanks to any help provided!


Using CNN's in Unity via Tensorflow and TensorFlowSharp I have a project that tracks hands made in python, shown here https github.com timctho convolutional pose machines tensorflow I want to effectively import this into Unity. I have generates the .bytes file from the model, but have no idea how to do anything further than this. If anyone has worked with ML Agents or TensorflowSharp in Unity and or would be willing to have a look, this would be great. The image processing stuff would be done probably in a C file beforehand, I just want to know how to run the network. Thanks.


Baking artifact in Unity I am using unity 2017.1.0 f3, Enlighten baking, with Generate lightmap UV ticked in import settings. Also the object has prioritized illumination and the light map resolution is high. An example of the artifact is shown. The lightmapping settings is as follows. The issue doesn't appear in Realtime illumination. The object is marked static. Can someone help me?


Unity How to add a shader to a material via c script? I found already some things but those seem not quite what I need. (perhaps outdated functions?) https docs.unity3d.com ScriptReference Material shader.html here, it seems you can add a shader to a renderer using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public Shader shader1 public Shader shader2 public Renderer rend void Start() rend GetComponent lt Renderer gt () shader1 Shader.Find("Diffuse") shader2 Shader.Find("Transparent Diffuse") void Update() if (Input.GetButtonDown("Jump")) if (rend.material.shader shader1) rend.material.shader shader2 else rend.material.shader shader1 well i dont have a renderer. i only have a material. and there is no "material.setShader" , only a material.setTexture" sooo can anyone solve this mystery of how to add a shader to a material via script?


Change value in arrays in array The title might be confusing and I don't think this short explanation is 100 accurate, but I will try my best to show the problem. So I have this hierarchy And I want to change quot measureOfTime quot value in all subWave in wave i , because I had no clue how to do this in a short way (at least I bet there is a shorter way) and I made this using UnityEngine public class EnemySpawner MonoBehaviour Header( quot Set this value here to set time to 1 wave quot ) public float timeUntilWave Header( quot Measure Time basically 0 quot ) public Wave waves public float waveTime public bool roundStarted public int wave private void Start() wave 1 roundStarted false private void Update() if (timeUntilWave gt 0) timeUntilWave timeUntilWave 1 Time.deltaTime else if (timeUntilWave lt 0) roundStarted true wave if (roundStarted true) waveTime waveTime 1 Time.deltaTime int subwaveLenght waves wave .subWave.Length int count 0 while (count lt subwaveLenght) waves wave .subWave count .measureOfTime waves wave .subWave count .measureOfTime 1 Time.deltaTime count And in lines 33 and 37 I see an error quot IndexOutOfRangeException Index was outside the bounds of the array. quot And here are 2 questions Why those errors appear here? Is there an easier way to raise the value in arrays in an array? I hope it's not too confusing, and thanks for your help!


When I exit the pause menu of my game the gun fires When The player exits the pause menu in my game the gun will fire. I figured out that it happens when the player clicks when the game is paused. Basically i the player goes to the pause menu and exits without clicking the gun will not fire, but if they go to the pause menu and click then exit the gun will fire. Here are my scripts public class Shooting MonoBehaviour Animator anim public float FireRate 15f private float NextTimeToFire 0f Start is called before the first frame update void Start() anim GetComponent lt Animator gt () Update is called once per frame void Update() if (Input.GetButton("Fire1") amp amp GetComponentInParent lt PlayerController gt ().moving false amp amp Time.time gt NextTimeToFire) NextTimeToFire Time.time 1f FireRate Shoot() public class PauseMenu MonoBehaviour public static bool GameIsPaused false public GameObject HUDPanel public GameObject PauseMenuPanel public GameObject OptionsPanel private void Start() Time.timeScale 1f GameIsPaused false void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (GameIsPaused) Resume() else Pause() void Resume() Cursor.lockState CursorLockMode.Locked Cursor.visible false PauseMenuPanel.SetActive(false) OptionsPanel.SetActive(false) HUDPanel.SetActive(true) Time.timeScale 1f GameIsPaused false void Pause() Cursor.lockState CursorLockMode.None Cursor.visible true PauseMenuPanel.SetActive(true) HUDPanel.SetActive(false) Time.timeScale 0f GameIsPaused true


Why is my inherited class's transform always null? I have a class inherited to another class, and I can't get the transform on the inherited class. Here's what i have and trying to do Class A Monobehavior Class B A somewhere else A object new B() but right now, whenever I try to get the transform of object, either from a function in B or out here via object.transform, it will always return null. How do I fix this?


UNet send message by Client.Send error I'm try to implement client server communication base on UNET. The problem i got now is send custom message to server, but the Client.Send always show error without my understanding. So what i'm wrong? I jus try to implement from scratch, not inherit from NetworkManager. Here is the code using UnityEngine using System.Collections using UnityEngine.Networking public class ZMessageTransfer NetworkBehaviour private static ZMessageTransfer instance public static ZMessageTransfer Instance get return instance NetworkClient m Client public class MessageType public static short Login 1001 public class LoginMessage MessageBase public string username public string password void Awake () instance this public void SendLoginMessage(string username, string password) LoginMessage loginMsg new LoginMessage() loginMsg.username username loginMsg.password password m Client.Send(MessageType.Login,loginMsg) Server using UnityEngine using System.Collections using UnityEngine.Networking using UnityEngine.UI public class ZMatchServer NetworkBehaviour public int listenPort public int maxConnection public bool enableNAT public Text currentPlayer public Text currentLog private int onlinePlayer void Start () Network.InitializeSecurity() Network.InitializeServer(maxConnection,listenPort,enableNAT) NetworkServer.RegisterHandler(ZMessageTransfer.MessageType.Login,OnPlayerLogin) void OnPlayerLogin(NetworkMessage netMsg) var loginMsg netMsg.ReadMessage lt ZMessageTransfer.LoginMessage gt () string username loginMsg.username string password loginMsg.password currentLog.text "Player send login " username " " password void OnServerInitialized() Debug.Log("Server Initialize completed! ") currentLog.text "Server Initialize completed! " void OnPlayerConnected(NetworkPlayer player) onlinePlayer 1 currentPlayer.text "Current player online " onlinePlayer.ToString() currentLog.text "Player connected" Debug.Log("Player connected " ) void OnPlayerDisconnected(NetworkPlayer player) onlinePlayer 1 currentPlayer.text "Current player online " onlinePlayer.ToString() currentLog.text "Player disconnected" Client using UnityEngine using System.Net using System.Collections using UnityEngine.Networking using UnityEngine.Networking.Types public class ZNetworkConnection NetworkBehaviour SerializeField private string serverURL SerializeField private string serverIP SerializeField private int serverPort NetworkClient m Client private static ZNetworkConnection instance public static ZNetworkConnection Instance get return instance void Awake() instance this void Start () ConnectToServer() protected void ConnectToServer() Network.Connect(serverIP,serverPort) public void LoginToServer(string username,string password) ZMessageTransfer.Instance.SendLoginMessage(username,password) protected void OnConnectedToServer() Debug.Log("Connected to server complete ")


Character on Moving Platform Shaky. How to Fix? I have an elevator (rigid body platform) that is meant to transport a character. The character (RigidBodyFPSController) shakes while platform descends. What is an elegant way to fix their relative motions while the elevator is in motion, still allowing the character to move around in it? NOTE I tried parenting the character but that flips him on his side.


How do I get light to go through a window texture in Unity? I'm having trouble with the lighting (I have windows and the light wont go through). How do I get the light to proceed through the glass?


Would I need to delete unused assets from my Unity packaged build? I'm going to make a release for my Unity game. Does Unity include unused assets in build output? Would removing unused assets from a project reduce build size Time? I want to know if Unity packages all the assets to my build (which I would need to delete), or if Unity packages only the assets that are actually used in the game.


Unity Client and Multiplayer Networking Architecture My background is in Enterprise and SaaS web infrastructure. Zero information about games and how their networking works. I only know about the world of browsers and RESTful APIs. I'm planning on using Unity for the client FYI. Authentication and Authorization I'm planning to use Unity and Firebase. Seems like this is fairly standard HTTP connections during the auth faze. Nothing surprising here unless there is something I missed. The client authenticates against a service, Firebase in this case. And then all future calls after authentication are made using the returned credentials. Gameplay and Player State This part confuses me. I assume shooters use a UDP type protocol or some proprietary protocol on top of UDP. But can a game use a REST API and HTTP or TCP connections to send client updates? Clients would then poll the game server or have a long running connection open to request updates. For example the Auction House in WoW. Is there a long lived TCP connection open between the client and the server updating the auction house data every X seconds? Then when a player submits a purchase order that same long lived TCP connection is used to update the game server state? Or is it all literally a REST API like a SaaS app would use? Is my experience with browsers and Single Page Apps in an Enterprise environment applicable to a WoW auction house type situation? Thank you, Any tips or feedback is helpful at this point.


Help understand Z value of CameraToWorldPoint I do not understand what this CameraToWorldPoint function is used for, what is the use case of this function 1.From my understanding, my cursor is sitting on the near clipping plane, so I am actually clicking all the points on the near clipping plane, the near clipping plane represents my screen, am I right? 2.When I use this function to convert B point to world point, I am getting the point C position, is that true? 3.Is part A gt C represent the Z value, or part B gt C is the Z value? 4.Then finally, is this function useless? Because I get a world position in the predefined Z position, and I do not even know what Z value should be in the first place, I can randomly assign a pointless Z value, so what is use case for this function, I know raycast can do anything I want, but when to use this function?


How do I use GetComponent on multiple children? I'm a beginner and I'm making a game in Unity where I set random colors for four enemies. I made an empty object called "enemies" for me to use it as a folder for the four enemies. I want to get the colors of the enemies and pick randomly one of them for my player. I wrote this piece of code and I wanted it to store the colors in a list, but whenever I try to print it I find out that it only stores the color of the first child in the "enemies" hierarchy. How do I fix this? enemies GameObject.Find("enemies") GameObject allenemies new GameObject enemies.transform.childCount List lt Color gt colors new List lt Color gt () foreach (Transform child in transform) allenemies i child.gameObject i foreach (GameObject child in allenemies) thecolor enemies.GetComponentInChildren lt Renderer gt ().material.color colors.Add(thecolor) finalcolor Random.Range(0, colors.Count) Debug.Log(finalcolor) mr.material.color colors finalcolor


Efficient way to store information about neighbour chunks I've finally managed to implement an infinite chunk loading system for my voxel engine. Since every chunk needs to have information about the border of the neighbouring chunks, I need to access them fast. First some information about how I'm storing the voxel data I have an Integer array of block information on each chunk (rather than byte because of the read write access speed), which is stored in an Dictionary(Vector3i chunkPos, Chunk chunk). When building a chunk I have to access the voxel data of the chunk and of the neighbouring chunks several times. Without information about their neighbours it currently looks like this So I've tried the following two things getting the chunk data every time like this public static int getBlockAt(int x, int y, int z) Vector3i chunkIndex new Vector3i( x gt gt ChunkManager.logChunkSize, y gt gt ChunkManager.logChunkSize, z gt gt ChunkManager.logChunkSize ) if (chunkManager.chunkData.ContainsKey(chunkIndex)) return chunkManager.chunkData chunkIndex .data x amp ChunkManager.chunkMask, y amp ChunkManager.chunkMask, z amp ChunkManager.chunkMask return 0 storing chunkSize 2 information on each chunk, which makes editing much, much slower, but improves chunk loading alot In general I want to implement something like using approach 1 only when the block data isn't on the chunk. I really don't know how I could do it! Do you have an idea, or experience from writing voxel engines? Thanks in advance!


Game 30 done on HTML5. Maybe it was a bad idea. Should I change to Unity3d? I'm creating a 3d game on HTML5. It's 30 complete and the hard part is already coded. The server is on node.js.Now I'm realizing that maybe it was not a wise choice. This is because I realized Three.js still has many bugs. I don't see the same thing on every machine. Each browser, OS, can give different results. I'm afraid my clients will have a great stress installing my game properly. I have tons of sprites and models on my game. I wonder if my clients will have to load all them again everytime they want to play? I wonder if a Node.js server will be fast enough to handle it, and I'm afraid it won't be scalable. What would you advise me? Should I continue and finish the game on HTML5 or is it better to remake it on something else, like Unity3d for the client and (what?) for the server?


Center Gravity in Unity a 2d planet in the center, where the players will be able to walk on it and also will be affected by center gravity. planet will be static and there won't be any other planets. so Is there a way that I can change the gravity position? yes you can adjust gravity via project settings but I want it to be in the middle x,y,z(0,0,0) I have tried creating my own gravity but it wasn't very useful because objects wouldnt fall, stand on foot and also in contact with another object they would vibrate instead of standing still. (if they stand on the planet they would vibrate) private void FixedUpdate() foreach(GameObject item in grav) Attact(item) private void Attact(GameObject gmf) Rigidbody2D rgg gmf.GetComponent lt Rigidbody2D gt () Vector3 direction rg2d.position rgg.position float distance direction.sqrMagnitude float forceMag (10 rgg.mass) distance Vector3 force direction.normalized forceMag 10 rgg.AddForce(force) I can create a script that will change the gravity by the opposite of the object's position. this does work but I cannot see any way to do it for more than one object.


Inconsistent CapsuleCast Collision behavior when a GameObject is selected My gameobject has a CapsuleCollider and I use CapsuleCast to check for horizontal collisions when moving horizontally so the gameobject won't pass thru obstacles. It works 100 of the time except when I select the gameobject in Hierarchy. When I have the gameobject selected, whenever I try to bump a wall continuously, it shakes jitters until it eventually goes thru the wall. But this only happens when I have the object selected in Hierarchy. If I click on the scene so that the object is not selected and do the exact same thing (bump a wall continuously), there is no shaking jitter and it doesn't pass thru the wall no matter how long I bump it. This passing in the wall when selected is also consistent. Hundred percent of the time it will pass thru when I have it selected (and does the shaking) and also hundred percent of the time it doesn't if I don't have the object selected. Shouldn't selecting an object don't have any effect on this? Please give me some ideas of why.


Smooth rotation for a bone? I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ? public Transform Target public Vector3 Offset Animator anim Transform chest public float rotation speed public bool aim at traget false void Start() anim GetComponent lt Animator gt () chest anim.GetBoneTransform(HumanBodyBones.Chest) void LateUpdate() if (aim at traget true) smooth rotation to face target chest.LookAt(Target.transform.position) chest.rotation chest.rotation Quaternion.Euler(Offset) else get back to you stand smoothly


Synchronization problem with Visual Studio 2017 and Unity 2017.1.1f Sometimes I need to change a lot of files and Clean and Rebuild the Solution to get the changes on Unity, am I missing some configuration on Visual Studio or Unity? I uninstalled everything and make a clean install and few days later I'm getting the same problems. Sometimes if I create a stardard MonoBehaviour script from Unity and I try to attack it to a gameObject I get the error "Can't add script component XXXXXX because the script class can't be found"(see image screenshot). The class name and file name are the same, with no syntax errors. Some times opening a file with an external editor changing the encoding, cleaning and rebuilding the project solves the problem, but just sometimes and I'm tired of do that for test any change, now I have a lot of Debug.Log just to check if Unity is getting my code changes. Any suggestion will be very greatful


Unity What changes to a game object trigger baked lights to need a rebake? I've noticed that sometimes when I make changes to game objects in scenes that have baked lights that the baked shadows will no longer be in effect and dynamic lights will instead be showing. Destroying and recreating the object seems to trigger this reliably, but what other changes to games objects in a scene can cause a rebake to be needed?


UNET Performance of (many) Kinematic Rigidbodies I am building a game in Unity in C using the UNET networking elements. I am trying to figure out what is the performance cost of kinematic rigidbodies? My understanding is that, when kinematic, rigidbodies are outside the physics system and therefore are not as resource heavy as non kinematic rigidbodies. For my game, I will need to use a lot of kinematic rigidbodies in the scene, because they are used to detect collisions between player placed objects (with box colliders) and the rigidbodies. All the objects instantiated in the scene will therefore need a kinematic rigidbody to allow this collision checking to take place. Thanks very much for your help.


How do I make an infinitely scrolling background? I am trying to make a game where a torpedos keep coming from random directions and the player has to maneuver a submarine to escape them. I am currently offsetting the background to give it an illusion that the submarine is moving i.e. if the submarine moves forward, I move the background (quad) backwards. This is primarily being done as I want it to be an infinite space. The position of the submarine does not change, the player just controls the rotation of the submarine and the background moves in the opposite direction. The background is set to repeat to give it an infinite space illusion. The torpedo gets spawned at a random distance and moves towards the submarine. Since, the position of the submarine does not change, the torpedo will always hit the submarine. How do I structure this game, specifically the background repeat so that I can actually move the submarine in absolute dimensions and still maintain the infinite space illusion?


Jittery collisions in Unity 2D I tried to implement a simple movement to my object. My object moves perfectly fine but I'm having issues with its collision. When I keep on moving object towards the obstacle ground, collision are jittery. Here the code for what I've written. using System.Collections using System.Collections.Generic using UnityEngine public class TempScript MonoBehaviour SerializeField float walk speed 5f SerializeField float jump speed 10f SerializeField float max up 7f SerializeField float max low 1.5f void Update() PlayerMovement() void PlayerMovement() if (Input.GetKey(KeyCode.W) amp amp transform.position.y lt max up) transform.position transform.position Vector3.up jump speed Time.deltaTime if (Input.GetKey(KeyCode.S) amp amp transform.position.y gt max low) transform.position transform.position Vector3.down jump speed Time.deltaTime if (Input.GetKey(KeyCode.D)) transform.position transform.position Vector3.right walk speed Time.deltaTime if (Input.GetKey(KeyCode.A)) transform.position transform.position Vector3.left walk speed Time.deltaTime The cube goes below the ground and bounces right back up. making it look like its jittering. what i want is movement should stop when its colliding with object. just like it happens with addForce method. for now you can ignore max up and max down variable, it was just to make sure its in the camera.


How to make multiple AI surround a player I am working on a top down RPG game and I have come across a problem. I am working on an AI system to allow the enemy AI to surround the player. I've been trying to keep my implementation really simple, however, I've been running into problems. Here is what it currently looks like X represents the player and Y represents the friendly AI. There are 42 waypoints in total that the enemy can potentially occupy. However, if any of the waypoints of the player object encounters an obstacle, or if another friendly AI is too close, it will disable those waypoints This poses a big problem because I do not have all 42 waypoints. From the looks of it, I might need something more dynamic in my case. Are there any alternative ways to allow a large number of AI to surround the player or its allies?


Unity aircraft physics I want to make a simple aircraft controller, what looks like little realistic in unity. I watch some video from airplane physics. and make a simple script in unity, but if I start, my plane cant move or if I change drag to zero, it cant lift. I tried to use real data and get it from wiki(F22 Raptor). To my game object, I gave the rigidbody component mass 19670 kg. Engine thrust 2 116000.0f Newton. private void calculateEnginePower() EnginePower engineThrust ThrottleInput private void calculateForces() angleOfAttack Vector3.Angle(Vector3.forward, rb.velocity) angleOfAttack Mathf.Clamp(angleOfAttack, 0, 90) coefficient Mathf.Pow(1225.04f rb.velocity.magnitude, 2) 1 M 2 2 where M is mach. if (coefficient gt 0.0f) coefficientLift (4 angleOfAttack) Mathf.Sqrt(coefficient) lift 1.2754f 0.5f Mathf.Pow(rb.velocity.magnitude, 2) coefficientLift 78.04f densy1.2754 kg m3, speed m s , (F22)Wing area 840 ft (78.04 m ) coefficientDrag 0.021f rb.drag coefficientDrag 0.5f Mathf.Pow(rb.velocity.magnitude,2) 1.2754f 78.04f rb.AddForce(transform.up lift) rb.AddForce(transform.forward EnginePower) roll, pitch... inputs from keyboard and mouse, EnginePower, RollInput... are simple properties and I call the Move function in a controller inside void Update. Move(float roll, float pitch, float yaw, float throttle) transfer input parameters into properties.s RollInput roll PitchInput pitch YawInput yaw ThrottleInput throttle AirBrakes false calculateEnginePower() calculateForces() calculateRotation() used these formulas for Lift force Lift formula for Lift coefficient Cl formula for Drag Drag formula and for Drag coefficient I used data from wiki too (0.021f).


How to find a non active gameobject in unity? I am trying to find a gameobject, which is not active in the current scene.It throws Null Reference error. GameObject gameObject void start() a non active gameobject tagged with InactiveTag gameObject GameObject.FindGameObjectWithTag("InactiveTag") void update() if(someCondition) gameObject.setActive(true) this line throws Null Reference error