_id
int64
0
49
text
stringlengths
71
4.19k
0
Game (Physics) work in Unity Editor Remote but won't on Android? I have a script attached to a car game object that allows the player to tap the screen and then accelerate, the game object has a RB2D and collider set to it , it works fine in Unity Remote , but when I download the APK , as soon as I tap the screen , collisions go completely bezerk and the car just starts ignoring collisions , what's going on? As I need this to work to complete my game , as the player can move side to side with the accelerometer but I also want them to move forward when they touch the screen. Also , my game is 2D. Plus , since then , when the car ( my object) collides with anything else in the scene , it ignores it ( the obstacles just have Box Colliders on them). I had to freeze rotation so it could stop spinning out when it hit soemthing , now it just won't recognize collision at all. What's going on? The code I think is causing the error starts at line 32. I have obstacles the player has to dodge and they all have box colliders and an appropiate script attached to them as well ( so when they collide with my player , it destroys it) I've figured it out , Collision works when I first start the game , but when the player dies and I press "Replay" , it goes crazy. Here's the script that controls the enemy cars spawning , what the hell do I do to fix this? Code (CSharp) using System.Collections using System.Collections.Generic using UnityEngine public class EnemyCar MonoBehaviour public float speed public float acceleration 0.5f Use this for initialization void Start () Update is called once per frame void Update () speed Time.deltaTime acceleration transform.Translate(new Vector3(0, 1, 0) speed Time.deltaTime) void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "Coin") Destroy(col.gameObject) I've done everything in the book trying to solve this , re install unity , add different colliders etc. What's weirder is that it is FLAWLESS in Unity Remote and the Editor , these issues only arise when I test out the apk. Here's how my game usually looks when the collisions work. Now when it collides with a car ( on android) , it just ignores it and is slightly pushed back. Help me! Here is my script attached to enemy cars ( the cars that should destroy the player on Collision) using System.Collections using System.Collections.Generic using UnityEngine public class EnemyCar MonoBehaviour public float speed public float acceleration 0.5f Use this for initialization void Start () Update is called once per frame void Update () speed Time.deltaTime acceleration transform.Translate(new Vector3(0, 1, 0) speed Time.deltaTime) void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "Coin") Destroy(col.gameObject) Also here is the inspector view of my Player Car Here is the inspector view of an enemy car ( they all have the same things)
0
In Unity, what does the camera script's "Behaviour missing" error mean? I started in Unity few days ago and made a cube with a tank control style. Now I'd like to create controls similar to 3D fighting games (Gunz, Blade Symphony, ) Control body direction with the mouse and walk with WASD. However, the Camera is giving me a error called "Behaviour missing" each time I try, with all the cameras scripts I saw. I think that is a error with tagging the character movement in the camera, but I don't know how to do that. What might be the problem?
0
Unity Controlling animation by switching between a GameObjects children I bought an asset the other day containing an Atlas of character parts (head, hairs, clothes, body parts). It's great and allows me to tint each piece any color I want. However, The artist decided to devide up the character like this Each child is a fully setup character, facing a certain direction, with an Animator attached to it, inside each Animator Controller you find this Some sample animations, pretty self explanatory. However, I have never worked with sprites like this where its several parts, the entire character is maybe 30 40 parts (allowing for some fun animations). I'm used to making Blend Trees (on a single GameObject) and have one animation for each direction. The best solution for controlling these animations I could think of was something like this private void AnimControl() call in update if(direction ! directionLastFrame) do not run method if we are moving same direction standing still if (direction.x 0 amp amp direction.y 0) directionLastFrame direction left else if (direction.x lt 0.5f amp amp direction.y 0) currentCharacterDirection.SetActive(false) set current gameObject (which is a character facing a certain direction) inactive currentCharacterDirection character.leftDirection change to correct direction currentCharacterDirection.SetActive(true) set gameobject active again anim currentCharacterDirection.GetComponent lt Animator gt () set the animation controller to the new gameObject directionLastFrame direction set the new direction to check for right else if (direction.x gt 0.5f amp amp direction.y 0) currentCharacterDirection.SetActive(false) currentCharacterDirection character.rightDirection currentCharacterDirection.SetActive(true) anim currentCharacterDirection.GetComponent lt Animator gt () directionLastFrame direction down else if (direction.y lt 0.5f amp amp direction.x 0) currentCharacterDirection.SetActive(false) currentCharacterDirection character.downDirection currentCharacterDirection.SetActive(true) anim currentCharacterDirection.GetComponent lt Animator gt () directionLastFrame direction up else if (direction.y gt 0.5f amp amp direction.x 0) currentCharacterDirection.SetActive(false) currentCharacterDirection character.upDirection currentCharacterDirection.SetActive(true) anim currentCharacterDirection.GetComponent lt Animator gt () directionLastFrame direction anim.SetBool("Moving", playerMoving) I mean it works, but feels wrong? Anyone that can think of a better Idea here, worried this might be too slow. setting an object to active inactive too often.
0
Unity HDRP transparent material back face rendering front face culling I try to render an object with 2 different transparent materials. One should only render the back faces (higher opacity more color) and one only the front faces (lower opacity less color). The purpose is to show another object inside the mesh better, while keeping the more saturated color on the back faces. I tried to only render the back faces using a shader graph, but it seems to be impossible to only render back faces with TRANSPARENT material. With opaque materials, it was not a problem to isolate the back faces. Is there a way to only render back faces of a transparent material, and overlap them with another material that only renders front faces? (btw. this is the model, I need it for. The bones should pretty much preserve their details color, while the jello is a rich green (screenshot from blender)) Any help is very appreciated! Thank you!
0
Display and render only a specific object in wireframe in Unity3D I want to know how to view and render a specific game object (mesh) in wireframe, not the whole scene. I can change the scene to wireframe using GL.wireframe but the problem I want to view and render only a certain object (not the whole scene) in wireframe. Any advice please?
0
"Hold to jump higher" suddenly outputs a much higher jump I'm programming my first game in Unity and I'd like to make a very controllable jump. The idea is to apply an upward force while the player is still pressing the jump button, and then after some time ignore jump input. Kinda like how Mario and Mega Man jump. Problem is, somehow, my character occasionaly jumps much higher than it normally does. I set three variables on the inspector jumpImpulse the initial speed after pressing the jump button riseAcc the acceleration applied to the character while holding the jump button maxJumpHoldTime the longest possible time one might hold the button while still rising. if ((onGround onPlatform) amp amp Input.GetButtonDown("Jump")) GetButtonDown prevents holding jump and keeping jumping rb.AddForce(Vector2(0,(jumpImpulse rb.mass)), ForceMode2D.Impulse) force that starts the jump itself. rb.mass makes F ma into F ma m gt F a, so "Force" is actually acceleration. This is to better control mass and jump mechanics. jumping true DEBUG debugJumped true if (jumping amp amp Input.GetButton("Jump")) rb.AddForce(Vector2(0,(riseAcc rb.mass)), ForceMode2D.Force) first acceleration jumpHoldTime Time.deltaTime if (jumpHoldTime gt maxJumpHoldTime) jumping false else jumping false jumpHoldTime 0 Made this so I know how high the character jumps. if (debugJumped amp amp (!onGround) amp amp rb.velocity.y lt 0) Debug.Log ("Jump height is " transform.position.y) debugJumped false In the console, the jump height is listed normally as 2.376213, but sometimes it appears as 5.008272. It appeared once as 2.377432. Also, this variation seems to appear more frequently when I'm also moving the character left or right. And I'm not sure if this is related, but there are many times when I press the jump button and the character simply doesn't jump. Also, I put everything here under the FixedUpdate function.
0
Problem importing Blender materials into Unity via FBX I've created a simply low poly house in Blender (2.92) that I have imported into Unity as an FBX. Materials (simple colours) are all set up in Blender. Initially this was all working fine. Colours all came across correctly (bit dark, but they always seem to do that), but now all of a sudden I am finding that in some cases the material for object A is applied to object B and the material for B applied to A, and so on. Most are fine, but not all (eg the window frames meant to be white, are coming out dark wood, and the sills meant to be dark wood, are coming out white. The only thing that appears to have changed between working OK, and not working, is that I started to apply different colours to different faces of the walls for different rooms. However, the walls themselves are fine, all the right colours in the right places, it is just some other bits as above and those bits were previously OK. I've read there are issues in importing complex textures from Blender, but these are nothing complicated, just plain colours. Everything looks fine in Blender. What I do before creating the FBX is join most of the objects together in Blender with CTRL J to minimise the number of objects going across, but again, this was all fine up to now. I'd be grateful for any suggestions. I don't really want to have to reapply all material in Unity if I can avoid it. UPDATE Having exported all the objects separately, the wrong ones actually have the wrong material assigned. For instance a window frame has material WindowSill assigned. It is the right colour for WindowSill it just isn't meant to be that material at all, it is meant to be WindowFrame, and in Blender, that is what shows up as assigned.
0
Unity 3d Raycast from localspace to worldspace I want a raycast direction not relative to the rotation, but what happens is that the raycast points to one place as if it was a transform.forward Why is the happening help if(Physics.Raycast(transform.position, vector3.forward, out hit, SupportedDistance, CanBeSupported)) NotSupported false
0
How to make a custom event system framerate friendly? I have a simple event system class GameEvent float executionTime Action action class EventMgr MonoBehaviour List lt GameEvent gt events new List lt GameEvent gt () void Update() float timeNow Time.time for(int i events.Count 1 i gt 0 i ) if(timeNow gt events i .executionTime) exents i .action() events.RemoveAt(i) public void ScheduleEvent(float delay, Action action) events.Add(new GameEvent() action action, executionTime Time.time delay ) Then, I schedule events like this eventMgr.ScheduleEvent(0.1f, () gt EVENT A should be fired first eventMgr.ScheduleEvent(0.15f, () gt EVENT B should be fired second Everything works fine when I play on 60 FPS. Update() is fired once every 0.016s. When I play the game on a device with 20 40FPS things got a little bit tricky. Events seem to run in an incorrect order (Event B fired before event A). The only possible cause is of course the framerate itself. If the game runs at 20FPS, Update() would be called less frequently and both of these events would be fired in the same frame and then, the order of their execution depends on the list itself. What to do here? Is there any trick to prevent this, is there any pattern for accurate, ordered event system in games which is FPS friendly?
0
How can I bake several variations of a substance? I have a substance (sbsar) that I'm using to generate a procedural material . I have applied this texture to reversi pieces. It works well, but all the pieces look identical. I addressed this by using a script to change the randomseed property and then call the RebuildTextures method for each piece. The effect is exactly what I want each piece has a slightly distinct marble pattern. The problem is that the process of rebuilding the textures for 64 pieces takes about 20 seconds. For a simple Android game, this is not acceptable performance. The designer has the option to "bake" the material under Load Behavior, but this only works for one variation. Is there a way I can bake many different random seeds? I'd be OK with pre generating a batch of non procedural materials from the substance and picking randomly from that batch at runtime, but I'm not sure how that can be done.
0
Character controller going down slopes When I go down slopes with character controller, if the speed is too high, the character just flies off the slope and lands at the bottom. I want my character to "stick" to the slope rather then just jump of it. I came up with code to do so, but it didn't turn out as I planned. Now the character just slides on the slope when I stop pressing the arrows (not staying at its place on the slope). Physics.Raycast (transform.position, Vector3.down, out hit) transform.position transform.position new Vector3(0f, distance hit.distance, 0f) Thanks for the help, i couldn't figure this out all day.
0
Unity facebook sdk 'Didn't find class "com.facebook.FacebookContentProvider"' any more fixes workarounds for this? How to replicate this error... Create a new Unity project. Import the facebook sdk unitypackage Set your App Id for facebook via Facebook Edit Settings Using Assets External dependency manager Android, press 'Resolve dependencies', then press 'delete resolved libraries' (otherwise the build will fail at the gradle stage) Build and run. When the app tries to run I immediately get the error message on my phone 'app has stopped working' and see this error in the logs ... Caused by java.lang.ClassNotFoundException Didn't find class quot com.facebook.FacebookContentProvider quot on path DexPathList zip file quot data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw base.apk quot ,nativeLibraryDirectories data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw lib arm64, data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw base.apk! lib arm64 v8a, system lib64, system vendor lib64 Suggested fixes I've tried from here I've tried different combinations of old or new facebook sdks and old or new versions of Unity. I've tried building from a few different machines to different Android devices. I've deleted the external dependency manager included with the facebook sdk and used this one instead. In order to get this one to resolve I had to set a 'Custom Gradle Properties Template'in the player setting under publishing settings. I've set a Custom Proguard file'in the player setting under publishing settings, and I added the following two lines to the file.. keep class com.facebook.internal. keep class com.facebook. So I've tried all the suggested fixes and various combinations thereof. I dont know what more I can do. Can anyone suggest anything else to try?
0
How can I import an Excel file in an Unity WebGL game? Currently, we have a project that runs on Windows and uses an Excel spreadsheet to save retrive some data information. Now we want to build that project for WebGL. The problem is that file reading support is not available on the WebGL platform. How do I solve this problem? Do I need to write a backend or there another way to use excel in WebGL platform even though the file reading API of the .NET framework is not supported on WebGL?
0
3D Object in 2D Unity Project Is there a way to bring 3D objects into a 2D project that is using the 2D Universal pipeline for rendering light? I have some 3D objects I want to bring in to the project I'm working on, but they just get imported as pure white. Is there a way to import 3D models into a 2D game, and keep the 2D pipeline for lighting? I'l tried a few different shaders, but if they're not pure white they're pink. I would like them to have shading as a 3D object, and still interact with light and rotate on all axis if possible. If it's impossible to use a 3D object, if there was a way to at least have a 2D sprite taken from a 3D object, but still react to light as if it were 3D, that'd work too I suppose. This is what it looks like, https i.stack.imgur.com HJeIN.jpg I've also tried adding 3D lights as well, but to no avail. I'm guessing the issue is because of my 2D lighting renderer, and for the record, this is what this tree looks like in a 3D project. https i.stack.imgur.com nKCyd.jpg I have since attached a custom shader graph to it that I made, it looks okay, but it still doesn't receive shading at all... Thanks in advance.
0
Change Shader on This Material Via Code? How do I change this material to have the Toon Lit Outline shader via code at the Start of the scene? Here is my code that I have as of now, that does not work using UnityEngine using System.Collections public class MainMenuManager MonoBehaviour public Material hatMaterial This is my character's hat shader I set this in the Inspector private Shader toonShader This is the Toon Shader with an Outline void Start () toonShader GetComponent lt Shader gt () toonShader Shader.Find ("Toon Lit Outline") hatMaterial GetComponent lt Material gt () hatMaterial.shader toonShader
0
Implicit conversion error why is this code trying to convert a 'World' to an 'int'? using System.Collections using System.Collections.Generic using UnityEngine public class World Tile , tiles int width int height public World (int width 200, int height 200) this.width width this.height height tiles new Tile width, height for (int x 0 x lt width x ) for (int y 0 y lt height y ) tiles x, y new Tile this, x, y public Tile GetTileAt(int x, int y) if (x gt width x lt 0 y gt height y lt 0) Debug.LogError ("Tile (" x ", " y ") is out of range") return null return tiles x, y anyone see anything wrong with this code because on line 18 of my code i get this error "cannot implicitly convert type 'World' to 'int' and i don't know what is going wrong.
0
Make Minecraft Main Menu Camera movement I intend to make exactly like this. I highly suggest you watch just 5 seconds of the video because it already explains what I intend to do. I've been trying cosine and sine on vector3s but I can't seem to make it work since I usually get these results This however is my intended result This is my current code public class CameraWave MonoBehaviour SerializeField float speed 1f how deep and how wide the sine waves should be SerializeField float depthXY 2f radius of the circle SerializeField float radiusZ 10f makes the waves on the y axis and translates it SerializeField Transform targetLookAt parent of target look at so we can move it in the z direction SerializeField Transform lookAtContainer set angle to middle float angle 0.35f Vector3 cameraOffset void Start() cameraOffset targetLookAt.position void Update() adjust angle angle Time.deltaTime speed angle 360 make cos sine wave float x Mathf.Cos(angle) depthXY float y Mathf.Sin(angle) depthXY set to look at Vector3 position new Vector3(x,y) targetLookAt.localPosition position update container to make it go in circles lookAtContainer.position MakeCircleZ(angle) cameraOffset Vector3 MakeCircleZ(float angle) Vector3 v Vector3.zero v.x (radiusZ Mathf.Cos(angle)) v.z (radiusZ Mathf.Sin(angle)) return v My hierarchy setup any help is appreciated
0
How do I calculate the required force to launch an object? I want to use a rigidbody AddForce() method on an object to launch it over from the enemy to the player, like throwing a ball at a target. The problem is, I'm not sure how much force is required to use in the AddForce() method and it is taking too long to figure it out, and adding to that, the force would be different if I was farther away. I found this helpful guide but it is not in 3D https forum.unity.com threads how to calculate force needed to jump towards target point.372288 post 2415612. Could someone explain step by step in an easy to understand manner how to calculate the force required to get an object launched perfectly onto a target? (I'm not very good at math, haha...) Here's some images from that thread that will help illustrate the desired result
0
Limiting interaction between certain RigidBodies I'm developing a 2D game in Unity and have been tasked with building a particular feature I'm not sure how to accomplish with Unity's physics engine. To simplify, a bunch of objects of type X and O are filled into a pit XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXoXXXoXXXoX Both objects have Rigidbody2Ds and colliders. Objects of type X have normal gravity and should settle into place. Objects of type O have inverse gravity and should float. However, O should not be able to push X, and X should not be able to push O. Another way of looking at it is that O should only be able to move upward, and X should only be able to move downward. If we remove some of the Xs directly above an O, the O should float upwards as the Xs fall downwards until the Xs settle on top of the O and everything stops moving XXXXXXXXXXXX XX XXXXXXXXX XX XXXXXXXXX gt XXXXXXXXXXXX XX XXXXXXXXX gt XXoXXXXXXXXX XXoXXXoXXXoX XX XXXoXXXoX (In the actual game Xs and Os can be different sizes their movement is continuous and they are not constrained into rows or columns). The Os should be able to support the weight of any arbitrary number of Xs without sinking. XXXXXXXXXXXX XXXXXXXXXXXX XooooooooooX X X Lastly, the Os should be able to float diagonally if there is a space available XXXX XXXXXXX XXX XX XXXXX XX gt XXXXX XXXX XXXX XXXX gt XXXXoXXXXXXX XXXo XXXXXXX XXXX XXXXXXX I can't solve this problem simply by adjusting the mass of the Xs or Os since the number of Xs on top of an O may vary. I can't use the built in RigidBody constraints since they don't allow you to disable only one direction along an axis (e.g. saying an object can move upward but not downward). What's the proper way to handle this? I could do something like this void FixedUpdate() if (movementDirection Direction.UP) if (transform.position.y lt lastYCoordinate) Vector3 position transform.position position.y lastYCoordinate transform.position position lastYCoordinate transform.position.y but that feels hacky to me and I suspect it will keep the objects from sleeping. Are there better solutions here?
0
In Unity, what's a better solution than having a bunch of singleton static managers? (SceneManager, UIManager, SfxManager, PfxManager) I always hand a bunch of public static manager classes in my game GameManager (singleton) for reading and writing persistent data and gamestate across scenes SceneManager for holding scene data (coins picked up, score, are we in a cutscene) UIManager for dealing with HUD stuff SfxManager for sound effects PfxManager for particle effects On the gameobject that holds these manager classes, there are also subordinate classes (e.g. HUDManager, a smaller class that managers tasks specific to HUD, and then delegate those tasks into other smaller scripts) in order to avoid monolithic manager classes. Is this method frowned upon in Unity game development and if so, what are some better solutions than this approach?
0
OnMouseUpAsButton not always called I'm working on a 2D implementation of Free Cell in Unity 4.6.1, and I'm having trouble getting my click detection code working consistently. The code below should be called every time a card is clicked (they all have BoxCollider2D components) but it doesn't always happen. Handle Clicks on Card void OnMouseUpAsButton() print ("test") int cardLayerMask LayerMask.GetMask("Cards") RaycastHit2D hit Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, cardLayerMask) print ("Hit length " hit.Length.ToString()) if (hit.Length gt 0) print ("Hit") Even the "Test" print statement doesn't get called consistently, so it's not a problem with the raycast. If it manages to print the test, the raycast always works. Each time the game runs, the cards get dealt onto the playing field randomly into stacks. On each run, some subset of the cards don't call the above code. The number of cards that work correctly varies, as does their position on the field. It's not consistent with any particular card. I'm wondering if maybe there's an issue with the BoxCollider2D instances overlapping. The other colliders in the scene, like the one on the "table", always trigger OnMouseUpAsButton() successfully. I need to be able to register clicks on every card, so I need to find a way to make this work. Have any of you run into a similar issue before? If not, is there a way for me to work around this? Maybe a different way to detect the clicks on the cards? Here's a screenshot of an example card from the inspector. Aside from transform position amp script property values, all of them are identical (from a prefab) Update w Solution from Accepted Answer Using Byte56's solution, I was able to take care of this pretty easily. I've included sample code below. Note that to get the sample to work, the "top" object has to have the highest transform.position.z out of all the objects the raycast hits. I also put all the possible hit objects into their own layers so I can trigger different behavior based on what type of object is clicked. Handle clicks if (Input.GetMouseButtonDown(0)) Cast a ray, get everything it hits RaycastHit2D hit Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity) if (hit.Length gt 0) Grab the top hit GameObject GameObject lastHitObject hit hit.Length 1 .collider.gameObject Determine layer of last hit object, take next steps as appropriate switch (LayerMask.LayerToName(lastHitObject.layer)) case "Cards" print ("Hit card!") break case "Table" print ("Hit Table!") break case "Cells" print ("Hit cell!") break
0
How to fix pink tiles when there is a problem with the Shader? Because of some dumb mistake I did fifth time, I had to repaint my level in my 2D game. The problem is that the tiles I use from the Tile Palette turn into pink because of some shader error. I came to this conclusion after a long time of browsing through the forums. I am 100 sure that this will happen again, because I don't know what causes this behavior. So, prevention is not an option for me. What is the solution? By DMGregory's suggestion, I was able to recreate this dumb behavior of mine in an empty project. What I do is dragging and dropping a tileset onto a tile palette which I am using, and then overwriting the current tile palette. Then, the former assets are lost (I guess?) leaving me with pink tiles. Attached picture is one of my levels created using Tile Palette. How do I take this back? I don't want to repaint my level everytime I do whatever that causes this behavior.
0
How to rotate CharacterController on slope I'm trying to rotate my characterController player on a slope on the 'x' and 'z' axises, however things aren't going so well. The player does rotate, but if I move and look in another direction, the characterController will still be on the same axis, and won't look down an up slope, and instead will be looking up a down slope. void Update () Vector3 rotateDirection (camera.forward Input.GetAxis("Vertical")) (camera.right Input.GetAxis("Horizontal")) Quaternion newRotation Quaternion.LookRotation( new Vector3(rotateDirection.x, 0f, rotateDirection.z)) transform.rotation Quaternion.Slerp( transform.rotation, newRotation, rotSpeed Time.deltaTime) private void OnControllerColliderHit(ControllerColliderHit hit) transform.rotation Quaternion.Euler(hit.transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, hit.transform.rotation.eulerAngles.z) Also, it doesn't work at all with spheres and terrain since their rotation is zero. Anyone know how to achieve what I am talking about? Also, the goal is to allow for the 'y' axis to be free and do what it needs to in void Update().
0
Unity won't slice images properly Okay, so I am very new to Game Development and I imported a .png file(made in Paint) to the assets and that file contains just a circle and an oval, not touching and far apart from each other, both of them coloured blue. When I open the sprite editor and click on splice, then select Automatic and Delete existing options and then click slice, I do not get different sprites, one containing the circle and the other containing the oval. The image isn't sliced at all. I have also set the sprite mode to Multiple, but to no avail. Can someone help me and tell me what I am doing wrong? The engine I am using is Unity. This is the image.
0
Move an object with other objects connected (via joints) the right way What is the best way to move an object with other objects connected to it via joints? Let's assume we have the following setup A player that can move on the x and the z axis "Normally configured" RigidBody Moving like this void FixedUpdate() Vector3 movement new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) movement movement.normalized 2f Time.deltaTime m rb is the RigidBody of the player m rb.MovePosition(transform.position movement) Another object that should be moving with the player as it were its child Connected to the player via a fixed joint "Normally configured" RigidBody When moving the player without any object connected the movement looks as expected Now moving the player with the object connected results in some kind of dragging effect as seen here One way to solve this behaviour would be to also move the connected object m otherRb is the RigidBody of the connected object (m other) m otherRb.MovePosition(m other.transform.position movement) Is there a better way to solve this? Shouldn't the joint handle the movement of the other object? Moving the connected object like this results in many problems like to high impulse forces when colliding with something as both elements get pushed towards the collider. Also handling the rotation of the connected object isn't as easy as the position.
0
Unity export package but on import, scene and folder structure are different (screenshots) I export a package and shows me all the files I am exporting. When I go to import this package, one of the files is renamed and placed in a folder that no longer exists. Can anyone explain what is happening here and how I can fix it? Here is the image of me exporting, including the assets folder in the screenshot. Then I start a new project, and I try to import that package. But a filename has changed itself, and there is a folder there that I did not export, I actually purposely deleted it and it exported anyway
0
Unity C Coding Better Camera Recoil I am trying to get a good camera recoil system in Unity, but what I have tried so far doesn't seem to look very good. My current method, is using Quaternion.Lerp. With the way I have my shooting system set up, the camera recoil going up all happens within one frame, so when you shoot faster, it tends to look choppy, whereas the recoil going back down is smooth and normal. My question is, is there a better way to handle the camera recoil, while keeping the same look and effect, but having it look much more smooth? I have a quick video to show how the camera recoil looks (watch as the camera moves upwards) https www.youtube.com watch?v HsS0rtoj9l4 And here is the part of my code that handles the camera recoil void Update () Recoil2() Vector3 cameraRecoil weaponSettings.CurrentWeapon.cameraRecoil Transform cameraClimb generalSettings.cameraClimbHolder.transform string fireMode weaponSettings.CurrentWeapon.fireMode.ToString() if (fireMode "Semi") if (Input.GetButtonDown("Fire1")) Shoot() else CameraRecoil1 Vector3.Lerp(CameraRecoil1, new Vector3(0, 0, 0), Time.deltaTime cameraRecoil.z 10f) if (fireMode "Auto") if (Input.GetButton("Fire1")) Shoot() else CameraRecoil1 Vector3.Lerp(CameraRecoil1, new Vector3(0, 0, 0), Time.deltaTime cameraRecoil.z 3f) void Shoot () if (shoottime lt Time.time amp amp !isBusy amp amp !isReloading amp amp !isRunning) shoottime Time.time weaponSettings.CurrentWeapon.fireRate WeaponInfo currentWeapon weaponSettings.CurrentWeapon Transform cameraClimb generalSettings.cameraClimbHolder.transform Vector3 cameraRecoil weaponSettings.CurrentWeapon.cameraRecoil CameraRecoil1 Vector3.Lerp(CameraRecoil1, new Vector3( cameraRecoil.x, Random.Range( cameraRecoil.y, cameraRecoil.y), 0), Time.deltaTime cameraRecoil.z) void Recoil2 () Vector3 cameraRecoil weaponSettings.CurrentWeapon.cameraRecoil Transform cameraClimb generalSettings.cameraClimbHolder.transform cameraClimb.localEulerAngles CameraRecoil1 Anyone have any ideas? I appreciate anyone who can help me!
0
Using Reflection to access an array from a ScriptableObject in Unity I am trying to get access to a set of stored variables inside a scriptible object in Unity. This class (SectorDeclaration) has a method to pull a variable with a string of the variables name from it public Weightings GetVariName(string variableName) Type this class Type.GetType("SectorDeclaration") System.Reflection.FieldInfo fieldtype this class.GetField(variableName) Weightings fieldFind (Weightings )fieldtype.GetValue(null) return (Weightings )fieldFind Here's the error I'm getting TargetException Non static field requires a target System.Reflection.MonoField.GetValue (System.Object obj) (at Users builduser buildslave mono build mcs class corlib System.Reflection MonoField.cs 108) SectorDeclaration.GetVariName (System.String variableName) (at Assets Code Gameplay Element level Elements SectorDeclaration.cs 54) BaseGameManager.InitializeNPCSystem () (at Assets Code Managers BaseGameManager.cs 87) BaseGameManager.Start () (at Assets Code Managers BaseGameManager.cs 73) It works until the code reaches Weighting fieldFind (Weighting )Fieldtype.GetValue(null) I've used this code in another area but it is not working here, I've tried with System.object obj but it comes up with namespace doesn't contain this type, as well as with the type I am trying to access. Honestly, not sure what's wrong. If you need more information please let me know.
0
Wrong contineous rotation to car In my 2d game, I want to rotate car face based on collision detected. But at present after 3 to 4 collision its doing continuous rotation only rather than moving straight after collision. Here is my straight movement related code myRigidbody.MovePosition (transform.position transform.up Time.deltaTime GameManager.Instance.VehicleFreeMovingSpeed) For better collision purpose, I have used Rigidbody position change approach. Here is my collision time code public void OnCollisionEnter2D (Collision2D other) if (other.gameObject.CompareTag (GameConstants.TAG BOUNDARY)) ContactPoint2D contact contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (transform.up, contact.normal) direction reflectedVelocity if (direction ! Vector3.zero amp amp pathGenerator.positionList.Count lt 0) float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg Quaternion targetRot Quaternion.AngleAxis (angle 90f, Vector3.forward) transform.rotation Quaternion.Slerp (transform.rotation, targetRot, 0.1f) if (Quaternion.Angle (transform.rotation, targetRot) lt 5f) transform.rotation targetRot direction Vector3.zero Rotation get applied within other code so that car was changing its face correctly and that method not affecting here that I have checked by placing debug statement. Share you side thought for this.
0
How to trigger onclick for Unity Selectable by script? As title, I know Button can be triggered onclick by button.onClick.Invoke() But how to simulate onclick event of Selectable? Thanks for the help.
0
Best way to connect multiplayer users with each other (matchmaking) on a low powered server? OK so I am using unity to make a multiplayer game, but I'm not sure how to connect players with each other over the internet. Unlike other questions, this isn't a general problem of working out how to do UPnp or using unity's matchmaking server. My issue is that my server that I would use is a simple low powered pc (running normal windows 10, no idea how to use windows server). I think it is powerful enough to match players with each other, but not to host more than one or two actual games. The other issue is that I have a residential internet connection with a dynamic ip that changes every few months. However the speed should be ok (150Mb s download, 20Mb s download). Also, I'm not planning to spend money on a monthly basis for a server (like unity's matchmaking service) as I plan to spend as little as possible (So far I've paid 12 to Microsoft for a dev account and I've received a 200 voucher from them so my current spending is 189!) So my question is should I use my server (would it work), are there any online services that are very cheap to use, or is there another way to make this work? Only other thing is I could use the free 20 users at once on unity's matchmaking, but would this limit be too small? EDIT just for information, my game is a simple tank shooter. I was thinking about limiting the amount of tanks in a game somewhere around 8 20. The bullets in my game are physical objects with rigidbodys and they move at a slower speed (if you've ever played tank trouble, it looks like that). The world is in 3D. There is a potential for there to be up to a hundred bullets in a scene at once at the worst. After hosting a LAN world with 7 players connected for about 20 30 minutes, windows reports the data usage being around 3 4MB.
0
To extract Grabpass image as texture2d via script We applied it to the plane object using Grabpass. I want to import the image shown in plane through script. I want to make the imported image in texture2d format. Is there a way? Below is the relevant code.
0
Bug with OnColliderEnter Exit when colliding with multiple objects at almost the same time Unity Version 2017.4.1f1 I currently have a game with a jumping mechanic. I only want the jump to work where you're on ground, so I have planes on top of everything, which, if you are on a plane, then you can jump. This works, however if you are in a position where you are falling and then in quick succession, hit one plane, fall off that plane (like when your centre of mass is hanging off the edge), then land on another plane, at the end of it all, it still thinks you are on the air. Note I don't think this is an error with the velocity of the player, at no point do you go through a collider. So my question is, is there an error in my code (shown below) which I can fix, or should I take another approach towards jumping, thanks. Relevant code below. private bool canJump private Rigidbody rb public float jumpStrength private void OnCollisionEnter(Collision collision) if (collision.collider.CompareTag("Jumpable")) canJump true private void OnCollisionExit(Collision collision) if (collision.collider.CompareTag("Jumpable")) canJump false private void Update() if (canJump amp amp Input.GetKey(Keyode.W)) rb.velocity new Vector3(0, jumpStrength, 0) canJump false Safety measure to ensure consistent jump height Thanks
0
How can I set up potentially dozens of cameras rendering to targets without killing performance? I'm thinking through how I'd do a particular trick for playing cards with animated 3D faces. Setting up a single card is pretty trivial. I would create another camera somewhere, maybe restrict some layers so it'll only show what I want it to show so I don't have to worry what's behind it, put an object in front of it that is the basis of the card, have the camera render to a texture, and put that texture on a quad (the card) with the same aspect ratio. Now whenever the main camera views the card, regardless of angle, the card displays what the other camera sees. I don't believe this approach would scale well as I'd have to duplicate everything for every card. The way I imagine it, there could be dozens of cards visible at once so every frame would require rending all of them. Even at low qualities that sounds bad for performance. Also the main reason I want to animate cards is to have them respond to input and actions happening to the cards so two instances of the same card won't show exactly the same thing. Another thing is where would I place all these cameras and their models in the 3D space so that they won't see each other? I could put them on top of each other and use layers to only capture what I want but something doesn't feel right about having dozens of layers. How would I begin to pull this off on a scale of dozens of cards?
0
Unity AI issue with recalculating NavMesh at runtime I am using Unity NavMesh to control my units. I am running into an Issue when updating Navmesh at runtime, It seems agents re calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an IndexOutOfBounds error agent.steeringTarget agent.path.corners agent.path.corners.Length 1 I guess something is happening while re calculating path that might mess with this for 1 frame. I solved this by putting a try catch around it, but is there some better way I can manage this so I don't get the error at all?
0
Game freezes, cannot see why My game freezes randomly, mostly when changing from one level to the next. I cannot tell why this is the case. There are no errors or warnings. This happens when i build the game and when I am testing the game in the Unity editor. It will say unfreeze itself after a few seconds. I have attached one of the level codes and the timer code. I have also attached a picture of how it looks when it freezes. This is one of the level codes using System.Collections using System.Collections.Generic using UnityEngine using System.IO.Ports public class Arduino5 MonoBehaviour SerialPort sp new SerialPort(" . COM5", 9600) Com port and the baud rate of the arduino Material m Material GameObject Sphere void Awake() Sphere GameObject.FindWithTag("Player") m Material GameObject.FindWithTag("Player").GetComponent lt Renderer gt ().material void Start() if (!sp.IsOpen) If the erial port is not open sp.Open() Open sp.ReadTimeout 250 Timeout for reading Update is called once per frame void Update() if (sp.IsOpen) Check to see if the serial port is open try string portreading sp.ReadLine() get the string output of the serial port float amount int.Parse(portreading) if ((amount gt 50f) ) m Material.color Color.grey Renderer rend Sphere.GetComponent lt Renderer gt () Sphere.GetComponent lt Renderer gt ().material rend.material rend.material.mainTexture Resources.Load("face4") as Texture else m Material.color Color.white catch (System.Exception) and this is the Timer code using UnityEngine using System.Collections using UnityEngine.UI using UnityEngine.SceneManagement public class Timer MonoBehaviour public int timeLeft 5 public Text countdownText Use this for initialization void Start() StartCoroutine("LoseTime") Update is called once per frame void Update() countdownText.text ("Time Left " timeLeft) if (timeLeft lt 0) StopCoroutine("LoseTime") countdownText.text "Times Up!" Invoke("ChangeLevel", 1.0f) IEnumerator LoseTime() while (true) yield return new WaitForSeconds(1) timeLeft void ChangeLevel() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1) In terms of trying to close the serial port, would something like this work void Start() if (!sp.IsOpen) If the erial port is not open sp.Open() Open sp.ReadTimeout 250 Timeout for reading else if (sp ! null) sp.Close()
0
Unity 3D Materials are Stretching and Tiling doesn't Help I am a programming student working with Unity 3D, version 2018.4.6f1 for this class. I wanted to add some materials to my wall, however, this results in a rather ugly result, because my walls are of different sizes. This also happens with actual textures. However, editing their "tiling" as suggested does not result in something pretty, because the sizes of the objects. (In the shown example, both tilings are x 3 and y 4.) I can't seem to edit the individual tiling on each object, either. How can I fix this, and make everything look nice? I obviously don't want to create a gazillion of the same texture material just so I can tile it differently for each object.
0
Effect only on one object (two cameras) I have a problem. I want a Grayscale effect to be applied ONLY to the chair on the stage. The chair has a layer CurrentItem. And I have two cameras Camera All renders everything except layer CurrentItem (I set this exception in CullingMask) Camera CurrentItem Finally I need to apply not just one effect, but a few.
0
Maya keyframe animation to unity Sorry guys! I am super new to this, and I'm trying to teach myself Unity. I have a very small knowledge of Maya from a 3d modeling course I took a year ago in college, and have made a very simple object and animated it using keyframes (2 keyframes to be exact) in maya, but I can't seem to figure out how to get that animation into Unity. I've been playing around with this for hours now, and all the tutorials and such I find online are for really complex objects like people, and they have joints and stuff going on. Are joints required for an animation to work in Unity? I've saved my maya file into my assets folder, but I don't see any animations in the import settings in Unity. Here is my object And it animates to this position
0
Screen Space Camera improper scaling on iOS device only I've reproduced the issue in a simple setup where I have two canvas's, one overlay and one camera. I put an image under both set to maintain aspect ratio, and set them to use anchors for sizing instead of pixels. On iOS the camera space canvas stretches the image improperly, and the overlay is fine. Both have identical settings, with Canvas Scaler set to screen size and to match width. This only seems to happen on older iOS devices, but my sample size is too small to say that for certain. I expect both images to maintain aspect ratio on device, but the image under Screen Space Camera stretches out of aspect ratio. Local Scale on all objects is what I would expect it to be so nothing interesting there. Has anybody run into this issue before or have any idea what might be causing it?
0
Unity raycasting not always detecting component I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work In update I call if (Input.GetMouseButtonDown(0)) selectedObject null selectedUnits new List lt Unit gt () Select(Input.mousePosition) startPos Input.mousePosition which calls void Select(Vector2 screenPos) Ray ray cam.ScreenPointToRay(screenPos) RaycastHit hit Debug.Log( quot 1 quot ) if (Physics.Raycast(ray, out hit, 100)) OnClicked(hit.transform.tag) Debug.Log( quot 2 quot ) if (hit.transform.GetComponent lt Unit gt ()) Debug.Log( quot 3 quot ) if (!selectedUnits.Contains(hit.transform.GetComponent lt Unit gt ())) Debug.Log( quot 4 quot ) selectedUnits.Add(hit.transform.GetComponent lt Unit gt ()) if (hit.transform.GetComponent lt Building gt ()) if (hit.transform.GetComponent lt Building gt () ! selectedObject) selectedObject hit.transform.gameObject Detecting a quot building quot always works and is fine, but clicking on a quot unit quot works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not). This is the Unit in the inspector and this is it in the hierarchy When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time. it seems like after each hit the ray penetrates the collider more and more But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider. I hope someone knows what's going wrong, thanks!
0
How can I find out where a particular texture is being used in my Unity project? I have a texture in my assets, and I need to find out where it's being used so that I can change some textures in my project. How can I find out where a specific texture is used in my project? The case is that the game needs to be updated to have a Christmas look, so there are a few game textures should be replaced. This resource checker does not work for me. It shows that there are no textures even though there are
0
Can UNet do Rigidbody2D prediction? (i.e. using gravity) Having a NetworkTransform with transformSyncMode set to SyncRigidbody2D (as opposite to a plain SyncTransform) I assumed it would try to sync all physics, hence handling gracefully forces, especially gravity. What I got instead, is a very simple linear interpolation, which smooths out the gravity, so that jumping up and down looks incredibly unnatural I would have expected this wish a SyncTransform of course, but, given the name I would have expected SyncRigidbody2D to solve this sort of problem So, am I missing something and might I have some value set wrong, or what?
0
Using different shaders based on desktop or mobile? Most of my assets use the Unity standard shader. It looks and runs fine on Desktop, but on mobile the performance isn't good. I assume the solution is to switch to one of the mobile friendly vertex lit shaders for mobile. But how can I switch shaders depending on platform? Is there a way that Unity can do this for you, or do I need to manually change them before building? Also, would I be able to just specify the shader, or would I need to create all new materials for all my assets? I really have no idea how to approach this, and I'd appreciate it if I can be pointed in the right direction.
0
Filling of a multidimensional array with string I'm trying to fill a dropdown with a lis,t if some input is correct. now when trying to create the list from a text file (to save the program) i should split the line on a comma so i have 3 settings for one asset For ex asset1,colour,used,broken. the list should show the asset if the item is broken (0 is not broken, 1 is broken). public string ,,, UsedAssetList string lines System.IO.File.ReadAllLines( "" Application.persistentDataPath " assetlist.txt") cmbAssetNumber.ClearOptions() for (int i 0 i lt lines.GetLength(0) i ) UsedAssetList lines i .Split(',') if (UsedAssetList i,0,0,1 "1") list new Dropdown.OptionData(UsedAssetList i,0,0,0 ) cmbAssetNumber.GetComponent lt Dropdown gt ().options.Add(list) The lines i .Split(',')gives me the error Error CS0029 Cannot implicitly convert type 'string ' to 'string , , , ' I think everything is on point, except the filling of my list. any idea on how i can get this right? EDIT I was thinking the list should look like this "asset1","Gold","1","0" , "asset2","Green","0","1" , ... EDIT While the text file looks like asset1,Gold,1,0 asset2,Green,0,1 ...
0
How can I add a sprite to gameobject to make the gameobject highlight? When I'm running the game and then moving the mouse cursor over the menu it's highlighting it with some blue color In the screenshot the OPTIONS is highlight. Now I want to use the same highlight sprite to highlight the word THE in white at the top in the screenshot but to make it highlight all the time without the mouse cursor. I have New Text in the Hierarchy and in the Assets I have Select and Select is the sprite I want to highlight with the word THE I tried to add a Sprite Renderer component to the New Text but the New Text have already a Mesh Renderer so I can't add the Sprite Renderer.
0
How do I listen for an Admob interstitial ad load event? I can show interstitial AdMob ads with the following code if (GUI.Button(new Rect(10, 300, 150, 50), "Load Interstitials")) interstitial.LoadAd(interstitialsRequest) if (GUI.Button(new Rect(10, 400, 150, 50), "Show Interstitials")) if (interstitial.IsLoaded()) interstitial.Show() That's all working well. Now I want to attach a listener for when the interstitial ad has loaded. I checked all the available source files, but can't find the right listener method. void onAdLoaded() print("Interstitial Ad Loaded") public void HandleAdLoaded(object sender) print("HandleAdLoaded event received.") Handle the ad loaded event. I use googleads mobile plugins for Admob ads. What listener should I be using?
0
How can I create a walking zone logic for my player? First I will show a screenshot and explain the logic I think of and what I'm trying to do In the diagram the circle is the player the big rectangle is the zone area for increase decrease speed movement of the player and the small black rectangle is the target. What I'm trying to do is to add some rules for this case. I'm controlling the player in third person movement with the keys WSAD and the mouse to rotate around looking around. This is the player structure screenshot in the Hierarchy There are few rules I'm trying to set for the player in this specific situation in the game and I want to make it generic so I can add the rules or create this behaviour in any place in the game when I need to. The idea is when the player is getting inside the green zone rectangle facing the target make the player slow down to stop smooth. The green zone is the distance from the target to start slow down only if the player is facing the target. If I rotate the player back facing away from the target in the green zone at any time increase the player speed back to normal speed. The idea is that if in the green zone I rotate the player at any time and move hi he will decrease increase the movement speed. Facing target decrease slowly to stop facing away from target increase the speed slowly to normal.
0
I imported a blend file into unity which contained 3 animations but I can only see one Unity and I need three I can only see one in unity But there are three in blender I thank thee answers.
0
Unity Blender models animations showing gaps As part of a college project, a member of my group has made some simple chests with an open animation. Importing these into Unity though, I instantly noticed there were gaps where the faces should be. After a bit of experimenting, I figured it was because the Normals were facing the wrong way. The outside seemed fixed, but faces were missing when the chest opens during its animation. I'm guessing the inside of the chest will need another layer of faces with the Normals facing the right way...? Though surely this would means having doubles...?
0
Developing for Unity without Editor I want to write a Unity app that doesn't use the Editor. That's the goal. Please don't ask why or tell me the Editor "is really great, you should try it", I know all that, I love the Editor, I'd personally love to WORK on the Editor (at Unity). That's not how this particular project goes, however. The goal is a 3D prototyping app. In the app, you make design changes to a set of 3D models, and the changes you make show up "live" in a Unity app. When you're done, you "bake" the changes into an actual Unity app, complete w the Unity project source code, so you can open it and further refine it. Sounds goofy, I know, I was assigned this project from somebody else. I know that for the live changes shown in Unity, I could of course make a nearly blank Unity project, and add GameObjects at runtime, and set their attributes. That much is obvious. What's not obvious is how to add C script behaviors at runtime. If the Unity "live" app is running all the time, and I'm adding GameObjects at runtime, how then do I add compiled C dlls at runtime, so the dynamically created GameObjects use the newly compiled C code? I'm thinking the GameObjects would call out to a C dll by some kind of name binding, each time the C code is updated, the dll is written out with a GUID hash, and in the GameObject code, it dynamically looks for that Dll and loads it, then steps into it. seems tricky and complicated, right? Has anybody done this and had some insight into it? Before anybody references "Futile", keep in mind I don't care much about looking into a 2D only answer for this, and don't want to dig though that 2D code even if it has the answer in it. I'd like to discuss the answer here, on this forum, about thoughts about how to approach this, in the hopes it may help other people too. Goals 1. I provide 3rd party users a prototyping app that throws together an "editor" or a "prototyper" which shows on one winodw, with live in Unity results in another window. Let's say the "prototyper" object in question is a GIANT terrain, populated with houses, trees, humans, etc. You can move around, see what the generated stuff looks like. Then, when you're happy with the look, you press "bake" and out pops a Unity project that you can go edit and flesh out. 2. I need the live Unity view to accept c code (over some kind of communication mechanism) that will get compiled and run by the live view. Examples for why might be trees in the scene waving in the wind, running waterfalls, etc. Thoughts?
0
Unity Quaternion.AngleAxis for two axes I am creating a character controller where the camera follows the rotation of the player, and allows the user to click and drag to rotate the camera around the player, and lerps back when its released. The part I am struggling with is being able to rotate the camera on both the x and y axes using the Quaternion.AngleAxis method. It gives me the functionality I want on the one axis, but I want to be able to move freely around x and y. I am able to do this when I am not clicking and dragging because I am just lerping the camera to the offset position. My code is below if (Input.GetMouseButton(0)) Vector2 mouseInput new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")) This only handles rotation around x axis currentOffset Quaternion.AngleAxis (cameraSpeed mouseInput.x, Vector3.up) currentOffset Vector3 newPosition target.position currentOffset This is where I am just temporarily setting the y position to look down at the character. newPosition.y target.position.y 2.0f transform.position newPosition transform.LookAt(target) else Vector3 targetPosition target.position target.forward cameraDistance Vector3 newPosition transform.position newPosition.x Mathf.Lerp(newPosition.x, targetPosition.x, 3.0f Time.deltaTime) newPosition.z Mathf.Lerp(newPosition.z, targetPosition.z, 3.0f Time.deltaTime) transform.position newPosition transform.LookAt(target) currentOffset transform.position target.position As you can see I am just temporarily setting the position to 2 units above the target position so the camera slightly looks down at the player. What I would like to do is be able to move both axes to get full observational control around my player. I am not sure if AngleAxis is the right method to be using, but its given me the closest results so far.
0
How to make a character sit in Unity? So I've got the animation, it has root motion but activating it in the settings doesn't seem to do much. What would be a good optimized way to have the character sit on the stool with the animation matching the movement? Would I need to do it through code?And if that's the case, could I specify in which frame do the movement? Or add a second animation that is in charge of Root Motion? I know either of these two options I give could work but I'm checking to see if there is a better way or if I'm missing something here. Thanks! EDIT Following DMGregory's comment I disabled the collider to see if it improved... it did change, but it isn't much better EDIT 2 This is how the animation preview looks like (what I'm expecting) Then I just hold the last frame while they're sitting and play the animation backwards for when they're getting off this is just while I get it to work.
0
Unity Handling external data files I'm moving from an old game dev tool to Unity, and wondering how to go about handling external data files. In my previous program I'd set up external (txt ini) files like this Group1 Count 1 1 Hello Group2 Count 2 1 lol 2 end Then I would simply reference which group name and line I wanted to pull. What's the equivalent to this in unity? I see I can import TextAssets but I can't find functions to pull select data from it. Do these exist? Do I have to split by lines, loop through them all and convert it into groups (lists) manually? What is the standard method for doing this? Is it moving to xml files?
0
How to show NGUI menu in the upper of a Game Scene? I am new to Game Development. I made a menu with NGUI plugin. I have a background image in the behind of this menu. Now, I want to place my Game Scene in place of the background image. I have tried in several ways. But, Failed. Any suggestions will be highly appreciated. Thanks
0
Problem with Parameters for polymorphism class This is going to be a bit tricky but it is really bothering me so I hope you will have the patience to follow along ) Here is my very basic architecture So in the framework, I am creating I have Actions these currently have a list of Conditions or Considerations (same thing different name). While each Condition share some of the same functionality such as Returning a float score Using an evaluation formula They implement these in very different ways depending on the situation. Take a look at the following code CreateAssetMenu(fileName quot Consider my health vs max health quot , menuName quot AnAppGames AI Example Decisions Health Consideration quot ) public class MyHealth BaseConsideration private float health public float maxHealth public override float Consider lt T gt (BaseAiContext context, BaseAction action, T value) health value as float return EvaluateValues(health maxHealth) What you are looking at is my first attempt at making some sort of quot reusable quot Consideration. Now in the continuation of my development, I had to make the following Consideration public class DistanceFromMe BaseConsideration public float minRange public float maxRange private float ConsiderWithValues(Transform target, Transform caller) return EvaluateValues(new FloatData(Vector3.Distance(target.transform.position, caller.position), minRange, maxRange).GetNormalizedData()) public override float Consider lt T gt (BaseAiContext context, BaseAction action, T value) Transform target value as Transform if (target null) return 0 return ConsiderWithValues(target.transform, context.transform) public override float Consider(float x) return EvaluateValues(new FloatData(x, minRange, maxRange).GetNormalizedData()) And now the trouble begins I thought quot This is not a scaleable solution quot as soon as I need more than 1 generic parameter I am screwed and have to create additional overrides of this Consider function. So what I need is somehow to add different types of parameters to the Consideration however these parameters will vary a lot. Another problem I have with this is that when I loop through the list I won't be able to tell what parameters i needed and how to fulfill the needs of the Consideration. I thought of different ways of dealing with this inside the editor but I have come up empty ( Can anyone help me out with this architectural mess? ) It is worth mentioning that at the current point each of these are ScriptableObjects I am not 100 set in the fact that they should be but i am just not sure how to deal with this problem.
0
How can I clean this if Statement up? I am busy working on a full solo project with no assistance from tutorials or guides. But I have created a monstrosity of an If statement. How could I clean this up and save on memory since I'm calling this in my Update() method and the game is for android? the hp1 to hp5 are images used as health bars on the hud, I need to deactivate the ones that are not in use when the hp value decreases. if(hp gt 81) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled true hp5.enabled true else if(hp gt 61) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled true hp5.enabled false else if(hp gt 41) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled false hp5.enabled false else if (hp gt 21) hp1.enabled true hp2.enabled true hp3.enabled false hp4.enabled false hp5.enabled false else if (hp gt 1) hp1.enabled true hp2.enabled false hp3.enabled false hp4.enabled false hp5.enabled false else if(hp lt 1) hp1.enabled false hp2.enabled false hp3.enabled false hp4.enabled false hp5.enabled false
0
Optimization for lots of UV coordinates update for tilemap animation In my game, I procedurally generate tile map mesh and modify it when travelling around the "world". Each tile is a quad. So they each, have their own UV points. (Obviously) I am using Unity for this, and in Unity, i can't have more then 65k vertices in a single mesh. So i made this "tile mesh", chunk based. It's still a single mesh. But while I am creating it, i first create the "chunks", (which are 16x16 quad meshes), then i "merge" the chunk meshes to create the tile map mesh. I keep these "chunk meshes" in a list. So basicly i merge all the meshes in the list when i want to "update" the tilemap mesh. While i am travelling in the world, i can remove farthest chunk from list, and add new chunkes when it's necessary. List capacity is fixed to 9, so i can never exceed the "65k vertices limit". Now the problem is, when i zoom out in game, there becomes almost 40k vertices in the scene since whole mesh becomes rendered. (Actually since it's a single mesh, it always renedered as whole, but the animation doesn't occur out side of the camera view) But when i zoom out, there are like atleast (6x6)x(16x16) 9.216 tiles. Which makes 36.864 vertices (and UV points). Now updating few tiles (so few uv points) is easy. But updating the whole 36k point takes like 1 2 seconds. Which is really bad for updating animation in that way. The code snippet for single quad uv update is here public void SetTile(Coord chunkCoord, Coord tileCoord, Sprite sprite) Vector2 uv meshFilter.mesh.uv Rect spriteRect sprite.textureRect int chunkIndex SearchForChunk(chunkCoord) if (chunkIndex 1) Debug.LogError("Chunk not found") return int ui chunkIndex (16 16) (tileCoord.Y 16 tileCoord.X) ui 4 uv ui ToUV(new Vector2(spriteRect.xMin, spriteRect.yMax), sprite.texture) uv ui 1 ToUV(new Vector2(spriteRect.xMin, spriteRect.yMin), sprite.texture) uv ui 2 ToUV(new Vector2(spriteRect.xMax, spriteRect.yMin), sprite.texture) uv ui 3 ToUV(new Vector2(spriteRect.xMax, spriteRect.yMax), sprite.texture) meshFilter.mesh.uv uv It takes chunk coordinate, and finds that chunk in the chunk list, so i can get the index of that chunk mesh for UV array. The sprite that i get as a parameter is in a "sprite atlas", so i call a helper function to convert it's rectangle to uv points. That's how i update a single tile's UV points. But It's too slow, how can i optimize it, make it faster?
0
Correctly get size from Canvas UI element on Unity Normally when anchors are on the same position, we can use .sizeDelta or .rect.width height from RectTransform, but if the anchor are stretched, both of them returns negative values Which in reality is not 5 in size at all There are already SetSizeWithCurrentAnchor but how to get other's RectTransform's absolute size?
0
How to run DOTween tweens in succession? I have a function in my Unity game which marks a given cell GameObject as a valid cell for next move by changing the texture on it. I wanted to spice things up a bit by adding some tweens to the changing cells so I decided to use a simple tween in DOTween I wanted to rotate the cell 360 degrees in place while changing the texture when it's facing away from the player (so that the texture doesn't suddenly pop to a different one when it's visible). So I did something like that public void markAsLegal() centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd) this.GetComponent lt Renderer gt ().material.mainTexture Resources.Load("textures legal hex") as Texture2D centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd) isLegal true This, however, doesn't seem to wait for one rotate before starting the next one and so the cells end up in some weird middle ground, slanted. How can I make DOTween Unity know that I want these commands to be executed in progression, ie. 180 degree rotation ends change texture finish the remaining 180 degrees?
0
How can I set the remaining distance of the nav agent? I have an issue with the nav agent in my game. That I am using the remaining distance to determine the next state of the AI. When the navagent is first given a destination it uses the previous distance until it is next updated. So my plan is to find the memory of the remaining distance and alter it when I set the destination. Is that possible or is there a better way?
0
The identifier is not in the scope! I have a typical foreach loop in a coroutine like foreach (DLine LineItem in DLINEs) GameObject NL GameObject.Instantiate(DXFLine) NL.layer LayerMask.NameToLayer("2D") LineRenderer NLLR NL.GetComponent() NLLR.positionCount (2) NLLR.startWidth (0.01f) NLLR.endWidth (0.01f) Color LineColor new Color() DLAYER DL TABLES.DLAYARs.FirstOrDefault(l l.LayerName LineItem.Layer) if ((LineItem.ColorNumber 1395 LineItem.ColorNumber 256) DL ! null) LineColor COLORs DL.ColorNumber else if ((LineItem.ColorNumber ! 1395 LineItem.ColorNumber ! 256)) LineColor COLORs LineItem.ColorNumber if (LineColor Color.clear) LineColor new Color(1.0f, 1.0f, 1.0f) NLLR.startColor LineColor NLLR.endColor LineColor NLLR.SetPosition(0, LineItem.StartPoint.ToVector3()) NLLR.SetPosition(1, LineItem.EndPoint.ToVector3()) NL.name "LINE " LineItem.Handle NL.transform.SetParent(Lines.transform) DXF Input.DXFLines.Add(NLLR) Debug.Log(item.Log()) Counter if (Counter 50) Counter 0 yield return WFS and I want to debug it using Visual studio by putting breakepoint on the lines with ' '. I'm running unity and attaching the VS to unity and it stops at the breakpoint so there is no problem there. But when I want to see the values, it says the Identifier LineItem is not in the scope. Why is this happening? How can I fix it?
0
Instantiate a new Prefab I m developing a little 3D game to improve my Unity C development. However, I am faced with a recurring error that I cannot find the solution to In fact, I always get the error Nullreferenceexception Object reference not set to an instance of an object when I want to create a new Gameobject in my scene. I wish I could spawn a bonus based on a percentage of chance when an enemy is killed. So I created a Bonus mother class and a Bonushealth daughter class. So Bonushealth inherits the Bonus methods. Here s the mother class code (Bonus) using UnityEngine public class Bonus MonoBehaviour protected int lifeTime public int LifeTime get gt lifeTime set gt lifeTime value protected void RandomDropBonus(Transform posEnemy) int chance Random.Range(1, 100) switch (chance) case int n when (n lt 100) Instantiate(Resources.Load lt GameObject gt ("bonus"), new Vector3(posEnemy.position.x, posEnemy.position.y, posEnemy.position.z), Quaternion.identity) break public void RandomBonus(Transform posEnemy) int rdn Random.Range(1, 1) Debug.Log(rdn) if(rdn 1) RandomDropBonus(posEnemy) Here's the daughter class code (BonusHealth) using UnityEngine public class BonusHealth Bonus public GameObject prefabHealth Start is called before the first frame update void Start() LifeTime 10 I call the RandomBonus() method when an enemy is killed (in the Enemy class), Here's is the code private Bonus bonus bonus.RandomBonus(this.transform) if I make Bonus bonus new Bonus() I always get this error ArgumentException The Object you want to instantiate is null. In my prefab folder is contained my bonus prefab named bonus. I added the Bonushealth script on it. I did a lot of research on the Internet but no way to find a solution Thanks in advance )
0
Unity prefab object limitations TLDR What are limitations on how many objects a single prefab can handle safely? keeping in mind that I could potentially have almost a 100 of these I am busy creating a system to essentially load the game world in chunks as the player moves. This means that every single object in the world will be streamed into the game through script when needed(still designed in the editor, impossible otherwise) The problem I am having is with methods to store and load objects. I have looked at everything I could think of or get information on. After researching all the methods I found, I started thinking that prefabs is the best solution since it can live anywhere in the project(unlike streaming assets folder, which is also not recommended for many assets, let alone every single asset). Creating Game Objects at runtime is not as easy once GO's get complex with components and settings, also I assume the performance hit from creating GO's this way is worse than using an existing prefab. So my question is if prefabs can handle massive amounts of objects(lets say 1000) safely? testing this is hard because i would have a prefab(or a few) for each tile that gets loaded.
0
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?
0
Unusual black squares in transparency effect after wake from sleep I've encountered unusual black squares in semi transparent textures for a while now, usually in processes that were resumed after the computer woke from sleep. For example I've seen the effect in the Battle.net launcher by Blizzard frequently, on different machines. But now I often encounter the effect in Unity in Play mode if I let the computer go to sleep. Restarting the scene fixes the display problem. My 2 questions are What is that effect? What do I need to do to prevent the effect from reaching my users? In this screenshot there are 3 semi transparent particle effects on top of one semi transparent billboard, and at the bottom we see a part of an opaque sphere. The black squares seem to only affect a single one of the particle effects, and disappear if the effect is disabled, and reappear if it's re enabled. And here is the same effect in the Blizzard launcher
0
Box Collider center relative to GameObject I'm trying to get the distance from the BoxCollider center of a gameobject to the bottom of that same BoxCollider. Note that the center of the collider is slighty modified. So far, I have float halfHeightCollider (bounds.size.y 2) I tried the following to take care of the slight modification float halfHeightCollider bounds.center.y (bounds.size.y 2) But seems like bounds.center give me the position of the center of the BoxCollider in the world, not relative to the gameobject, like in the inspector That value is the one I want. How can I get it?
0
Actions abstraction in Goal Oriented AI I am back with another question about Goal Oriented AIs. To explain my problem, I will use a specific example. In my game, population nodes are spawned on a world map, and important characters called "Migration leaders" can spawn, take in migrants, lead them to a good spot, and then establish a new population node there and finally despawn as they have served their one time purpose. What I want to achieve is having only one action called "MoveToTarget" which has no pre conditions apart from having a target location, and has the effect of setting the fact "Reached target location" to true, which itself is the precondition for other actions. Not sure this is the right way to structure that in the GOAP but that's not exactly my problem, at least I do not think so. My problem is that, since you can't work with actions that take in an argument, I have little notion of how the AI should determine the location which it will move to when the "MoveToTarget" action triggers, for the following reasons Depending on the character type and generally what is happening, each character will think differently about where they're interested in going. Furthermore, what happens when I have to interrupt the AI's "plan" for some reason ? The original target location for, say, transporting migrants is lost ! I do not which to make different actions like "MoveToMigrationTarget" because then I'll have to make many MANY more actions, like "MoveToCombatTarget" or "MoveToRessources" and I do not think that will work as that will make me have to keep a "Migration target", a "Combat target".. in memory even for characters that have nothing to do with either of those. So my question exactly is, where is the AI supposed to do the "practical thinking" in a GOAP ? The Actions themselves must be abstract, and can't take in any argument so I have to somehow have target location(s) in memory and have the GOAP planner know which target corresponds to which action. I could also extend that question to basically any action that need a specific target object to work.
0
Star glowing shader graph How could I make a shader graph that makes spheres that look like on this image? I'm new to shaders and I don't know how to do this. Also, if it's possible I would like a property to change the glowing intensity
0
Why the Vector3.Dot value is 12 when running the game? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.Events using System public class InteractableItem MonoBehaviour public string currentMode private Transform player private InteractableMode currentInteractableMode private string currentDesription private float originDistance private void Awake() player GameObject.Find( quot Player quot ).transform originDistance transform.GetComponent lt InteractableItem gt ().distance public enum InteractableMode Description, Action, ActionWithoutThrow public enum ViewMode FrontView, AllView public ViewMode viewMode ViewMode.AllView public InteractableMode interactableMode InteractableMode.Description public float distance TextArea(1, 10) public string description quot quot public bool IsAnyAction() return interactableMode InteractableMode.ActionWithoutThrow interactableMode InteractableMode.Action public bool IsActionWithoutThrow() return interactableMode InteractableMode.ActionWithoutThrow private void Start() currentMode GetComponent lt InteractableItem gt ().interactableMode.ToString() currentInteractableMode GetComponent lt InteractableItem gt ().interactableMode currentDesription GetComponent lt InteractableItem gt ().description private void Update() var heading transform.position player.transform.position var dot Vector3.Dot(heading, transform.forward) if(viewMode ViewMode.FrontView amp amp dot lt 1) transform.GetComponent lt InteractableItem gt ().distance 0 if (viewMode ViewMode.FrontView amp amp dot gt 1) transform.GetComponent lt InteractableItem gt ().distance originDistance The script is attached to some objects and one of them the ViewMode is set to FrontView and then when running the game first time the dot value is 12 and then it's getting inside and going the line if(viewMode ViewMode.FrontView amp amp dot lt 1) transform.GetComponent lt InteractableItem gt ().distance 0 but it should not set the distance to 0. only if I'm getting close enough to the item then it should see the item from the front and then only if I'm moving the player behind the item the dot should be minus and set the distance to 0 but for some reason the dot is minus 12 when running the game so it's setting the distance to 0 right away.
0
Input.GetKeyDown need to press button more than once to work So in Unity3D I'm checking for Input.GetKeyDown(KeyCode.E) for stuff like pickups and opening doors. Sometimes it doesn't work the first time I press it and I must press the key E like 2 4 times, and then it works. What could be the possible reason for this to occur? As a further note, Input.GetKeyDown() is being called from OnTriggerStay()
0
Count Unity terrain size In blender? My unity terrain size is 150 150, and I want to create a plane in blender have the same size. How to figure the correct size ?
0
My timer won't work in Unity In my game, you can spawn a cube by clicking. After 10 seconds I want the cube to disappear. That's what I'm trying to do in my code but it won't work using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class circleThing MonoBehaviour public GameObject circle public GameObject block public float time void Start() Vector3 temp Camera.main.ScreenToWorldPoint(Input.mousePosition) temp.z 5f transform.position temp if (Input.GetMouseButtonDown(0)) StartCoroutine(timer()) Instantiate(block, temp, Quaternion.identity) if (time gt 10) Destroy(block) void Update() IEnumerator timer() while (true) Debug.Log(time) yield return new WaitForSeconds(1) time What am I doing wrong? I get the error Destroying assets is not permitted to avoid data loss.
0
How do I deal with scale of the universe when generating a simulated universe? I have a dataset of 100,000 actual stars. I wish to create a game where I can fly between the stars and fly up to them and click on them etc. How do I go about dealing with the problem of the scaling of the universe, even If I were to allow fast as light travel it would be too vast. Should I cluster my data and then implement a subtle sort of scaling to move around? Sorry for the broad question but I'm rather stuck at the moment.
0
What is the unit of speed in unity3d? I have cars in my unity scene, I am not sure in what units speed is specified in unity.
0
why does Physics.Raycast always return my player game object instead of the object I clicked? I have 3D world. I want to detect when the player clicks on a game object in the world. In this image, I have 2 objects I want to detect mouse click on. The white sphere does have collider on it. The dumpster does not. The behavior is the same as noted below. I am getting the mouse down detection. When I check the RaycastHit, I always get the player game object transform and not the game object I clicked on in the world. If I remove the raycaster checks, then I get mousedown for anything in the game not just mouse down over the game object. I need to be able to distinguish between clicks on different game objects. I found a post here and added a PhysicsRayCaster, but it didn't change the behavior. The problem isn't getting the event. My problem is detecting which game object the player clicked on in the world. Here's my code public class InventoryItemSearchHandler MonoBehaviour private void Update() if (Input.GetMouseButtonDown(0)) Ray ray UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) CompareTo always fails because hit.transform.name is always "Player" and not the name of the object clicked on if (0 hit.transform.name.CompareTo(transform.name)) print("mouse down") EDIT In the image below (compared to the one above) I do get the correct transform in the RaycastHit type when I click on the white sphere (and when I click on the dumpster I get the player transform as noted above). So it looks like the player object is getting in the way. What would be causing that?
0
In unity, how do I rotate a vector in relation to the player? I am making a radar script in a unity FPS game project I am making for class. I already have a working example of a radar script that works in relation to the player's position. However the rotation is in relation within the world map, not the player's view. In code I have it kinda like this (not actually my code, as I don't have it with me right now, but basically the same algorithm) if (isPlayerInViewRange(otherPlayer i ) these are both normalized Vector dir getDirectionFromPosition(player, otherPlayer) dir rotateDirectionInRelationshipToPlayer(player, dir) problem here dir new Vector3(dir.x, dir.z, 0) dir.Scale(MapToRadarPosition, 0, MapToRadarPosition) radarDot i dir radarDot i .setActive(true) else radarDot i .setActive(false) Any ideas what I am missing, I feel like I am missing some obvious function to do it.
0
Unity apk vs aab for the same scene I'm new to Unity , i use mac os catalina , unity 2019.4 and build for android mobile. I downloaded a unity project from internet. It's already in format of unity project. so i just copy it into my unity folder. THere's only 1 scene there. I can load , run and built with no problem. It created 160mb of .APK file. But now i need to bring this project into my other project (let's name it B project ). Basically i only need to bring that single scene (and all its linked assets) into that B project. What is the proper way to do this ? Last time, what i did was i export the whole things as package then imported it into my B project. When i open the scene , i can run and build with no problem. But it create .AAB rather than .APK and size is 300mb (2x of the previous APK). Is this big size become the reason it become AAB ? Can someone tell me what's wrong ? why the size is doubled when i just build the same scene. Does unity build includes unused asset ? because in B project there's already asset from my other scenes. What is the proper way to do this ?
0
Basic Character Controller Not Working Properly in Unity I've been trying to setup a simple mouse camera which I had all the code working fine, except when I move with wasd and move my mouse to turn the camera simultaneously the input freezes up and gets stuck repeatedly inputting whatever the last input was. I've tested the simplest way to replicate the issue and it doesn't even need a camera for the issue to come up. If anyone would like to test and try to replicate the issue these are the steps its super fast and simple. create new project(basic PC 3D project) create a plane, and a cube Add a basic character controller script to the cube (this time I used the official Unity code to be sure it's not an issue with code) and that's it, that's actually all that was needed to create the issue for me. And to explain to anyone who may want to test it the issue is as follows when you use wasd keys normally, everything works fine and the controls are responsive. However if you hold down one of the wasd keys while also moving your mouse (just wiggling the mouse should suffice) suddenly things will lock up and the cube will keep moving for a bit even after you let go of the respective wasd keys. In general if you hold a direction while simultaneously wiggling the mouse for a longer period of time, it will extend the amount of time the cube keeps moving after you let go of the direction. And this was done on Unity version 2020.1.16f1 If anyone has any idea what the issue may be its really appreciated.
0
How to blur entire scene but a specific spot in Unity? What I want is basically A way to blur every object sprite on the scene, but have a "blur free" circular zone, that can move. And everything that's behind that circular zone won't have the blur effect applied to it. In a 2D mobile game, how would I do that, especially in a way that's not too heavy, performance wise(if possible). And if it's not possible to do that in a way that won't completely destroy my performance, I also have those sprites already "pre blurred" so maybe there's a way to have both blurred and "unblurred" objects at the same position, and only draw the right parts of them as they go through the scene and reach the blur free zone. If there's a way to do that, that'd also help immensely. Thanks for your time.
0
Combining Rotation, Jump, and Crouch Animations with 2D Blend Tree I have a 2D Freeform Blend Tree that I'm using to animate a character that can currently Walk Sprint Forward Walk Sprint Backward Strafe Sprint Strafe Left Strafe Sprint Strafe Right Idle My goal is to add in rotation, jump, crouch, and quot firing when walking quot animations. In just dealing with turning or even jumping for now, I understand how to handle and call the animations in the code, but not sure of how it should be set up in the animator. Do I transition to rotation jump animations on the base layer? I'm reserved doing it this way because I lose the ability to blend and take advantage of those transitions. Can I build it into my current 2D blend tree even though the blend tree is only X and Z axis? public class twoDControllerMovement MonoBehaviour Animator animator public CharacterController controller SerializeField private float walkSpeed 12.0f SerializeField private float strafeSpeed 10.0f SerializeField private float sprintMultipler 2.0f SerializeField private float rotationSpeed 120.0f Start is called before the first frame update void Start() animator GetComponent lt Animator gt () controller GetComponent lt CharacterController gt () Update is called once per frame void Update() handle sprint float currentWalkSpeed walkSpeed float currentStrafeSpeed strafeSpeed bool runPressed false handle shift if (Input.GetKey(KeyCode.LeftShift)) currentWalkSpeed walkSpeed sprintMultipler currentStrafeSpeed strafeSpeed sprintMultipler runPressed true calculate movement float strafe Input.GetAxis( quot Strafe quot ) currentStrafeSpeed Time.deltaTime float translation Input.GetAxis( quot Vertical quot ) currentWalkSpeed Time.deltaTime float rotation Input.GetAxis( quot Horizontal quot ) rotationSpeed Time.deltaTime execute movement transform.Translate(strafe, 0f, translation) transform.Rotate(0, rotation, 0f) handle movement animations if (runPressed) animator.SetFloat( quot VelocityZ quot , Input.GetAxis( quot Vertical quot ) sprintMultipler) animator.SetFloat( quot VelocityX quot , Input.GetAxis( quot Strafe quot ) sprintMultipler) else animator.SetFloat( quot VelocityZ quot , Input.GetAxis( quot Vertical quot )) animator.SetFloat( quot VelocityX quot , Input.GetAxis( quot Strafe quot )) handle roration animations if (Input.GetAxis( quot Horizontal quot ) lt 0.1f) Debug.Log(Input.GetAxis( quot Horizontal quot )) else if (Input.GetAxis( quot Horizontal quot ) gt 0.1f) Debug.Log(Input.GetAxis( quot Horizontal quot )) Also open to any feedback on improving the code above, my goal is as small and clean as possible! I do have a slight delay in animations starting when switching directions that I have to work out at some point and would eventually.
0
rigidbody cube falls off the ground Inspite my ground and cube contains colliders as i apply rigidbody it falls down....use gravity
0
How do you calculate a sprite's localScale to resize the sprite to a defined height? I'd like to uniformly scale a Sprite in Unity, so that its height on the screen matches the height of a button on a canvas. The scene setup looks like Canvas with a CanvasScaler and a reference resolution of 800x1280 pixels. A button on the canvas with a height of 90 pixels. A sprite with a texture size of 250x250 pixels. The sprite's pixels per unit setting is set 100. An orthographic camera with a size of 5. The transform.scale values of all involved components are (1,1,1). Now the question is, how do you calculate the sprite's localScale value so that it appears with the same height (90 pixels) as the button? What's the math behind it?
0
How do you technically represent a procedurally generated map in the scene? I've always wanted to create the type of map generator they use in Kingdoms and castles. Basically you provide a seed, and it generates land water trees resources. Their maps are also completely flat (except water seems to be 1 2 positions down, which I assume would make it easier. However I do not know where to look for guidance for this type of system, I am wondering if anyone can explain the logic of how that type of system works, or even better, point me to a tutorial that could get me started. While there are tutorials on perlin noise and the like, I never really understood how to connect it to a proper tile, and what properties that tile should have, does it need colliders? is each tile a gameobject? If not, how do I create tiles with trees rocks that I can gather? and so on.
0
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
0
Understanding animations of controllable characters I am a newbie trying to learn basics of Unity3D (5) before starting to do the real thing. Even though I tagged it as Unity3D, the logic should be the same for every kind of game engine. So I will be glad if you share your experience even though you do not use Unity. Assume that you are importing the "Lamp" character (fbx) of Pixar. (Jumping, moving forward by little jumps, etc..) OR Assume that you are basicly importing a humanoid model with animations from Unity Asset Store. (I know that they generally include controllers too, assume that there are no controllers) In unity, I want to make the character jump so I use jump animation. But I really want to make it jump. Also when I move it forward I really want it to move forward by appying a force or setting it's velocity. These will probably will not match the animation and even if they match, my own physics manipulations will be mixed with the animation's transformations. Even if I put the animation object into another GameObject, it changes the position and or rotation of the parent gameobject. So, animation changes those values and I also change them myself... The result will be the combination of all which is very hard if not impossible to sync or calculate. The same thing is valid for almost every animation including Jumping. For example, the animation jumps and I also make the object jump.. It will create a double jump.. If I only let animation does that, I won't be able to control how it really behaves and If I make the animation look like it's crouching (actually jumping, but transformed to 0,0 in every frame, so in Unity changing the vertical position will fix it...) it will be hard to sync too. What am I missing here? What is the guideline here?
0
Export UnityProject inside Android Studio's existing project I am new to the Unity3D, but I have made a small Unity project with a humanoid gameobject. I can move this humanoid with the demo data but I want to move it with the quaternion data which I am already getting inside the android app. I have searched on the internet, but everyone just tells about the android plugin that we have to make for the unity, and that way we can use the JNI to send or receive the data (I need to access the c scripts from the android). But, I wanted to import the unity project inside the android project so that I can(access the c scripts from android and send the quaternion data to the Quaternion variable of the gameObject and make it move) make changes to the android app and test it instantly!! (Also I don't need to make further changes inside the unity project but I need to make further improvements to the data inside the android project). Please help and provide a guide for the android studio. Thanks.
0
Creating custom types that extend certain objects Really new to C scripting. I'm trying to extend a TileBase type object to be able to hold custom methods and variables. I want to create a pathfinding script and I need to store certain information for each tile. Something like this TileBase startPoint tilemap.GetTile (tilemap.WorldToCell (transform.position)) startPoint.customVariable 5 Is there a way to extend TileBase into a new type and create custom methods inside it? How can I achieve this in Unity?
0
ScriptableObjects lose references stored objects upon build restarting the Unity Editor? I'm working on implementing room prefabs for my 2D procedural map generation algorithm. Basically I made a tool which parses a scene's monsters, items, etc into an ObjectContainer prefab, and into a ScriptableObject containing the tilemap's TileDatas, EntryTiles, and the ObjectContainerPrefab. It works well, but my problem occurs when I try to build the game, or just restart the editor. The TileData array will be empty. And thus for example the EntryTiles' TileData reference will be null. Here 's how I use them MenuItem("Custom Tools Parse room prefab from scene") private static void ParseRoomPrefabFromScene() var tilemap GameObject.Find("Tilemap").GetComponent lt Tilemap gt () RoomPrefab roomPrefab ScriptableObject.CreateInstance lt RoomPrefab gt () ParseTilemap(roomPrefab, tilemap) ParseObjects(roomPrefab, tilemap) ParseEntryTiles(roomPrefab, tilemap) AssetDatabase.CreateAsset(roomPrefab, "xyz.asset") AssetDatabase.SaveAssets() How I setup my scriptable object, i.e. in ParseTilemap var tileDatas new List lt TileData gt () ... var tileData new TileData(coordinates, unityTile, isWall) tileDatas.Add(tileData) ... roomPrefab.tileDatas tileDatas.ToArray() Here are the classes public class RoomPrefab ScriptableObject public TileData tileDatas public EntryTile entryTiles public ObjectContainerPrefab ObjectContainerPrefab Serializable public class TileData public TileBase UnityTile get private set public Vector2Int Coordinates get set public bool IsWall get private set public TileData(Vector2Int coordinates, TileBase unityTile, bool isWall) Coordinates coordinates UnityTile unityTile IsWall isWall ... Serializable public class EntryTile public TileData TileData get private set public Vector2Int LeaveDirection get private set public EntryTile(TileData tileData, Vector2Int leaveDirection) TileData tileData LeaveDirection leaveDirection ... Serializable public class ObjectContainerPrefab public Vector2Int Coordinates get private set public float Rotation get private set public GameObject Prefab get private set public ObjectContainerPrefab(Vector2Int coordinates, float rotation, GameObject prefab) Coordinates coordinates Rotation rotation Prefab prefab UPDATE here is a freshly parsed scriptable object. In the Editor everything is fine, while in its file its tileDatas array is already empty. Why? YAML 1.1 TAG !u! tag unity3d.com,2011 !u!114 amp 11400000 MonoBehaviour m ObjectHideFlags 0 m CorrespondingSourceObject fileID 0 m PrefabInstance fileID 0 m PrefabAsset fileID 0 m GameObject fileID 0 m Enabled 1 m EditorHideFlags 0 m Script fileID 11500000, guid 30263215ad3a45a479bb2dd6409fb0a9, type 3 m Name TestRoom m EditorClassIdentifier tileDatas entryTiles DebugCube fileID 0 DebugCube fileID 0
0
Is it still possible to install Unity? When trying to install Unity I am getting the following error The download of version ... was cancelled. I checked that there are no spaces in the path. Also I can not Sign in. When I provide the correct email and password the Sign in window just closes with no result. Also I tried to report a bug using the Report Bug feature, but it seems not to work. Also I tried to post a question on Unity Forum. But the Sign In over there does not work as well. What else may I try? Thank you.
0
How to arrange child objects in a grid i have a gameobject that have a group of plane meshes that created randomly as child every one of this planes have a "2f" offset in x axis between every plane what i wanna do is i wanna make the parent object arrangement the child objects on rows and columns even if one of this child deleted during the game or added so if i have 8 planes mesh it should look like that 2 rows and 4 columns like that but i don't know how to do that ? i know how to get child objects and making offset but i do't know how to get the format like that in the image i wanna to arrangement the planes meshes that i can acces from this for loop void Update() Transform children new Transform transform.childCount Debug.Log(transform.childCount) for (int i 0 i lt transform.childCount i ) children i transform.GetChild(i)
0
The farther I move my character, the more its projectiles fire in the wrong direction I'm making a top down shooter, and the movement is working fine. However, I'm having trouble getting my Fire function to work correctly. When I run the game, it kind of fires in the right direction, but the more I move, the more off the shooting becomes. Anyone have any idea why? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour private float horizontalInput 0 private float verticalInput 0 public int movementSpeed 2 public int rotationSpeed 2 Rigidbody2D rb2d float coolDown 0 public Rigidbody2D bulletPrefab public float attackSpeed 0.5f public float bulletSpeed 500 public float yValue 1f Used to make it look like it's shot from the gun itself (offset) public float xValue 1f Same as above Start is called before the first frame update void Start() rb2d GetComponent lt Rigidbody2D gt () Update is called once per frame void FixedUpdate() MovePlayer() RotatePlayer() void Update() GetPlayerInput() Determines if the player can fire if (Time.time gt coolDown) if (Input.GetKeyDown(KeyCode.Space)) Fire() private void GetPlayerInput() horizontalInput Input.GetAxisRaw( quot Horizontal quot ) verticalInput Input.GetAxisRaw( quot Vertical quot ) public void MovePlayer() rb2d.velocity transform.right Mathf.Clamp01( verticalInput) movementSpeed private void RotatePlayer() float rotation horizontalInput rotationSpeed transform.Rotate(Vector3.forward rotation) private void Fire() Rigidbody2D bPrefab Instantiate(bulletPrefab, new Vector3(transform.position.x xValue, transform.position.y yValue, transform.position.z), transform.rotation) as Rigidbody2D bPrefab.GetComponent lt Rigidbody2D gt ().AddForce(transform.position bulletSpeed) coolDown Time.time attackSpeed
0
Unity Video Player Resolution exceeds the Microsoft Media Foundation decoder limit I'm using Unity's Video Player component to play a short intro video before the main menu. The problem is that its resolution is 2560x1440, and on Windows 7 or earlier operating systems it says Context Setting media type for first video stream Error details The data specified for the media type is invalid, inconsistent, or not supported by this object. Track types Audio Track, type 10 16 Video Track 2560 x 1440 , type H264 Resolution exceeds the Microsoft Media Foundation decoder limit of 1920 x 1088 on Windows 7 and below. Is there a way to check whether it's supported or not? Because then I could change the played video to a lower resolution version. And if that's not supported as well, I would just skip the intro all together. I would be happy with other solutions as well. EDIT What I'm trying now is subscribing to errorReceived, and if currently it's the 1440p version, I switch back to the 1080p version and play it. If errorReceived is fired again (so the current version is 1080p), I just skip the whole intro phase. videoPlayer.errorReceived OnErrorReceived ... private void OnErrorReceived(VideoPlayer videoPlayer, string message) if (videoPlayer.clip Intro1440p) OnIntroFinished(videoPlayer) videoPlayer.clip Intro1080p videoPlayer.Play() else OnIntroFinished(videoPlayer) Now the intro is skipped if no suitable format is found, which is good, but for some reason even the 1080p version is unsupported Context Setting media type for first video stream Error details The data specified for the media type is invalid, inconsistent, or not supported by this object. Track types Audio Track, type 10 16 Video Track 1920 x 1080 , type H264 I've now added an 1080p wmv version, after all that's a Windows format, it must be supported by Windows 7. But it's still unsupported Context Setting media type for first video stream Error details The data specified for the media type is invalid, inconsistent, or not supported by this object. Track types Audio Track, type a 01 Video Track 1440 x 1080 , type WMV3
0
Unity keepy uppies game Hello guys I'm tryting to make a game in unity of keepy uppies but I can't make the ball bounce to different directions like keft and right only staright up. using System.Collections using System.Collections.Generic using UnityEngine public class physics MonoBehaviour public Rigidbody rb public float force 10 void Start() rb.velocity new Vector3(0, 0, force) void Update() if (Input.GetMouseButtonDown(0)) RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit, 100.0f)) if (hit.transform ! null) PrintName(hit.transform.gameObject) if (rb hit.transform.GetComponent lt Rigidbody gt ()) LaunchIntoAir(rb) private void PrintName(GameObject go) print(go.name) private void LaunchIntoAir(Rigidbody rb) rb.velocity new Vector2(rb.velocity.x, 3) This is what I have done until now.
0
Unity3d Rotation of game object Quaternion objectRotation Quaternion.identity Quaternion rotation Quaternion.AngleAxis(angle, Vector3.forward) objectRotation rotation gameObject.transform.rotation objectRotation here angle 90 But the gameobject isn't rotating as desired, when I replaced gameObject.transform.rotation objectRotation with gameObject.transform.Rotate (0,0,angle) Then the gameobject rotated 90 degree, dont understand why the Quaternion part isn't working? It rotated 90 degrees
0
Making a master server in Photon Unity Network? I am trying to make a game that requires a dedicated server running 24 7 and I would like to use Photon Networking but can Photon Network handle do a dedicated server setup? The reason I ask is because every tutorial I watch read is talking about client hosting and not server to client. Another question I have is that if PUN can handle dedicated servers will I have to make separate applications, one for the server and one for the client? To me that seems to make the most sense. The third question is that if I do have to make a server and client application how do I connect to my server application with my client application? Does PUN provide a URL which I can connect to or is there something else that I have to do? If you guys have any tutorials you could point me to working with PUN and dedicated servers that would be awesome and if you guys have any information you are willing to bestow upon me that would be greatly appreciated!
0
Is it possible to get a Vector3 from a single Input Action in Unity's Input System? I'm trying to implement moving up down (R F), left right (A D), forwards backwards (W S) all at the same time using Unity's new Input System. There is an Action type for Vector3, but there doesn't seem to be a corresponding type for it. The way movement works right now means that it would be a lot better to get the whole vector at the same time for it to work smoothly. Is there a way to do this with a single Input Action, or will I just need multiple?
0
What's wrong with my food generating code? This script is intended to produce amount of (food) objects for the players over the network. What should happen is that when a player eats one food, another food object gets created in another random place. Somehow it doesn't do that. Here's the script. public class FoodManager Photon.MonoBehaviour SerializeField GameObject smallCirclePrefab SerializeField float widthOfBoard 100 SerializeField float heightOfBoard 100 SerializeField int amtOfSmallCircle 100 SerializeField int sizeOfCircle 5 Use this for initialization void Start() if(PhotonNetwork.isMasterClient) produceSmallCircle(amtOfSmallCircle) Update is called once per frame void Update() void produceSmallCircle(int n) Vector2 position GameObject circle float positionX, positionY int ratioOfSize 5 for (int i 0 i lt n i ) positionX Random.Range( widthOfBoard 2, widthOfBoard 2) positionY Random.Range( heightOfBoard 2, heightOfBoard 2) position new Vector3(positionX, positionY,0) circle PhotonNetwork.InstantiateSceneObject(smallCirclePrefab.name, position, transform.rotation, 0,null) as GameObject circle.transform.localScale new Vector3((float)sizeOfCircle ratioOfSize, (float)sizeOfCircle ratioOfSize, (float)sizeOfCircle ratioOfSize) and here's the other script using UnityEngine using System.Collections public class FoodCollision Photon.MonoBehaviour public static float amtOfIncreaseSpeed 1f public static float amtOfIncreaseHealth 1f public static float ratioOfSpeed 150.0f public static float increaseSize 0.001f PhotonView photonView BoxCollider2D boxCollider SpriteRenderer sp void Awake() photonView PhotonView.Get(this) boxCollider GetComponent lt BoxCollider2D gt () sp GetComponent lt SpriteRenderer gt () Use this for initialization void Start() Update is called once per frame void Update() public void DestroyGO() photonView.ownerId PhotonNetwork.player.ID boxCollider.enabled false sp.enabled false photonView.RPC("DestroyRPC", PhotonTargets.MasterClient) PunRPC void DestroyRPC() PhotonNetwork.Destroy(gameObject)
0
Why do my point lights disappear when another nearby light is above 1.85 range? I'm making a game with a dungeon setting in Unity 3D. Many torches line the walls. I'm using a point light over each torch to simulate the flame. However, when two torches are across from each other, and one goes above the 1.85 range, the other disappears completely, giving off no light. What might be causing this?
0
How to create and choose sprite sheet for different mobile screen resolution in Unity Background We re working on a 2D mobile game. We want to publish the game on all apple devices which at least support iOS 7 and to all android devices which at least support Android 4 OS. These devices come with different screen size and resolution. For example, in following image we have different Aspect ratios and resolutions that we almost found in every mobile device. Question Do we need to choose a higher resolution to design a sprite sheet for those devices which share same aspect ratio? For example, iPhone 3Gs and iPhone 4s share aspect ratio of 3 2. But they have different screen resolution. If those devices come with different aspect ratio. Do we need to create multiple sprite sheet for multiple aspect ratio? What are the best practices that unity offer us to design and create sprite sheet for multiple mobile device, which are optimize to even lower mobile device?