_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Adding a feedback survey to a game So I am currently making a game that aims to help people with anxiety management. I , however, would like to ask them how they feel before playing the game and then again after playing the game. Would it be possible to do this directly on Unity? I would like for them to be able to log their entries much like an online journal. I have attached pictures from the daylio app. I would like to do something similar. At this point, I really do not know how to begin doing this on Unity. Any advice, or tutorial suggestions would be appreciated. This far I have managed to do the following (in the picture below) This is how the survey looks (its pretty rudimentary at this point) And this is where the information is getting displayed (in the inspector) So now, what I would like to know, is how would I go about sending this data to somewhere else i.e. as it is in the daylio app?
|
0 |
How can I avoid a stack overflow when recursively checking adjacent game objects? I am building a simple game on Unity to learn the system. I am using C . The game is a basic "blocks" game, whereby when the player clicks on a block, the block and its neighbours of the same colour all disappear (get destroyed). My process is this To keep a track of which blocks are neighbours of the same colour, on each refresh each block checks their details on the event OnCollisionEnter and adds these collision neighbours to a List of valid neighbouring gameobjects. When a block is clicked, this list is checked and each neighbour has its own neighbours list checked, after list checking each block is distroyed. Somehow, this process is causing a StackOverflowException StackOverflowException UnityEngine.GameObject.GetComponent setupscript () (at C buildslave unity build artifacts generated common runtime GameObjectBindings.gen.cs 35) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 86) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) .... Here is my script, first my List establishment private List lt GameObject gt neighbours new List lt GameObject gt () Next, here is how the neighbours list is populated void OnCollisionEnter (Collision other) Rigidbody other rb other.rigidbody if(rb.velocity.magnitude lt 1f amp amp other rb.velocity.magnitude lt 1f amp amp other.gameObject.tag tagName amp amp !neighbours.Contains(other.gameObject)) Same tag so add to list of valid neighbours neighbours.Add(other.gameObject) Now, there are four conditions above to check when adding to the list Is the current block stationary. Is the "other" colliding block stationary (so they're at rest next to each other). do these blocks have the same tag (so they're the same type colour) does this block not already exist in this list. So once all four conditions are met, the block GameObject is added to the List. ( On conditions of OnCollisionExit blocks are removed from the List in a similar fashion. ) Now, my CheckNeighbours() script public void checkNeighbours() if (neighbours.Count gt 0) foreach (GameObject othercube in neighbours) setupscript otherCubeScript othercube.GetComponent lt setupscript gt () otherCubeScript.checkNeighbours() Destroy (gameObject) This should, as far as I understand it, run once through each List element and check that element for any neighbours who match. As I write this question out I think I'm realising that the issue is that we're in a loop as block 1 references neighbour block 2, which references neighbour block 3, which references neighbour block 1, etc. etc. But my StackOverflow exception occurs when there are only two blocks, so one refers to the other, refers to the first, etc. But as they should destroy after running the reference, this shouldn't (ideally) be an issue? Do I need to make the checkNeighbour() a Corountine to allow it to not hold up destroying the GameObject? If this repetition cycling is indeed what's going on, what would be the best way of getting each neighbour to be checked only once? Or checking that the GameObject referenced in the List still exists in the game itself? I have a quick edit here foreach (GameObject othercube in neighbours) if (othercube ! null) setupscript otherCubeScript othercube.GetComponent lt setupscript gt () otherCubeScript.checkNeighbours() But I'm not sure this will work as I feel this List will purely be a reference rather than the actual GameObject in the level?
|
0 |
Not able to upload to Oculus Store I am building for Quest and signing the package with V2. I am also creating store based Android Manifest file. Unfortunately the upload stops at 2nd step where I receive the error quot The APK was signed with the V1 signature system, previously marked with V2 and signed again with V1. Such APKs are considered corrupted and cannot be installed. quot Here is my Android Manifest file lt manifest xmlns android quot http schemas.android.com apk res android quot package quot com.VR.VRCube quot android versionCode quot 1 quot android versionName quot 1.0 quot android installLocation quot auto quot gt lt application gt lt meta data android name quot com.samsung.android.vr.application.mode quot android value quot vr only quot gt lt meta data android name quot com.oculus.supportedDevices quot android value quot quest quest2 quot gt lt activity android screenOrientation quot landscape quot android theme quot android style Theme.Black.NoTitleBar.Fullscreen quot android configChanges quot density keyboard keyboardHidden navigation orientation screenLayout screenSize uiMode quot android launchMode quot singleTask quot android resizeableActivity quot false quot gt lt activity gt lt application gt lt uses sdk android minSdkVersion quot 21 quot gt lt uses feature android glEsVersion quot 0x00030001 quot gt lt uses feature android name quot android.hardware.vr.headtracking quot android required quot true quot android version quot 1 quot gt lt manifest gt
|
0 |
How to enable Unity related syntax highlighting with VSCode? I'm using VSCode, not VisualStudio for Unity scripting. VSCode has syntax highlighting for C , which works fine, but all the Unity related stuff like Vector3 doesn't get any highlights. I know, that you can change somehow the files, but I can't even find the C folder in my extensions folder (There is everything else like cpp, css etc. just no c ). Would be great if someone could lead me to the folder location and how to add keywords for the highlighting. Here is a screenshot, where you can see that float is highlighted, but Transform not.
|
0 |
How to align edge vertices of modular props snapped on a 2D grid? For a project I am working on I create some 3D props in Blender that can be put together in a modular way on a 2D grid in Unity. In Unity I generate the grid contents using these props. Now given these two simple shapes (imagine a pipe or railing in top view) If they are put next to eachother on the grid like so (left) I want to make a smooth transition between the two so that their edge vertices align nicely (snap together, see right image above). Note that the angle between the shapes is always the same. However there are variations like straight, left, right for each intersection and also numerous shapes. How can I achieve this? I have thought of the following possibilities Just model each possible variation in blender and use the matching prop when generating the grid (I hope I can avoid this since its a lot of effort, also it's not reusable) Rig the shapes in Blender. In Unity move the bone transforms accordingly so that they align (I like this idea, but is it practical?) (Somehow) mark the vertices on the edge of the shapes and move them to where they belong i.e. modify the mesh in Unity. Are there other better ways to achieve this? I appreciate any hints and tips. I also know I am not the first one to try this so any guidance on where to look for resources and what terms to search for is also appreciated.
|
0 |
How do I successfully implement Google Mobile Ads and Google Play Services into my Unity arcade game? I have been trying for like a month now to properly implement Google Play Services and Google Mobile Ads into my Unity Android Game. I have had success in getting Google Play Services to work but when I added Google Mobile Ads at first it didn't work. I just didn't see any ads pop up. Now when I build my app it won't open it just crashes. Not exactly sure what I did. I have configured all the services correctly according to my knowledge and I'm am just using code from the documentation for the ads. Heres that code public static AdManager Instance set get public string bannerId public string videoId public string deviceId BannerView bannerView InterstitialAd interstitial private void Start () Instance this DontDestroyOnLoad(gameObject) interstitial new InterstitialAd(videoId) AdRequest request new AdRequest.Builder().AddTestDevice(deviceId).Build() Load the banner with the request. interstitial.LoadAd(request) public void ShowInterstitial() if (interstitial.IsLoaded()) interstitial.Show() I am using the correct ad Ids, I double checked that. I don't know what else to do. I can provide any other information you may need upon request. Anyone with experience with this would be super helpful! Thanks!
|
0 |
Enemy clones don't target player In a small game that I'm making enemies multiply when you kill them, however when clones are instantiated they don't chase the player like the original prefabs do (example http gfycat.com VastActualElver) Here is relevant part of my code pragma strict var moveSpeed int 3 var player Transform var MaxDist 10 var MinDist 1 function Update () if(curhealth lt 0) Dead() transform.LookAt(player) if(Vector3.Distance(transform.position, player.position) gt MinDist) transform.position transform.forward moveSpeed Time.deltaTime function Dead () Destroy(gameObject) var posx Random.Range( 10, 10) var posz Random.Range( 10, 10) Instantiate(enemys, Vector3(posx, 0.5, posz), transform.rotation) What am I missing?
|
0 |
Proper way to supply different textures and multiply matrices for thousand of terrain meshes What I have Terrain chunks of size 64x64 meters in a custom format PVR textures OpenGLES2 renderer GLSL shader None of the above can be changed in any way, i.e. I can't modify the existing code of shader or change the renderer. Terrain Each terrain chunk consists of 64 tiles of size 8x8 meters and are placed in a grid. Each tile has 3 layers of textures so theoretically there can be 192 different textures per chunk. The way I currently load terrain is via script. I create a mesh for every tile in a chunk, so that's 64 meshes per chunk. Shader The shader input consist of 3 textures and their texture mask 3 matrices minor stuff The matrices needed are calculated in every frame in the following way var M object.transform.localToWorldMatrix var V Camera.main.worldToCameraMatrix var P Camera.main.projectionMatrix material.SetMatrix("WorldViewProjectionMatrix", P V M) material.SetMatrix("WorldViewT", (V M).transpose) material.SetMatrix("World", M) What I need Loading the entire terrain would take a lot of time and resources, so I only load the nearest chunks depending on player position and its a 5x5 chunks area. And still on average I have 25 chunks 25 64 1600 tile meshes 25 64 1600 materials up to 25 192 4800 different textures (only theoretically! Currently there is no more than 20 30 per chunk and the average across loaded chunk is about 300 textures) about 6400 matrix operations The amount of materials does not seem to have a huge impact on performance, but the matrix calculates make the fps drop from 80FPS to 12. I could've reduced the matrix operations down to 100 if I could render single chunk as a single mesh instead of 64 submeshes, but I don't see a way to properly pass the textures to shader. So basically what I need is an approach that would allow me to render terrain chunk as a single mesh and a way to pass different textures for different tile parts of a mesh. Do I even look in the right direction?
|
0 |
Interpolating between positions unfeasible at 30 frames per second? I am working on a 3D platformer in Unity and I am targeting Android devices. The game consists of a lot of objects smoothly interpolating from the bottom of the screen to the top. This whole time I've been testing my game at 60 fps and the performance was quite good. However, when I tested the game at 30 fps, the interpolation of the objects was no longer smooth. I initially thought that I have way too many objects in my scene and this might be affecting the interpolating performance. So I created a new project which only has the interpolation stuff and object pooling (you can download it here). But even then, the interpolation wasn't smooth at 30 fps. Here's the code I'm using for interpolating the object void FixedUpdate() rb.MovePosition(transform.position transform.up Time.fixedDeltaTime speed) I'm using the object's Rigidbody to interpolate it. I've already set the rigidbody to "Interpolate" and I turned on "isKinematic". I first thought that the interpolation isn't smooth since I'm using Rigidbody. So I ditched the rigidbody and used transform.Translate instead. But even then the interpolation wasn't smooth. Next I tried Vector3.Lerp. Nope. That didn't work either. The stutter was still there. I even tried Vector3.MoveTowards. That didn't work. The interpolating was still laggy. I even tried turning on GPU instancing for the objects being interpolated (since they all use the same material). That didn't do it either. Next I started playing around with the fixed timestep (in the Time settings). I thought that maybe if I set the timestep to 0.033, then the objects will interpolate smoothly at 30 fps. But that didn't work either. I think it's really bizarre that a simple interpolation performs so poorly at 30 fps on an Android device. If the interpolation is only for a short distance, then you don't always notice the stutter. But like I said, in my game the objects have to interpolate from the bottom of the screen all the way to the top. In this case, you can clearly see the laggy movement during interpolation. Is it possible that long distance interpolation is simply unfeasible for Android devices at 30 fps? How do so many Android game developers manage to achieve good performance at 30 fps? Feel free to download the new project I mentioned which only has the interpolation stuff and the object pooling. It is available here. It's a very simple projects. It only has the prefab that should be interpolated, the material for the prefab, the script for interpolating the prefab, the spawning and object pooling system (for spawning the prefab), and the script for setting frame rate to 30. That's it. Below a gif of the objects' interpolation. It's not as shaky in reality (since I had to use a bad screen recorder and compress the gif) but it's still pretty close to how the objects move at 30 fps.
|
0 |
ScollRect Jumps while Filling I have a UI panel with a scollrect inside, which I fill dynamically. It can only be moved vertically. When filling this scollrect, the content jumps up and down for one frame, creating a weird look. When I check for the VerticalNormalizedPosition of the scrollrect after each added GameObject, it always tells me, the position is 1. When I check for the position in an Update method, it sometimes gives me a small rounding error. Instead of 1 it's somewhere between 0.9999995 and 0.9999998. The height of the content holder is less trhan 2000 units, whereas the jumps seems to be more than 2000 0.9999998. I tried to set the VerticalNormalizedPosition of the scrollrect to 1 every frame which didn't help. It also didn't help setting it after every newly added GameObject. Locking vertical scrolling also didn' help. Is this soley a rounding error and I can't do anything about it, or is there a way to stop this jump from happening? Here you can see the jump happening in 0.05 speed
|
0 |
Unity Button still interactable even when interactable is set to false my button can still be pressed in game even if I set it to button.interactable false What I'm trying to achieve is when the Panel CropsPanel is opened, or active in Unity, I want the EquipmentButton to be disabled and to be not usable by the user. Here is the code I've written public void Start () GetComponent lt Button gt ().interactable false if (CropsPanel.activeInHierarchy true) EquipmentButton.interactable false I have also set all buttons in the inspector, placed a Debug.Log("msg here") to see if the particular code is working. But I can't seem to get it working. Am I missing something? Thanks guys!
|
0 |
Which files of addressable assets should be committed to Git? I would like to keep my Git repository as small as possible and exclude any automatically generated files. The developers can re build their Unity Addressable Assets themselves. Any developer should be able to build the final project and the final result should contain the same assets packed in the same way. I noticed that Unity generates the following files and folders Which of these files are important settings that should be included and which files are safe to exclude from a Git repository?
|
0 |
Adding biome support to procedural landmass generation tutorials I've spent the past week studying the procedural landmass generation tutorial series and have been toying around with the source code. The following is an example of the core Noise module he wrote. Essentially, it accepts some noise settings (seed, octaves, lacunarity, etc) for every "chunk". I've been trying to figure out on my own how best to implement "biomes" but this is too different than noise systems I've used in the past (they handled octaves etc internally didn't build those with chunk coordinates, etc). I know I need different noise settings based on the biome, but I just can't figure out the best way to implement here. My biggest dilemma is that this logic calculates the octaves frequency etc for the entire chunk but those values would be different for different biomes. Since I need biomes to blend a bit (aka I don't want biomes limited to entire chunks), I need to either Use different noise settings for every "coordinate" (which won't work since this code uses one noise settings for the entire chunk) Calculate the entire chunk once for each biome in it and then somehow "sum" biomes Ditch this noise entirely with something I'm more familiar with (FastNoise, LibNoise.Unity). I've tried this, but absolutely will not work with the mesh generation he built, so I'd need to rewrite that too. public static CoordinateProfile , GenerateCoordinateProfiles(int mapWidth, int mapHeight, NoiseSettings settings, Vector2 sampleCentre) var profiles new CoordinateProfile mapWidth, mapHeight System.Random prng new System.Random(settings.seed) Vector2 octaveOffsets new Vector2 settings.octaves float maxPossibleHeight 0 float amplitude 1 float frequency 1 for (int i 0 i lt settings.octaves i ) float offsetX prng.Next( 100000, 100000) sampleCentre.x float offsetY prng.Next( 100000, 100000) sampleCentre.y octaveOffsets i new Vector2(offsetX, offsetY) maxPossibleHeight amplitude amplitude settings.persistance float maxLocalNoiseHeight float.MinValue float minLocalNoiseHeight float.MaxValue float halfWidth mapWidth 2f float halfHeight mapHeight 2f for (int y 0 y lt mapHeight y ) for (int x 0 x lt mapWidth x ) amplitude 1 frequency 1 float noiseHeight 0 for (int i 0 i lt settings.octaves i ) float sampleX (x halfWidth octaveOffsets i .x) settings.scale frequency float sampleY (y halfHeight octaveOffsets i .y) settings.scale frequency float perlinValue Mathf.PerlinNoise(sampleX, sampleY) 2 1 noiseHeight perlinValue amplitude amplitude settings.persistance frequency settings.lacunarity if (noiseHeight gt maxLocalNoiseHeight) maxLocalNoiseHeight noiseHeight if (noiseHeight lt minLocalNoiseHeight) minLocalNoiseHeight noiseHeight float normalizedHeight (noiseHeight 1) (maxPossibleHeight 0.9f) noiseHeight Mathf.Clamp(normalizedHeight, 0, int.MaxValue) profiles x, y new CoordinateProfile(noiseHeight) return profiles
|
0 |
How to create custom 3D "areas" at runtime I've been puzzled for a few days trying to solve this problem, so far with no results. On a map, currently a Terrain, I'd need to have some "areas" which can be controlled by a specific players. The shape of those areas can arbitrarily change during the course of the game, such as you add a marker in any point, and the area evolves (like a spline, say) to pass through that point too. The problem isn't drawing the boundary itself, of course, but having the GameObjects detecting the area they are in. Currently I have absolutely zero idea on how to make this exactly. I've thought about a nice approximation, which is splitting the terrain in fixed chunks, and having the player control them "chunk by chunk" every chunk can have its own collider, and that should be easy if not trivial. So the question is how to do it "properly", since I already have this workaround.
|
0 |
How to detect RayHit on part of model and not entire model I'm building a low poly role playing Hack and Slash game. When I click it renders a sprite amp character moves to that location(with RayCast). But in this case. I don't want the click to occur on side of the bridge. Clicks should only occur in green coloured part amp not in the red part. How should I fix this problem?
|
0 |
Two game object efficient and fast on off switch I have two game object, on GUI button click i am toggle between them but the problem is one game object which is small contains less vertx etc., is loading fast while the other which heavy taking time. How do i efficiently and quickly load it ? I don't want to show loading window i want to load that game object quickly?
|
0 |
Using Unity as a front end GUI for a non unity application? I'm working on a game right now that is 2D, and grid based, and for a variety of reasons have decided making it in Unity wouldn't be worth the hassle I'd have fighting the engine. That said, I want to possibly add in VR support at some point, and Unity seems the easiest way to make that happen. Right now, the game is structured so that part of the code takes in a grid from the game core, and that grid tells it what sprite(s) to stick in each spot on said grid. My thought was that it might be possible to replace the "take grid array, render sprite grid" portion of my game with a Unity front end. For example, perhaps this would be like a board game sitting on a table, and rather than a 2D grid, the "sprites" would be simple models on the grid board, with the user looking down at it in VR. Is this a thing that is possible? Essentially, all I would need is for my Unity program to take inputs, and send trigger signals to the game core, then receive an updated grid array and respond accordingly. I've not been able to find any information on this kind of thing, interfacing Unity with an external program in this way. The game is turn based, so 2 3 updates per second would be the absolute max I'd need, performance wise, and the game core could run on a potato. In specific can Unity send triggers to and receive a data array from an external binary (written in c ), and how would I do this? I really hope this is possible.
|
0 |
How can I reference the frontmost part of a mesh in my Unity code? (and help making FPS projectiles seem more real) I have started making a PC game using Unity. It's just a test project, where I'm making as basic as possible FPS shooter. I'm using the FPS Controller prefab, and I have also a rifle model attached to it. The result is pretty much what I wanted. Now I'm considering how I want to create projectiles for the gunfire. I think it will be best for me to create each bullet as just being a ray from the gun barrel heading forwards, OR I might create rigidbodies from the gun barrel I'm not sure yet. My question is What is the proper way to reference the point in space in which the gun barrel current ends? At the moment, I am thinking just attach ANOTHER gameObject to the gun model, and just manually position it where the barrel finishes. But this seems 'cheaty' and I think perhaps there is a better way (something like mesh.position.z mesh.length, but I can't seem to find anything like mesh.length). I haven't posted code at all, because I haven't really written any on this project yet. I would also be very interested to hear the pro tip version of how best to simulate this gunfire (ie. is it best to use rigidbodies? or somehow use raycast or something? or some better way that I haven't even dreamt of)
|
0 |
UnityEngine.PlayerPrefs corrupts string? I need to use PlayerPrefs to store arrays of bytes for my game. For some reason, the string I save with PlayerPrefs doesn't come out with the same length. I.e. byte TestArray new byte 256 for (byte i 0 i lt 256 i ) TestArray i i char charBuffer new char TestArray.Length for (int i 0 i lt TestArray.Length i ) charBuffer i (char)TestArray i PlayerPrefs.SetString ("Storage", new string(charBuffer)) PlayerPrefs.Save () Debug.Log (new String(charBuffer).Length) Debug.Log (PlayerPrefs.GetString ("Storage").Length) Log 256 5 Is this possibly an issue with encoding? How do I fix it?
|
0 |
Generate static 2D Tilemap from array How do I generate a 2D tile map from an array like in this tutorial for XNA ? I basicly want to generate a static map based on my tile prefabs.
|
0 |
How to make player stay on a moving object I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window. Thanks, Nova
|
0 |
How can I start a new row when instantiating UI elements in a grid? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() int counter 0 imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.Find( quot Slots quot ).transform slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () if (counter 3) raw.anchoredPosition new Vector3(1 , 0.3f, 0) counter 0 else raw.anchoredPosition new Vector3(1 counter gap, 6, 0) counter Update is called once per frame void Update() Now it's creating a line of 3 objects but then when it's filled with 3 objects in a line I want it to move one step down and start a new line of 3 and so on. The problem is I can't make it automatic move one step down with the right gap on the Y and start a new line. I'm doing the new line with this raw.anchoredPosition new Vector3(1 , 0.3f, 0) but the result is that the fourth object is too much down And it should be like this
|
0 |
Unity Access animation clips motion of an animator So I have an animator on my GameObject. I need to change the animation clip motion of different states in my animator to the one I assign in my EditorGUILayout.ObjectField. Problem is, I have no idea how to access those clips. This is purely Editor Scripting.
|
0 |
How can I make that when the first animation end the next animation will start but from the same position? I have two animations. The first animation I downloaded from the Mixamo site. The game start when the player is on his back on the ground and then slowly stand up. When the animation end the player is standing Look at the player legs Then it's starting playing the next animation idle animation Look at the player legs now when the idle animation start There is no problems with the animations. It's just when the first animation end the player legs move close to each other because the legs position in the start of the second animation is not the same position when the first animation end. I need somehow to make if it's possible that the first animation legs will end at the position of the second animation start. Now the legs are moving to each other and it looks funny. If I was showing a gameplay you will see the legs moving to each other like the player is closing his legs. This screenshot is of the Animator controller where the left New State is the first animation and the Grounded is a blend tree with the idle animation inside And this is a screenshot of the blend tree and the first top state is the idle animation The transition between the two animations looks bad funny. The player is closing his legs. Instead I wish there was a way to make the first animation to end with the legs close like in the second animation start.
|
0 |
How to rotate a rigidbody with a Pid controller I would like someone to describe me how to use a PID controller to rotate a rigidbody with AddTorque to a specific position. (like a spacecraft that rotates the Y axis of rotation towards Camera.forward for example). Can anyone show it to me with a script? Actually I already use this script to rotate with AddTorque but the object almost never stops at the precise point. Vector3 camForward Camera.main.transform.forward Vector3 rbForward rb.transform.forward Vector3 torqueY Vector3.Project(torque, Vector3.up) Vector3 torque Vector3.Cross(camForward, rbForward) rb.AddTorque(torque) rb.AddTorque( rb.angularVelocity)
|
0 |
Counting triangles and vertices in Unity's cube I want to understand logic behind drawing triangles of primitives in Unity. When we spawn simple cube, variable mesh.vertexCount gives us value 24. Also when we list all vertices positions (from mesh.vertices) and triangles numbers (from mesh.triangles), we get 0. (1.0, 1.0, 1.0) 0 1. ( 1.0, 1.0, 1.0) 2 2. (1.0, 1.0, 1.0) 3 3. ( 1.0, 1.0, 1.0) 0 4. (1.0, 1.0, 1.0) 3 5. ( 1.0, 1.0, 1.0) 1 6. (1.0, 1.0, 1.0) 8 7. ( 1.0, 1.0, 1.0) 4 8. (1.0, 1.0, 1.0) 5 9. ( 1.0, 1.0, 1.0) 8 10. (1.0, 1.0, 1.0) 5 11. ( 1.0, 1.0, 1.0) 9 12. (1.0, 1.0, 1.0) 10 13. (1.0, 1.0, 1.0) 6 14. ( 1.0, 1.0, 1.0) 7 15. ( 1.0, 1.0, 1.0) 10 16. ( 1.0, 1.0, 1.0) 7 17. ( 1.0, 1.0, 1.0) 11 18. ( 1.0, 1.0, 1.0) 12 19. ( 1.0, 1.0, 1.0) 13 20. (1.0, 1.0, 1.0) 14 21. (1.0, 1.0, 1.0) 12 22. (1.0, 1.0, 1.0) 14 23. (1.0, 1.0, 1.0) 15 (i th element, vector from mesh.vertices i , number from mesh.triangles i ) Obviously we need only 8 vertices to create cube, but we need 6 2 12 triangles, three vertices every array of 36 vectors. So... what is the logic of Unity primitive?
|
0 |
Making animations not smooth while using Record button In my 2D sidescroller game, I want to separate the animations for the head and the body of my character. While idling, my charcter's body bounces slightly up and down (kind of a breathing motion). Thus, the head should keep up. However, when I press Record and make adjustments for the head, the head moves up and down smoothly instead of following the body frame by frame. How can I remove the smooth transitions from one position to the other? Here is a screenshot from Unity demonstrating the hierarchy and the animation keyframes.
|
0 |
UNITY Prevent 3D Text Render Trough All Object Without Shader im tired of those answer i found trough search engine that just keep saying " the trick is to modify the shader " without thinking because they want to gain reputation , in my case , i have 2 3D text , one of them using special font and the other one using default font , and the shader to prevent the text render trough all object from http wiki.unity3d.com index.php?title 3DText is not working and giving weird white square plus i don't want to change from default Arial font because i want to make them look different , i also cannot use sprite as background because i need to change their color trough script to give some effect , this is my picture showing my problem If the picture is not clear , go here https i.stack.imgur.com hLqC9.png The menu dropped is at Z 100 while the background is at Z 20 , as you see , the text is rendered while the other not ( such as the border , ect ). And this is the picture when my special font without using the shader If the picture is not clear , go here https i.stack.imgur.com vbrQ1.png Now the picture of my special font using the shader If the picture is not clear , go here https i.stack.imgur.com hMAR2.png Is there any possible way to prevent the text rendered without shader change the background to sprite ? Im sorry if this already asked somewhere , i just cannot find it at search engine ( neither here ) .
|
0 |
How can I implement simple distributed processing in a Unity game? I'm looking to set up a game which uses distributed processing. Just a simple brick shooter in unity with the distributed part being that the calculations for the falling blocks are handled by another PC and the transformations are sent back and applied to a clients machine. To use this in Unity I assume I'll be using Remote Procedure Calls? Will I also require socket programming? Any other networking elements I require?
|
0 |
Avoiding singletons for puzzle system Say for instance I have a puzzle with 3 switches that need to be in some configuration (say all on) in one room, that opens a door in another, with a load screen separating, so I can't link the switches directly to the door. My first thought was to create a singleton that stored the state of each "solution element" which in this case is the switches, but could be a correctly turned knob, ect. then a given "Puzzle Gate" like a locked door would check the required solution elements to decide it's own state, but I'm hesitant to use singletons for all of the commonly given reasons. What alternatives do I have to singletons that would give me the same or similar control?
|
0 |
Visually updating the position of a game object controlled by an animator controller I have a game object that is controlled by an animator controller. In order to activate the next animator state, the user is supposed to grab this game object, and then move it from Point A to Point B. As a test, in said game object's Update() method, I added the following line this.transform.localPosition Vector3.up When running the game, I can see that the y coordinate of the game object's position increases every single frame, just as intended. However, visually, the game object's position is not changing at all it remains in the same place all the time. What should I do to ensure that game object's position is also visually updated? EDIT Here are the properties of the animator I am using EDIT If relevant, here is the skinned mesh renderer for said game object
|
0 |
How can I get a background image and game objects to fill black areas of letterbox or pillarbox? I have used the Aspect Ratio Enforcer to force my game's aspect ratio to remain as 9 16. I need to prevent some game objects and the backgrounds from being affected by the enforced aspect ratio to cover the black areas that result from other aspect ratios. How can I prevent some game objects and background images from getting affecting by the Aspect Ratio Enforcer?
|
0 |
Consistent normals at any angle in bezier curve Could not work out or find any solution for this. I have a spline which consists of bezier curves (in 3d space) in fact, any straight line will also have such problem. I take a point on the curve and need to get a normal to this point at any given angle 0 360 (say, to build a mesh around it or to calculate an offset for the movement). I understand that in 3d space we have to define a plane to build normal, normally by using Vector3.Cross(A, B) In general, one uses curve's tangent as A and, e.x., Vector3.up or right as B. But, if curve becomes vertical (it can go in any direction, imagine any track that is ground independent, like in space), it gets aligned with Vector3.up, and the direction of normals goes crazy, swaps direction and so on, which is quite logical. More, it does so not only in straight vertical position, but start to change gradually around it. So, the question is how can I get consistent (all in equally correct direction) normals, using any given curve point position and angle for normal rotation? Update The initial approach looked like this public Vector3 GetTangent(...) Vector3 q2 CalculateTangent (...) Quaternion lookAt Quaternion.LookRotation (q2) Vector3 normal lookAt Vector3.up normal Quaternion.AngleAxis (angle, q2) normal return point normal size Which generated the following normals (blue is up) Now, if I try to use the previous normal for the direction Quaternion lookAt Quaternion.LookRotation (q2, previousNormal) first of all, I don't understand what to place here Vector3 normal lookAt ? And any combination of tangent, normal and rotation gives me something like this Where it can be clearly seen that normals on the vertical are improved (though not correct), but on the horizontal all went wrong, as if I just changed Vector.up to Vector3.right. In addition, the code for generating the tube in its main part looks like this float vStep (angleTo angleFrom) pipeSegmentCount if (b 0 amp amp tP 0f) tP 0.01f if (b 0 amp amp t 0f) t 0.01f if (b spline.Nodes.Count 2 amp amp tP 1f) tP 0.9f if (b spline.Nodes.Count 2 amp amp t 1f) t 0.9f Vector3 vertexA spline.GetTangent ( pP, tP, bP, Vector3.up, pipeAngle, pipeRadius) Vector3 vertexB spline.GetTangent ( pointsTotal b s , t, b, Vector3.up, pipeAngle, pipeRadius) for (int v 1 v lt pipeSegmentCount v , i 4) vertices i vertexA vertices i 1 vertexA spline.GetTangent ( pP, tP, bP, Vector3.up, v vStep pipeAngle, pipeRadius) vertices i 2 vertexB vertices i 3 vertexB spline.GetTangent ( pointsTotal b s , t, b, Vector3.up, v vStep pipeAngle, pipeRadius) Where 0.01f and 0.99f are because ends of spline do not have control points and LookRotation produces an error about zero rotation. b and bP are node indexes, and P suffix is for "previous". This particular code is used to generate a round rail and move an object beneath it. Thus, it is important that the bottom normal is consistent and always at the bottom (when it is vertical, this bottom is not the world bottom of course, but it protrudes at the side of the tube, object will turn itself accordingly, looking forward the curve).
|
0 |
How can I stop showing camera image in my Scene? Unity How can I stop showing camera image in my Scene in Unity? As you can see on the screenshot there is an image of a camera inside a player in the Scene view. How can I disable the image?
|
0 |
Is it possible to prevent the collider 2D outline from hiding in Unity? Is it possible to prevent the collider 2D outline from hiding in Unity? I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation. In my case the collider outline is red I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow?
|
0 |
"The associated script cannot be loaded", how can I see what script is associated? I have a couple objects that are throwing errors in the warning log The referenced script on this Behaviour (Game Object 'myObject') is missing! Here is what they look like in the inspector How can I see what script is (or was) associated?
|
0 |
How to execute a code from many scripts I want to execute a function from many scripts attached on gameobjects which will be spawned. Since game objects are spawned, I can't assign the script in the inspector. What i want is that, there are three gameobjects, A,B,C. C is already in the scene. A and B are spawned with different scripts,the spawned gameobject's script should call the function on the gameobject C. I can make a delegate but there are different scripts that want to call the function. So should i have to create different delegates for each script on A and B and then assign them onto the gameobject C so that A and B can call their delegates and these delegates will trigger the function on C or there is something like a event that i can call from B. If it was possible, i can create a event on A and assign it on C. Now A can call the delegate and B can also call that event and trigger the function on C, but this is not possible as event can't be called from another script. I need something like a function that i can call from any script and it calls the function from C. Note that function should not be static. As i can call a static function from any script but it can call only static methods, which i don't want.
|
0 |
Box2d on authoritative server for Unity client I'm creating a multiplayer platform and shooting game in unity, using unity2d's own physics system (box2d). But the truth is that I am quite lost in the creation of an authoritative server in c . I have quite clear and experience in the use of socket for communication between client and server, I do not know how to approach the issue of simulating the physics of my game on the server so that it decides the positions movements of the clients. Can anyone guide me to use box2d on the server, as I simulate the game on the server? Is this a good option or would it be better to implement my own game physics than to use the non deterministic engine? Thank you very much and sorry for my level of English
|
0 |
Programmatically creating new tags in Unity I'm writing a custom editor script to add tags programmatically. I got the error of IndexOutOfRangeException Array index is out of range from the lines below SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") These are my codes SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") Adding a Tag string s "Instantiated" First check if it is not already present bool found false for (int i 0 i lt tagsProp.arraySize i ) SerializedProperty t tagsProp.GetArrayElementAtIndex(i) if (t.stringValue.Equals(s)) found true break if not found, add it if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s Latest Update Error IndexOutOfRangeException Array index is out of range is solved by resolving file location in my original script. I apologized for that. Fixed Added a line in the script to update the properties if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s tagManager.ApplyModifiedPropertiesWithoutUndo()
|
0 |
Random.range giving me the same value at the same time I created a random direction in x and y axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y axis. How do I not let this happen, I only want one axis to have a value, not both? ERROR HOW I WANT IT TO HAPPEN CODE public Vector2 randomDirection void Awake() void Update() randomDirection new Vector2(Random.Range( 1, 2), Random.Range( 1, 2))
|
0 |
Static variable not holding its value I am creating a real time multiplayer game in Unity 3d. When a game ends I set a static boolean value called "waitingToEndGame" to true. In Update() it waits a few seconds before moving to a new scene like this if (waitingToEndGame) waitTime Time.deltaTime if (waitTime gt 5f) showGameScores false waitingToEndGame false if (type "Multiplayer") MultiplayerController.Instance.LeaveGame() GameObject levelManager GameObject.Find("Level Manager") levelManager.GetComponent lt LevelManager gt ().LoadLevel("MainMenu") DisableAllMovingObjects() My problem is that even though I am setting the boolean value to true it acts as if it doesn't change and it doesn't make it into the code above to move to the main menu. I even had debug statements printing here as well and they seem to just suddenly stop.
|
0 |
Enlarge screen space Texture by set pixel amount I have a texture shown over the screen using screen space UV's. The Texture is 495x,596x, Screen size is 888,500, but can change. The Texture has a Tile of (3.469775f,1.392644f) to correct for distortion from being stretched to the Screen's size, and has repeat set to Clamped. So basically, I'm showing a Texture of an arbitrary size on screen and using Tile and Offset in the shader to correct for distortion and keep the texture at its original aspect ratio. Now my problem is I want to Zoom in and out by a set pixel amount in Screen space. So lets say I need the texture to increase in width by 10 pixels in screen space. What is a formula I can use to recalculate the Tile and Offset so that the texture stays at the same aspect it was but increases by the amount I want it zoomed? I've been trying things like 1 Pixel (1f Camera.main.pixelWidth). So to zoom by 10 pixels I would go something like Tile.x (10f (1f Camera.main.pixelWidth)) But this doesn't seem quite right, I'm not seeing it increase the Texture by the right number of pixels... My current function is something like this, but for Zoom 5f, it's only enlarging by about 2px. AspectRatio Tiling in the Material and WidthOffset HeightOffset is just the Offset. public void ZoomOverlay(float ZoomAmount) AspectRatio.x ZoomAmount (AspectRatio.x (float)Camera.main.pixelWidth) AspectRatio.y (ZoomAmount (AspectRatio.x (float)Camera.main.pixelHeight)) 2f WidthOffset ((ZoomAmount 2f) (AspectRatio.x (float)Camera.main.pixelWidth)) HeightOffset ((ZoomAmount (AspectRatio.x (float)Camera.main.pixelWidth)) 2f) AspectRatio.x
|
0 |
How can I find and get all enabled cameras and switch between them? I have 5 cameras in the scene. In the Inspector I added to the cameras array 3 cameras. In the script I store this cameras using storedCameras array. In cameras array there are 5 cameras. I added a flag allCameras to change between the stored cameras mode and all cameras mode. And I'm using the G key to switch between the cameras either the stored or the all cameras. But when I press on G I see in the Inspector that each press on G remove one camera from the array cameras in the end I left with one camera. And the idea is to press G and switch between the cameras either if it's on stored cameras mode or all cameras mode depending on the flag. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class SwitchCameras MonoBehaviour Header("Cameras Init") public Camera cameras public Vector3 originalPosition HideInInspector public Vector3 currentCameraOriginalPosition, currentCameraPosition public bool allCameras false private Camera storedCameras Space(5) Header("Cameras Switch") public string currentCameraName public Vector3 lastCameraPosition private int currentCamera 0 void Start() storedCameras cameras if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras lastCameraPosition new Vector3 cameras.Length if (cameras.Length gt 1) originalPosition new Vector3 cameras.Length for (int i 0 i lt cameras.Length i ) originalPosition i cameras i .transform.position if (cameras.Length 1) Debug.LogError("Need more then 1 camera for switching..") else Debug.Log("Found " cameras.Length " cameras") for (int i 0 i lt cameras.Length i ) cameras i .enabled false cameras 0 .enabled true currentCameraName cameras 0 .name currentCameraOriginalPosition originalPosition 0 void LateUpdate() if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras else cameras new Camera storedCameras.Length cameras storedCameras if (Input.GetKeyDown(KeyCode.G)) cameras currentCamera .enabled false if ( currentCamera cameras.Length) currentCamera 0 cameras currentCamera .enabled true currentCameraName cameras currentCamera .name currentCameraOriginalPosition originalPosition currentCamera lastCameraPosition currentCamera cameras currentCamera .transform.position currentCameraPosition lastCameraPosition currentCamera
|
0 |
game object disappears when I add OnTriggerEnter script I'm setting up collision detection for my enemy objects and projectile. When I add the detect collision script below, my enemy object just disappears. Projectile has the same detect collision script and also disappears. I get this error code NullReferenceException Object reference not set to an instance of an object MoveForward.Start () (at Assets Scripts MoveForward.cs 16) This is a copy of my prefab settings for enemy object I'd appreciate any advice. Thank you Detect Collision Script using System.Collections.Generic using UnityEngine public class DetectCollision MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() private void OnTriggerEnter(Collider other) Destroy(gameObject) Destroy(other.gameObject) Move Forward Script using System.Collections using System.Collections.Generic using UnityEngine public class MoveForward MonoBehaviour public float speed 20f public GameObject Trump public GameObject Player private Rigidbody enemyRb Start is called before the first frame update void Start() enemyRb GetComponent lt Rigidbody gt () Player GameObject.Find( quot Player quot ) this.transform.LookAt(Player.transform) Update is called once per frame void Update() transform.Translate(Vector3.forward Time.deltaTime speed)
|
0 |
Unity character customization parts I'm relatively new to unity, started a couple weeks ago and so far I managed to setup a character with multiple parts, like hair, head, and body. Here's how it looks like I also managed to import some animation thanks to https www.mixamo.com and everything works perfectly well for now... Now, I'm struggling with the quot change quot part mecanism. I'd like to swap the quot nude quot body mesh part, to an quot armor quot mesh or any other body mesh. Problem is, when I change the model in the SkinnedMeshRenderer it tells me the following with this result I did some reseach about this error message, and it actually makes sense, the given mesh doesn't have any bone setup, bone weights or such. I would like to know if it's possible to use quot common quot skeleton for every models and assign it throught code?
|
0 |
GraphicRaycaster performance OnClick Let's say I have two Canvases BackgroundCanvas and UICanvas. Now, on BackgroundCanvas I have multiple moving, not clickable objects so I removed the GraphicRaycaster ( 69 to performance). On the UICanvas, all the objects are on the UI layer. I also have some additional layers somewhere else. Now, if I change the GraphicRaycaster's (on UICanvas) blocking mask to UI only, would it improve performance if there are other objects on the Default and other layers? Or would it still ray all these objects on other layers? How does this really work? I'm asking cause I don't see any performance impact while switching these Blocking Masks, but after disabling the entire component I do (but the input is not working S).
|
0 |
Does transparency work with SSS in Unity's HDRP Lit shader? I am using Unity's HDRP Lit shader in Shader Graph (all are version 4.8.0 preview) on Unity 2018.3.0b12. I am trying to use both transparency and subsurface scattering on the material. However, it appears that the visual appearance loses SSS when transparency is introduced. Example The cube on the left has transparency enabled, and has no visible SSS. The cube on the right has the same SSS settings as the left cube, however the right cube has no transparency enabled. I need transparency to fade in the cube depending on its position, like this And here is my master node If anyone has an alternative solution that sidesteps this potential limitation, I am all ears. Cheers!
|
0 |
How To Use Unity With C ? In the C Visual Studio installer, there is an option Game Development With Unity. However, after selecting that, I didn't find any changes to regular Visual Studio. So I looked it up, and found no results regarding C . How can I use Unity with Visual Studio for C ?
|
0 |
'Edit Collider' exits after every adjustment When I click the Edit Collider button I can see the collider's region and the handles to adjust it. After every adjustment (with the mouse) the collider outline disappears as Edit Collider finishes. It's frustrating to use, having to reclick Edit Collider after every drag click. How do I stop Edit Collider mode from exiting after every change and only exit if I click the button, or press some commit key?
|
0 |
Add buttons into List when mouse is HoldDown? I have three buttons in my menu. What I need to do is when I click on first button it becomes the first element in my list. Now, when I keep mouse button down and move it to the second button it becomes the second second element in my list. The same with the third button. public List lt GameObject gt UI Button List new List lt GameObject gt (3) void Update() if (Input.GetMouseButtonDown(0)) if (UI Button List 0 null) UI Button List 0 EventSystem.current.currentSelectedGameObject.gameObject if (UI Button List 0 ! null amp amp UI Button List 1 null) UI Button List 1 EventSystem.current.currentSelectedGameObject.gameObject if (UI Button List 0 ! null amp amp UI Button List 1 ! null amp amp UI Button List 2 null) UI Button List 2 EventSystem.current.currentSelectedGameObject.gameObject end if
|
0 |
how to detect Unity UNET errors? I'm working on a simple multiplayer online game. and I use UNET and Networkmanager. In my game I have some rooms and players that they can join to this rooms by connecting to specific server.exe file that I runned on a dedicated server. My problem is when I use port 7777 for first server, if I run another server, then this error Appear Cannot open socket on ip ,and port 7777 For now I solved this issue by building servers with specific ports. for example in server1.exe I used port 7777 by default. and server2.exe , 7778 and same for other servers . But I want to do this automatically. I mean when the server recognize port 7777 is busy , then increase port number. I want to know can I use try catch for this kind of errors ? because I used try catch but it's not work. I don't know how to use it. this is part of my code try StartServer() catch(Exception ex) networkPort then change port number and run server again I just looking for a way that my servers run by choosing right port automatically.
|
0 |
How do I stop rotation after colliding with a specific object? How do I stop rotation after colliding with a specific object? I want player to stop rotating when they collide with walls. I am using Unity, with C .
|
0 |
How can I reduce the size of bundled Unity DLLs on Android? I have created a simple project (I am a Unity beginner) for Android but the apk size is around 18 MB! I checked the documentation. One way to decrease the apk size is to check the editor log. Then I discovered that imported DLLs have a size of 3.9MB. I only used UnityEngine and Collision packages. So how can I avoid to import the other big DLLs?
|
0 |
How to make a string from the words of a file in Unity? I have .txt file containing all the English words separated by line breaks. I want to turn them to a string so I can easily pick a random one from them. The way I would do that in normal C is the File.ReadAllLines(path) function in the System.IO namespace. But, I don't think that I can use System.IO with Unity so the alternative that I could come up with is the TextAsset class which I can use to reference an imported text asset and get its text property as a string. But, if I have a giant string how can I simply split it up into individual words and store them as a string ?
|
0 |
"Your license does not cover Android Publishing" error I recently installed Unity 2017.1.0f3. I imported a project from an older version of Unity it worked perfectly and allowed me to build for Android. I logged in to the Asset Store through the tab in the Unity editor, now I can no longer build for Android. This is the error I receive I created my Unity account before Android was free. Is there a way to update my account to allow me to build with Android again?
|
0 |
Intantiating objects across multiple container pages I have this script here that generates buttons based on an array and a serialized grid transform public void InitializeUI() LevelItem levelItemsArray LevelSystemManager.Instance.LevelData.levelItemArray for (int i 0 i lt levelItemsArray.Length i ) if (i n 0) sets it to 15 LevelButtonScript levelButton Instantiate(levelBtnPrefab, levelBtnGridHolder) levelButton.SetLevelButton(levelItemsArray i , i, i LevelSystemManager.Instance.LevelData.lastUnlockedLevel) var page GameObject.FindObjectOfType lt UI.Pagination.PagedRect gt () page.AddPageUsingTemplate() Now what I'm trying to do is make that array instantiate a new page (calling the page.AddPageUsingTemplate() function which is from another script) once for every 15 items of the array. I have 75 levels and want to instantiate the buttons on a new game object which has a grid layout group, so it would be 15 buttons on each grid with 5 pages grids in total. I do indeed get 5 pages when I run this code, but since the transform is only set to the first one the buttons don't get placed on the other pages. How can I place buttons after the first 15 on the following pages?
|
0 |
Gamemaker vs Unity2d Speed of Development I know coding, so programming is not a problem Money is not a problem at all, I can get both GameMaker Master Collection and Unity Pro I want to make a 2d game. So which one is better for speed of development? On which one would I be able to finish my project earlier?
|
0 |
How to set up bloom in Unity Last time I used image effects in Unity it was back when 3.0 was released and for bloom you used the object's alpha to indicate whether it should glow or not. Now in 4.2 I couldn't grasp how to apply the image effect properly. It seemed to put the whole scene to glow and alpha did not affect it. There was no help from the Unity docs which are pretty much just spec sheets for the effects and no proper tutorials around. This leads to couple of questions How do you create something like the screenshots in the Bloom page in the docs? Only the car windows and metal parts glow, but no glow on the concrete. How do you make a light source like the second image on the above link? I tried different shaders and lights on a gameobject but none of them produced anything like that. What does the HDR checkbox in the camera actually do?
|
0 |
How can I make object to follow first person character and the camera without making the object child? using System.Collections using System.Collections.Generic using UnityEngine public class ObjectFollowCamera MonoBehaviour public Transform cameraToFollow public Transform objectToFollow public float distanceFromCamera private void Update() objectToFollow.position new Vector3(cameraToFollow.position.x,cameraToFollow.position.y,cameraToFollow.position.z distanceFromCamera) This script is attached to a empty GameObject. The objectToFollow will move once i'm moving the Player with the keys. But when i'm rotating the camera of the player around the objectToFollow is not moving. The Player have attached to it Character Controller , First Person Controller , Rigidbody And the Camera is child of the Player.
|
0 |
Unity wall jump issue I've got a very annoying problem that I have been stuck on for a few days and I can't figure it out. It is for a wall jump. I basically want my wall jump to have a bit of force away from to wall to make it look and feel better than just jumping up straight. The problem is, when i add a force on the x axis, it does not register when i am also holding the arrow towards the wall. If I am not holding down the walking button, then press jump...then the x force works. I have a feeling that the horizontal axis force is competing with the opposite force that i want to add to the player when he hits the jump button... Walking code private void ApplyMovement() if (isGrounded) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection ! 0) Vector2 forceToAdd new Vector2(movementForceInAir movementInputDirection, 0) myRigidbody.AddForce(forceToAdd) if (Mathf.Abs(myRigidbody.velocity.x) gt movementSpeed) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection 0) myRigidbody.velocity new Vector2(myRigidbody.velocity.x airDragMultiplier, myRigidbody.velocity.y) if (isWallSliding) if (myRigidbody.velocity.y lt wallSlideSpeed) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, wallSlideSpeed) Jump code private void Jump() if (canJump amp amp !isWallSliding) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, jumpForce) numberOfJumpsLeft else if ((isWallSliding isTouchingWall) amp amp !isGrounded amp amp canJump) isWallSliding false numberOfJumpsLeft Vector2 forceToAdd new Vector2(wallPushForce facingDirection, wallJumpForce wallJumpDirection.y) myRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse) Where I call The code void Update() CheckInput() private void FixedUpdate() ApplyMovement() private void CheckInput() movementInputDirection CrossPlatformInputManager.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() if (Input.GetButtonUp("Jump")) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, myRigidbody.velocity.y variableJumpHeightMultiplier) Any help would be much appreciated. Thanks in advance
|
0 |
Why use Time.deltaTime in Lerping functions? To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t 0, the value a is returned, at t 1, the value b is returned. At 0.5 the value halfway between a and b is returned. (The following picture is a smoothstep, usually a cubic interpolation) I have been browsing the forums and on this answer I found the following line of code transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime) I thought to myself, "what a fool, he has no idea" but since it had 40 upvotes I gave it a try and sure enough, it worked! float t Time.deltaTime transform.rotation Quaternion.Slerp(transform.rotation, toRotation, t) Debug.Log(t) I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?
|
0 |
Child transform's position not updated as parent moves I have a parent game object Object1. It has a child, which is simply an empty game object called ReferencePoint. ReferencePoint can be any arbitrary point on Object1 itself. I have another game object Object2. It has a public field called RotationReference, of type Transform. In the inspector, the ReferencePoint on Object1 is assigned to the RotationReference field on Object2. As Object1 moves, I expect ReferencePoint to change its position as well. Object2 is supposed to change its rotation to face its RotationReference in this case, the ReferencePoint on Object1 public override void Rotate() Vector3 relativeRotationReferencePosition this.RotationReference.position this.transform.position this.transform.rotation Quaternion.LookRotation(relativeRotationReferencePosition) However, I noticed that Object2 is not rotating at all, even when Object1 is moving. When I step through the call stack multiple times, I discover that this.RotationReference.position always has the same value, even though Object1 is moving. What am I missing here?
|
0 |
Why does Unity Eventsystem lag on first touch? Hi I am making a very simple simple platformer game for android devices. I am using Unity's event system for player movement. The problem is when I touched the button first time there is a lag (hiccup) after then everything is ok. I have profiled my game there is a spike in EventSystem Update method. here is the simplified code, using System.Collections using System.Collections.Generic using UnityEngine RequireComponent (typeof(Rigidbody2D)) RequireComponent (typeof(BoxCollider2D)) public class PlayerController MonoBehaviour public float movementSpeed 5f public float jumpForce 5f public float distanceToGround 0.2f public LayerMask staticCollider public playerState state private Rigidbody2D rBody public Transform leftmost public Transform rightmost Collider2D platforms new Collider2D 2 public int hrInput 0 Use this for initialization void Start ( ) rBody GetComponent lt Rigidbody2D gt () FixedUpdate is framerate independent, and therefore completely unrelated to your framerate void FixedUpdate () state.grounded isGrounded () if (hrInput gt 0) MOVE RIGHT () else if (hrInput lt 0) MOVE LEFT () else STOP MOVE () public bool isGrounded() print ("ground") if (Physics2D.OverlapAreaNonAlloc (leftmost.position, rightmost.position, platforms, staticCollider) gt 0) return true else return false public void setHrInput (int h ) print (h) hrInput h public void JUMP() if(state.grounded) state.onAir true rBody.AddForce(Vector2.up jumpForce, ForceMode2D.Impulse) rBody.velocity Vector2.up jumpForce public void MOVE LEFT() rBody.velocity new Vector2 ( 1 movementSpeed Time.deltaTime, rBody.velocity.y) public void MOVE RIGHT() rBody.velocity new Vector2(1 movementSpeed Time.deltaTime, rBody.velocity.y) public void STOP MOVE() rBody.velocity new Vector2(0,rBody.velocity.y) end Here is the profiler Image. Please help me to fix this issue.
|
0 |
Changing Pixels Per Unit First off, excuse my ignorance. I am just getting started in game dev. and ran into a little issue. So I had these weird rippling lines going across my screen, and saw in a couple forums that this means I don't have what is called a quot pixel perfect quot game. To fix this, I am supposed to change the pixels per unit of each sprite down to 1. Currently I had it on 32 because that is my sprite size and I am a complete noob. Now, I change it down to one but it completely destroyed my game. Everything that is generated on my map grid is sucked into the center in this giant orb of sprites (I procedurally generate my map off a grid of 1 0s). I am guessing there is just a setting or some such thing that I am missing. Any ideas? Also would be happy with an alternative to remove the rippling lines.
|
0 |
Euler (right handed) to Quaternion (left handed) conversion in Unity I'm having trouble figuring out the proper conversions from Euler angles to Quaternions. The Eulers come from BVH files, which use a right handed coordinate system (Y is up, Z is forward) and can have any rotation order specified. The Quaternions are in Unity, which is left handed (Y is up, Z is back). I'm composing the Quaternions from three AngleAxis rotations, but messing up the order somewhere. So far I can't find understandable and generalized information for doing these types of conversions. public enum AxisOrder XYZ, XZY, YXZ, YZX, ZXY, ZYX, None public Quaternion EulerToQuat(Vector3 eulerAngles, AxisOrder rotationOrder) I've tried various combinations of axis angles here, but would like to understand what's wrong rather than brute force every combination var xRot Quaternion.AngleAxis(eulerAngles.x, Vector3.left) var yRot Quaternion.AngleAxis(eulerAngles.y, Vector3.down) var zRot Quaternion.AngleAxis(eulerAngles.z, Vector3.back) switch (rotationOrder) case AxisOrder.XYZ return (xRot yRot) zRot case AxisOrder.XZY return (xRot zRot) yRot case AxisOrder.YXZ return (yRot xRot) zRot case AxisOrder.YZX return (yRot zRot) xRot case AxisOrder.ZXY return (zRot xRot) yRot case AxisOrder.ZYX return (zRot yRot) xRot return Quaternion.identity ...and converting translation data like so (I believe this is working) public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos) return new Vector3(xPos, yPos, zPos) If anyone can help me better understand how to conceptualize coordinate system conversions, and where I'm going wrong, I'd greatly appreciate it.
|
0 |
Combining lots of small polygons to one (some) big poly(s) I am looking for algorithm to merge lots of relatively small 2d polygons to one or some big polygons. In case two small polygons are touching or overlapping, they should be merged to one polygon. My big goal is to sufficiently decrease amount of points lines required to describe collider. Resulting collider can include some polygons, btw. Could you propose an algorithm or library to do this? (Finally I will implement solution in C for Unity3d). P.S. Here is one picture of task I need to solve. Look this http epsiloncool.ru i E20160624 224050.png Green lines is a colliders. I need to merge them all to get one collider (or some)
|
0 |
How can I add a delay for each moving object? The waypoints script using System.Collections using System.Collections.Generic using System.Linq using UnityEngine public class Waypoints MonoBehaviour public Transform objectToMovePrefab public int numberOfObjectsToMove 1 with this approach, you use GameObjects to represent your waypoints (they can be empty if you want the waypoint to be invisible) SerializeField private List lt Transform gt waypoints private void Start() for (int i 0 i lt numberOfObjectsToMove i ) var parent GameObject.Find( quot Moving Object Parent quot ) var objectToMove Instantiate(objectToMovePrefab, parent.transform) objectToMove.name quot Platfrom quot public int Count gt waypoints.Count public Vector3 GetWaypoint(int index) return waypoints index .position Then in the editor I added this script to the prefab using System.Collections using System.Collections.Generic using UnityEngine public class WaypointsFollower MonoBehaviour SerializeField private Waypoints waypoints SerializeField private float speed 5f SerializeField private bool goBack false SerializeField private float delay private float startTime private int waypointIndex 0 private void Start() startTime Time.time delay waypoints GameObject.Find( quot Waypoints quot ).GetComponent lt Waypoints gt () void Update() if (Time.time lt startTime) return Vector3 waypoint waypoints.GetWaypoint(waypointIndex) movement float distance speed Time.deltaTime transform.position Vector3.MoveTowards(transform.position, waypoint, distance) check if we've reached the waypoint float threshold .1f how close is considered having reached the waypoint if (Vector3.Distance(transform.position, waypoint) lt threshold) wraps back to 0 when we reach last waypoint if (goBack) waypointIndex (waypointIndex 1) waypoints.Count else if (waypointIndex ! waypoints.Count 1) waypointIndex waypointIndex 1 The delay is working but it's delaying all the WaypointsFollower's so they move at the same time after the delay. I want that even if all the Followers have the same delay value for example 3 so the first one will start moving after 3 seconds then the next follower will start moving after another 3 seconds and so on and not that they all delay for 3 seconds and move together but to make delay so there will be spaces between the followers when they are moving.
|
0 |
Raycast Movement on a sphere so I'm working on a mobile game where I have touch input from a Asset from the asset store. It all works perfectly fine, except for one thing I want to implement a "drag and drop" feature so when I pick up an Item it should follow to the position of my finger. But because the playground is a sphere, I have to do the movement with a Raycast. So my plan is that the item should follow the Raycasts position. My current attempt looks like this public void DragTo(float screenX, float screenY) if (draggingObject null) return Debug.Log("Dragging") Converts the screen space to world space Vector3 mousePosFar new Vector3(screenX, screenY, Camera.main.farClipPlane) Vector3 mousePosNear new Vector3(screenX, screenY, Camera.main.nearClipPlane) Vector3 mousePosF mainCam.ScreenToWorldPoint(mousePosFar) Vector3 mousePosN mainCam.ScreenToWorldPoint(mousePosNear) shoots an ray to the world space RaycastHit hit if (Physics.Raycast(mousePosN, mousePosF mousePosN, out hit)) float step speed Time.deltaTime draggingObject.GetComponent lt Rigidbody gt ().MovePosition(hit.point) I already have tried the following options draggingObject.GetComponent lt Rigidbody gt ().MovePosition(hit.point) draggingObject.GetComponent lt Rigidbody gt ().MovePosition(hit.normal) draggingObject.transform.position hit.point draggingObject.transform.position normal They all work, but they all have really buggy and strange behaviors. Also when I dont freeze the z. axis on the Rigidbody the item just "flies" up on the z axis, until it reaches the camera. Then it teleportes again down and it all starts again. So its flying up on the ray. So if you have any Ideas why this happens let me know. Any help is appreciated. (Also dont forget that its all happens on a sphere) UPDATE It works now. When the dragging began i changed the layer from the object to "Ignore Raycast" and when it end changed it back to "Default".
|
0 |
I want to test the Animator component of a gameobject using nunit, but I am having issues I made a Blender 3D model with animations. Then I used the Animator Controller, and attached it to the model. The Animator Controller has a few Boolean parameter variables like isWaving, isDoing, and isIdle and more variables like that. If, say, a non idle action is true, then the animation of my model transitions to the next one. I am into test driven development, but I have never done it with Unity. I tried writing the following code to test my project SetUp public void SetUp() Crystal GameObject.FindGameObjectWithTag("CrystalModel") CrystalScript Crystal.GetComponent lt CrystalChanPlayer gt () CrystalAnimator Crystal.GetComponent lt Animator gt () unity game animator Test public void ifSetAnimationIstodoThenToDoAnimationIsPlayed() CrystalScript.setAnimationStrategy("todo") set strategy CrystalScript.playAnimation() sets todo boolean to true and idle to false first debug output Debug.LogError("todo is " CrystalAnimator.GetBool("isDoing") " idle is " CrystalAnimator.GetBool("isIdle")) second output Debug.LogError("current state is " CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("idle")) Assert.True(CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("todoAnimation")) I received the following output "todo is true and idle is false" "true" I think this is because Unity isn't really running, and my Animator doesn't get to update based on the variable changes. The first output assures me that todo is set to true and idle is false, hence the Animator should transition that animation to the todoAnimation. Yet, I can't seem to show that, in my tests. Is there any way to test the Animator class? Are there any design patterns I can use?
|
0 |
Unity 2D Tap to shoot at mouse position on android device Hello everyone i am really stuck at the moment and would appreciate any help if possible. I have my game where i move the player up and down with 2 buttons on the bottom left of screenshot. I also have a button over the entire screen for tap to shoot and this moves the weapon to my finger position where i have tapped and it shoots towards that position using mouse.position. Now the problem is when i am on my android device and i am moving up and down but when i also tap to shoot the gun it moves towards my up and down buttons and this is not what i want. i want to be able to move with my finger and also shoot towards the second finger. Any ideas would be greatly appreciated. Here is my Tap to shoot button code! public void ShootButton() timer 0 Face true if finger presses Shootbutton then activate this Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position subtracting the position of the player from the mouse position. difference.Normalize() normalizing the vector meaning all the sum of the vector will be to 1. float rotZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg find the angle in degree. WeaponTrans.transform.rotation Quaternion.Euler(0f, 0f, rotZ rotationOffset) if (reloading false) if (fireRate 0) Shoot() else if (Time.time gt timeToFire) timeToFire Time.time 1 fireRate Shoot()
|
0 |
Unity Items not being removed from list So I finally perfected my RTS multiple movement. The situation is that the game objects are added into a list in a script bound to the camera called UnitController they are added from a unit client script MultiselectClient, this client accesses the UnitController class and adds itself the gameObject into the list. Each time I do the drag select I want it to clear the list first before adding any more. But for some reason, it doesn't work? This is in my UnitController (below) void MultiSelect(RaycastHit hit) Debug.Log(SelectedUnits) if (SelectedUnits.Count gt 0) Debug.Log("Moving group to " hit.point) foreach(GameObject gameObject in SelectedUnits) gameObject.GetComponent lt NavMeshAgent gt ().SetDestination(hit.point) This is in my client (below) public bool Selected false void Update() if (Input.GetMouseButton(0)) Vector3 camPos Camera.main.WorldToScreenPoint(transform.position) camPos.y Screen.height camPos.y if inside the cameras drag selection area then mark player as selected Selected UnitController.selection.Contains(camPos) Debug.Log("Selected") if(selected) addTo() void addTo() UnitController.SelectedUnits.Remove(gameObject) I have also tried .clear() which also hasnt worked. if (!UnitController.SelectedUnits.Contains(gameObject)) UnitController.SelectedUnits.Add(gameObject) Debug.Log("Added to list " UnitController.SelectedUnits) else Debug.Log("Im already in that list.")
|
0 |
Recenter User Orientation on X and Y axis on with Oculus GO and Unity I am working on an Oculus GO App for patients in a doctors chair. They'll be using Oculus GO Headsets while sitting, lying, or something in between. So what I am trying to do is to recenter the HMD orientation when the HMD is mounted. But since the patients position can be seated or lying horizontally, I will need to recenter the rotation on all three axis, or at least X and Y. Unity provides UnityEngine.XR.InputTracking.Recenter() But that will only recenter the Y Axis. Oculus Integration provides OVRManager.display.RecenterPose() But under the hood its just using the Unity InputTracking.Recenter() again. So how can I recenter my whole scene or the player on y axis as well? If you go to Oculus GO main menue and push the recenter button on your controller, it does exactly what I want. However I can't find a way to do the same thing in my Unity application. Thanks in advance!
|
0 |
How can I prevent pixel artifacts on programatically generated textures? In the game I'm developing, rooms can be of various sizes, which means I need to vary the size of the floor texture appropriately. The way I've solved this problem is to generate a Texture2D programatically, and set each pixel to be transparent (or not) as appropriate appropriately. I get something like this Where, if you look at the top left, you'll clearly see the pixel artifacts from the floor texture against the dark blue background. When I run into this with static textures, the fix is simple. Set the Texture's wrapmode to clamp instead of repeat. But when I try to do that programatically... (and change nothing else!) I get this I'm not quite sure what's happening, or why setting the wrapMode changes the results so markedly. Anyway I can avoid the pixel artifacts? I suppose it's possible to add an extra border around the generated texture (so that all edges can be transparent), but that doesn't seem a particularly clean solution. Code is here void DebugFloorTextureMerge() sizeVector makes up the rectangle circumscribing the room's parallelagram Vector2 sizeVector new Vector2(roomBounds.topRight.x roomBounds.bottomLeft.x, roomBounds.topLeft.y roomBounds.bottomLeft.y) get the texture of the filled sprite Texture2D patternTexture (Texture2D) floorTexture.image make a new texture of the size of the room. Texture2D fillTexture new Texture2D( (int) sizeVector.x, (int) sizeVector.y, TextureFormat.ARGB32, false) COMMENTING THIS LINE OUT MAKES THE TEXTURE WORK WITH ARTIFACTS fillTexture.wrapMode TextureWrapMode.Clamp LEAVING IT IN MAKES THE FOLLOWING CODE WORTHLESS int patternX 0, patternY 0 Vector2 pointVector Color transparent new Color(0,0,0,0) for(int x 0 x lt sizeVector.x x ) for(int y 0 y lt sizeVector.y y ) pointVector new Vector2(x,y) if(roomBounds.Contains(pointVector)) get the next pixel fillTexture.SetPixel(x,y, patternTexture.GetPixel(patternX, patternY)) else pixel was not in the room, so set it to transparent. fillTexture.SetPixel(x,y, transparent) resultx x resulty y increment the pattern counter and reset if necessary. if you only increment this when Contains is true, you'll warp the texture patternY if(patternY gt floorTexture.fillSize.y) patternY 0 increment the pattern counter and reset if necessary. also reset y, so the pattern will line up properly. patternY 0 patternX if(patternX gt floorTexture.fillSize.x) patternX 0 set the PixelChanges. fillTexture.Apply()
|
0 |
Trying to trigger dialogue when the space bar is clicked, and two objects are colliding I'm getting a NullReferenceException on OnTriggerStay. I've been going crazy trying to figure out why. I have tried to cut this down to only the relevent information. I got this code through a tutorial https www.youtube.com watch?time continue 48 amp v nRzoTzeyxU (just for credits). using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(Rigidbody)) public class MainCharacter MonoBehaviour public int limbs public float speed public Vector3 jump public float jumpForce Rigidbody2D rb public float fire start time Time.time Animator animator public DialogueManager dialogueManager Checking if we are grounded public bool isGrounded public LayerMask groundLayers private SpriteRenderer myRenderer public Sprite LimbSprites void Start() dialogueManager gameObject.GetComponent lt DialogueManager gt () public void OnTriggerStay2D(Collider2D collision) if (Input.GetKey(KeyCode.Space)) Dialogue dialogue collision.GetComponent lt Dialogue gt () dialogueManager.StartDialogue(dialogue) Here is my dialogue manager using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DialogueManager MonoBehaviour public Text nameText public Text dialogueText public Animator animator private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () public void StartDialogue (Dialogue dialogue) animator.SetBool("IsOpen", true) nameText.text dialogue.name sentences.Clear() foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() dialogueText.text sentence void EndDialogue() animator.SetBool("IsOpen", false) Here is DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue () FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Here is Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue MonoBehaviour public string name TextArea(3, 10) public string sentences
|
0 |
Move relative to screen I use top down 60 degree tilted camera and want move always visually straight directions relative to screen (up, down, left, right). When object is near screen edges it starts moving diagonally (visually) probably because of camera tilt. I tried with WorldToViewportPoint ViewportPointToRay but it doesnt work exactly because even when there is no input, conversion to viewport and back to world same value sometimes gives slighltly offset from start position. float delta Time.deltaTime float h Input.GetAxisRaw("Horizontal") float v Input.GetAxisRaw("Vertical") Vector3 view MainCamera.WorldToViewportPoint(transform.position) view.x (h gt 0) ? 1 (h lt 0) ? 0 view.x view.y (v gt 0) ? 1 (v lt 0) ? 0 view.y Ray ray MainCamera.ViewportPointToRay(view) RaycastHit hit Physics.Raycast(ray, out hit, Mathf.Infinity, 1 lt lt 15) 15 ground plane layer Vector3 world new Vector3(hit.point.x, transform.position.y, hit.point.z) Vector3 dir (world transform.position).normalized transform.position dir Speed delta
|
0 |
Unity how to position items into a Scroll View? I'm trying to add items (prefab) into a Scroll View but either if I simply add items without set positions and trying to setting position it not work. Case 1 without setting position Result All items overlapping Case 2 forcing positions (like commented row code below) Result Items not overlapped but X position take the same value (that not is 0) for (int i 0 i lt rows.Length i ) GameObject newObj Instantiate(MyRowPrefab) newObj.transform.SetParent(ScrollViewObject.transform, false) newObj.transform.localPosition new Vector3(0, ( 1 ((i rowHeight))), 0) If i decomment this line, X isn't set to zero... why ?
|
0 |
Unity Animation parameters are not being set I have the following animation controller with two parameters of walkingSpeed and Jump. I have the following code which should change the values animator.SetFloat("walkingSpeed",0.9f) animator.SetBool("Jump",true) and animator is the correctly referenced animator object. However the values that the parameters are set to do not appear to change in the animator window, nor do they appear to impact what is happening on the screen. However they do seem to impact the values obtained when doing the following animator.GetFloat("walkingSpeed") The animator consists of the shown blend tree, which works correctly and is always active, however due to the values not being changed it does not blends, and always acts as if the value with which it blends (walkingSpeed is 0). What is going on?
|
0 |
Why do I get this error with FB.LogInWithPublishPermissions? I don't know what's wrong. I know that FB.Login is already deprecated. I don't know what syntax to use. public class FBholder MonoBehaviour void Awake() FB.Init (SetInit, OnHideUnity) private void SetInit() Debug.Log ("FB Init Done") if (FB.IsLoggedIn) Debug.Log ("FB Logged in") else FBlogin () private void OnHideUnity(bool isGameShown) if (!isGameShown) Time.timeScale 0 else Time.timeScale 1 void FBlogin() FB.LogInWithPublishPermissions ("user about me, user birthday", AuthCallback) void AuthCallback(ILoginResult result) if (FB.IsLoggedIn) Debug.Log ("FB Logged in worked") else Debug.Log ("FB Logged in failed") and I'm getting this error Assets FBholder.cs(40,6) error CS1502 The best overloaded method match for Facebook.Unity.FB.LogInWithPublishPermissions(System.Collections.Generic.IEnumerable, Facebook.Unity.FacebookDelegate)' has some invalid arguments and this Assets FBholder.cs(40,35) error CS1503 Argument 1' cannot convertstring' expression to type System.Collections.Generic.IEnumerable'
|
0 |
how can i fix my code in order to get rid of the error that says that the object I want to instantiate is null? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class replicate MonoBehaviour public void replicateCube(InputField T) int H int.Parse(T.text) for (int i 0 i lt H i ) GameObject prefab Resources.Load("Cube") as GameObject GameObject go Instantiate(prefab) as GameObject go.transform.position new Vector3(0, i 5, 0)
|
0 |
Sprite editor "minimum size" feature alternative in Unity 5 As you know , unity has been removed its minimum size feature in sprite editor multiple auto slice mode. In some pics Unity discovers a lot of tiny rubbish sprites for example as 4x3 or 10x5 pixels. Is there anyway to set minimum size for good auto slicing in Unity 5?
|
0 |
Help with the calculation of the usage of my speed stat I am working on a freeroam, action RPG (before you read further, I am not noobish to programming, plus have friends to help with actual content rather than the base code). Anyway, I am trying in Skills to the game. I decided the movement based skills and animations should be a priority, so I began integrating it in. The animations work fine, but alas my movement skill Athleticism is making the character move unrealistically fast at a higher skill. The skill ranged from 1 to 100. After realising I should do some calculations to make you go from normal to Sonic the Hedgehog, I am using this formula currently (Athleticism Mathf.Sqrt(Athleticism)) 0.05f runMod This has helped, but it still looks weird. I need some help to make a formula that makes that the skill doesn't have such of a linear effect on the movement. EDIT Trying to be specific. The player moves, currently about 0.05 walking units per second at Athleticism 10, which is nice. However, the movement rate at Athleticism 100 cranks up to 0.15 units, which is a little too fast. I am aiming for 0.1 instead.
|
0 |
How to rotate an object to a specific transform? I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels?
|
0 |
Tile set showing grid with lighting Hi so I have this tile set generated procedurally at the start of the scene. When I activate the point light in the middle of the screen I keep getting this grid in the game view, i tried changing the size of the tiles but no luck if I change them before pressing play in the game view. But if I do it at run time from the inspector the bug goes away , hiding the square of the tile that I have moved...for that tile in particular even just moving it a bit solves it. This happens in edit and game mode ,and the grid is made of loads of sprites put together. The import settings of these sprites is dont generate mip maps, no compression. And each of the tiles have the default shader sprite diffuse. I deactivated gizmos but no luck either Any idea what can this be ? anything related with baking the light or something? thank you for your help!
|
0 |
How to override the NetworkManager in Unet properly? I need some customization on the NetworkManager Class for my game I'm working on. I've read, that it's pretty common to override stuff from the NetworkManager. So I've implemented the NetworkManager as CustomNetworkManager class like this using UnityEngine.Networking public class CustomNetworkManager NetworkManager I hope I'm right, that I don't have to implement a method to get all the functionality from the base class? I duplicated my NetworkManager Object, which basically was just the NetworkManager with another CustomNetworking Script. Then I replaced the old NetworkManager with my new CustomNetworkManager and changed the references in the other script accordingly. So my old GameObject looks like this And this is my new GameObject The old GameObject works (I just have to change the NetworkManager type in my CustomNetworking class) But the new GameObject with the custom implementation is getting the following error NullReferenceException Object reference not set to an instance of an object CustomNetworking.EnableMatchmaker () (at Assets CustomNetworking.cs 27) The CustomNetworking class with the error looks like this using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.Networking.Match using UnityEngine.Networking.Types public class CustomNetworking MonoBehaviour public CustomNetworkManager manager public MatchInfo currentMatch Use this for initialization void Start() manager GetComponent lt CustomNetworkManager gt () public void EnableMatchmaker() manager.StartMatchMaker() This is the first call which is made and where the error occurs public void CreateMatchmakerMatch() manager.StartMatchMaker() manager.matchMaker.CreateMatch( manager.matchName, manager.matchSize, true, "", "", "", 0, 0, manager.OnMatchCreate) public void FindMatchmakerMatch() manager.matchMaker.ListMatches(0, 20, "", false, 0, 0, manager.OnMatchList) if (manager.matches ! null) for (int i 0 i lt manager.matches.Count i ) var match manager.matches i manager.matchName match.name manager.matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, manager.OnMatchJoined) public void DestroyMatchmakerMatch() manager.client.Disconnect() manager.matchMaker.DropConnection(manager.matchInfo.networkId, manager.matchInfo.nodeId, 0, manager.OnDropConnection) manager.matchMaker.DestroyMatch(manager.matchInfo.networkId, 0, manager.OnDestroyMatch) manager.StopMatchMaker() public void StartMatchmakerMatch() manager.StartClient() manager.ServerChangeScene("MainScene") I think I did some failure with implementing the overwritten NetworkManager, hopefully someone can help me with this issue.
|
0 |
Stuck on walls or sliding on top dilemma I'm making a 2.5D platformer game. I earlier had problem with my character getting stuck on walls when holding the forward button. I solved this problem by adding a physics material with zero friction to my colliders on the wall. So now when hitting a wall the character slides down, which is correct. My walls consits of 1 unit cubes tiled together, and box colliders are generated and merged at runtime. Now I've created a ladder and by pressing a button the player will rotate 180 degrees, and I also add some force along the y and z axis var force transform.forward Vector3.up force.y JumpOffForceY force.z JumpOffForceZ rigidBody.AddForce(force, ForceMode.Impulse) Now when the player lands on the top of the wall, which has the same box collider, and physics material, the player slides very jerky for a long time before coming to a halt. I understand why this happens, I've been trying to find a solution. One solution I'm thinking of is to change my algorithm that creates the box colliders and divide them so there is one box collider on the top with higher friction, and one for the walls with zero friction. Before I delve into that, is that a good solution? Or is there any other way? Have a nice day!
|
0 |
Should I be concerned that my microtransaction based game will often be hacked? I used to play Diablo II, both online and offline. The game was so easily hackable offline that one could download a program called Hero Editor and, using a nice, comfortable interface, change their character in many ways. However, it was harder to hack the online portion of the game, and many that did were caught. Thus some of the game s content was restricted to online play, doubling up as a way to promote people playing together. Now I m making a mobile TD using Unity, targeting the iOS, Android, and perhaps PC Mac Linux platforms initially. Players would slowly earn some rare currency during play that can be used for permanently unlocking exciting (but non essential) extras, or they can just pay for them. I m concerned that if I allow this gradual unlocking to happen offline (without a server to confirm the accrual of said currency), then it ll be as easily hacked as Diablo II s offline mode and that many people would simply resort to doing that instead of either playing it through or paying for it. However, I m also reluctant to force online play, as the mobile environment has significantly lower network stability and this is a relatively long game to be playing in such conditions, so drop out is very likely. So my question is how concerned should I be about the mobile game getting hacked for the purpose of acquiring these unlocks without going through the correct methods? Is it so easy that your average user could do it, like they could for Diablo II, having the potential to significantly damage the game s bottom line? Or is it difficult such that only a small percentage of people who are interested enough would bother to try, so I can focus on providing the best UX for all players without worrying about these hackers? Brownies for anybody who can summarise how it may actually be hacked!
|
0 |
Unity Free Inverse Depth Mask? How would it be possible to create an inverse depth mask? In this case, I refer to a depth mask as a shader attached to a mesh that 'pokes a hole' through the current camera layer to let you see the camera render layer one depth down, usually by using ColorMask 0. What I want is for, instead, the mesh to determine what ISN'T cut out, without everything that is NOT seen through the mesh being cut out.
|
0 |
World Space canvas rendering in front of line mesh I'm attempting to attach a pointer to my steamvr controller to simplify world interactions. I'm very new to unity, but found a nice volumetric line asset (VolumetricLines) that aesthetically is exactly what I want. However, it seems to be rendering behind my canvas, as you can see here The canvas is set to world space with the event camera set to the VR camera, and renders properly for all world objects except this line. The line also renders properly with all objects except this canvas. What exactly is the mechanic that causes the line to render behind the canvas, when it renders in front of other game objects, and what could I do to fix the render order?
|
0 |
How can I turn a Unity game into an MRAID compliant playable ad? I need to create a mini game, one really simple scene, and export it as a playable that comply with the MRAID requirements. Basically, I can export a WebGL. The question is which adaptations the code needs to have (if any) in order to become compatible with MRAID. I saw the Luna tool that claims to solve this issue and export the scene on its own engine, to avoid any future adaptations, but honestly, I don't really understand what they're doing differently, if their engine still converts to JS and HTML5. It seems really blurry at the moment and I can't find concrete, coherent answers. All I'm getting from the company that approached my to get it done is quot it needs to be MRAID compatible quot . Does anyone have any experience and can shed some light on this subject? Thanks in advance, Omer
|
0 |
Can Unity support use textures that are not square? I have been told by another highly skilled Unity artist that Unity cannot efficiently handle non square images. Since that doesn't sound right to me, I wanted to get a second or third confirmation to that claim. Having worked in the game development industry for almost 15 years, I have always understood that best practice was keeping in powers of two, but that if the UV map called for it, a 1024x512 map was acceptable, rather than using a 1024x1024 map with 1024x512 pixels of wasted UV space. Granted, that was best practice on game engines other than Unity. Can anyone confirm that in Unity's case, it is better (best practice) to have a 1024x1024 image containing UV islands occupying 1024x512 pixels, rather than using a 1024x512 image map to exactly accommodate the UVs? Which platforms can use non square images and which ones cannot with the Unity engine? I am particularly interested in whether or not this limitation affects PC builds.
|
0 |
Unity Serialize IConvertible variable How can i Serialize IConvertible variable to show up in the inspector? As it now, i can only see the string name. But not the value. E.g adding CStat item.AddCStats("description", "This a long ranged boosted weapon.") item.AddCStats("attack", 10) item.AddCStats("speed", 50f) item.AddCStats("unique", true) System.Serializable public class Item ISerializationCallbackReceiver SerializeField public int id 0 SerializeField public int amount 1 SerializeField public List lt CStats gt cstats new List lt CStats gt () public Dictionary lt name, IConvertible gt cstatsDictionary new Dictionary lt name, IConvertible gt () public Item(int id, int amount) this.id id this.amount amount public void AddCStats lt T gt (string name, T value) where T IConvertible if (!cstatsDictionary.TryGetValue(name, out )) cstatsDictionary.Add(name, value) else cstatsDictionary name value for (int i 0 i lt cstats.Count i ) if cstats i .name name) cstats i .value value return cstats.Add(new CStats(name, value)) public T GetCStat lt T gt (string name) where T IConvertible return cstatsDictionary.TryGetValue(name, out IConvertible value) ? ConvertToType lt T gt (value) default public void OnAfterDeserialize() cstatsDictionary new Dictionary lt string, IConvertible gt () for (int i 0 i lt cstats.Count i ) cstatsDictionary.Add(cstats i .name, cstats i .value) public void OnBeforeSerialize() private T ConvertToType lt T gt (IConvertible value) where T IConvertible return (T)value.ToType(typeof(T), null) System.Serializable public class CStats SerializeField public string name String.empty SerializeField public IConvertible value null public CStats(string name, IConvertible value) this.name name this.value value
|
0 |
How do you render planets without distortion? I've recently been working on a little spaceship flying sim in Unity and want to add planets. Up till now, I've been hand modeling them in Blender. But I want to have a way to generate large planets with heightmaps. While researching the topic, I found this video about a voxel planet game and its tech, Here. In the video, they describe a way to render a planet with low distortion. They also relate it to how No Man's Sky does it. My question is, Are there other methods of rendering planets that have zero distortion? I would prefer if the answers wouldn't be Unity3D specific since i'm considering switching to Monogame or DirectX. Thanks in advance! Edit. I've been asked to describe the distortion. The distortion is what happens when a cube gets mapped to a sphere. The video suggests a method of using shader warping when on the ground but using the method of squishing a cube to a sphere when in space. This method causes a noticeable warp when going from space to ground because it switches rendering methods. My question is if there is a way to prevent that warp and provide a truly seamless transition from space to ground. One more edit, I have found another video on a seamless planet engine called Outerra here It seems to have no warping when leaving the atmosphere. It can be seen at 0 50 and at2 22 in this video.
|
0 |
How to create rotating mode selection knob on multimeter I want to create something looks similar to this for electrical and electronic troubleshooting simulationw. I need to know how to program the drag interaction that and rotates the knob to select the mode of operation. I checked several videos including this one, but this is not what I'm looking for. I am hoping to drag and rotate the knob in a circle. I also need to know how to set the operating mode based on rotation. For instance, if the knob is pointing at 0 5 degrees (after drag and release), the knob position is set to 0, and the device is in off mode if it is at 85 95 degrees then angle 90 degrees, and the device is set to resistance measurement mode.
|
0 |
How do I set meshCollider.cookingOptions to MeshColliderCookingOptions.Everything in code? I'm procedurally generating some meshes for a project, and I need to add colliders to them. The meshes are generating fine, but after setting the shared mesh in the mesh collider, I need to be able to set the cookingOptions to Everything. In the inspector, I can do this fine and the colliders work correctly. Since I am generating these at runtime, I can't really do this after making a build. How do I go about doing this? Works Correctly Does not Work Correctly
|
0 |
Unity open UI from ScriptableObject I have a Canvas that has multiple UI Panels in it for an inventory, crafting, etc. To open these panels I currently have a monobehaviour class on the Canvas with methods like OpenInventory(), etc. For every item within the inventory I use ScriptableObjects. However, some items open the crafting panel when right clicking, I created a class that extends the Item class and added a method to it that gets added to the inventory slot and gets called when right clicking that item. Because the monobehaviour on the Canvas is an instance, I can't access it from a ScriptableObject. Long story short, is there a way to open a UI panel from a ScriptableObject? If not, what would be the best way to fix this issue?
|
0 |
An invisible object that deletes anything behind it? I am using augmented reality to put a 3D object on top of a "camera detected" object. The 3D object can be though of as leaves that go above the real world object but also fall in front behind on the sides of it. The leaves are not uniform so they appear as arcs which let more of the "camera detected" object be seen in some parts and less in others. Because of this I want to only show the leaves that would normally be seen if there was a real 3D object (instead of the camera detected one) in that place. But since the camera detected one is just a background image part of the leaves on the side or behind are seen when the object is rotated. I was thinking it might be possible to use an "invisible" object that moves and rotates the same way as the "camera detected" one so it behaves as a placeholder for depth testing but is not actually rendered. Is this possible? May I have some pointers on how to achieve this? Thank you
|
0 |
FBX animation works in 3DSMax but not with Assimp I have an FBX file that represent a plane with an animation of the gear opening. In my editor 3DSMax or in the Unity editor, the file and animation seem good, but when I use Open 3D Model(the official viewer of Assimp) or when I call the FBX file simply in an application, to see what the file will look like with the use of Assimp, I got some issues. The object seems normal at the beginning, but when I try to launch the animation, all my animated elements are going crazy. Here's what it looks like Here's my FBX FILE Do you have experience something similar ? Does it come from my file or a parameter in Assimp ? I am beginning to think that there is a problem with how Assimp handles pivot points, looks like objects are rotating using a different pivot point in Unity open3mod.
|
0 |
How to set "useGravity" for Rigidbody to entities in Unity For the position you can use this Inject private ComponentDataFromEntity lt Position gt position But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities?
|
0 |
Setting a texture's "Max Size" while ensuring that its dimensions are still multiples of 4 A version of my game has several large textures with dimensions that are multiples of 4 so that Crunch compression can kick in. A ported version of my game, for platforms that have very limited RAM restrictions, will need us to limit the quot Max Size quot of our textures to 512 or 256, etc. There are some cases in which a Crunch friendly texture, when resized by Unity's quot Max Size quot parameter, will actually end up with dimensions that aren't multiples of 4. 944x800 would end up as 512x434, if we select quot 512 quot , which isn't good for Crunch. The naive solution in my mind is to write a simple script tool that resizes pads all my textures by a couple of pixels in such a way that Unity's resize will end up in a Crunch friendly way. However, I'd rather do that as a last recourse if possible. Is there a more standard way to approach this situation of mine?
|
0 |
Unity UNET, problems spawning and then destroying that instantiated prefab I am very new to networking, and have ran into an issue, read below. I have multiplayer system setup, where players can spawn, they can pick up weapons and drop them, there is an object representing a pickup with network identity component attached and local player authority enable, the player can come up to it and press "E", which will destroy the pickup object, then the player can press I to to "drop" that weapon, which instantiates it infront of the player, now this is what should happen, and it works on single player, but when there's 2 players, for second player(client only) it doesn't work as it should. I have 1 script weapon manager and another small, Pickup (on pickup object child with trigger). Below is the code and according description of my attempt so far Below is PickUp script (on 1st child of pickup object with trigger enabled) private void OnTriggerStay(Collider other) if (other.CompareTag("Player")) if (Input.GetKeyDown(KeyCode.E)) Call pickup function on player, passing the weapon id and parent gameobject other.GetComponent lt WeaponManager gt ().PickUpWeapon(weaponID, transform.parent.gameObject) Below is WeaponManager script (on player) public void PickUpWeapon(int id, GameObject go) CmdDestroyObj(go) ... (other code, not relevent) Command void CmdDestroyObj(GameObject obj) RpcDestroyObj(obj) ClientRpc void RpcDestroyObj(GameObject obj) HERE obj is NULL (!!ERROR!!) Destroy(obj) Above in RpcDestroyObj() obj is null void Update() if(isLocalPlayer) if (Input.GetKeyDown(KeyCode.I)) if (slots currentActiveSlot ! null) CmdDropWeapon() Then here's CmdDropWeapon() function Command void CmdDropWeapon() RpcDropWeapon() Here's RpcDropWeapon() function ClientRpc void RpcDropWeapon() GameObject drop (GameObject)Instantiate(drops currentGun.GetComponent lt WeaponStats gt ().id , transform.position transform.forward, Quaternion.identity) drop.GetComponent lt Rigidbody gt ().AddForce(transform.forward 25000f Time.deltaTime) CmdDestroyWeaponHeld() Destroy currently held weapon (don't pay attention, not relevent to current problem currentGun null if (isLocalPlayer) GetComponent lt PlayerSetup gt ().playerUIInstance.GetComponent lt PlayerUI gt ().SetInventorySlotFill(currentActiveSlot, 1) emptyHanded true On single player (so host amp client), everything works besides destroying the pickup prefab that is Instantiated. On multiplayer, second player (client only), can pick up and drop weapons as well as the originally spawned weapon is destroyed, but destroying the newly instantiated (so after player drops it) pickup object doesn't work. (In the console there are no errors when UnityEditor is the Lan host server, when 2 players are playing and I try picking up and dropping weapons several times from client side) Why is this not working? I would appreciate any help assistance in getting this right and sync over network for all players. My guess is that, rpc function Instantiates the drop prefab but it's kind of different on all clients, so the server or another client doesn't have exactly the same object in the scene which means it will not find it and return null. Let me know if you need any additional information. Thanks a lot in advance!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.