can't make my unity character move so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https docs.unity3d.com Manual ScriptingRootMotion.html If you ask I'll give you my project . EDIT ok so I made some advances void OnAnimatorMove() m Rigidbody.MovePosition(m Rigidbody.position m Movement m Animator.deltaPosition.magnitude 10000) m Rigidbody.MoveRotation(m Rotation) Debug.Log("m Animator.deltaPosition.magnitude " m Animator.deltaPosition.magnitude) m Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ?


Stop player following cameras cameras direction Okay I'm not going to go to much into it but this is what I need my script to do. The way I have my controller set up is that the camera looks to the side of the player a little bit. I use this for aiming attacks, bullets and what not. The problem is that it follow the camera when it looks up causing my character to slightly jump ever time I aim and look up. So i want the player to move with the camera while ignoring its y axis. and i need my character to jump so i cant just make the players y movement 0. Here's the code I've been using transform.position Time.deltaTime cameraMain.forward Input.GetAxis("Vertical") speedWilAim and I am trying to avoid separating the mouse look script into x and y pivots but if there is no alternative I will do that.


How do you exactly implement a Semi Implicit Euler type of movement in a 2D platformer? So I've been following along Sebastian Lague's 2D platformer tutorial, and to understand exactly how the physics of how a jump is done, I dug into the subject and noticed a lot of people, from GafferonGames and Kyle Pittman, all mention using Semi Implicit Euler in making an accurate jump. Now my problem is How do you exactly implement this type of integration scheme in a game? Specifically a platformer. A comment on the tutorial I was following said that the code below uses the Explicit Euler type of integration. Though I'm not exactly sure myself on whether or not this is true another tutorial I found on the topic, specifically Jorge Rodriguez's Math for Game Developers uses the Semi Implicit Euler integration to make a spaceship simulator, but the code used was C and I only have some limited C and I was not able to fully understand parts of the code that went into implementing the integration. Specifically auto v vn, gravity (Vector x, float h) gt Vector return vn gravity(x) h auto a xn, gravity (Vector v, float h) gt Vector return gravity(xn) gravity(xn v h) h from what I understand, this function returns a Vector2, but I don't know if the auto a xn, gravity is supposed to be about declaring a variable or what, or how the vector bit fits in the whole code. All in all, I need help, I'm still pretty new to programming and general and these small nuances confuse me. Any help is greatly appreciated, Thank you. This is the code for the Platformer Character controller I followed from Sebastian Lague. using System.Collections using System.Collections.Generic using UnityEngine RequireComponent (typeof(EntityController2D)) public class PlayerController MonoBehaviour EntityController2D playerController region Y Velocity Fields public float jumpDisplacementDeltaTime 0.75f public float jumpHeight 6.0f float gravity float jumpVelocity endregion float moveSpeed 6.0f Vector2 velocity public void Start() playerController GetComponent lt EntityController2D gt () gravity (2 jumpHeight) Mathf.Pow(jumpDisplacementDeltaTime, 2) jumpVelocity Mathf.Abs(gravity) jumpDisplacementDeltaTime print ( "Gravity gravity ") Update is called once per frame public void Update() Vector2 input new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if (playerController.collisions.below playerController.collisions.above) velocity.y 0 if (Input.GetKeyDown(KeyCode.Space) amp amp playerController.collisions.below) velocity.y jumpVelocity velocity.x input.x moveSpeed velocity.y gravity Time.deltaTime playerController.Move(velocity Time.deltaTime)


How To Disable A Select Collider I have a character with 2 2D Colliders, one for the head, and one for the feet, How do I Disable only the Head Collider in C .


How I add gap between Instantiated objects? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () raw.anchoredPosition new Vector3(1 1 gap, 6, 0) Update is called once per frame void Update() The way I'm doing it now is not working it's moving all the objects to the same position and not adding equal gap's between them. In the loop I tried to do it this way in this line raw.anchoredPosition new Vector3(1 1 gap, 6, 0)


Objects rendering only on editor, but not on build (they get invisible) Everything works fine in the editor, but when I build the game, none of the objects in the scene are rendered, and only the skybox and UI text is visible. But although they aren't appearing, they are working as normally (i.e. these objects' triggers work normally when the determined event occurs, like for example, colliding to a specified object, or in other words, they are invisible). I searched for this issue but didn't found any answer. Could it be my cheap computer's fault (Intel Celeron without an external graphics card)? In editor game mode In buit game I ran both the editor and the built game in the same quality, and also tried to run it in Fastest quality, but no, it made no difference in the built game. Also, there is no object tagged with "Editor only", only one have a custom tag and all the others are "Untagged". And the camera's culling mask is set to "Everything". The result is the same either for web or Windows. Edit OK, I built for Android and the objects render normally. So, I'm not completely sure, but probably it's my PC that can't render the objects, because both building for web plugin and desktop have this disappointing result, but for Android it works perfectly (even the shadows, which wasn't being cast in the editor), so...


Unity 2D Input.gyro eulerAngles X value strange behaviour I am working on a project where I want to create an 'scrolling' effect using gyroscope on mobile devices. The basic idea is that I have an Image object in my Scene and I want to be able to show different part of it using gyroscope like for example you see the wall of a room and rotation your phone you see different parts of the room, but in 2D. For now I managed to move my Image using Input.gyro.attitude.eulerAngles.x from gyroscope like this protected void Update() var x transform.localPosition.x var gyroX Input.gyro.attitude.eulerAngles.x x gyroX Speed BackgroundImage.transform.localPosition new Vector3(x, transform.localPosition.y, transform.localPosition.z) The problem which I am seeing is that when Input.gyro.attitude.eulerAngles.x reaches 86.0 it starts decreasing and even if you are rotating your phone to right it changes it's direction. Checked the documentation, examples over internet, but didn't find anything about that. If you have any idea what can cause that issue and how can I fix it, or any other suggestions how can I achieve the thing which I want to create, pleae share your knowledge. Thanks in advance! Edit The only rotation axis which I am interested in is X, because the app will be in portrait mode and I want to be able to move the image only horizontal (by X). So the phone's rotation has to be similar to while taking an panoramic photo on your mobile as shown on the first picture


BIM Model clipping issues in Unity 2020 I have BIM model that I am using in 2018 version of Unity engine. When import the model into my project on 2019 OR 2020 version of the Unity engine, clippings on certain surfaces of the model occurs. Has anyone encountered this issue with Unity 2020? Any solutions that can be suggested for me to try? Examples attached. Appreciate any help in advance...


Sending RPC calls from server to client inside Unity In my game inside Unity, I have two scenes setup. One for the main server ( acts like authoritative server ) and the other scene for my client. The game starts once my client connects to the server. Now I am able to send RPC function calls from my scripts in my client scene to the server but I am not able to do it the other way around. Further edit to my code after comments This is my client side script attached to GameObject CursorDetection inside Scene2 using UnityEngine using System.Collections ON THE CLIENT SIDE public class CursorDetectionScript MonoBehaviour private bool hasGameStarted false void Update() if (Input.GetMouseButtonDown(0)) networkView.RPC("mouseDown", RPCMode.Server,true) RPC public void mouseDown(bool isMouseDown) On the server side script inside scene1 private void OnPlayerConnected(NetworkPlayer player) Debug.Log(" PLAYER CONNECTED " player) networkView.RPC("AddNetworkPlayer", RPCMode.AllBuffered, player) RPC public void AddNetworkPlayer(NetworkPlayer player) playersList.Add(player) Debug.Log(" FIRST PLAYER IS " playersList 0 ) if(startGame) networkView.RPC("SendMessageToClient1", RPCMode.AllBuffered, playersList 0 ) RPC public void mouseDown(bool isMouseDown, NetworkMessageInfo sender) isMouseDown true Debug.Log("CAN PLACE PANELS NOW" " VIEW IS " sender.sender.guid) back on the client side script inside scene2 I called the SendMessageToClient1 function call RPC public void SendMessageToClient1() Debug.Log(" INSIDE CLIENT 1 ")


2D player controller moves to the left, but not to the right I wrote a C script to control a 2D player, but the script is not fully working. When I press the right arrow d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is using UnityEngine public class PlayerController MonoBehaviour SerializeField private Rigidbody2D rb2d SerializeField private float speed SerializeField private float jump private static float tempspeed private static float tempjump private bool isRight private bool isLeft private bool isSpace private void Start() isLeft false isRight false isSpace false speed 5f jump 7f tempjump jump tempspeed speed private void Update() ReadInput() private void FixedUpdate() Move() private void ReadInput() if (UnityEngine.Input.GetKey("d") UnityEngine.Input.GetKey("right")) isRight true else isRight false if (UnityEngine.Input.GetKey("a") UnityEngine.Input.GetKey("left")) isLeft true else isLeft false if (UnityEngine.Input.GetKey("w") UnityEngine.Input.GetKey("up")) isSpace true else isSpace false private void Move() Vector2 speedVectorRight new Vector2( tempspeed, rb2d.velocity.y) Vector2 speedVectorLeft new Vector2( tempspeed, rb2d.velocity.y) Vector2 jumpVector new Vector2( rb2d.velocity.x, tempjump) if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight if ( isLeft) rb2d.velocity speedVectorLeft else speedVectorLeft.x 0f rb2d.velocity speedVectorLeft if ( isSpace) rb2d.velocity jumpVector When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight The rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance!


How to rotate a local position offset based on a direction vector? I'm trying to fire three raycasts in the direction of movement, from offset starting points. I'm having trouble calculating the start positions of the rays based on the direction. As you can see in the animation, the three parallel lines in the middle overlap when moving upwards using the code below, but I want them to remain evenly spaced. I cannot use transform.right (up etc) etc because the transform is always facing the same direction by design. Instead I am using the currentDirection which is the normalized last movement velocity. I want the lines to always be evenly spaced based on the direction the object is moving without rotating the actual transform the problem is I don't know the math behind it and have spent last several hours trying to figure it out. Current code Debug.DrawRay(this.transform.position, currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.magenta, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) I've tried to get the position based on direction by using var drawRayTopPos currentDirection localpos position


In Unity, why do I get a "does not implement right interface" error when trying to sort my list of objects? I am trying to create a crafting panel that sorts the list of items you can make alphabetically, yet I cannot figure out why .Sort() is not working. What I have is a game object that holds a list of all the items you can make and the requirements, then in my crafting script I access the game object for the list and display the info. Everything works fine until I try to sort anything. craftDatabase is what I need to be sorted. Also, it needs to be sorted by ItemID. using UnityEngine using System.Collections using System.Collections.Generic public class CraftDatabase MonoBehaviour public List lt Blueprint gt craftDatabase new List lt Blueprint gt () System.Serializable public class Blueprint public string itemId public int itemAmount public float itemCraftTime 1f public CraftPanel.subsections subsection public CraftPanel.workstations workStation public List lt requiredItem gt requiredItems new List lt requiredItem gt () HideInInspector public string desc System.Serializable public struct requiredItem public string itemId public int itemAmount public Blueprint() When I try to throw in craftDatabase.craftDatabase.Sort() it gives me this error ArgumentException does not implement right interface How do I fix this error to use Sort()?


why is my (from example) shader appearing as black? I have the following (very simple) shader pragma kernel CSMain RWTexture2D lt float4 gt Result numthreads(8,8,1) void CSMain (uint3 id SV DispatchThreadID) Result id.xy float4(1,0,0,1) Here is the dispatcher code using UnityEngine using System.Collections public class SkyShaderDispatcher MonoBehaviour public ComputeShader shader public RenderTexture output void Start() RenderTexture output new RenderTexture(256,256,24) output.enableRandomWrite true output.Create() void Update() RunShader() void RunShader() int kernelHandle shader.FindKernel("CSMain") shader.SetTexture(kernelHandle, "Result", output) shader.Dispatch(kernelHandle, 256 8, 256 8, 1) which is the default red shader (it makes the texture red). However, when I put the texture in a material and give that to an object, then that results in the object being black. Anyone seeing what I'm doing wrong? As the shader is the default example right now it should work suggesting that maybe something is wrong with the texture? Edit Trying to fit the same code on a skybox also fails. I have changed the dispatcher code into using UnityEngine using System.Collections public class launchClouds MonoBehaviour public ComputeShader shader private RenderTexture output void Start() void Update() RunShader() void RunShader() int kernelHandle shader.FindKernel("CSMain") RenderTexture output new RenderTexture(256,256,24) output.enableRandomWrite true output.Create() Material mat gameObject.GetComponent lt Skybox gt ().material mat.SetTexture(" FrontTex",output) mat.SetTexture(" BackTex",output) mat.SetTexture(" LeftTex",output) mat.SetTexture(" RightTex",output) mat.SetTexture(" UpTex",output) mat.SetTexture(" DownTex",output) shader.SetTexture(kernelHandle, "Result", output) shader.Dispatch(kernelHandle, 256 8, 256 8, 1) but that turns the sky black rather then making the sky red. This is using unity 5 32 bits with DirectX11.


Extend distance for rendering grass and tree objects on terrain I am trying to make an adventure game with a big landscape (made the terrain with terrain tools) with 3D models of grass (that I placed using terrain tools) but it only shows the grass trees that are within a small area. Here is a pic of what I am talking about I would not want to totally remove this because otherwise the framerate will go too low. I just want to make the circle bigger. thanks (


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


Setup script variables before attaching to an object I need to attach a script at runtime, but that script requires some public members to be set in order to be helpful. Is there a way for me to setup the public members of the script before attaching it to a GameObject at runtime?


Animations not accepted in animator In the official Unity Animator State Machine tutorial video animation clips are dragged out from the assets folder into the animator and dropped. I have a 3D model that i bought online to experiment with that comes with animations. I added a custom made animation as well. These all work well in my demo project. But when i add a animator to the assets and try to drag and drop animations onto it it doesnt work. I get a forbidden sign as a mouse pointer. I try to add animations through the inspector but that does not work either. The tutorials makes it seem so easy and does not talk anything about what animations can be used. What am i doing wrong?


Can I save a score as highscore, if it's a float? So I have this infinite runner type of game, subway surfers style. I chose a method where the player doesn't move, and instead the obstacles move towards him. My score is a float and it increases as time passes. However, I'm unable to figure out how can you save this as a highscore. I tried a few methods but most of them were for int so it didn't work out. Here is what I have for the score counting. It's currently missing the save score part completely. public class GameManagerC MonoBehaviour float score 0 public float scoreMulti 5 void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot ) EDIT Many of you asked how I tried to implement the code I've found so here it is public float score public float highScore void Start() score PlayerPrefs.GetFloat( quot score quot ) highScore PlayerPrefs.GetFloat( quot highScore quot ) if (score gt highScore) highScore score StartGame() Update is called once per frame void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot )


Animated lighting in amusement parks What is the best way to handle animated lights on rides in a night time amusement park scene? Is there a better way that doing lots of emission lights? At the moment I have been using emission lights, but there could be a lot of them in a park (some are just static lights) and I would also like to animate some of them on some rides. Best example I could find was from GTA 5 Video https youtu.be zVj8D0lqgl4?t 146


Why won't my ball bounce? (Unity, 3D) I'm trying to do a very simple ball bouncing setup in Unity. I have a sphere with a sphere collider and a plane below it was a rectangular mesh on it, isTrigger set to false for both, and they both have a physics material with bounciness of 1. I have the ball start a couple units above the plane, gravity pulls it down, but instead of bouncing it stops right at the collider for the plane, then (weirdly) slowly falls through the collider. Once it falls through the bottom it starts falling normally again. The collider is already really thick (I've been trying to fix this by changing collider types and making them way bigger than needed). I just have no clue what's going on and feel like I'm missing something obvious.


using Mathf.Clamp in Vector3 to restrict object drag I'm making a checkers game and I've got a movement controller working to move the pieces. I want to restrict the drag to be within the board. The center of the board is 0,0 so the far left side's x value is 4, top of the boards y is 4, etc... This is my drag script so far void OnMouseDrag() float distance to screen Camera.main.WorldToScreenPoint(gameObject.transform.position).z transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance to screen)) but when I try to clamp my new Vector3's x and y between 4 and 4 like this, transform.position Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x, 4f,4f), Mathf.Clamp(Input.mousePosition.y, 4f,4f), distance to screen)) it shoots the pieces way off camera. This may be because don't truly understand Camera.main.ScreenToWorldPoint, is it returning different x,y coordinates than the global ones?


Why the rotation switching mode is not working right when using bools? using System.Collections using System.Collections.Generic using UnityEngine public class Objects MonoBehaviour public float maxScale 10.0f public float minScale 2.0f public float shrinkSpeed 1.0f public float rotatingSpeed 3f public bool automaticScale false public bool rotateOnMouseMove false public bool rotateOnMouseDrag true private float targetScale private Vector3 v3Scale void Start() v3Scale transform.localScale void Update() RaycastHit hit Ray ray if (Input.GetMouseButton(1)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit) amp amp hit.transform transform) targetScale minScale v3Scale new Vector3(targetScale, targetScale, targetScale) if (automaticScale false) transform.localScale Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime shrinkSpeed) if (Input.GetMouseButton(0)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit) amp amp hit.transform transform) targetScale maxScale v3Scale new Vector3(targetScale, targetScale, targetScale) if (automaticScale false) transform.localScale Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime shrinkSpeed) if (automaticScale true) transform.localScale Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime shrinkSpeed) if (rotateOnMouseMove true) transform.Rotate(Input.GetAxis("Mouse Y") rotatingSpeed, Input.GetAxis("Mouse X") rotatingSpeed, 0, Space.World) if (rotateOnMouseMove true) rotateOnMouseDrag false if (rotateOnMouseDrag true) rotateOnMouseMove false private void OnMouseDrag() if (rotateOnMouseDrag true) transform.Rotate(Input.GetAxis("Mouse Y") rotatingSpeed, Input.GetAxis("Mouse X") rotatingSpeed, 0, Space.World) The problem is at the bottom if (rotateOnMouseMove true) rotateOnMouseDrag false if (rotateOnMouseDrag true) rotateOnMouseMove false Once I'm starting the game by default the rotateOnMouseDrag is set to true. When I click on the check box of rotateOnMoseMove it's switching between them the rotateOnMouseDrag is false and rotateOnMouseMove is true. The problem is when then I click again on the check box of rotateOnMouseDrag but it's never switching between them again it keep staying true on the rotateOnMouseMove. I want it to act like a switch each time one of them is true the other should be false.


Bullet hits the object not in the center of the screen When player shoot, the bullet fly to the center of the screen. But if player stay too close to some object, then bullet hits it not in the center, because it flies from the gun on the right side of the screen. How can I fix this? public Rigidbody projectile public int speed 50 public Transform startBulletPosition void Update() if (Input.GetButtonDown("Fire1")) Rigidbody clone clone Instantiate(projectile, startBulletPosition.position, transform.rotation) as Rigidbody var centre new Vector3(0.5f, 0.5f, 0f) var ray Camera.main.ViewportPointToRay(centre) clone.velocity ray.direction speed Edit 1


Unity3d Transform.position float range I thought floating point has a very large range, for example up to 3.4 10 38. However today I tried to set my player's Transform.position.x to 1000000 in the GUI and it gave me a warning "Due to floating point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range." Does that mean that my single scene has to be smaller than 1000000 1000000 1000000. Is this considered big enough? I will need multiple scenes if I want a larger world? When a new scene gets loaded, will my player's position be reseted? How do I manage the position data so that it doesn't go out of range? I'm using Unity3D Pro.


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


Why does my character move diagonally? So i've been trying to make the player face towards the direction i pressed. That part works just fine but when I try to move the player it moves diagonally instead of left right. Any clues? if (Input.GetKey(KeyCode.RightArrow)) moves the player rb2d.velocity new Vector3(2.5f, 0, 0) transform.Translate(rb2d.velocity Time.deltaTime) flips the player right if (human.flipY true) human.transform.rotation Quaternion.Euler(0, 0, 270) else transform.rotation Quaternion.Euler(0, 0, 270)


Make transform.up face toward velocity while preventing transform.forward from rolling? I have been working on a personal project that is suppose to mimic Anthem. I am using a state machine for the character controller that I intend to integrate with the Unity's Animation state machine. I am calculating a new velocity that makes the player follow the mouse when flying, and I am making transform.up Velocity so that the player appears to be going head first towards its velocity. The issue is that when you start to rotate in a circular way on the xz plane, the player will start to roll and its transform.forward moves from facing towards the ground (which is what I want) to facing the sky. The core code is in public override Update() public class s MechFlyt MechStates float flySpeedPercentage public s MechFlyt(in MechController Master) base(Master) flySpeedPercentage 2.5f public override void Update() if ( Master.SprintButtonHeld) Quaternion Rot Quaternion.Euler( Master.DMouse.y , Master.DMouse.x , 0) Master.Velocity Rot Vector3.forward Master.Stats.Speed flySpeedPercentage Vector3 Rotation Master.Velocity Rotation.y Mathf.Clamp(Rotation.z, 0, 50) Master.transform.up Vector3.Normalize(Rotation) Master.transform.rotation Rot Master.transform.rotation Quaternion.RotateTowards( Master.transform.up, Master.Velocity, 5) Master. Controller.Move( Master.Velocity Time.deltaTime) if ( Master.JumpButtonHeld) Master.ChangeStates( quot hover quot ) Master.transform.up Vector3.up else Master.ChangeStates( quot fall quot ) Master.transform.up Vector3.up public override void EnterState() Master.CamController.ChangeStates( quot flying quot )


Unity Manually sync location of players from server to client I am new to Unity networking. I've set up my scene with NetworkManager and the Player prefab having NetworkIdentity. I originally had my players set up to sync with a NetworkTransform. This worked, but the objects were very choppy whenever they were children of a moving object. In order to fix this issue, I've replaced NetworkTransform with a class extending NetworkBehavior, using UnityEngine.Networking, and containing the following code to sync localPosition void Update () CmdSyncPos (transform.localPosition, transform.localRotation) Command protected void CmdSyncPos (Vector3 localPos, Quaternion localRotation) transform.localPosition localPos transform.localRotation localRotation This works really well! The only problem is that this is one way, the server now has the updated position of all clients but the clients only have the updated versions of themselves. How can I do this in reverse Manually sync the location of non local players from server to client?


Unity 2d Not Destroying enemies impact on memory I know pretty much zero about game performance in Unity. I am trying to figure out if I can afford to put this feature in my game I would like to have the enemies killed to pile up in a sort of heap, so I was thinking about not using the same old destroying routine after they die. The game itself is really simple, it's 2D and for mobile. It has a fixed background and there's not much moving around aside from the player, the enemies and few npcs (which would get destroyed when offscreen), we're talking around ten 32X32 sprites onscreen at a time. Once dead the enemies would not be removed but they wouldn't need to be raycasting, colliding, ecc.. Just only be there for visual sake. So the question is would a mobile device easily handle not removed enemies in the order of a hundred or so (I could destroy those at the bottom of the heap) and not slow down or crash the game? Are there some example of this kind of feature (other games that don't destroy dead enemies)? Or is there a good practice too keep enemies in game without impacting memory resources? Thanks for the attention.


Animation inside GUI Good day. I would like to create a "rich" GUI for my game. How can i add a 3d model to a GUI Button (with continous rotation ) ? If I can't add a 3d model to a GUI button, what is the best way to visualize a 3d model rotating ? Maybe creating a video file or animated gif and adding it to my button ? Thanks


Visually updating the position of a game object controlled by an animator controller I have a game object that is controlled by an animator controller. In order to activate the next animator state, the user is supposed to grab this game object, and then move it from Point A to Point B. As a test, in said game object's Update() method, I added the following line this.transform.localPosition Vector3.up When running the game, I can see that the y coordinate of the game object's position increases every single frame, just as intended. However, visually, the game object's position is not changing at all it remains in the same place all the time. What should I do to ensure that game object's position is also visually updated? EDIT Here are the properties of the animator I am using EDIT If relevant, here is the skinned mesh renderer for said game object


Set default values by script? Insted of Inspector, I want to set default values by script because there is MeshRenderer, a RigiBody etc. I don't know how to write this in script. These are not numerical values.


How can I record gameplay footage as a video within Unity? I am building a traffic simulator in Unity. I need to record my game as a video, so that I can use the video for machine learning purposes. I used fraps for the same but didn't find it worked for me since it's not within Unity. How can I make a video recording of the gameplay?


How do I set a scene up for two players? I m finishing a game in Unity, but I have a new requirement make it multiplayer. I will do this by splitting the screen and running two instances. Is there a way to instance a scene twice at the same time, and render them two a different part of the screen? Alternativley, what is the best approach to achieve this?


first person character controller error I have opened new scene, deleted camera and imported first person character controller from Standard assets. I placed plane on scene and put first person character controller on plane. I got this error Assets Standard Assets Characters FirstPersonCharacter Scripts RigidbodyFirstPersonController.cs(3,27) error CS0234 The type or namespace name CrossPlatformInput' does not exist in the namespaceUnityStandardAssets'. Are you missing an assembly reference? How to fix it?


Setting up a low res viewport to stretch in Unity I am working on porting a low res game over to Unity. In my previous engine, I had the option to set a native resolution (say, 160 x 144), and it would automatically stretch when the player entered fullscreen (with options for whether you wanted to keep the same aspect ratio, or stretch). I am having trouble figuring out how to set up something similar in Unity. I see that you can play around with resolution settings from Edit Project Settings Player. I tried various combinations of Default Is Fullscreen, Default Is Native Resolution, and Default Screen Width and Default Screen Height, but I haven't been able to get it to work. When I play the scene in the editor, the viewport is still much larger than my desired resolution. And when I Maximize On Play, the FOV is even larger. I Googled around, but couldn't find an answer that helped. Any advice?


How do you have rigged clothing animate with a base model? How do you have rigged clothing animate with a base model? Or how can you coalesce multiple skinned mesh renderers or have them all be controlled by just one? Or, do you just have multiple animators for each SkinnedMeshRenderer (and there would be quite a number, for a character with a complex outfit that is modular)? Have not been able to get it to work from the only thing I can find online (surprised there aren't more tutorials on this) https forum.unity.com threads tutorial how to make clothes animate along with character.475253 I've applied the method by looping through the SkinnedMeshRenderers present in the clothing assigned when a character root is loaded in ApplyClothing(clothing,root). Clothing and character have the same bone structure, as the clothing is custom modeled to the character model and rig. I get a few unable to map L R Knee Ankle Foot errors, but I have removed the break. I've tried rotating several other joints in the root character but the clothing is still not deforming with the joints. void ApplyClothing(GameObject clothing,Transform root) GameObject g Instantiate(clothing) g.transform.parent root g.transform.localPosition Vector3.zero BoneSyncer(clothing, root) void BoneSyncer(GameObject clothing,Transform root) SkinnedMeshRenderer smrclothing clothing.GetComponentsInChildren lt SkinnedMeshRenderer gt () for(int i 0 i lt smrclothing.Length i ) SkinnedMeshRenderer rootsmrs root.GetComponentsInChildren lt SkinnedMeshRenderer gt () SkinnedMeshRenderer rootsmr null for(int j 0 j lt rootsmrs.Length j ) if (!rootsmrs i .name.ToLower().Contains( quot haircut quot )) rootsmr rootsmrs i if(rootsmr! null) BoneSyncer(smrclothing i , rootsmr) void BoneSyncer(SkinnedMeshRenderer clothingmeshrenderer, SkinnedMeshRenderer targetmeshrenderer) Dictionary lt string, Transform gt boneMap new Dictionary lt string, Transform gt () foreach (Transform bone in targetmeshrenderer.bones) boneMap bone.gameObject.name bone Transform newBones new Transform clothingmeshrenderer.bones.Length for (int i 0 i lt clothingmeshrenderer.bones.Length i) GameObject bone clothingmeshrenderer.bones i .gameObject if (!boneMap.TryGetValue(bone.name, out newBones i )) Debug.Log( quot Unable to map bone quot quot bone.name quot quot to target skeleton. quot ) break clothingmeshrenderer.bones newBones


Can't Get .enabled to Work for Children Sprites. What Gives? So I have an object with a few children. I want to be able to disable enable 2 of their SpriteRenderers via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below public bool isAiming false Animator playerAnim GameObject arm GameObject weapon SpriteRenderer armRenderer SpriteRenderer weaponRenderer void Start() playerAnim gameObject.GetComponent lt Animator gt () arm GameObject.FindGameObjectWithTag("Arm") weapon GameObject.FindGameObjectWithTag("EquippedWeapon") armRenderer arm.GetComponent lt SpriteRenderer gt () weaponRenderer weapon.GetComponent lt SpriteRenderer gt () void Update() CheckIfAiming() void CheckIfAiming() if (Input.GetButton("Fire2")) Holding right click isAiming true armRenderer.enabled true weaponRenderer.enabled true playerAnim.SetBool("isAiming", isAiming) else isAiming false armRenderer.enabled false weaponRenderer.enabled false playerAnim.SetBool("isAiming", isAiming) What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false true) is not an option as I still want code to affect them while they're not visible. Am I just trying to access the SpriteRenderers incorrectly?


Getting distance between point of an object and another object in Unity First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development. I understand that I can find a distance between two objects using float dist Vector3.Distance(other.position, transform.position) However, how can I find the distance between a point of one object to other object? For instance let's say my object is this sphere Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5? Thank you for your patience and understanding


Unity Editor wont open When attempting to open an old project or create and open a new project unity won't open. The hub will open and when you choose a project it will close and then nothing will happen. Also when a new project it will state the unity version for the new project as unknown. I have tried uninstalling, deleting all the files under the registry editor, and also removing the files from the appdata and reinstalling and it doesn't appear to fix it. Does anyone have any suggestions on how I can fix this?


Bounce with multiple collisions Here's the problem I'm writing an Arkanoid like game in Unity 5.3. I'm using 3D physics and simply ignoring z axis in computations. No gravity, 0 drag and velocity reset every bounce by script. My ball has sphere collider and rigidbody with continuous dynamic collision detection on it, and bricks have box colliders with continuous detection. They are set like tiles, one by one, without gaps. The problem occurs when a ball collides with two bricks at once, which causes a wrong bounce angle. Smaller sphere colliders makes this situation occur less often, but causes the ball to ignore collisions sometimes and phase through a single brick. I know the probable reason for this bug, I think a collision with two objects affects ball physics twice. The question is how to avoid it?


Calculating the distance from a line to a point in 2D I have a simple setup How do I calculate the orange distance? It's the distance between the block on the left to the white line in the center (X amp Z axes combined). I don't have the intersection point. My only knowledge of the white line is that it goes through the point (0, 0, 0), running between (10, 0, 10) and ( 10, 0, 10) My problem is that I need to calculate this distance without the depth (Y value). Only on two planes combined X amp Z


How to update Unity? I have clicked on check for updates but it says I have latest Unity. But latest is 5.6. How to update it to 5.6?


What will happen with PlayerPrefs data after updating the app? I'm using PlayerPrefs (Unity3D, on Android). If a user updates my application via the Google Play store, what happens to the data I've stored in PlayerPrefs?


How to best apply colliders on a rough 3D shape I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D


Unity how do I edit a second scene when my objects are still in the first? I have my game set up so that objects like the Canvas and the main character are set to DontDestroyOnLoad they're only initiated in the first scene. However, this means that when I load my second scene in the editor, those objects aren't there yet. I could copy and paste them over, but then the objects in the second scene will be duplicates of the ones in the first. This is a problem because I can't, for instance, create a public variable on the character controller and attach an object from the second scene to it. The character doesn't exist in scene 2 yet and the object doesn't exist in scene 1.


How to have 3d multiple planet gravity in unity c ? Im using unity and I want to make a game where you can walk around small planets and the further away you get, the weaker the gravity, so you can go to other planets. All the tutorials so far only work with one planet, how do I code this? Is there anything I can download that does it for me?


Disable and re enable image tracking ARKit Is there a way to disable and re enable tracking for images in ARKit? From the older versions, this was the solution. But the newer versions have removed the UnityARSessionNativeInterface script. void Start () m session UnityARSessionNativeInterface.GetARSessionNativeInterface() void AddImageAnchor(ARImageAnchor arImageAnchor) at the bottom of this function StartCoroutine(RemoveAnchorCoroutine(arImageAnchor)) IEnumerator RemoveAnchorCoroutine(ARImageAnchor anchor) yield return new WaitForSeconds(3.0f) doesn't have to be in a coroutine, but for my uses it is m session.RemoveUserAnchor(anchor.identifier)


Using a object as origin for a Raycast using mouse position as direction Is there any way to cast a ray from an object using the mouse position as the direction for the ray? I ve been looking for a while but I can t find something like that anywhere, so if anyone could help with this it would be great. I m using kind of a top view, you can see how here And what I want to do is set a empty game object on top of the character to act as the origin for the ray, then when I press a key the mouse is unlocked and an area appears, here s how that looks And I want to use the position where the mouse clicks to be the direction of the ray.


Playing a video in AR using Vuforia and Unity 5 I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon.


Will importing more items from unity packages increase the build size? I'm developing a GoogleVR (formerly Google Cardboard) application and need to import the GoogleVR SDK. While I only expect to use some of the items available in the Unity package, I'd like to import them all at once and save potential headaches later when I can't find something I might need. However I'm worried that including everything in the project may affect the build size, which would be troublesome on a mobile application.


Building an Octree for terrain generation I've previously implemented marching cubes tetrahedra to render an IsoSurface. It worked (YouTube), but the performance was dire as I never got around to implementing variable Level of Detail based on view distance (or even removing old, distant chunks). I decided to have another go and do it properly this time. I've started by creating an OctreeNode that works as follows when Build() is called. If the chunk is too small to build, return immediately. Work out if the surface passes through this chunk's volume. If so, then decide if we want to raise the LOD (because the camera is close) If so, then spawn 8 children and call the same process on them If not, build the mesh using the current node's dimensions Some PseudoCode OctNode Build() if(this.ChunkSize lt minChunkSize) return null densityRange densitySource .GetDensityRange(this.bounds) if(densityRange.min lt surface lt densityRange.max) if(loDProvider.DesiredLod(bounds) gt currentLoD) for(i 1 to 8) if(children i null) children i new OctNode(...) children i children i .Build() else BuildMesh() return this As well as returning density at a point, the density source can determine the possible density range for a given volume. The LoD provider takes a bounding box and returns the max desired LoD based on camera position frustum, user settings, etc... So... This all works fairly well. Using a simple sphere as the Density source, and showing all nodes And just the leaves However, there are a couple of issues I have to define the initial bounding volume (and the larger it is, the more processing I need to do) At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes qualities. I've thought of a couple of options but both seem flawed Maintain a collection of Octrees and add remove depending on distance. Can't see how I'd mesh across nicely , plus I'd need a list of known empty nodes, especially if I want arbitrary 3D surfaces (to avoid re calculating empty volumes repeatedly) Add a parent Node to the current root, then add seven siblings for the original node. This would work and be on demand but it seems complex to shrink back down sensibly as the player moves through the landscape. It would also make LoD numbers even less meaningful. In clarification to Q below At present, if 2 physically adjacent nodes in the tree are at different LODs, I have some code to coerce the verts such that there's no seam when the meshes are generated. I'm able to do this by knowing the the density for multiple of surrounding nodes. In a scenario where I have 2 independent octrees side by side, I'd have no easy way to retrieve this information, resulting in seams. What's an optimal way to approach this?


How to use a .cube LUT file with Color Lookup? I have used quot Image 2 LUT quot to create a LUT for Unity from a certain movie. However, currently quot Image 2 LUT quot only outputs quot .cube quot files. For HDRP, this is great, but for some reason, URP doesn't accept .cube file. URP expects specially laid out .png LUT file. Is there any way to convert a .cube LUT file to a PNG that I can put into the slot of Color Lookup gt Lookup Texture with URP? Unity expect this format The tutorial that Google finds and recommends is this. However, I don't have Photoshop. Also, the tutorial deals with a square LUT that looks like this So even if I had Photoshop and I would follow the tutorial, I would still have a square LUT which is not laid out as Unity would expect it, so I did not use that tutorial. How do I create a LUT png from a .cube file that I can use with URP? Thank you.


2 D character not falling to the ground I am very new to Game Development and I am making a game with a simple Ragdoll which has a body, a head, and 2 limbs(hands). The head and the limbs are hinged to the body and I have kept the Ragdoll above a cube to be used as the ground on which the Ragdoll falls. Till now, I haven't added any scripts for movement or anything, I just want my Ragdoll to fall on the cube below it properly. But when I click play, the Ragdoll just starts to float above its original position. When I move it through the editor away from the cube(ground), it does fall down. It's like the cube is opposing the downward acceleration of the Ragdoll. The Ragdoll won't land on the cube. All the bodies have Rigid body and collider scripts. The Ragdoll also doesn't disassemble, it manages to keep itself together. Can someone please tell me what I am doing wrong. I researched about this but I have found no solution. I am using the free version of Unity.


How can I create an extending chain like the hookshot in Zelda in Unity? In the Zelda games, there is an item called the hookshot. It is a small mechanical apparatus held in one hand that acts similar to, but not the same as the gun. When it is triggered, the hook at the tip of the item springs forward and an extending chain follows behind it. This chain is spawned when the hookshot is triggered and disappears when the hook is retracted. The chain is not visible beforehand, i.e, it is not spooled around any kind of cylinder and unspooled when shot.There are also other games where characters use grappling apparatus that can be made shorter or longer when a character is hanging from a specific point or pivot. Similarly, this grappling tether is created or hidden as needed to support whether the player wants to shorten or lengthen it. My question is, how could one create an extending chain whose links are only visible when triggered and when retracted disappear from view? This chain does not need to necessarily interact with physics. I've thought of a couple of ways someone could create an effect like this, but I would rather see if there is a better known solution or implementation of this or a similiar effect before I dive in. Potential solutions could include A particle effect between the base of the hook and the tip of the gun. This might be far better suited for displaying a non physical, energy tether, but I am not as familiar with the particle system in Unity and I am curious to see if a chain link could be faked with a particle. Creating a chain link by link or section by section procedurally based upon the direction the hook was firing in and the distance between the positions of the gun tip and hook base. This seems like a more direct solution, but could have higher processing cost as the links are created on the fly and in rapid succession. Creating a chain that is hidden when not fired and is made to slowly appear when fired as the hook leaves the hookshot apparatus. This seems like the most likely solution, but I have little to no idea as to how it could be implemented. I would not be surprised at all if there is a better solution that I didn't mention. I look forward to seeing what people suggest. Thank you.


Unity sprites and layouts I am trying to learn Unity for a simple board game. The question is, is it possible to use grid layout group (or any layout component) with sprites? The goal is to fit a board into my view regardless of the aspect ratio of the device. The following grid should contain 7 by 7 sprites and it should scale up and down (no more then lets say 100 px) and have an aspect ratio of 1. I've tried adding a canvas and a panel that has a grid layout group component but it seems like sprites are not affected when added to the panel. Also it seems like when I try to work with a panel or a canvas they have a fixed sizes in units. Having fix sizes feels a little bit off. Is there a way to use layout components so sprites can have relative distances between them. So far I am stuck and lost in tutorials and feeling like the answer should not be this complicated. Any push to the right direction is welcome.


Make half of the sprite transparent Guys if I have two sprites placed on the same spot. How can I show the half of each Sprite instead of the one on top? The sprites are basic circles All sprites have basic colors, no textures.


How to edit key value pairs (like a Dictionary) in Unity's inspector? I have a spell system I am creating, the principle is as follows Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector. I have a Spell enum listing all possible spells in the code, which is used in the game logic When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations Each actor (be it players or enemies) needs to have a list of possible animations for the spells The problems with how I am trying to implement are For listing each actor's animations I could use a Dictionary lt Spell, Animation gt , but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type. I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations


Per component Shader Blend in Unity Context I'm writing a 2D mobile game in Unity where the graphics are essentially black lines drawn on a background image plus some lighting. Running full RGB calculations for every step seems like a waste of processing power. What I'd like to do is render everything in grey, alpha and then multiply by the sRGB background image in a separate shader at the end. Actually, ideally, I'd like basically to specify custom components like grey, highlight, additive, alpha , each of which can be ignored in a given pass, and then do a custom operation with those when I apply the background image, like ceil(src (dst.r dst.g)) half4(dst.b). I can figure out how to do that between 2 textures within a shader, but not between texture and screen (a.k.a. src amp dst). Question Basically, is there a way of writing a per component replacement of the built in Blend functions? Because something like Blend SrcAlpha OneMinusSrcAlpha only works with the full float4 or half4 vectors. Or do I need to grab the screen like a texture and handle it within a pass block, and then do Blend Off or Blend One Zero? Or do something with RenderTextures perhaps? My intuition suggests that that would undo some of the efficiency I'd gained in previous steps, though...?


Unity assets turned binary from text I'm working with unity and git, and for some reason, from some point the assets started being Binary files, meaning that they're not visible as normal YAML files, and I cannot see textual git diff results on them. Has anyone experiences it and knows how to revert to the textual format from the binary format?


Help with modifying a geometry grass shader to allow removing areas? So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a quot guiding quot texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice!


Unity Get list of gameobjects close to object clicked? I have a stack of balls of 4 colors some touching some not. When you click on one color ball I want to destroy that ball and any other balls of that color that are close. They may not be touching so collision wont work. How do I detect gameobjects close but not touching that are the same color? Say half a radius away from the edge of the ball clicked. Here are the two scripts I'm working with to create and touch the game objects. public class SpawnBalls MonoBehaviour public Rigidbody ball public float waittime 0.5f Use this for initialization void Start () spawn () Update is called once per frame void Update () Instantiate (ball) public void spawn() yield WaitForSeconds(waittime) for (var i 0 i lt 10 i ) Instantiate (ball) Selecting the balls public class Ball MonoBehaviour public Color colors private Color ballpicked Use this for initialization void Start () GetComponent lt Renderer gt ().material.color colors Random.Range (0, 4) Update is called once per frame void Update () void OnMouseDown() if (Input.GetKey("mouse 0")) ballpicked GetComponent lt Renderer gt ().material.color if (ballpicked "Any other balls within a half a ball width") Destroy (gameObject)


Unity build error "Could not find file...build.asm.js " I made a WebGL game and the first few times it built well, then I continued working on it a bit and when I build it it gives me an error (and does not generate the build files), error FileNotFoundException Could not find file "C Users Public Documents Unity Projects Infinite Side Scroller Temp StagingArea Data Native build.asm.js". Heres the full error message FileNotFoundException Could not find file "C Users Public Documents Unity Projects Infinite Side Scroller Temp StagingArea Data Native build.asm.js". System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) (at Users builduser buildslave mono build mcs class corlib System.IO FileStream.cs 305) System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share) (wrapper remoting invoke with check) System.IO.FileStream .ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) System.IO.File.OpenRead (System.String path) (at Users builduser buildslave mono build mcs class corlib System.IO File.cs 363) System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) (at Users builduser buildslave mono build mcs class corlib System.IO StreamReader.cs 167) System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding) (wrapper remoting invoke with check) System.IO.StreamReader .ctor (string,System.Text.Encoding) System.IO.File.ReadAllText (System.String path, System.Text.Encoding encoding) (at Users builduser buildslave mono build mcs class corlib System.IO File.cs 587) System.IO.File.ReadAllText (System.String path) (at Users builduser buildslave mono build mcs class corlib System.IO File.cs 582) UnityEditor.WebGL.CodeAnalysisUtils.ReplaceDuplicates (System.String builtCodePath, Int32 interations) (at Users builduser buildslave unity build PlatformDependent WebGL Extensions Unity.WebGL.extensions CodeAnalysisUtils.cs 145) UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (BuildPostProcessArgs args) (at Users builduser buildslave unity build PlatformDependent WebGL Extensions Unity.WebGL.extensions BuildPostprocessor.cs 589) UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C buildslave unity build Editor Mono BuildPipeline PostprocessBuildPlayer.cs 186) UnityEditor.HostView OnGUI() What is the problem? And how can I fix it? Feel free to ask me for more information? Thanks in advance for the help!


Networking and Timing issue I have been trying to use the low level API for UNET and the focus of this problem is this NetworkEventType recData NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error) This line is supposed to take in information from many different clients and sits within Update() function. I haven't actually started coding anything in yet... But the point is, if the clients are all transmitting data to the server at a rate equivalent to Update() then this line of code will not be able to (I think?) receive all of them at once (10 clients vs 1 server). So is there a way to not lose any of the incoming data and process them accordingly?


Improving the look of a character with solid parts inside a translucent jello exterior So my problem is a bit hard to explain. I have a character made out of a jello shell, with an internal skeleton. So let me introduce you to ma boi quot Chonker McJello quot The problem is, that I want a rich green slightly transparent jello, without loosing too much details and quot whiteness quot on the internal skeleton. If I turn the transparency or saturation of the jello down, the jello looks ugly, if I put the jello as I want, the Skeleton looses too much details turns green. I have thought of different approaches, but do not really know how to achieve the effect I want. Single sided emission Is there a way to make the jello glow internally and light the skeleton up? The emission should only come from the backfaces. Doing something with the render layers, like rendering the skeleton with transparency on top of the jello again, to make it appear quot less affected quot by it's color Everything I have in mind sounds easy but is propably pretty complicated and I don't have a lot of experience with shadergraphs and unity's hdrp. If you have any idea how to achieve the desired effect (maybe not in the way I thought) I would really appreciate your help! Thanks a lot!


How to make colliders for a darts board in Unity? I was wondering how to make a darts board in Unity? Of course it doesn't make triangular objects, or non symmetrical boxes as far as I know, so I would make the board mesh in Blender or something like this. But how would I be able to detect where a dart had hit the certain area? Until now I have only used box, sphere and capsule colliders


How can I convert screen space to GUI Space View Space? Is there any way available to convert screen space into view space as like in the following figure


How to create reel slider with mobile controls How can I create a reel slider with mobile game controls so that it looks something like this? The slider is normally non visible, and can be accessed if I slide my finger from the right side of the screen to the left. The slider allows me to switch my current weapon and use items in my inventory. This is my current setup in Unity. I can figure out the inventory portion of the slider, as there are many tutorials out there on an inventory system, and how to make the slider move based on touch, using something similar to a mobile joystick script, but I can't figure out how to make the slider so that it Can quot jump quot from icon to icon (not have the slider be completely fluid prevent it from stopping in between item icons) Detect what item slot the slider is currently on (in the case of the example, the item that will be used is the icon in the center of the screen. Make the icons more transparent the further away it is from the icon in use (I'm guessing that I would have to set the alpha channel value in the color settings of the item to a lower value, but I'm not sure how to detect the icon in use and count how many icons away the other icons are from the one in use.


Placing units on isometric map (2D) I'm making a map editor for further RTS game (2D), something like the first StarCraft Editor. Terrain tiles will be a rhombuses. So I'll probably just make an 2D array with intigers, that corresponds proper tiles. Then, after creating the terrain, you'd probably like to add some units and structures to map (especially if you're making a scenario). I'm not sure how do I check if the unit can be placed somewhere. I decided to make units almost independent from terrain tiles like in StarCraft (1), so the units are not placed in any grid. I'll give a simple image As you can see, those green tiles represent a passable area (grass, let's say), and a blue one impassable (for example water). That stickman in a box is our unit. You can place it only in green area. That means the box can't go outside the green rhombuses. I have some ideas how to achieve this, but I'm not sure which one would be the most optimal. 1) Since I work in Unity, I could add a collider to every tile. That will be very simple to do and will probably have terrible optimalisation in maps 256x256. 2) Math. I can calculate if any of those boxes crosses tile's borders. If so, I'll have to check if all those tiles are passable. It won't be that easy to programme (well, for me at least) and... yeah, here comes my dillema. Am I right that it would have much better optimalisation? Is it worth the effort? What about saving this map? I can easily save the array with tiles, but how can I do it with units? Just save their positions or is there a better way to do it? EDIT I've tested the first idea (I've written script to create 256x256 map that will be probably the biggest, and to move a camera). The map generates quite long (comparing to tiles without collider), but after that there isn't much difference in performance (it doesn't mean it won't cause problems when I add more features than moving a camera )). I can also attach colliders only to impassable tiles, not all. This should improve the performance even more. Still not sure if that's a good idea. EDIT 2 I've just realised how bad my idea was. Let me visualise this So if you consider not the whole rectangle, but only a circle, it's not only easier to implement, but also more reasonable. You can now convert rhombus' vertices' position from isometric to cartesian like B lint said CartX ( 2 IsoY IsoX) 2 CartY ( 2 IsoY IsoX) 2 You can also do it with circle's center point. Radius is equal to half of square (rhombus) side length OR sqrt(2) square side length (when square is inscribed in circle). So now I have a square grid and a circle. How can I check if all squares that this circle lays on are passable? What's the most optimal way to do it?


Applying movement to a Rigid Body Isometric in Unity 3D I'm making an isometric dungeon crawler. I initially used transform to get isometric movement and things worked well, but I couldn't use collision which meant it was unsuitable. So I'm now trying to use Rigidbody and I'm having some weird issues. First of all, this is the code I currently have public class CharControllerRigid MonoBehaviour SerializeField private Rigidbody characterRigid private Vector3 inputVector void Start() characterRigid GetComponent lt Rigidbody gt () void Update() inputVector new Vector3(Input.GetAxis("Horizontal") 10f, characterRigid.velocity.y, Input.GetAxisRaw("Vertical")) transform.LookAt(transform.position new Vector3(inputVector.x, 0, inputVector.z)) private void FixedUpdate() characterRigid.velocity inputVector I have two issues First, how do I get the movement to work on an isometric plain? Second, how do I get the movement to work in all directions? Current when I move left and right the movement is good, but up and down are really slow in comparison.


InvalidCastException when instantiating a prefab on the network using Photon As stated in the title, I get this error when I try to instantiate a game object using Photon InvalidCastException Cannot cast from source type to destination type. NetworkingPeer.DoInstantiate (ExitGames.Client.Photon.Hashtable evData, .PhotonPlayer photonPlayer, UnityEngine.GameObject resourceGameObject) (at Assets Photon Photon Unity Networking Plugins PhotonNetwork NetworkingPeer.cs 3069) PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group, System.Object data) (at Assets Photon Photon Unity Networking Plugins PhotonNetwork PhotonNetwork.cs 2493) PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group) (at Assets Photon Photon Unity Networking Plugins PhotonNetwork PhotonNetwork.cs 2437) GunController.EquipGun (.Gun gunToEquip) (at Assets Scripts Gun GunController.cs 38) GunController.init () (at Assets Scripts Gun GunController.cs 19) NetworkPlayer.Start () (at Assets Scripts Network NetworkPlayer.cs 20) Old, working code equippedGun Instantiate(gunToEquip, weaponHold.position, weaponHold.rotation) as Gun equippedGun.transform.parent weaponHold New code, using Photon equippedGun PhotonNetwork.Instantiate(gunToEquip.name, weaponHold.position, weaponHold.rotation, 1).GetComponent lt Gun gt () equippedGun.transform.parent weaponHold (I do GetComponent, as normal instantiate returns Object and PhotonNetwork.Instantiate returns GameObject) equippedGun is by default an empty variable of type Gun gunToEquip is again a Prefab variable of type Gun that gets passed into the function. (PhotonNetwork.Instantiate takes in the name of the prefab, not the actual prefab, thus gunToEquip.name) In this particular case, gunToEquip is the default gun that fails to instantiate, which is set by the unity inspector weaponHold is just a transform variable, again set by the inspector. I somehow managed to fix it for my player prefab, I have no idea how. I was just changing and reverting stuff until it magically worked. How can I resolve this error? Not sure if it is the problem, but I've attached the prefab settings


Working with Blender (Model individual objects or scenes?) I've been working in Unity for awhile but I'm pretty new to making my own models. I'm using Blender since it seems like a pretty good tool for the job. Let's say I am making a simple scene in Unity with a table that has a cup and plate on it and some chairs. Assume I want to be able to move each of these objects around independently from the other objects. Does this mean that when modeling in Blender, I have to model each object individually and import them separately in Unity? It would be nice sometimes to be able to model entire scenes in Blender, but if stuff in the scene isn't intended to be static, then there is no way to treat parts of these scene as objects and manipulate them individually in Unity right?


Trees swaying in the wind using Tilemap I am working on a top down, tile based game (think 2D RPG). However, I would like to have trees that sway in the wind and shake a little if the player bumps into them! How should I approach this? Is it achievable with trees that are composed of tiles and part of a tilemap? Or should I exclude my trees from the tilemap and turn them into game objects instead? If I were to turn them into separate game objects, would I then manually tweak their rotation position to achieve the sway and shake, or is there some form of shader I can use?


Disabling and re enabling the clicked child objects I am currently working on 2D platform game. The following script adding the child objects inside the array and identifies the child object I click on and checks the tag on it. Now I don't know how to disable the child object that I have clicked and I want the disabled child object to be re enable when I click on another child object inside the same parent object. Any help would be appreciated. public class SelectedPlatform MonoBehaviour public GameObject platform void Start() Transform children new Transform transform.childCount for (int i 0 i lt transform.childCount i ) children i transform.GetChild(i) void Update() if(Input.GetMouseButtonDown(0)) RaycastHit2D hit Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero) if(hit.collider.gameObject.tag "Platform") Debug.Log ("Target Position " hit.collider.gameObject.transform.position)


Unity procedural smooth normals I have a Unity project, which heavily relies on the marching cubes algorithm. Because this algorithm doesn't return the triangles in order, I can only index them in the order they are present in the vertices array. For example vertices Vector3(0, 0, 0), Vector3(1, 0, 1), Vector3(1, 1, 0)... triangles 0, 1, 2, 3... Because of this, Unity's RecalculateNormals method doesn't work properly and it gives me the following result Is there anyway I can make the normals smoother? Keep in mind, that I need to possibly recalculate these vertices everytime the values change, so I can't rely on very heavy methods.


Raycasting to AddForceAtPosition goes to the wrong direction I'm trying to get my coin object's Rigidbody to move whichever way it was swiped on by the user through RayCast void Awake() coinRigidBody coin.GetComponent lt Rigidbody gt () void Update() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) firstTouchPos new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane) if (touch.phase TouchPhase.Moved) lastTouchPos new Vector3(touch.position.x, touch.position.y, Camera.main.farClipPlane) if (touch.phase TouchPhase.Ended) Vector3 firstTouchWorldPos Camera.main.ScreenToWorldPoint(firstTouchPos) Vector3 lastTouchWorldPos Camera.main.ScreenToWorldPoint(lastTouchPos) Vector3 diffWorldPos lastTouchWorldPos firstTouchWorldPos direction3D diffWorldPos.normalized power diffWorldPos.magnitude (force Time.deltaTime) Ray firstTouchRay Camera.main.ScreenPointToRay(firstTouchPos) Ray lastTouchRay Camera.main.ScreenPointToRay(lastTouchPos) RaycastHit hit Debug.DrawRay(firstTouchRay.origin, lastTouchRay.direction firstTouchRay.direction, Color.red, 50.0f) if (Physics.Raycast(firstTouchRay.origin, lastTouchRay.direction 100, out hit)) Vector3 hitLocation hit.point if (hit.collider.tag "Coin") projectedVector Vector3.ProjectOnPlane(direction3D, plane.normal) coinRigidBody.AddForceAtPosition(projectedVector power, hitLocation 5) throwCoinObject.throwWithForce(power, hitLocation, direction3D) The Code is working but my only problem is that it goes only in a certain direction? And it seems that direction is manipulated by how the camera is facing the objects. I just want it to hit the first touch origin then move to the direction the swipe was made. Help would be really appreciated


Animation doesn't play in one state I have created an Animator and two sprite based Animations. Both Animations preview correctly. In the Animator, I have created two states and two transitions between them based on a Boolean parameter. In the GameObject's script, the Boolean value is set based on distance to the player. When the player is far away Animation A plays and when the player is close Animation B plays. However, while the transition from Animation A to B happens correctly when the player gets close, I only see the first frame of Animation B and it doesn't animate. If while in Play mode I preview Animation B (using the Animation window controls), it animates correctly. Meanwhile, Animation A always plays correctly when it is supposed to. What could cause this behavior? How can I get Animation B to play during runtime and not just when previewing? What's going on? Edit Some screenshots. quot Saw slow quot is quot Animation A quot above, and quot Saw fast quot is quot Animation B quot . Animator Animator State Slow Animator State Fast Transition slow to fast Transition fast to slow Animation Slow Animation Fast The code is very simple bool trigger playerDistanceSqr lt (activeDistance activeDistance) animator.SetBool( quot IsFast quot , trigger)


Move gameobject from fixed position to pointposition following curve Unity2d I want to move the object from the fixed position to the mouse position according to the curve as shown in the illustration. The altitude is the same and the horizontal distance is equal.


Extending control remapping script to work with mouse buttons I have created a default key map for my game, however I have also included an option in the settings where the player can change the key bindings. My issue is if the player clicks on the button for shooting, which is defaults to mouse0, or aim on mouse1, then click on another key, they can never go back to mouse0 or mouse1. I am unsure of how to include all the mouse buttons scroll wheel into the viable buttons the player can choose from. Here is the part of my code that deals with the changing of the keys private void OnGUI() if(curKey ! null) Event e Event.current if (e.isKey) keyBinds curKey.name e.keyCode curKey.transform.GetChild(0).GetComponent lt Text gt ().text e.keyCode.ToString() curKey.GetComponent lt Image gt ().color normal curKey null


Unity Light Baking for Best Balance between Performance and Visuals I'm trying to optimize my Unity game. I have static objects, dynamic objects and (only) static lights. I wish to fully pre compute lighting and shadows for the static objects while still maintaining realtime lighting and shadows for dynamic objects, and making them work together seamlessly. From the documentation Realtime "Unity calculates and updates the lighting of Realtime Lights every frame during run time. No Realtime Lights are precomputed." So, If I set it to realtime, I'm not really optimizing anything, am I? Mixed "Unity can calculate some properties of Mixed Lights during run time, but only within strong limitations. Some Mixed Lights are precomputed." It's unclear what "some properties" are and what would the consequences be. Baked "Unity pre calculates the illumination from Baked Lights before run time, and does not include them in any run time lighting calculations. All Baked Lights are precomputed." This will work for static objects. However, dynamic objects will look as if there are no lights in the scene. From what I see, Mixed would be what I need, but I would still have to adjust its sub modes in the Lighting window which is non trivial for me Subtractive Its description suggests it would solve all my problems and still be a nice optimization. However, static objects don't seem to receive dynamic objects' shadows or the other way around either. Baked Indirect, or Shadowmask Does not seem to pre compute direct lighting for static objects, throwing away performance gains. The final question is what method will lead me to the best performance in Unity with these requirements There are static and dynamic objects that both need to be lit by direct lighting Both static and dynamic objects should be able to cast and receive shadows from each other All lights are static Indirect lighting is not important in this case


Unity transform.position question Looking at example code for mesh deformation in unity https answers.unity.com questions 746673 sine wave mesh deform with different directions.html And i see theyve used public Transform Target1 public Transform Target2 void CalculateWaves () waves 0 .Direction Target1.position transform.position waves 1 .Direction Target2.position transform.position And i dont understand the difference between Target1.position and transform.position without any reference to an instance. Arent they the same thing. And how does transform.position function without a reference.


Can a Game Engine be built into a Game Engine? This confuses me as the title says "Mostly Civilized A Hex Based 4x Game Engine for Unity Part 1" Unity is a Game Engine, and he is building a game engine for a game engine. Did he word this incorrectly, or is building a game engine into a game engine a real thing?


Array but with a name for every element (value) Say I have 10 different types of grenades, I would like to create one variable, to allow me to set the number of grenades given from the inspector, I could create an array with 10 integers and set the number of grenades there, however it would be much easier for me if every element of the array (10 in total) had a name next to its value in the inspector so I could clearly see which grenade type am I assigning the value. Is there any variable type or something that would allow me to do this? If so what is it? And how can I create what I want? Thanks in advance! If more information better explanation of some aspect is needed ask.


Weird windowed resolution can't seem to change without changing the name My game is windowed, and when I set the resolution in the build settings (960x540 16 9 Windows standalone), and build it, it works as intended, but from then on, I can no longer change the resolution (can change it in the editor, and it also saves, but when I build it, it is still the original res (960x540))unless I change the Product Name as well. When I change the product name, I can change the resolution, build it, and it will change, but then it is stuck as well. When I change back to the first name, the resolution automatically change it the resolution for the first name (960x540) (it doesn't show up in the editor, only when you build it.) So basically Name1 960x540 Name2 1280x720 Name3 1024x576 etc So you can change the resolution every time you change the name and build it, and that name is stuck with that resolution (no matter what you change it to in the editor later). I am fairly new with unity, so am I missing something very basic here? Thanks for any help!


score and high score system for multiple levels I'm trying to create a scoring system for a game with multiple levels. For this I'm using the binary formatter instead of playerprefs (I read online that playerprefs are not that secure). I have created the system but whats happening is that the score is not resetting to 0 when I load a new level. If in one level the score was 10 and I start some other level, the score in this level starts from 10 instead of 0. This is the code I have so far public class ScoreIncrease MonoBehaviour public Text scoreTxt public int score void Start() LoadScore() void Update() if (Input.GetKeyDown(KeyCode.Space)) Save() public void Save() score scoreTxt.text "Score" score BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Create) ScoreContainer scoreContainer new ScoreContainer() scoreContainer.score score bf.Serialize(file, scoreContainer) file.Close() public void LoadScore() if(File.Exists(Application.persistentDataPath " scoreContainer.dat")) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Open) ScoreContainer scoreContainer (ScoreContainer)bf.Deserialize(file) file.Close() score scoreContainer.score scoreTxt.text "Score" score Serializable public class ScoreContainer public int score How can I change this so that each level has a separate highscore and all levels have a start score of 0?


Unity map size limit? Does Unity have a map size limit and if there is what is the limit? Is there a way to work around it? I am making a open world zombie survival world and I want to make a really big map. Thanks!


Which image effect is this? This is a screenshot from RE7. I have once seen the same image effect in Unity, but I don't remember the name I'm not talking about AA or DOF here, I mean this grainy greenish thing, I don't know how to describe it... At first I thought the name was something like quot Anisotrophic filtering quot , but that didn't bring up anything that looked like it. Can anybody tell me the name of the effect that I see here? Edit It can be seen in the start screen of this video, too https www.youtube.com embed aaN3MNb9ij0?feature oembed Both screenshots look pretty similar to me, so I guess it's the same effect? Edit 2 The pixels seem to shift into red blue the closer they get to the edge of the screens. I have drawn red arrows to region where this effect is very visible to me. These pixels appear as quot shifted quot to me. I think this effect is more visible at the edge of the screen. Thank you.


C Unity Getting which function affects a GameObject I have this little code that moves a GameObject over time public void Move(Transform from, Transform to, float overTime) StartCoroutine( Move(from, to, overTime)) IEnumerator Move(Transform from, Transform to, float overTime) Vector2 original from.position float timer 0.0f while (timer lt overTime) float step Vector2.Distance(original, to.position) (Time.deltaTime overTime) from.position Vector2.MoveTowards(from.position, to.position, step) timer Time.deltaTime yield return null Which is easy as it is, I plan to use it for UI animations. However, things get interesting when I wish to use this for a bit more complex animations, or I want it to stop upon restart. More complex animations I click a button which then moves to the side and bounches back. For this I need to know when the exact same method finished moving the button so I can restart it to bounce back. Stop upon restart Say I hover my mouse over a button which moves then. However, if it's still moving, I want its current animation to stop, and a new one to start. For both of these I need to know which function affects which GameObject so I can manage that. Question is, how? Shall I use one script on each of the animated components which affects only that one? Or if I could use only one script on the whole Canvas, then how?


Unity Android Immersive mode leaving a black bar in the soft key area? The black bar is not hiding anything. Everything is drawn above it. But the black bar is there in place of the soft keys even when they are hidden. I don't know how to hide it and render using whole screen. The bar is only visible with device having soft keys not for device with physical keys. I have set the Screen.fullScreen true. Unity 2018.3.4f1


Need help with using Player Prefs to save number of coins collected I'm using unity 3D to make a game where the character collides with coins in order to collect them. When playing the game, the player should start out with zero coins and each time he collides with a coin, the amount should increase by one. On a main menu scene, the total number of coins (that have been collected across multiple games) should be displayed. The total number of coins is being displayed on the main menu but once in the gameplay scene, the total number of coins is being displayed there too (where it's supposed to start at 0 and then increase by 1 each time a coin is collected). Here is the script I use for when the player collides with a coin using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CoinScript MonoBehaviour void OnTriggerEnter(Collider target) CoinScoreManager.coinAmount 1 Destroy(gameObject) Here is the script I use to manage the UI and coin number in the game play scene using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CoinScoreManager MonoBehaviour public static int coinAmount public Text coinText void Start() coinAmount PlayerPrefs.GetInt( quot CoinAmount quot ) void Update() coinText.text coinAmount.ToString() PlayerPrefs.SetInt( quot CoinAmount quot , coinAmount) Here is the script I use to manage the UI and total coin number in the scene with the main menu using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class MainMenuController MonoBehaviour int coinAmount public Text coinAmountText void Start() coinAmount PlayerPrefs.GetInt( quot CoinAmount quot ) void Update() coinAmountText.text coinAmount.ToString() I think the problem is in the second script shown above. In the Start function I'm calling the coinAmount which is the same variable used to show the total coin number. I think that's the problem but I'm not really sure how to fix the problem as I'm still kinda of new to Unity and programming. Please let me know if there's anything else you need to know about the game in order to figure out how to fix this. Thanks for your help!


Unity3d 2017 trail renderer behaving weird Please see the screenshot I attached, I am trying to make skid marks using trail renderer, but one side of trail is going upwards just after it renders, it was working fine Unity 5.4, but when I upgraded it to 2017, it is behaving like this.


C (Unity) Use a method common to multiple classes with the same base class The Problem I'm building one of those empire kingdom building games and so I am trying to create an efficient way of making a "ResourceManager" class handle the games resources (wood, food, iron, stone). I currently repeat a function 4 times to do the same thing. Attempt 1 I created a "Resource" class (abstract) and derived the four resources from it. In each resource there are multiple methods which are similar Example Food.CS new public static void AddResources(int amount) Player.currentFoodSupply amount foodText.text Player.currentFoodSupply.ToString() Compare to Iron.CS new public static void AddResources(int amount) Player.currentIronSupply amount ironText.text Player.currentIronSupply.ToString() The AddResource() function is static because I have other scripts (like buildings, when they get upgraded) needing to communicate with each resource. The base building class currently has a method like this public void DeductResources() Food.DeductResources(FoodCost) Wood.DeductResources(WoodCost) Iron.DeductResources(IronCost) Stone.DeductResources(StoneCost) This seems like it's so repetitive that there needs to be a more efficient way to do this. Attempt 2 A "ResourceManager" class that anything to do with the 4 resources can go through this one script. I can update that one script instead of numerous scripts that does something with the resources. Where I am undecided is this one public static void DeductResources(Resource resource, int amount) if(resource.GetType() typeof(Food)) Player.currentFoodSupply amount resource.resourceText.text Player.currentFoodSupply.ToString() else if (resource.GetType() typeof(Wood)) Player.currentWoodSupply amount resource.resourceText.text Player.currentWoodSupply.ToString() else if (resource.GetType() typeof(Iron)) Player.currentIronSupply amount resource.resourceText.text Player.currentIronSupply.ToString() else if (resource.GetType() typeof(Stone)) Player.currentStoneSupply amount resource.resourceText.text Player.currentStoneSupply.ToString() It looks like it works and I can't see a way around calling the above method 4 times as I need to know how much food or wood to add or deduct. Does anyone have any suggestions please on how to improve this code call the method once? I'm always willing to learn! Thank you


Slow down in the same time over different distances I'm trying to slow down a object over different distances in the same time, say 3 seconds. My slow down code is. function lerpSpeed (speed float, lerpSpeedTime float) incomingFlightSpeed flightPathScript.flightSpeed i 0 while(i lt 1) i Time.deltaTime lerpSpeedTime i Mathf.Clamp(i, 0, 1) flightPathScript.flightSpeed Mathf.Lerp(incomingFlightSpeed, speed, i) yield So I call it with. waypointScript.lerpSpeed(1,(totaFlighpointsDistance flightSpeed)) In the picture below I've draw a bezier curve and at the last 8 flight points (the red and yellow spheres) I want to start the slow down from the yellow sphere to the last red sphere. I get the distance in between each of the last 8 flight points and total them up to give me the total distance, I understand to get the time it will take to travel that distance is time total distance speed, but as I'm slowing the speed in my function above this will not work. And because every bezier curve I generate is different, some stretched out, with total distances sometimes ranging from 30 to 8. So I'm a bit stuck here, thought I'd get this one, but unless I'm missing something simple I can't get my head around it, so any help would be greatly appreciated, thanks.


How to prevent a cube from falling through a plane in Unity I am trying to prevent a player cube from falling through the plane (Battleground) in Unity, but after adding Mesh collider to both the cube and plane, as well as adding a rigidbody, nothing seems to work. The only way I can prevent this from happening is by locking the y axis of the cube, but this is a problem because I am adding in a jumping ability, and the player needs to be able to fall of the map. Is this something I can do within the Unity editor, or do I need to make a script that does that. To verify, all 3 colliders have "Is Trigger" Enabled, the platform is not designed to be moved, so the X, Y and Z of both the plan's rotation and position are locked, and the material for the colliders are all default. Each of the cubes and the plane's material are custom (Not the collider's material). The X, Y and Z of the cube's rotation are locked. Both cubes have the tag 'player' The code for player movement is using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMove MonoBehaviour private Rigidbody rb Use this for initialization void Start() rb GetComponent lt Rigidbody gt () Update is called once per frame void FixedUpdate() float h Input.GetAxis("Horizontal") 5 float v Input.GetAxis("Vertical") 5 Vector3 vel rb.velocity vel.x h vel.z v rb.velocity vel


Are there performance benefits to using WaitForSeconds vs checking elapsed time in FixedUpdate in Unity? I was considering that perhaps just checking the time and then doing some work in the Update function might look cleaner than calculating how long to wait for and calling yield new WaitForSeconds() on two interleaving processes, so I became curious whether there is a huge difference between the two options. Doesn't WaitForSeconds just work by calling an iterator after a certain amount of time has elapsed? So I assume that a timer is checked on each update, and when the time has elapsed, the IEnumerator's movenext function is called. However, I thought it couldn't hurt to ask someone just in case there is some huge difference in performance.


How to implement Microwave Signals in Unity? I need to implement microwave signals for object detection in Unity. I know there are raycast sensors in Unity, but can microwave signals be simulated or can a proxy of microwave signals be created in Unity using the raycast sensors?


Setting up a shader for RTS construction grid visibility (around cursor) I've set up a shader, thanks to the good help of DMGregory over at Draw animating grid with terrain deformation and variable colors here's what I got so far here's what it's supposed to look like here's what my shader code looks like as it stands forgive my non 2K screen it's only a 1080p but this is the full shader. here's each bit in isolation here's the main options for the node If I set surface to transparent... I get a much better result yet still not what I want because the grid area fades out immediately instead of staying at the center of the cube also the corner clearly has a green and red line overlap when line should only ever be red or green. this is the mock file that I'm currently using for buildable and non buildable area it's 256x256 (the size of my map) for now because I want to start small (where 1px maps to one unity square on the terrain of 1 unit) before I move on to the real deal which should be a 3584x3584 Texture 2D (where 1px corresponds to 1 14th of a unity unit). I want my grid to be 1 14th of an digit. eg cell one is (in diagonal) from (0.0f, 0.0f) to (0.14f, 0.14f). I've got preliminary code which will serve to generate this texture 2D programmatically editable2DconstructibleMap new Texture2D(256, 256, TextureFormat.RGBA32, false) constructionGrid GameObject.FindGameObjectWithTag( quot GridViewer quot ).GetComponent lt MeshRenderer gt () fill texture color corresponding to navMesh for (int x 0 x lt editable2DconstructibleMap.width x ) for (int y 0 y lt editable2DconstructibleMap.height y ) NavMeshHit hit if (NavMesh.SamplePosition(new Vector3(x 1.0f, 0f,y 1.0f), out hit, 1.0f, NavMesh.AllAreas)) editable2DconstructibleMap.SetPixel(x, y, Color.white) else editable2DconstructibleMap.SetPixel(x, y, Color.black) constructionGrid.sharedMaterial.SetTexture( quot BuildableMask quot , editable2DconstructibleMap) Here I'm using the navMesh which itself is automatically generated based on terrain slope. I target each point of the map and see if it falls in or out of the navmesh. Instead of redrawing this texture 2D when a building is placed and placement becomes impossible. I think I'll simply programmatically edit the 2D texture to add the new black pixels whilst the navmesh will be updated independently. Anyways, I guess the green red overlap issue comes from my texture2D being currently too small, but if I don't know yet what one pixel corresponds to, I'll have trouble getting this right. Update so changing the texture to one of 3584x3584 did not help. I still have the exact same behavior. So basically what did I get wrong in following the instructions from the other answer?


Prevent Unity click go trough Canvas I'm currently facing this problem If I click on a Button on my Canvas, the currently selected Unit moves towards the location under the Button. Is is there any option to solve this? I'm using the A Project for this. Sadly, I can not provide a lot of things I've done so far as I absolutely have no clue how to solve this problem. If I disable the Button Option "Raycast Target" ist still moves to this position but holds a bit earlier. Also, adding this as check didn't work if (!EventSystem.current.IsPointerOverGameObject() ) I also checked if the Raycast hit's the layer of the GUI My Movement code so far public override void MouseClick(GameObject hitObject, Vector3 hitPoint, Player controller) base.MouseClick(hitObject, hitPoint, controller) if (hasAuthority amp amp player amp amp player.human amp amp currentlySelected) if (hitObject.name "Ground" amp amp hitObject.name ! "UI" amp amp hitPoint ! ResourceManager.InvalidPosition) float x hitPoint.x float y hitPoint.y player.SelectedObject.transform.position.y float z hitPoint.z destination new Vector3(x, y, z) Debug.Log("Start Move") StartMove(destination)


How manage multiple images in Unity? I'm new in Unity and creating a game. So I have a class PicManager in which I have to load my images(sprites) from assets into a List and then use them in my game. What is the proper way to load multiple images from a folder in Assets? I know, that I can use Sprite sprites Resources.LoadAll lt Sprite gt (texture.name) But this article of Unity says not to use Resource folder.


Processing Vs Memory Optimization I'm creating a game with a lot of elements. Should I store all components that I'll eventually access on class variables (memory) or should I access them when running the script(processor)? Example private SpriteRenderer sprite void Start () sprite GetComponent lt SpriteRenderer gt () public void StartMovement() sprite.doSomething() VS void Start () public void StartMovement() GetComponent lt SpriteRenderer gt ().doSomething()