_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Blinking color shader Currently i'm using Unity3D, and i want to make one variable blink along time in a fragment shader. Now i have code like this half4 frag(v2f i) COLOR float4 r OutlineColor r.a r.a SinTime return r But this blinking is too slow and not suit me, any ideas ? |
0 | What is the geometrical interpretation of Input.GetAxis("Mouse X")? According to the documentation, Input.GetAxis("Mouse X") produces a range of values from 1 to 1. However it will produce another range if it is setup to be delta mouse movement. Returns the value of the virtual axis identified by axisName. The value will be in the range 1...1 for keyboard and joystick input. If the axis is setup to be delta mouse movement, the mouse delta is multiplied by the axis sensitivity and the range is not 1...1. Question I don't understand what the value means geometrically. Is it a displacement between two points each in consecutive frame updates? If so what is its unit? Pixels, points, centimeters, etc? |
0 | OnCollisionEnter only triggering if colliding object starts inside collider Despite the absurdly high number of "OnCollisionEnter not working" threads around the internet, no one else seems to have had this specific problem. To start off with, I have a spherical "shield" object around my ship, which has a shader designed to give off impact effects when hit by an object. To trigger the shader impact effect, you need to give it the position from which do the effect. So, the easiest way to do this is to give the shield a Collider and, whenever OnCollisionEnter is called, it sends the contact.point details to the shader. That's not the difficult part. The part that isn't working is that OnCollisionEnter is not being called when the laser bolt fired at the shield actually collides with the shield. Both the shield and the laser bolt have Sphere colliders, both are not triggers. Only the shield has a rigidbody, which is not kinematic. void OnCollisionEnter (Collision collision) Debug.Log (Time.time) if (collision.transform.tag "Impact") Debug.Log ("go") Does the shader stuff That script is attached to the shield object. Not only is "go" never being logged, but neither is the Time, so OnCollisionEnter is not being called. The odd thing about this scenario is that, OnCollisionEnter will be called by objects that begin inside the shield's collider so if I start the laser bolt inside the shield, then the function gets called as usual. But when I start the laser outside the shield and Translate it into the shield, nothing happens. For the life of me, I can not work out what's going wrong with it. |
0 | How do I make dialogue only appear once? So I made it so when I walk over a NPC it brings up 12 lines of dialogue, and you press E to get to the next line. When the dialogue is over you can keep pressing E and it will bring the dialogue up every time. I want it so it only brings the dialogue up once. How do I do that? This is my script for it using System.Collections using System.Collections.Generic using UnityEngine public class dialogHolder MonoBehaviour public string dialogue private DialogueManager dMan public string dialogueLines public float questComplete Use this for initialization void Start() dMan FindObjectOfType lt DialogueManager gt () Update is called once per frame void Update() private void OnTriggerStay2D(Collider2D other) if (other.gameObject.name "Shrump") if (Input.GetKeyUp(KeyCode.E)) dMan.ShowBox(dialogue) if (!dMan.dialogActive) dMan.dialogLines dialogueLines dMan.currentLine 0 dMan.ShowDialogue() |
0 | Health zone heals player but I have a problem Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this? Here is the health zone script. public PlayerHealth playerHealth public float healthGain 2f void OnTriggerStay2D(Collider2D other) if (playerHealth.currentHealth lt playerHealth.maxHealth) playerHealth.currentHealth (int)healthGain playerHealth.healthBar.SetHealth(playerHealth.currentHealth) if (playerHealth.currentHealth gt playerHealth.maxHealth) playerHealth.currentHealth playerHealth.maxHealth playerHealth.healthBar.SetHealth(playerHealth.currentHealth) |
0 | Unity Shader Outlined Uniform uses undefined Queue 'Geometry 1' my outline shader was working fine but suddenly it started throwing this error. the game still works fine in the editor though but when i try to build it gets stuck on the step Packing assets sharedassets0.assets this is my shader Shader "Outlined Uniform" Properties Color("Main Color", Color) (0.5,0.5,0.5,1) MainTex ("Texture", 2D) "white" OutlineColor ("Outline color", Color) (0,0,0,1) OutlineWidth ("Outlines width", Range (0.0, 2.0)) 1.1 CGINCLUDE include "UnityCG.cginc" struct appdata float4 vertex POSITION struct v2f float4 pos POSITION uniform float OutlineWidth uniform float4 OutlineColor uniform sampler2D MainTex uniform float4 Color ENDCG SubShader Tags "Queue" "Geometry 1" "IgnoreProjector" "True" Pass Outline ZWrite Off Cull Front CGPROGRAM pragma vertex vert pragma fragment frag v2f vert(appdata v) appdata original v v.vertex.xyz OutlineWidth normalize(v.vertex.xyz) v2f o o.pos UnityObjectToClipPos(v.vertex) return o half4 frag(v2f i) COLOR return OutlineColor ENDCG Tags "Queue" "Geometry" CGPROGRAM pragma surface surf Lambert struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 c tex2D( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG Fallback "Diffuse" i tried looking on the internet but couldn't get any help on this error. |
0 | Colliders slightly intersecting each other any solution? Consider this simple scene In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider. And the problem if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall. This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist. Is there a workaround? How can the box smoothly move across the floor without colliding with the seam? Notes This does occur with capsule colliders but rare and is not very noticeable. A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks. This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity position of the transform. |
0 | How can I resize the Unity Facebook SDK's login dialog to fit my vertical phone screen? I have a Facebook login button for my iOS game, but Facebook's login panel is entirely too big The panel is cut off on both sides. It allows for input, but I cannot see most of it. My aspect ratio is 2 3 for vertical phone screens. I tried to use FB.Canvas.SetResolution and .SetAspectRatio both did nothing. I have not attempted to view this on an iPhone yet, only in my Unity debug view. I have never worked with Facebook SDK before, and can't find this issue discussed elsewhere, so help would be appreciated! |
0 | In Unity, can I make a GameObject within a prefab disabled by default? If I create a simple object hierarchy in my scene... ExampleGameObject Child1 is active Child2 is not active ...how can I accurately store this as a prefab? If I drag ExampleGameObject to a new prefab, then instantiate that prefab, both Child1 and Child2 will be active, which isn't what I want. |
0 | How to make an illusion where the contents of a 3D shape change based on which face you look through? I remember coming across a Unity 3D tutorial where there was a technique where the contents of a 3D shape change based on which face you are looking at, similar to this screenshot from Antichamber What is this techique called? And how do I implement it into a Unity 3D project? Thanks in advance. |
0 | How to physically move a rigid body up the stairs? When an object is controlled by a CharacterController, it is easy to make it climb ramps with a certain slope, or climb steps with a certain height. When the object is controlled by a RigidBody instead, it can still climb ramps naturally I just use AddForce and it walks on ramps just like on any other surface. I do not have to add any special logic for a ramp. However, it does not climb stairs. Is there a natural "physical" way to make the RigidBody climb stairs, without explicitly checking that there are stairs ahead? |
0 | Game states passing data between scenes I'm not entirely sure if I'm doing this right, but I always considered the scene system in Unity as some sort of state management (rather than e.g. a level system) which allows to group the contents (entities, components) into the usual main states of the game (menu, ingame), which can then be invoked or replaced together. Now I have a very specific concern and I have no clue how to deal with that in Unity, mostly because of it's abstractions from code and other restrictions My game features a procedurally generate terrain where as I'd like to tweak the generator before actually launching it. The tweaking is done in some sort of 'pre game' state (as part of the main menu) where the values are stored in e.g. TerrainData model class. Usually in other engines, I'd to it like this Providing an UI within the menu state to tweak the parameters of the game Storing the parameters in a view model (and data model) Instantiate the ingame state (which requires said data model in the .ctor Pass the data model to a generator and start the generation Now, here are the main problems Most types in unity (scenes, monobehaviors) do not allow constructors because they use it for themselves It doesn't seem possible to instantiate scenes manually (there's only e.g. Application.LoadLevel("") which only takes the name of the scene, not a instance reference etc. it doesn't seem possible to pass data between scenes, without reverting to awkward workarounds such as singletons, playerprefs, DontDestroy etc. which are all not really suitable for this case. So, how can I properly solve this? Is there a better way to manage states rather than scenes? Prefabs maybe? Backlink to UntityAnswers question http answers.unity3d.com questions 1149480 game state management and passing data between sce.html |
0 | Custom 2D physics on unity I have seen a lot of people think that for a 2D platformer game, Unity2D physics is not really the best approach, and recommend implementing your own physics. I found the idea interesting, but I don't know how to approach the issue. Using 2D Rigidbodies, and setting them as kinematic, allows you to ignore unity's physics. But how would collisions be handled without relying on Unity collision system? |
0 | Trying to 'stamp' an arbitrary assortment of pixels to a texture2d that may be rotated at an arbitrary angle This one is hard to explain but I'll try to not to overcomplicate it. Engine is Unity, for reference. I have a system where an object has a 2d texture to display a custom splat map. The user can 'paint' to this texture, which uses world space coordinates of the mouse to see which pixel should be painted to. They can also paint larger shapes, which are essentially just implementations of square circle drawing algorithms that choose what pixel coordinates to paint to based off the starting world space coordinates. This works fine while the object texture are unrotated, but if I rotate the object an arbitrary amount of degrees (say, 45 for the most extreme result), like squares and circle etc are drawn to the texture with missing pixels. I assume this is because the 'grid' of the texture is now rotated, and because I'm still trying to 'stamp' the shape in the original world space orientation (without respect to the rotation), the pixel 'sizes' or coordinates aren't the same? I can't post screenshots as I'm at work, but this is what my desired output would be (Ignore the pixelisation, had to use an online crappy paint program), where the first square is the object in its original rotation, with a red square stamped on to it as expected. The second square is after the object is rotated 45 degrees, and the yellow square stamped on it is what I want (and what is currently appearing with missing pixels in my implementation). EDIT And here is the actual result I'm getting, pixels per unit is 16. The first square was stamped, the rect then rotated 135 degrees, and then the second square was stamped (shown with the missing pixels) Anyone have any idea how I would go about drawing onto a rotated texture like this without ending up with missing pixels? I can post code snippets build images later. EDIT This is the code executed on the object to register a single pixel draw (very loosely), which uses the RotatePointAroundPivot function to get the pixel on the original pixel grid location in world space by rotating the point against the transforms current rotation. This works perfectly for individual pixel draws from mouse position clicks, but with the larger shapes I end up with the issue described void DrawToTex(Vector2 worldPos) worldPos RotatePointAroundPivot(worldPos, transform.position, transform.rotation.eulerAngles) (xPixelCoordinate, yPixelCoordinate) GetPixelCoordinatesFromWorldPos(worldPos) pixels xPixelCoordinate, yPixelCoordinate color public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) return Quaternion.Euler(angles) (point pivot) pivot public void DrawSquare(Vector2 worldPos, int size) (int startXCoord, int startYCoord) GetPixelCoordinatesFromWorldPos(worldPos) Literally just gets an array of the correct size int , squareMatrix GetSquareMatrix(size) sizeHalved size 2 pixelWorldSize 1f pixelsPerUnit pixels per unit is 16 in my build for(int x 0 x lt size x ) for(int y 0 y lt size x ) int newX startXCoord sizeHalved x int newY startYCoord sizeHalved y Vector2 pixelWorldPositionToDraw worldPos new Vector2((newX startXCoord) pixelWorldSize, (newY startYCoord) pixelWorldSize) DrawToTex(pixelWorldPositionToDraw) (int, int) GetPixelCoordinatesFromWorldPos(Vector2 worldPos) float xMin bounds.min.x float yMin bounds.min.y float distFromStartX worldPos.x xMin float distFromStartY worldPos.y yMin float xScaled distFromStartX pixelsPerUnit float yScaled distFromStartY pixelsPerUnit int xPixelCoordinate (int) xScaled int yPixelCoordinate (int) yScaled return (xPixelCoordinate, yPixelCoordinate) |
0 | How to generate multiple particles at once? I am tying to create a cartoony balloon pop animation. I want there to be particles that come from all sides of a sphere. However they should all come at once, in a single burst. What I've done is this. I generated a particle system as a child of the sphere. I set the shape to sphere, reduced the duration, and increased the rate. However it doesn't seem like any particles are being generated at the same time still, only one is created at once. How can I make all of the particles come at the same time? |
0 | How to build a hidden 3D snapping grid effect? Looking to build a 3D grid similar to the image below taken from Google Blocks. Seems like it consists of these main components A set of spheres that can go transparent. A stencil that follows the controller's location. When stencil overlaps with spheres, they show up, otherwise, alpha fades to zero. Any advise on how to approach building this? |
0 | Get Closest point between a Box 3D and a Point I have a point A (x, y, z), and a Box Center (x, y, z), Size (Width, Height) How to get the closest point in the box from the point A ? In Unity I can create a bound, and I can find the non rotated position like that Bounds bounds mesh.bounds Vector3 closestPoint bounds.ClosestPoint(pointA) But then If the bound is rotated, the result is not correct. So I have 2 options Find the way to rotate my closestPoint from the pivot. Find the math formula myleft. If someone can help ! thanks. EDIT here a video the red point is the one find with bound.ClosestPoint the yellow point is the one find with Vector3 closestPointInverse currentTarget.InverseTransformPoint(closestPoint) https youtu.be RMRRtSaJv8w I have also tryed to do my own rotateFromPivot function public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) return Quaternion.Euler(angles) (point pivot) pivot When I use it, I get the same result with the InverseTransformPoint method. |
0 | How can I move two couple of objects? Now it will move all the objects of allLines and instancesToMove at the same time. But I want to take each time one object from the allLines and one from the instancestoMove and move this two together then the next two objects and so on. if (animateLines) counter for (int i 0 i lt allLines.Count i ) endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(startPos, endPos, counter 25f speed) if (Vector3.Distance(instancesToMove i .transform.position, endPos) lt 0.1f) DestroyImmediate(instancesToMove i ) instancesToMove.RemoveAt(i) DestroyImmediate(allLines i ) allLines.RemoveAt(i) Both allLines and instancesToMove are List |
0 | Can I export animated models from Unity? Into what formats? I have an animated 3D model from the Unity Asset Store that I would like a new animator to touch up (the license allows this). But they need it in a format they can use (in Maya or... something else?). All I have been able to find so far is how to export from the Editor into Unity Package format scripts to export the mesh (only?) into OBJ format 1 Is it possible to export a textured and rigged model from Unity? If so, into what formats and how? 1 ObjExporter and ExportOBJ |
0 | Recursively find neighbors I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors. Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow. private List lt Bubble gt FindAllRecursiveNeighbors(Vector2Int originPosition) List lt Bubble gt allNeighbors FindNeighbors(originPosition) List lt Bubble gt result new List lt Bubble gt () foreach (Bubble bubble in allNeighbors) if (result.Contains(bubble)) continue result.Add(bubble) Recursion starts here. foreach (Bubble bubble in result) List lt Bubble gt neighbors FindAllRecursiveNeighbors(FindPositionOfBubble(bubble)) foreach (Bubble neighbor in neighbors) if (result.Contains(neighbor)) continue result.Add(neighbor) return result |
0 | Unable to list target platforms. Please make sure the android sdk path is correct For some reason, I am unable to test my android program because of this error. Here are some pictures of the errors. This error is not allowing me to test my app on my test Android device, I have tried uninstalling and reinstalling, checking if it is acatually the root folder, everything, PLEASE HELP! 1st error CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. C Users jayso AppData Local Android sdk tools bin avdmanager.bat list target c stderr stdout ERROR JAVA HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA HOME variable in your environment to match the location of your Java installation. exit code 1 UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunAndroidSdkTool (System.String toolName, System.String arguments, Boolean updateCommand, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.ListTargetPlatforms (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit) UnityEditor.Android.AndroidSDKTools.GetTopAndroidPlatformAvailable (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK SDKPlatformDetector.GetVersion (UnityEditor.Android.AndroidSDKTools sdkTools) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK SDKComponentDetector.Detect (UnityEditor.Android.AndroidSDKTools sdkTools, System.Version minVersion, UnityEditor.Android.PostProcessor.ProgressHandler onProgress) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (System.Version minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (Int32 minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.BuildPlayerWindow BuildPlayerAndRun() 2nd Error Error building Player CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. C Users jayso AppData Local Android sdk tools bin avdmanager.bat list target c stderr stdout ERROR JAVA HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA HOME variable in your environment to match the location of your Java installation. exit code 1 |
0 | Activating particle system after 2 triggers on enter I would like that particle system must play indefinetely at some position after two triggers on collision are triggered on enter. When game starts, particle system is deactivated. I have make this script where I can attach particle system into prefab and I have set spawnpoint position. 1) Is it possible to activate particle system differently (without Instantiate) ? 2) How to make that two triggers on enter activate particle system? One trigger is not enough. using System.Collections using System.Collections.Generic using UnityEngine using System.Collections using System.Collections.Generic using UnityEngine public class spawn object MonoBehaviour public Transform spawnpoint public GameObject prefab public int i 1 Use this for initialization while (if lt 2) void OnTriggerEnter () Instantiate (prefab, spawnpoint.position, spawnpoint.rotation) i |
0 | How to convert RotateAround speed to directional speed in Unity? I am currently using transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond Time.deltaTime) to make an object rotate around another object. This works well, but I want to make the object stop rotating around and instead move in a certain direction at the same speed that it was rotating. However, I can not figure out how to convert the degreesPerSecond into a directional speed. My goal is to have something like this if(rotating) transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond Time.deltaTime) else transform.position transform.right DegreesToDirectionalSpeed(degreesPerSecond ) Time.deltaTime float DegreesToDirectionalSpeed(int degrees) Code that I don't know goes here Any tips on how to achieve this? |
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 | What's the proper way to use static objects and singletons in Unity? I have a GameObject in Unity, which I've attached this script to, in order to make it function as a Static Singleton using UnityEngine using System.Collections public class SceneStatics MonoBehaviour private static SceneStatics instance public static SceneStatics Instance get if (instance null) instance new GameObject ("SceneStatics").AddComponent lt SceneStatics gt () DontDestroyOnLoad(instance) return instance public void OnApplicationQuit () instance null I have two other scripts that I'd like to be able to access from scene to scene. What's the proper way to do that? Do I attach my Inventory and Room scripts to the same game object as the SceneStatics? If so, how do I access them? Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent? Alternatively, what happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics? Or is the intended use that I simply make any other static items I need properties of the SceneStatics class? (I.e., add in a Public static Inventory and Public static Room attributes)? |
0 | GUI.Button inside GUI.Window not responding I am trying to do some GUI work with unity but am having some issues. I call a window with this code fortuneRect GUI.Window(0, fortuneRect, fortuneWindow, "Your future") and inside the window I have a button if(GUI.Button(new Rect(10, 10, 150, 20), "save fortune")) Debug.Log("save fortune button press") writeToFile("Button pressed!", "fortune.txt") Debug.Log("After save fortune button press") but the button doesn't fire any of its events on click. I tried commenting out the writeToFile but even with only Debugs in the body it doesn't fire. |
0 | Is it possible to apply a texture to a 2D sprite in unity 2 d? I want to take an (animated) 2 d sprite and apply a texture to it. Basically, I want every non transparent pixel to be covered by the texture (color is disregarded). I understand I can probably accomplish this using masks but I am worried that may not be the most performant solution. I know you can put textures onto 3 d models, so I was wondering if there was a similar process for 2d sprites. Below I have a graphic demonstrating what I want. What I have tried so far I see there is an option to add a material to a sprite, so I tried creating various materials. 1. Default material When I tried applying this material to my sprite, the sprite disappeared entirely. I suspect because this default material type only works on 3D objects 2. Sprite Material I figured sprites probably expect sprite materials, so I tried creating one. However, there does not appear to be anywhere to upload an image to use as a texture. This appears to only be useful for adding tints to sprites. |
0 | Find closest point on NavMesh if current target unreachable I have a mock environment set up with a cube that has a specified "Not Walkable" layer. I'm using NavMeshAgent and NavMeshPath to set destinations of the player. The way I'm setting paths is by ray casting points on the terrain by mouse clicking. I'm having trouble figuring out a way to fix if I click on the cube that has a "Not Walkable" layer, the player just runs into the cube and tries to reach that point. I've read about the FindClosestEdge function in unity but I don't think that's exactly what I'm looking for. So basically I need the target location to change to the nearest point next to the cube when I click on the cube. Any ideas? |
0 | How can the player select his weapon among many? I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https youtu.be Dn BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded? I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project. sorry for the bad english |
0 | Not able to find the constraints option in the Rigidbody component I am working on a game tutorial right now and I need to freeze constraints for a model prefab. I add a Rigidbody component and I want to freeze rotations on the x and z axes. However, I am not able to find the option in the component. Is there another way to access rotation constraints (I do not want to code the constraints at the moment)? Or is there something I am missing in the new version. Please do let me know. Thanks I am using Unity 5.6.7f1 Personal |
0 | Gravity not being applied to character, using character controller So I just copy and pasted the unity example class to use with my character controller. public float speed 6.0F public float jumpSpeed 8.0F public float gravity 20.0F private Vector3 moveDirection Vector3.zero void Update() CharacterController controller GetComponent lt CharacterController gt () if (controller.isGrounded) moveDirection new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) moveDirection transform.TransformDirection(moveDirection) moveDirection speed if (Input.GetButton("Jump")) moveDirection.y jumpSpeed moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) The code seems to work okay if I comment out the isGrounded check statement (which means that gravity isn't being applied). So what could be the reason that the gravity is not being applied to my character controller? |
0 | Couldnt visualize the mechanism describe by the code Was reading this article http www.jgallant.com 2d liquid simulator with cellular automaton in unity but couldn't understand the mechanism in quot CalculateVerticalFlowValue quot . Is the remaining liquid represent the tile just above the tile quot destination liquid quot ? Would appreciate if can provide simpler example to visualize the mechanism as I couldn't see the logic behind this code. using UnityEngine using System.Collections.Generic public class Liquid Max and min cell liquid values float MaxValue 1.0f float MinValue 0.005f Extra liquid a cell can store than the cell above it float MaxCompression 0.25f Lowest and highest amount of liquids allowed to flow per iteration float MinFlow 0.005f float MaxFlow 4f Adjusts flow speed (0.0f 1.0f) float FlowSpeed 1f Keep track of modifications to cell liquid values float , Diffs public void Initialize(Cell , cells) Diffs new float cells.GetLength (0), cells.GetLength (1) Calculate how much liquid should flow to destination with pressure float CalculateVerticalFlowValue(float remainingLiquid, Cell destination) float sum remainingLiquid destination.Liquid float value 0 if (sum lt MaxValue) value MaxValue else if (sum lt 2 MaxValue MaxCompression) value (MaxValue MaxValue sum MaxCompression) (MaxValue MaxCompression) else value (sum MaxCompression) 2f return value |
0 | Objects stick together on Collision I have a ball which has CircleCollider2D attached to it. It is also rigidbody. When it lands on a platform, it jumps . The platform is static, with Edge Collider attached. It also has a platform effector attached with quot Use One Way quot selected. Most of the times it works fine, but some times, the ball lands on the platform and instead of bouncing, just sits on the platform. When ball lands on the platform, following code is executed rb.AddForce(upForce, ForceMode2D.Impulse) upForce is Vector2(4,10) image shown below Why is this happening? |
0 | Are the prefabs stored in RAM or in the Hard disk? (Unity3D) I have many prefabs objects (65 MB) in an Unity3D project. My game use 100 different levels with combinations of the prefab objects. What is better create 100 scenes or create only one scene where the prefab objects are placed with data from a XML?. Each Scene load your own prefab objects? Are the prefab objects loaded in the RAM when the scene is loaded or are stored in the hard disk and then loaded in the RAM when come in the scene? |
0 | Matching collider to character mesh size in different postures What's the optimal method in Unity to match the size of a Capsule Collider to the actual size of the game object it is part of? To understand what I'm trying to do let me give an example I have a 3D player character with a Capsule Collider that is used to check collision. The character can go into various postures, e.g. crouch, prone, jump. I'm having difficulties to match the height of the collider to the height of the character when crouching or jumping because depending on the used animations the character's height is smaller by various amounts when crouched or jumping. All I could do so far is set a multiplier for a specific posture by that the collider scales but this is very inefficient, especially when the character tries to jump onto a higher ground. There seems to be no way of knowing the exact size of a mesh. I'm not sure if it might help to loop through all child meshes (torso, hair, etc.) in a game object and obtain their bounds through SkinnedMeshRenderer. |
0 | Creating a list of buttons dynamically in code I have a list of contacts. I need to create a scrollable list of buttons that are created dynamically so I can add each contact name as the button text. How would I do this all in code? My biggest concern is making sure the sizes stay consistent. I haven't had to do that in code before. EDIT And here is the code to add the buttons to this for (int i 0 i lt count i ) if (i gt 0) crt.sizeDelta new Vector2(crt.sizeDelta.x, crt.sizeDelta.y initHeight) GameObject contactButton Instantiate(Resources.Load("Contact Button")) as GameObject contactButton.transform.parent contactsList.transform contactButton.GetComponentInChildren lt Text gt ().text names i |
0 | Box collider rigid body eventually moves through static collider I found this question, but I'm not sure if it applies to my problem. I'm hacking together a Pong style game, and my problem is with the walls (box collider, no rigid body) not completely stopping movement of the player paddle (box collider, yes rigid body.) Sufficiently fast mouse movement eventually moves the paddle through the wall. There is initial resistance, but I would expect Player Paddle to stop moving abruptly at the wall. How can I make this happen? I'm new to Unity colliders game dev. My player paddle simply moves up and down (Z axis) with up down mouse movement public class MouseMovement MonoBehaviour public float speed 10f Update is called once per frame void Update () var translation Input.GetAxis("Mouse Y") speed translation Time.deltaTime transform.Translate(0, 0, translation) I exported an asset package that reproduces the problem. My problem objects are Player Paddle, Upper, and Lower https www.dropbox.com s yx9svb51nywdvgg pong export.unitypackage?dl 0 |
0 | Tracking small moving targets in Vuforia I am trying to track up to two small moving objects the size of a small toy car (about 7x4x4 cm 3x2x2 ) from a 75cm 2ft distance. I m aware that the distance size ratio is about 20, which is off by factor compared to the by Vuforia recommended ratio. I've tried frame markers and while frame markers are super fast close up, they don't work well at a distance. I'm hesitant to use expensive object recognition on moving targets. I ve tried black and white QR codes and AR markers as image targets but Vuforia seems to have trouble recognizing them, even though the QR code has a five star rating. I m considering two more options 1) an optimized 4x4cm color image target 2) add LEDs to the objects and track the LEDs, for example like this https www.youtube.com watch?v IoL0bIGk uE My questions 1) Are there specific tips for creating small image targets (I have read the generic image target optimizations tips assume not all those tips apply to small targets) 2) Is there an easy way to track LEDs in Vuforia? |
0 | How do I check if there is already an object in this scene with the same name upon reloading the scene? If the title wasn't clear enough (I don't really know how to explain it), basically I have an Audio Manager that is DontDestroyOnLoad. I also have a pause menu, that takes me back to the main menu, and in the main menu, I can reload the scene again. The problem is, upon reloading the scene, multiple copies of AudioManager is created in DontDestroyOnLoad, and I don't know how to solve it. My AudioManager script to give you a reference (only the important parts) using System.Collections using System.Collections.Generic using UnityEngine public class AudioManager MonoBehaviour region Instances private static AudioManager instance public static AudioManager Instance get if (instance null) if instance doesn't exist, find an AudioManager instance FindObjectOfType lt AudioManager gt () if (instance null) if instance still doesn't exit, then it will create a new one instance new GameObject("Spawned AudioManager", typeof(AudioManager)).GetComponent lt AudioManager gt () return instance private set instance value endregion region Fields the audio source can only play one looping sound at a time private AudioSource musicSource private AudioSource musicSource2 purpose of having 2 musicSources is that we can use them to achieve effects like CrossFade private AudioSource sfxSource private bool firstMusicSourceIsPlaying endregion private void Awake() Make sure we don't destroy this instance DontDestroyOnLoad(this.gameObject) Create audio sources, and make them as references musicSource this.gameObject.AddComponent lt AudioSource gt () musicSource2 this.gameObject.AddComponent lt AudioSource gt () sfxSource this.gameObject.AddComponent lt AudioSource gt () loop musicSource musicSource.loop true musicSource2.loop true If you are reading this, thanks for taking your time and try to help me! |
0 | How to solve problem with Terrain Flashing and then disappears when flying away? I am making flight simulator( my first Unity project) , the biggest challenge so far is terrain, so whenever I fly away from it (not that far) the terrain starts flashing and disappears which is just green mountains, so when i come back to it, i have no idea where its position is, but it suddenly appears (again flashing) when I am close , the terrain size is normal but it's on top of a huge other terrain (about 100,000 100,000 which is the max),I tried changing pixel error and base map distance, no change, I looked at big terrain solutions online, but non of them really helped me, Any advice? Thanks |
0 | Unity 5 The Editor has stopped working Windows 7 64bit As soon as I press the play button to attempt to run any of my updates games crashes the editor immediately and I can't run my games. Does anyone know how I could debug this or where to start? Does Unity keep a log of errors when it crashes? I have both a 2D and 3D game that do not work and the editor is not throwing any errors or telling me there are compile time issues. EDIT If it makes any difference it is the 64bit version and I am using a Student Pro License |
0 | Discoordinated Chromatic Aberration Effect The game Teleglitch heavily utilizes the CA effect with screen distortion. I am trying to achieve this effect. Issue 1. How to not apply the effect onto the floor? (solved) They render the screen then apply the CA effect. However, the floor is not rendered with the post processing effect. Issue 2. How to have discoordinated position for each rendered CA effect? Currently I have three offsets for each channel red, green, and blue. However, I cannot assign different offsets for the channels for certain areas only. What would be a way to have discoordinated positions? |
0 | UnityEditor.SyncVS.SyncSolution putting wrong language version in generated files I'm working on getting our Unity projects building in bamboo for our build server. We have a cli step that runs through the Unity commands for creating a build. It works fine on several projects, but for some reason this particular project I'm working on I'm getting an error that states I need to use c version 7.2 or newer. If I log in to the build server and open the .csproj files in notepad and check the language version, it's setting them to 7.0. However, if I deactivate the cli step so that the build job only clones the project, then manually log in and open unity and go through the process so it generates the .csproj files, then check them, the language version is set to 8.0. The project works fine locally on my own pc. And it works when setup manually on the build server pc, but when ran through the cli step, it generates them at an earlier c version. This leads me to believe there is a problem with the UnityEditor.SyncVS.SyncSolution step in my commands. I'm just not sure what it could be, or why it's behaving differently for this project as opposed to other projects that are using the same code base (where the problem is said to occur), same Unity version, same build server, etc. Anyone else experience this issue or have any thoughts on a solution? |
0 | Why is Unity ignoring my camera on Android? I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app. Here's what it should look like Here's what it ends up looking like My game is forced in portrait, and I want to keep it that way. I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera I think it is just using the canvas. I tried many different things, including changing the scaling and setting the anchors. None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor. Why is Unity ignoring my camera on Android? |
0 | How can I look up an object given only the name of its type? This question came from a fellow developer on Twitter, and I figured StackExchange would be a better format for explaining amp sharing the answer. To paraphrase the question I'm setting up an in game dev console in my Unity game, where a user should be able to call any method on any MonoBehaviour in the scene. I want to use something like FindObjectsOfType lt gt , but because it's coming from a string input by the user, the class name is unknown at compile time. I also want this to work universally, on any MonoBehaviour, not just ones I've specially instrumented or registered with the console system. Is there a way to find instances of a type with a particular name, and call methods on them, using something like reflection? |
0 | Emulating 3d trajectory in top down 2d game? As the title suggests, I am wondering if it's possible to emulate a 3d arrow trajectory to a top down 2d game? If you would look at this clip of Age of Empires 2 game, especially when archers are firing from bottom to top. Can the parabola arc of the trajectory (in that certain view angle) be emulated in a 2d orthographic, top down game? So that the arrows would look like they're in 3d space. I know it's tricky but I wonder if there's some computation available for this. If you could point me in the right direction or some sample code I would be very grateful. I've only implemented this projectile motion in a side scroll view. Thank you in advance. |
0 | Failed to spawn server object, Unity UNET I'm familiar with Unity and programming but I'm new to this site. So I have an issue with clients on Unity. I start servers with no errors, flawless. But when I join a server as a client I get a bunch of the error mentioned in the title. What causes this issue? I am using the UNET networking components. I think it's lines like these, when executed by a client NetworkServer.Spawn (objectNameHere) How can I fix it if that's the case? Edit After hours of having this issue I have become so frustrated that I think it's best I take a break. I'll check back on this site from time to time. |
0 | Updating GameObject Position in Unity 5 I have a simple Sprite called Player that has the follow components (Transform, Sprite Renderer, Box Collider 2D, Rigidbody 2D, Player Controller Script). In my Player Controller script I want to update the player's position when a key is pressed. using UnityEngine using System.Collections public class PlayerController MonoBehaviour Vector2 playerPos Use this for initialization void Start () playerPos gameObject.transform.position Update is called once per frame void FixedUpdate () if (Input.GetKey("d")) playerPos new Vector2(playerPos.x 0.2f, playerPos.y) This script is attached to my gameobject but whenever I press or hold down the 'd' key, nothing happens to the player. Does anyone know how to fix this? |
0 | Unity 5 Google Cardboard VR SDK Frame Rate I am running the Google Cardboard's official demo which doesn't really have much things on the scene (https developers.google.com cardboard unity download) on my Personal Unity 5 on my Nexus 5. The fps is around 40 and I am wondering if the fps is so low because of my Nexus 5's hardware specs or is there a way to optimize the fps in Unity or some configuration in Google Cardboard's SDK? |
0 | Is There a Way To Keep Precision When Transforming GameObjects I've seen this issue before, but it's never been a particular issue for me until today. I have each "room" of a dungeon created with a class script that contains details of that room. During the process of building the dungeon, rooms may be mirrored or rotated. When I rotate the y axis, it updates properly the first time, going from 0 to 180, but if I mirror it back and forth, it begins to get very small variances away from true 0 and 180. Over time, this could impact some things. The code I'm using to do this is public void RoomMirror() transform.Rotate(0, (transform.localRotation.y 180) ? 0.0000f 180.0000f, 0) Mirror !Mirror Swap(ref east, ref west) I added the four places in the float to try to overcome this issue, but it doesn't seem to be making any difference. Thanks! |
0 | App icon on phone looks squished in Unity I am working on a 2D platformer. And I am alomost finished!! I am trying to work on adding the app icon. The icon that you would see on your phone. I imported the picture and added it to player settings. But when I put my game on my phone the icon looks squished. These are the settings that I imported it on Texture Type (sprite 2D and UI) sprite mode Single Filter mode Blinear (not pixel art) Here is a link to a screen shot on my phone of the icon https www.dropbox.com s jbgciscda7nykjd app 20on 20phone.png?dl 0 Ok I am getting closer to an solution now. My first problem was that the image was not square as staed below. But now the image is smaller compared to the rest of the app icons. the resolution of teh image now is 2000X2000 Here is a screenshot of what it looks like now https www.dropbox.com s t45vylzpi3chnsf App Icon 2.png?dl 0 |
0 | how do I tile this generated terrain infinitely around the player? i made a script that instantiates cubes with for loops and perlin noise. is there any way i can tile this infinitely around the player? here is the script for the generation of one tile public GameObject grass public int mapSizeX 50 public int mapSizeZ 50 public float heightScale 20f public float detailScale 20f float seed Use this for initialization void Start() if (instance null) instance this for (int x 0 x lt mapSizeX x ) for (int z 0 z lt mapSizeZ z ) int y (int)(Mathf.PerlinNoise((x seed) detailScale, (z seed) detailScale) heightScale) GameObject g Instantiate(grass) as GameObject g.transform.position new Vector3(x, y , z) g.transform.SetParent(this.transform) |
0 | How to move a player along Waypoints with Rigidbody.MovePosition in Unity? I have a player with a Rigidbody, I want it to follow along the Waypoints. I have used MoveTowards but it seems also not to work however. I want to use MovePosition to add force while grinding. I commented a code that could maybe work but I got an error on that, check ADDFORCE lines. Here is my code public GameObject waypoints public float grindSpeed public float turnSpeed public int currentWaypoint private Animator anim private Rigidbody rb public bool isGrinding false void Start() anim GetComponent lt Animator gt () rb GetComponent lt Rigidbody gt () void FixedUpdate() MoveAlongWaypoints() if(isGrinding) anim.SetBool ("isOnGrinding", true) else if(!isGrinding) anim.SetBool("isOnGrinding", false) void MoveAlongWaypoints() if(isGrinding) TRANSLATE transform.position Vector3.MoveTowards(transform.position, waypoints currentWaypoint .transform.position, grindSpeed Time.deltaTime) ADDFORCE Vector3 movePosition transform.position movePosition Mathf.MoveTowards(transform.position, waypoints currentWaypoint .transform.position grindSpeed Time.deltaTime) rb.MovePosition(movePosition) ROTATE var rotation Quaternion.LookRotation(waypoints currentWaypoint .transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, rotation, turnSpeed Time.deltaTime) if(Mathf.Abs(transform.position.x waypoints currentWaypoint .transform.position.x) lt 1 amp amp (Mathf.Abs (transform.position.y waypoints currentWaypoint .transform.position.y) lt 1) amp amp (Mathf.Abs (transform.position.z waypoints currentWaypoint .transform.position.z) lt 1)) rb.useGravity false currentWaypoint void OnTriggerEnter(Collider other) if(other.gameObject.tag "GrindWayPoint") Debug.Log ("Waypoint!!") isGrinding true |
0 | Does duplication happen quicker than generation? I am evaluating performance of bullet instantiation methods in Unity. I have a thing against prefabs. So each bullet is made from a function that sets the shape material, scripts and behaviors (tracking, velocity, duration, etcetera). Call this the "ammo type" if you like. Here are my instantiation methods Generate one bullet from script. Disable it. Instantiate(duplicate) new bullets from this bullet and enable them when gun fires. Each time the gun fires, generate a new bullet from the script. Still technically a duplicate but arrived at through a different method. Which of these would have better performance? Would it be a drastic difference or a minor one? The first method makes much more sense than the second. However there is a problem with delegates not being transferred when duplicating. Thus I am considering the second method and wondering how bad it would be on performance. For more information on the problem with delegates when duplicating a prefab read this post. I am happy to clarify any of the above should you find my explanation lacking. |
0 | Change Time.timeScale during an animation event Unity I have an animation. A few seconds after this animation starts I set an animation event that is correctly being triggered. This animation event calls a method where I am trying to modify Time.timeScaleand set it to 0.05f. This event is calling the following method public void Slowmotion() Time.timeScale 0.05f Time.fixedDeltaTime Time.timeScale 0.02f But this Slowmotion method is not working. Any ideas on what may be happening? |
0 | Why the OnCollisionEnter is not working? This script is attached to the wall(3D Cube) with a box collider using System.Collections using System.Collections.Generic using UnityEngine public class LockedRoomTrigger MonoBehaviour private void OnCollisionEnter(Collision collision) Debug.Log(collision.transform.name) But when the player is moving and hit the cube it's not getting to the Debug.Log I used a break point on the Debug.Log line. A screenshot of the cube wall with the box collider component and the script attached to it. The problem is not with the player since if I'm moving with the player near doors they open so the player does trigger things and also not walking through walls. This is a screenshot of NAVI. NAVI is a bit in front of the player and moving with the player and part of the player in the game like a friend helper. NAVI is the one that collide and hit stuff if doors walls not the player since the NAVI is a bit in front of the player. NAVI have only a box collider And this is the Inspector screenshots of the player. I will add two screenshots since it's not getting inside in one screenshot The player is a first person view |
0 | Allow a game object to pass out of a collider but not back in Unity In my game I have enemies that shoot projectiles out at the player, the only way for the player to get rid of them is by guiding them into a structure. An example of my enemy shooting a projectile. The problem I have is that sometimes the enemy spawns on top of one of these structures as seen below. This results in the projectile exploding colliding with the structure the moment it is spawned. I'm not entirely sure how to go about fixing this issue. I have tried to find a way to disable the collider on the projectile for a few seconds but I couldn't get the timer right. I also think this might cause some odd game play issues. The second thing I tried was a platform effector, however I could only get it to form a circle and this didn't work out because my structures are of all different sizes and shapes. If anyone could point me into the right direction or even help me find a better solution I'd be extremely grateful. Thanks ublic class MultiBullet MonoBehaviour public float speed 1f private Rigidbody2D rb Use this for initialization void Start () rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () rb.velocity transform.up speed private void OnTriggerEnter2D(Collider2D collision) Add explosion Effect if (collision.gameObject.tag "Player") Add game over screen here Debug.Log("Player Killed") Destroy(gameObject) Debug.Log("BOOM") Destroy(gameObject) if(collision.gameObject.tag ! "BulletIgnore" amp amp collision.gameObject.tag ! "Cloud") Debug.Log("BOOM") Destroy(gameObject) Just a simple class to handle when projectiles collide with objects. |
0 | How to do gear physics I've realized this gear using primitive. My object is Main cylinder with with a Rigidbody and a script who rotate Y axis All Prism as child who has MeshCollider I've got also a pivot for each gear. The problem is that the right gear not rotate when "prism" collide with others. The collision not happen. Any ideas ? Thanks |
0 | Unity Texture huge areas with decals I'm using 1024 textures for smaller buildings and 2048 for larger one's. Basic workflow 1) Unwrap in Blender 2) Smack a concrete texture on it 3) paint some dirt here and there. Result This only works for small buildings. Here is an example from Battlefield 2, they put a small 128x128 brick texture and tiled it across the entire building and added Dirt on top of that. Is there a way to do this using Unity or do I have to create my own custom shaders? (God forbid) |
0 | How can I put a Unity3D game on an Xbox 360 disc? I've made a simple shooter in Unity that I'd like to play on an Xbox 360. Mass production not required, just a one off game, completely non profit. Perhaps burning to a DVD? Is it a relatively simple procedure to burn the game to disc? I have a nasty feeling the Xbox 360 needs to be chipped. Is this the case? |
0 | Am I experiencing a gimbal lock problem when rotating my cube? So I'm trying to build a simple mechanic where the player see's 3 sides of a cube at a time top, left and front(I called the front side "Right" in my code, due to the orthographic view). The player can click on the front side or left side of the cube to rotate the cube so that the side that was pressed moves and becomes the top face. I want to smooth animate the rotation. The red faces are the faces that the user can click on. My Logic seems to work quite well when I click on the left face (Rotating along the x axis), but doesn't seem to work well for the front right face(It usually works once and then does weird stuff on the next click, this is on the z axis) public class CubeRotator MonoBehaviour private const float STOP THRESHHOLD 0.1f private const float ROTATE AMOUNT 90f SerializeField, Header("Touch Quads Colliders") private Collider touchQuadLeft SerializeField private Collider touchQuadRight SerializeField, Space(10) private float timeToRotate private bool mustRotateLeft false private bool mustRotateRight false private float targetX 0.0f private float targetZ 0.0f private float xVelocity 0.0F private float zVelocity 0.0F int layerMask private void Start() layerMask LayerMask.GetMask("Touch Quad") void Update() ListenForTouch() RotateCube() private void ListenForTouch() if (Input.GetMouseButtonDown(0)) Vector2 touchPoint Input.mousePosition RaycastHit rayCastHit Ray ray Camera.main.ScreenPointToRay(touchPoint) if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask)) if (rayCastHit.collider touchQuadLeft) mustRotateLeft true targetZ targetZ ROTATE AMOUNT zVelocity 0f else if (rayCastHit.collider touchQuadRight) mustRotateRight true targetX targetX 90f xVelocity 0f private void RotateCube() float zAngle transform.rotation.eulerAngles.z float xAngle transform.rotation.eulerAngles.x if (mustRotateLeft) zAngle Mathf.SmoothDampAngle(zAngle, targetZ, ref zVelocity, timeToRotate) if (Mathf.Abs(zVelocity) lt STOP THRESHHOLD) mustRotateLeft false if (mustRotateRight) xAngle Mathf.SmoothDampAngle(xAngle, targetX, ref xVelocity, timeToRotate) if (Mathf.Abs(xVelocity) lt STOP THRESHHOLD) mustRotateRight false transform.rotation Quaternion.Euler(xAngle, 0f, zAngle) Inspector Values I've tried several things, the only problem I can think of is, gimbal lock. Thanks in advance. |
0 | Spot Light color fade in Unity 3d I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight. void Update() if(Time.time() 120 0) transform.light.color new Color(Random.Range(0,255),0,0,1) I know I am missing something big here. Help is appreciated. Thanks in advance. |
0 | No Support for UnityScript (JavaScript) on 2018.3 Hey I ve been working on a project for over 3 years and yesterday I have updated the unity from 2018 to 2018.3 and lost support for JavaScript. All of my scripts attached to gameobjects are there but not working while playing the game. I ve tried the UnityScript to C website but didn t work. I m a macOS user so couldn t use the converter tool on git (because it s been developed only for windows). I ll appreciate any suggestions. |
0 | Why transform.find() does not need actual object unity I m new to unity and C . I suspect that transform.find() function below does not need actual object reference like player.transform.find() because it transform find is already applied to the gameObject the script is attached to? Am I right? Why transform.find() does not have any game object in front of it? public class PlayerControl MonoBehaviour private Transform groundCheck void Awake() groundCheck transform.Find("groundCheck") |
0 | Unity3D and Photon Networking RPG Good time of the day. My question might sound stupid, due to the knowledge you might have, but here it is. I've purchased Diablo 3 a long time ago and been enjoying it since then. Since many of my friend are playing other Blizzard titles, i tried to convince them to purchase Diablo and to play all together. However, they don't want to invest money in the game they don't understand (yet). So i've decided to write a game, which will be similar to the Diablo in the way of interaction and gameplay, but will (obviously) have some unique points in it (since i'm not only doing this for them, but also to educate myself in the game development area). Other this is, i've decided to take Masters in the Game Development (later this march, just got my bachelors in computer security) and wanted to have some basic knowledge about game development. I used to make "RPG" games before, tho only browser style ones using LAMP stack, and have some basic knowledge on storing retrieving data to from server. In order to implement multiplayer part of the game, i've decided to use free package PUN (Photon Unity Networking). Had no problem with creating my first room and spawning a player prefab for every new connection (tho they all move no matter on which client action is performed). Now to the question(s) By using PUN, i'm able to create new room for players (limited to 5), is it possible to set room names BEFORE they are actually initialized by the player? (set of rooms might be stored on MySQL server and retrieved by the API call) Is it possible to save progression of the player on the server, and later pass it back to the spawned player (by PUN). This is my main concern, since i've no actual access to the data processed by the server. (Solution is to create another connection to the "storage" server, and keep both of them "online"?) Does PUN allows you to select which scene should be loaded upon first player entering the room, if so, a bit of pseudo code might be helpful. What will happen to the player, if there is no spots left to join the server (this is just theoretical question, since i'm not going to publish this game, and amount of friends playing games is less than 20) How would one deal with the item equipped, which is received during the gameplay? (This one links to the second question) What i'm talking about is, is it possible to restore player object with the set of data received form the server (if possible, ofcourse) I know, the first suggestion will be to go and to read documentation (i'm in the process of reading it, don't worry). But i've decided to write here, since there are many skilled people out there in this area, who can give me basic understanding on how this whole PUN system works. I would like to thank you for all of the responses, which you are about to post (or maybe not), and again, have a great day. |
0 | How can I speed up Unity3D Substance texture generation? I'm working on an iOS Android project in Unity3D. We're seeing some incredibly long times for generating substances between testing runs. We can run the game, but once we shut down the playback, Unity begins to re import all off the substances built using Substance Designer. As we've got a lot of these in our game, it's starting to lead to 5 minute delays between testing runs just to test a small change. Any suggestions or parameters we should check that could possibly prevent Unity from needing to regenerate these substances every time? Shouldn't it be caching these things somewhere? |
0 | Unity 3D How to stop reset 2D sprite animation after releasing key? Im following a tutorial to create animations with a 2D sprite character. But i put in my own. Which has 8 animation positions. For some reason when my guy walks around,then stop, the walkings animation continues to play out then resets to idles. I need the animation to reset as soon as i release the key. Im using Animator if you are wondering. EDITED Original video with all the keys for each animations. Youtube video Second video with only 2 keys per animation, it was a test. Second Video Here Code Snipet! using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float speed private Animator animator private Rigidbody2D rigidbody2D Use this for initialization void Start () animator GetComponent lt Animator gt () rigidbody2D GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () CheckDirection() void CheckDirection() if (Input.GetKey (KeyCode.A)) WalkAnimation( 1,0,true) else if (Input.GetKey (KeyCode.D)) WalkAnimation(1,0,true) else if (Input.GetKey (KeyCode.W)) WalkAnimation(0,1,true) else if (Input.GetKey (KeyCode.S)) WalkAnimation(0, 1,true) else animator.SetBool("Walking", false) void FixedUpdate () Move() void Move() float dirX animator.GetFloat("VelX") float dirY animator.GetFloat("VelY") bool walking animator.GetBool("Walking") if (walking) rigidbody2D.velocity new Vector2(dirX,dirY) speed else rigidbody2D.velocity Vector2.zero void WalkAnimation (float x, float y, bool walking) animator.SetFloat("VelX", x) animator.SetFloat("VelY", y) animator.SetBool("Walking", walking) |
0 | Can you create input actions using more than one key in the editor with the new Input System? The new input system documentation says it's possible to add actions that require input combinations within the editor or code. I only see an option to add one binding path per action within in the Actions UI. From the documentation ... require the left trigger to be held and then the A button to be pressed and held for 0.4 seconds? var action new InputAction() action.AddBinding(" lt gamepad gt leftTrigger") .CombinedWith(" lt gamepad gt buttonSouth", modifiers "hold(duration 0.4)") Again, setting this up with the inspector in the editor is an alternative to dealing with the path strings directly. |
0 | Bold black bar on right side of game in Unity (Android) I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone. Here are the screenshots One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left. Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go. I hope I can get some help. Ask me if you need any piece of code. EDIT "CameraFollow" script using UnityEngine using System.Collections public class CameraFollow MonoBehaviour public GameObject targetObject private float distanceToTarget Use this for initialization void Start () distanceToTarget transform.position.x targetObject.transform.position.x Update is called once per frame void Update () float targetObjectX targetObject.transform.position.x Vector3 newCameraPosition transform.position newCameraPosition.x targetObjectX distanceToTarget transform.position newCameraPosition My "GeneratorScript" using UnityEngine using System.Collections using System.Collections.Generic public class GeneratorScript MonoBehaviour public GameObject availableRooms public List lt GameObject gt currentRooms private float screenWidthInPoints Use this for initialization void Start () float height 0.0f Camera.main.orthographicSize screenWidthInPoints height (Camera.main.targetDisplay) Update is called once per frame void Update () void FixedUpdate() GenerateRoomIfRequred () void AddRoom(float farhtestRoomEndX) int randomRoomIndex Random.Range (0, availableRooms.Length) GameObject room (GameObject)Instantiate (availableRooms randomRoomIndex ) float roomWidth room.transform.FindChild ("floor").localScale.x float roomCenter farhtestRoomEndX roomWidth 3.0f room.transform.position new Vector3 (roomCenter, 0, 0) currentRooms.Add (room) void GenerateRoomIfRequred() 1 List lt GameObject gt roomsToRemove new List lt GameObject gt () 2 bool addRooms true 3 float playerX transform.position.x 4 float removeRoomX playerX screenWidthInPoints 5 float addRoomX playerX screenWidthInPoints 6 float farhtestRoomEndX 0 foreach(var room in currentRooms) 7 float roomWidth room.transform.FindChild("floor").localScale.x float roomStartX room.transform.position.x roomWidth 6.0f float roomEndX roomStartX (roomWidth 13.0f) 8 if (roomStartX gt addRoomX) addRooms false 9 if (roomEndX lt removeRoomX) roomsToRemove.Add(room) 10 farhtestRoomEndX Mathf.Max(farhtestRoomEndX, roomEndX) 11 foreach(var room in roomsToRemove) currentRooms.Remove(room) Destroy(room) 12 if (addRooms) AddRoom(farhtestRoomEndX) (I tried playing with the numbers on GeneratorScript, but nothing seemed to help. |
0 | Function Not Storing New Value of Variables? I'm currently building a small scope RPG and running into an issue with modifying variables. My goal is to alter my character's stats when I run a procedure to change their equipment. My code is as follows public class Player MonoBehaviour Base stat variables public static int PAtk 12 public static int PDef 6 Battle exclusive stats. Will have equipment added onto them. public static int Attack PAtk public static int Defense PDef Equipment variables. public string weapon public string armor private void Awake() Get equipment EquipWeapon( quot Bronze Sword quot ) EquipArmor( quot Bronze Armor quot ) void EquipWeapon(string WeaponName) weapon WeaponName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, WeaponName) void EquipArmor(string ArmorName) armor ArmorName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, ArmorName) public class Equipment MonoBehaviour Create dictionary to give each weapon a key ID. This will be used for calling items in another array. Dictionary lt string, int gt WeaponDictionary new Dictionary lt string, int gt () Create weapon array for stats. public int , WeaponStats Start is called before the first frame update void Awake() Declare weapon IDs WeaponDictionary.Add( quot Bronze Sword quot , 0) WeaponDictionary.Add( quot Bronze Armor quot , 1) Declare stat array Table ID, Atk, Def WeaponStats new int , 0,4,0 , 1,0,4 public void EquipStatIncrease(int BaseAtk, int BattleAtk, int BaseDef, int BattleDef, string Equipment) BattleAtk BaseAtk WeaponStats WeaponDictionary Equipment , 1 Debug.Log(BattleAtk quot Battle Power quot ) BattleDef BaseDef WeaponStats WeaponDictionary Equipment , 2 Debug.Log(BattleDef quot Battle Defense quot ) The general gist of it is once EquipWeapon or EquipArmor is ran, the equipment variables in the Player class will be updated. Afterwards, another function in the Equipment class will be ran with variables from the Player class passed over, in order to be modified by the WeaponStats array. The Debug logs in EquipStatIncrease show me that I am getting the desired results. However, the Attack parameter that is being placed into the function is not being permanently modified. During the first execution of the EquipStatIncrease method, I will get a result of 16 BattleAtk and 6 BattleDef, due to the weapon being equipped. However, once it's run a second time to equip the armor, I'm shown a result of 12 BattleAtk and 10 BattleDef, even though BattleAtk should have stayed at 16. This leads me to believe that the variables I'm trying to transform are not being modified, and I'm not sure what to do about this. In the EquipStatIncrease parameters, BattleAtk gives the message Parameter 'BattleAtk' can be removed if it is not part of a shipped public API its initial value is never used However, I don't know what action to take to resolve this. I'm aware of being able to use an int function instead of void, but unless I'm missing something, that only works if I'm trying to change one variable. If I want to have an equipment object that affects 2 different stats at once(ex. a weapon that increases BattleAtk and BattleDef), then I don't see how an int function would work. |
0 | How do I install the Unity Editor on Linux? I have installed Unity trough the Hub but still need the editor. I cannot for the life of me figure out how to do that? I'm running a Ubuntu based Linux system. I already have MonoDevelop installed I just need the darn editor. I then get greeted with the following popup but nowhere does it give me the chance to install the editor. |
0 | Photon Unity Instantiation not working I use Unity and Photon for the multiplayer. I Instantiate my gameObjects using this method void LoadGameObject(PhotonPlayer player,bool isMaster) if (isMaster) GameObject baby PhotonNetwork.InstantiateSceneObject(babies 0 .name, babies 0 .transform.position, Quaternion.identity, 0,null) baby.SetActive(true) Debug.Log("playerpref created on " player.ID) else Nothing for the moment I call the method in "OnJoinedRoom()" and "OnPhotonPlayerConnected(PhotonPlayer other)", but when the second player join the room, he can't see the gameObjects because they aren't activated on his scene. Any Idea of the mistake ? |
0 | Melee Range trigger collider does not detect object with Player tag In my 2D game, I have a Player which has a BoxCollider2D with isTrigger false a dynamic Rigidbody2D a Player script ...tagged as quot Player quot and in the quot Player quot Layer. Also I have an Enemy in the scene which has a BoxCollider2D with isTrigger true an EnemyMelee script ... tagged as quot Enemy quot and in the quot Enemy quot Layer. The Enemy has its own collider because when to handle taking damage or changing colors when shot by the Player's bullets. The Enemy has an empty child game object following it where it goes, called MeleeRange and it has a BoxCollider2D with isTrigger true a kinematic Rigidbody2D an EnemyMeleeAttack script ...tagged as quot MeleeRange quot and in the quot MeleeRange quot Layer. What I want is When Player is inside of the MeleeRange area, the EnemyMeleeAttack script will detect this and call the Coroutine from the EnemyMelee script. I want my Enemy to trigger its quot attackMove quot animation and attack my Player every 1.5 seconds. It has an exit time to the idle animation, and because the Player is still in the MeleeRange collision area, the attack will start again and return to idle again. The problem is MeleeRange simply cannot see the Player tag in the area. I put Debug.Log if it detects the player but nothing happened. EnemyMeleeAttack script public class EnemyMeleeAttack MonoBehaviour public EnemyMelee enemyMeleeScript void OnTriggerEnter2D(Collider2D coll) if(coll.tag quot Player quot ) Debug.Log( quot MeleeRange Collision Reached! quot ) enemyMeleeScript.anim.SetBool( quot isRunningBool quot , false) enemyMeleeScript.StartCoroutine(enemyMelee.attackStance()) EnemyMelee script public class EnemyMelee Enemy region Variables public bool inRange endregion region Attack public float attackTime public float timeBetweenAttacks endregion region Movement with AI public bool isRunningBool public AIPath aipathScript public EnemyMeleeAttack emeleeattackScript endregion public override void Start() base.Start() anim gameObject.GetComponent lt Animator gt () aipathScript gameObject.GetComponent lt AIPath gt () aipathScript.OnTargetReached() private void FixedUpdate() Code for if Enemy dies, disable all functions attached to Enemy. if (health lt 0) GetComponent lt AIPath gt ().enabled false StopCoroutine(attackStance()) DamageColorUpdate() Reference from A Pathfinding for following player and running animations when following occurs. if (aipathScript.reachedEndOfPath false) anim.SetBool( quot isRunningBool quot , true) inRange false else anim.SetBool( quot isRunningBool quot , false) inRange true StartCoroutine(attackStance()) public IEnumerator attackStance() if (Time.time gt attackTime) anim.SetBool( quot isRunningBool quot , false) player.GetComponent lt Player gt ().TakeDamage(damage) attackTime Time.time timeBetweenAttacks anim.SetTrigger( quot attackMove quot ) yield return null |
0 | Strange warping shimmering effect with Unity Tilemap and Cinemachine I'm using a Cinemachine Virtual Camera in a 2D project to follow around a target. The ground background is a Unity Tilemap GameObject. As you can see in the gif above (or on Imgur), when following around the player (a 24x24 sprite), the background tiles seem to warp or shimmer a bit. I've tried to script all types of solutions to adjust the Virtual Camera transform position and hopefully snap move it "correctly" to no avail. I don't even know for sure that the source of the issue is with the camera setup. I'm running out of solutions to something that seems like a pretty straightforward and very common scenario. I've created a sample project illustrating the issue which can be downloaded here. Using Unity 2017.3.1f1 Personal. The background sprites are 32x32, with a PPU of 32. No compression, Point (no filter), rendered using a material with Shader Sprites Default, and Pixel snap. Cinemachine Virtual Cam is set to Ortho lens size 16, Body Framing Transposer with default settings. Thank you so much for any suggestions or tips!!! It feels similar to what's being described here with sub pixel movement but I don't know for sure, and the solution in that blog post seems like it should be unnecessary (but again maybe not). I've created camera scripts and attached them to the virtual camera as follows float maxPixelHeight 32 CinemachineVirtualCamera vcam public void Awake() float scale Screen.height maxPixelHeight float orthographicSize (Screen.height scale) 2f vcam GetComponent lt CinemachineVirtualCamera gt () vcam.m Lens.OrthographicSize orthographicSize public void Update() Vector3 tempPos vcam.transform.position Vector3 newPos new Vector3(Mathf.RoundToInt(tempPos.x), Mathf.RoundToInt(tempPos.y), Mathf.RoundToInt(tempPos.z)) vcam.transform.position tempPos I've also tried public void Update() Vector3 tempPos vcam.transform.position Vector3 newPos new Vector3((float)System.Math.Round((decimal)tempPos.x, 2) , (float)System.Math.Round((decimal)tempPos.y, 2), (float)System.Math.Round((decimal)tempPos.z, 2)) vcam.transform.position newPos and something like public void Update() Vector3 tempPos vcam.transform.position vcam.transform.position new Vector3(RoundToNearestPixel(tempPos.x), RoundToNearestPixel(tempPos.y), RoundToNearestPixel(tempPos.z)) public float RoundToNearestPixel(float unityUnits) float valueInPixels unityUnits maxPixelHeight valueInPixels Mathf.Round(valueInPixels) float roundedUnityUnits valueInPixels (1 maxPixelHeight) return roundedUnityUnits |
0 | Object array in unity not instantiating properly I'm trying to instantiate my CarMovement class with my population class for a Genetic Algorithm, but when i run the project, the car prefab doesnt spawn. Everything is wired up in the inspector correctly. Anyone know whats going on? Here's the population class using System.Collections using System.Collections.Generic using UnityEngine public class Population MonoBehaviour public int populationSize 10 private CarMovement cars Use this for initialization void Start () cars new CarMovement populationSize for (int i 0 i lt populationSize i ) cars i new CarMovement () cars i .score 1 i Debug.Log (cars i .score) cars 0 .Start() Update is called once per frame void Update () Here's the CarMovement Individual class public class CarMovement MonoBehaviour public float speed 2f public Rigidbody2D rb2d public Vector2 spawnPosition new Vector2((1.0f) 0.1f,3.83f) public int score public GameObject carPrefab Use this for initialization public void Start () rb2d GetComponent lt Rigidbody2D gt () GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity) Debug.Log ("YAAAA") Update is called once per frame public void Update() rb2d.transform.Translate (speed Time.deltaTime, 0, 0) |
0 | How can I unregister an event from another scene or another script? This is where and how I register the event void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (Time.timeScale 0) DisableEnableUiTexts(true) SceneManager.UnloadSceneAsync(0) if (fadeImage ! null) fadeImage.SetActive(true) GetGameMusicVolume() Cursor.visible false Time.timeScale 1 else Time.timeScale 0 MenuController.LoadSceneForSavedGame false SceneManager.LoadScene(0, LoadSceneMode.Additive) SceneManager.sceneLoaded SceneManager sceneLoaded Cursor.visible true And the event private void SceneManager sceneLoaded(Scene arg0, LoadSceneMode arg1) I need to be able to unregister the event either from another scene or another script. |
0 | How to make an event happen only at the first start of the game? I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again. I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ... So I want to know how to make something happen only once in a game application.. I hope you get my point ... thanks .. |
0 | Getting child collider when collision occurs in compound object in unity3d? I have a compound object. The parent of the compound object hierarchy has a script that is listening to the OnTrigerXXX callbacks of the children. When this compound object collides with other objects is there any way to get both colliders? I mean the "other" collider and the collider that belongs to the compound object itself that collided? P.D All rigid bodies must be kinematic, so, I can't use OnCollisionXXXX with the collision info param that has all the information I need in the contacts array. Edit to add a bit more information as Savlon suggested When we are not using compound objects and we want to have a centralized place to handle children collision events, we could have something like this In Children void OnTriggerEnter(Collider c) (parent's script).TriggerHandler(this, c) In Parent public void TriggerHandler(GameObject theChild, Collider c) do stuff This is ok and will work. The "problems" with this way are I could have a lot of children, so, using compound objects I would need to add just a rigid body component to the parent. This could be a pretty good memory reduction usage. However if I don't use compound objects I will have to add a rigid body to every child like in the previous code. In my case children under a parent are always touching. Not intersecing but touching. Think about a set of blocks one beside the other. They do not intersect but there are no gaps between them. With compound objects I don't have to mess with it. It authomatically treats all the children as a whole and no collision callbacks will be fired among them. On the other hand when using compund objects, you get all the advantages listed before but if you need information about what children collided with another collider you won't be able to get it because your script listening to callbacks is in the parent and you will only receive as parameter the "other" collider when unity calls you back through OnTriggerXXXX callback. I was asking if there is any way to get both colliders using a compound object. Hope everything is clearer now. Cheers |
0 | Cannot use imported image with Unity's UI controls I know this question sounds banal but its a problem. I received a project and opened it. Now I try to edit it by adding my own images. I do the import but the image does not show up when selecting images, for example, for a button What is the correct folder in this case? |
0 | Get the current time of animation using script Unity3d I want to know the current time of the played animation using script in Unity3d. I tried using currentState.normalizedTime but this time is not the time of the animation, like it's the time of the runtime I think. Any advice please? |
0 | How can I prevent seams from showing up on objects using lower mipmap levels? Disclaimer kindly right click on the images and open them separately so that they're at full size, as there are fine details which don't show up otherwise. Thank you. I made a simple Blender model, it's a cylinder with the top cap removed I've exported the UVs Then imported them into Photoshop, and painted the inner area in yellow and the outer area in red. I made sure I cover well the UV lines I then save the image and load it as texture on the model in Blender. Actually, I just reload it as the image where the UVs are exported, and change the viewport view mode to textured. When I look at the mesh up close, there's yellow everywhere, everything seems fine However, if I start zooming out, I start seeing red (literally and metaphorically) where the texture edges are And the more I zoom, the more I see it Same thing happends in Unity, though the effect seems less pronounced. Up close is fine and yellow Zoom out and you see red at the seams Now, obviously, for this simple example a workaround is to spread the yellow well outside the UV margins, and its fine from all distances. However this is an issue when you try making a complex texture that should tile seamlessly at the edges. In this situation I either make a few lines of pixels overlap (in which case it looks bad from upclose and ok from far away), or I leave them seamless and then I have those seams when seeing it from far away. So my question is, is there something I'm missing, or some extra thing I must do to have my texture look seamless from all distances? |
0 | Maintaining facing direction at the end of a movement I want to make my 2D top down walking animation stop and revert to the idle animation while continuing to face in the same direction as the previous movement. For example, when I go up then stop, my character should continue to look up. If I go down, it should continue to look down. I use lastmoveX and lastmoveY floats for idle and for walking I use moveX and moveY floats. moveX and moveY change when I move with the joystick, but lastmoveX and lastmoveY do not change, and I don't know how to fix this. Here is my code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody2D myRB private Animator myAnim public Joystick joystick public MoveByTouch controller SerializeField private float speed Use this for initialization void Start () myRB GetComponent lt Rigidbody2D gt () myAnim GetComponent lt Animator gt () Update is called once per frame void Update () myRB.velocity new Vector2(joystick.Horizontal, joystick.Vertical) speed Time.deltaTime myAnim.SetFloat( quot moveX quot , myRB.velocity.x) myAnim.SetFloat( quot moveY quot , myRB.velocity.y) if(joystick.Horizontal 1 joystick.Horizontal 1 joystick.Vertical 1 joystick.Vertical 1) myAnim.SetFloat( quot lastMoveX quot , joystick.Horizontal) myAnim.SetFloat( quot lastMoveY quot , joystick.Vertical) |
0 | Rendering Mode transparent is not applying in webgl build I am using this method to convert opaque rendering mode to transparent. item.color new Color(1, 1, 1, value) item.SetFloat( quot Mode quot ,3) item.SetOverrideTag( quot RenderType quot , quot Transparent quot ) item.SetInt( quot SrcBlend quot , (int)UnityEngine.Rendering.BlendMode.One) item.SetInt( quot DstBlend quot , (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha) item.SetInt( quot ZWrite quot , 0) item.DisableKeyword( quot ALPHATEST ON quot ) item.DisableKeyword( quot ALPHABLEND ON quot ) item.EnableKeyword( quot ALPHAPREMULTIPLY ON quot ) item.renderQueue (int)UnityEngine.Rendering.RenderQueue.Transparent This is working fine but not working in my webgl build. |
0 | Changing handedness coordinate system between unity and opencv For my problem given System A, opencv and unity. I have the Inversed extrinsic parameters in the quot System A convertion quot . Intrinsic parameters (Can form into projectionMatrix) in the quot Opencv convention quot . My first question is When I'm doing the projection. Do i need to convert a convention to have the same direction as opencv then I do the projection. Or I can do it directly without any negated axis?. The step you can see below. I want to set the camera from System A into the unity. What I did is following the image. I rearrange the axis from System A to be the same as Unity. (Rotating Negated the sign) Once it had the same convention to the unity.I took the rotation matrix and use the scipy.transform.as euler(R, order 'zxy'). Then negated the sign the get the angle for left handed. Rotation into Euler angles by using scipy.transfrom.as euler (order of 'zxy' following unity document). Since the scipy accept the right handed coordinate system. Then i will got an angle of rotation. Then negated the axis. Translation I don't know that this should got negated the direction of an axis My second question is I think my procedure is wrong. Since the scipy libs accept the right handed system. So I don't know that how to find the euler rotation angle from given rotation matrix in the right handed system and change it into the left handed system. Thank you very much, Regards, Puntawat Ponglertnapakorn |
0 | Trying to Access Components of an Object in another class I think my C is a bit lacking here but I am trying to access a component in a list of objects in another class. I am trying to access UnitController from MultiSelectClient and I'm not sure how to do this. I can remove the objects from the list but I can't seem the access each one even if I try a ForEach loop, I can't wrap my head around it. UnitController.SelectedUnits Is the list I'm trying to access. Ive tried doing UnitController.SelectedUnits.Find FindAll(gameObject) but that returns an error This is where the list is defined public class UnitController MonoBehaviour bool clicked false bool dragging false public float speed 10f public float rotationSpeed 10f public LayerMask groundLayer public NavMeshAgent playerAgent public static Vector3 mouseDownPoint public static Vector3 mouseUpPoint public static Vector3 currentMousePoint public static Rect selection new Rect(0, 0, 0, 0) private Vector3 startClick Vector3.one public Texture2D selectionHighLight public static List lt GameObject gt SelectedUnits public RaycastHit firstRay public RaycastHit secondRay private void Start() SelectedUnits new List lt GameObject gt () This is the script that needs to access it. At least I want to be able to iterate through the list and access each unit in the list and its components. public class MultiSelectClient MonoBehaviour 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() else UnitController.SelectedUnits. something UnitController.SelectedUnits.Remove(gameObject) |
0 | Pathfinding in a 2D "sidescrolling" strategy game I've been thinking up a real time strategy game that plays on a platformer type of map. The collidable portion of these maps will be made up of square tiles. I've done A pathfinding in top down tile based games before, but I'm unsure how to lay out my tile map in such a way that allows for easy pathfinding. I've thought up some examples, but I'm not sure if it's the right way to go about it, so I thought I'd throw it out here and see if someone who knows what they're doing can give me some tips. The first solution I thought of was to use a 2D array storing all of the tiles and empty space, similar to what I would most definitely do in a top down tile based strategy game. The 2D grid would be invisible in the background but really store whether each grid section is empty, or has a tile on it. like this In this example I'm unsure as to how I would pathfind up hills, or in that specific example, determine that a wall is too high to cross. Lets say that dude can jump over 1 tile high blocks, but 2 tiles is too much. How would I effectively determine that through a pathfinding algorithm? The other example I was thinking of was to place pathfinding nodes on top of traversible terrain, like this Each node might be able to give directions or commands on how to get to the next (Like the need to jump to cross a gap, or it's faster to go under rather than over, etc). Now I would want to do this logically through code, and not manually place them at design time. This might be a better solution, but something I'm thinking of in this game is to have destructable terrain. Say an explosion happens and leaves a big hole like this Suddenly those nodes I placed earlier won't work. I'd need to remake them on the fly. In this case the 2D grid sounds like the better option since I can just flip the value of that tile from full to empty. So hopefully those 2 examples made sense, and I'd like some opinions on which might be the best option, or even if there's some other solution I didn't think about I would be glad to hear it! I'm using Unity if that helps. I just want to get this design choice out of the way early, as it would be a pain to have to tear it apart later. Thanks! |
0 | Unity3d Rigidbodies overlap even at low speeds I have an issue that I can't solve. There are many questions relating to similar issues and they come down to "change some settings" and "object is travelling too fast". My problem doesn't seem to equate to either of these. I am running through the basic tutorial for the Breakout Game and have added some of my own tweaks to the code, my issue is that even at low speed my ball overlaps with the bricks, rather than bouncing off them. I have read various related questions but nothing seems to fix this for me. Things I've done Set Project Settings Physics2d Maximum penetration For Overlap 0.0001 Set Ball RigidBody Collision detection to "Continuous Dynamic" . Set Brick RigidBody Collision Detection to "Continuous" Forced a speed limit on the ball of 25 15. Which I think is not fast at all, as most the given solutions are talking about situations arising when the offending object is travelling at much higher speeds. Bricks are standard rigidbody cubes and ball is a standard rigidbody sphere. According to this answer I have also set the rigidbody interpolation to "interpolation" for both ball and bricks. But this seems processor expensive and doesn't solve the issue. As well as set the Project Settings Physics Solver Iteration Count to 25. This does seem to have helped somewhat (ball no longer gets "stuck" inside brick wireframes, but still overlaps). Below are some screenshots of my issue and my code. The only aspect that I can't fully account for is that I've added an acceleration function so when ball is launched it accelerates over a course of several seconds to it's max speed. It's start speed is 8 (although the force applied is actually 1000 when launched, ignore that figure), and the max speed is set to 25 15. I don't know enough to say if this is somehow "breaking" rigidbody overlap detection but it seems pretty silly if so. See line 63 below Ball Source Code using UnityEngine using System.Collections public class Ball MonoBehaviour public float initialVelocity 500f public float accelerationSpeed 5f public float MaximumSpeed 15f private Rigidbody rb private bool ballInPlay false void Awake () rb gameObject.GetComponent lt Rigidbody gt () void Update () if (Input.GetButtonDown("Fire1") amp amp ballInPlay false) transform.parent null rb.isKinematic false rb.AddForce(new Vector3(initialVelocity,initialVelocity,0)) ballInPlay true void FixedUpdate () Gradually increase ball speed if (ballInPlay true amp amp rb.velocity.magnitude lt MaximumSpeed) speedUp() Debug.Log("Ball Speed is " rb.velocity.magnitude) Clamp to maximum speed if (ballInPlay true amp amp rb.velocity.magnitude gt MaximumSpeed) rb.velocity rb.velocity.normalized MaximumSpeed rb.velocity.magnitude void speedUp() This is line 63 rb.AddForce(rb.velocity.normalized accelerationSpeed,ForceMode.Acceleration) Why are the rigidbodies not detecting and preventing overlap? |
0 | Grid movement of game units I am trying to achieve a grid movement for a character and enemies. This is what I have so far. public float moveSpeed 5f Rigidbody2D rb public Animator animator Vector2 movement private void Start() rb GetComponent lt Rigidbody2D gt () void Update() animator.SetFloat("Horizontal", movement.x) animator.SetFloat("Vertical", movement.y) animator.SetFloat("Speed", movement.sqrMagnitude) private void FixedUpdate() rb.velocity movement public void MoverHaciaDelante() movement.y 1 moveSpeed public void MoverHaciaAtras() movement.y 1 moveSpeed public void MoverHaciaDerecha() movement.x 1 moveSpeed public void MoverHaciaIzquierda() movement.x 1 moveSpeed public void Parar() movement Vector2.zero And on the part of the enemies I carry this movement system. private Animator myAnim private Transform target SerializeField private float speed SerializeField private float maxRange SerializeField private float minRange void Start() myAnim GetComponent lt Animator gt () target FindObjectOfType lt Player gt ().transform void Update() if(Vector3.Distance(target.position, transform.position) lt maxRange amp amp Vector3.Distance(target.position, transform.position) gt minRange) FollowPlayer() public void FollowPlayer() transform.position Vector3.MoveTowards(transform.position, target.transform.position, speed Time.deltaTime) |
0 | Best way to save game data in Unity I am currently developing a game in unity and I want to add some sort of saving system that saves the following Locked unlocked level. The amount of money the player has. Items perks that the player has. As you can see, the data I want to save is global, and has nothing to do with any specific scene. How would you reccomend save this kind of data? I have heard about the EasySave asset but I don't know if it is the right choice it is pretty expensive and I belive that there has to be some easier, cheaper (even free) way to save the data. I'll appreciate any answer or consideration. |
0 | How do I create a prefabs when a button is clicked(Unity) So I want to be able to spawn prefabs when a button is pressed Shop script using System.Collections using System.Collections.Generic using UnityEngine public class Shop MonoBehaviour public static string Item01 public static string Item02 public static string Item03 public static string Item04 public static int ShopNum Update is called once per frame void Update() if(ShopNum 1) Item01 quot Cannon quot Item02 quot Tower quot Item03 quot army Camp quot Item04 quot Baracks quot if(ShopNum 2) Item01 quot Archer quot Item02 quot Barbarian quot Item03 quot Goblin quot Item04 quot Wizard quot And then my Shop Access script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Shop01Access MonoBehaviour public GameObject ShopInventory public GameObject Item01Text public GameObject Item02Text public GameObject Item03Text public GameObject Item04Text public GameObject ItemCompletion public GameObject CompleteText void OnTriggerEnter() ShopInventory.SetActive(true) Screen.lockCursor false Shop.ShopNum 1 Item01Text.GetComponent lt Text gt ().text quot quot Shop.Item01 Item02Text.GetComponent lt Text gt ().text quot quot Shop.Item02 Item03Text.GetComponent lt Text gt ().text quot quot Shop.Item03 Item04Text.GetComponent lt Text gt ().text quot quot Shop.Item04 public void Item01() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item01 quot ? quot public void Item02() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item02 quot ? quot public void Item03() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item03 quot ? quot public void Item04() ItemCompletion.SetActive(true) CompleteText.GetComponent lt Text gt ().text quot Are you sure you want to buy quot Shop.Item04 quot ? quot public void Cancel() ItemCompletion.SetActive(false) How could I spawn a cannon when button item01 is pressed into my 3d scene |
0 | Why I cant change the GUILayout.Button color to green when click on a button? I used a break point and it's getting to the line style.normal.textColor Color.green But not changing the color of the clicked button. And there are no any errors or exceptions. using System.Collections using System.Collections.Generic using System.Diagnostics using System.Linq using UnityEditor using UnityEngine using System.IO public class Manager EditorWindow MenuItem("Tools Manager") static void Manage() EditorWindow.GetWindow lt Manager gt () private void OnGUI() var style new GUIStyle(GUI.skin.button) style.normal.textColor Color.red style.fontSize 18 string assetPaths new string 2 string 0 "Test" string 1 "Test1" foreach (string assetPath in assetPaths) if (assetPath.Contains(".test") var i assetPath.LastIndexOf(" ") var t assetPath.Substring(i 1) if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50))) style.normal.textColor Color.green |
0 | How can I find when moving the mouse pointer over raw image to what file it belong to? I have on the hard disk some images and saved files. Each image have his saved file. 10 images and 10 saved files Then I'm loading the images to rawimages and when running the game it looks like that This script is loading the images to raw images using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName go.GetComponent lt RawImage gt ().texture thisTexture Update is called once per frame void Update() And the last script is for moving the mouse over the raw images and then it's making each image the mouse cursor is over to be brighter using System.Collections using System.Collections.Generic using System.Drawing using System.Drawing.Imaging using UnityEngine using UnityEngine.EventSystems using UnityEngine.UI public class MouseHover MonoBehaviour public SaveLoad saveLoad public SceneFader sceneFader public RawImagePixelsChange rawImagePixelsChange private bool loadGame false public void OnHover() Debug.Log( quot Enter quot ) rawImagePixelsChange.modifyPixels(0.3f) PlaySoundEffect() loadGame true public void OnHoverExit() Debug.Log( quot Exit quot ) rawImagePixelsChange.restorePixels() loadGame false private void Update() if(loadGame) if (Input.GetMouseButtonDown(0)) StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, quot Game quot )) loadGame false private void PlaySoundEffect() transform.GetComponent lt AudioSource gt ().Play() In this script the MouseHover I want to find and get the save file name the mouse cursor is over the image that belong to the saved file. Either inside the OnHover function or inside the GetMouseButtonDown. Maybe it's be if I will save each image and it's saved file in another folder to identify easier what image belong to what saved file. now the way the images and saved files are on the hard disk each image the saved file to his left are belong to each other they have saved the same time. So when I click the button mouse down in the MouseHover script it should load the specific saved file the mouse cursor is over the image. |
0 | Vision Cone for Enemy AI in Unity 2d I am trying to develop an Enemy AI with vision cone in unity 2d top down game, can you please suggest me some approach or sample script, so I can get an idea. |
0 | How to instantiate a prefab only when something is hit, and for some seconds? How do I instantiate a prefab only when something is hit for a few seconds? I mean, I just need to activate the particle system when something is hit. Now it always runs, even before I hit something. I need it to activate the particle system when something is hit and for 2 3 seconds. This is what I do now public void Shot() Destroy(gameObject) Instantiate(effect, transform.position, transform.rotation) |
0 | Do i need to integrate leader board and achievement in my game and then publish in alpha testing for google play? I'm confused about whether I need to publish my .apk file on Google Play Console with or without achievements and leaderboard. If I publish the game without achievements and leaderboards, then, how can I integrate the google play service at a later date? The first thing I saw was that I should go for alpha publish. Is that necessary? If I do publish the alpha version for the game without including achievements and leaderboard, how can I add these later? In this video, first the game is published without the achievements leaderboard, and later he integrates them. So how does it show results since we didn't include these buttons for leaderboard and achievements? |
0 | Inspector stuck on Editor Settings Probably a silly question, but I'm having an issue where I can't view the properties of an object in the inspector window. It seems to be stuck on "Editor Settings". If I click an object I can't view its properties. Any idea what's going on it's confused me for the past 20 minutes. |
0 | Can I create new UI elements and use them from Unity? I created the following class, that should be used to display numeric text in a UI canvas (score, lives, etc.) public class NumericField UnityEngine.UI.Text SerializeField int value 0 override protected void Start() base.Start() text value.ToString() public int Get() return value public void Set(int newValue) value newValue text value.ToString() public void Add(int toAdd) Set(value toAdd) Now, I would like to add a NumericField into my Canvas, instead of adding a Text. But, when I right click the Canvas object, I do not see my NumericField. How can I add it to the menus, so that I can add it to the canvas? |
0 | How do I make an object destructible? How do I make one of my objects break into random pieces? I've tried Add Ons, Blender, and a few other things that I can't remember of the top of my head. |
0 | Unity LoadLevelAdditive and baked light scene settings I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light. So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive). Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ... So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override? Thanks. |
0 | How to stop camera rotation after reaching a specific angle? I have a camera in my scene that I want to rotate around the player. The rotation is done when the camera rotation state is at CameraRotation.Left or CameraRotation.Right and CameraRotation.None indicates that the camera should stop rotating and just follow the player. I want the camera to rotate around the player and stop after it reaches a specific angle (180 degrees) in the y axis in the CameraRotation.Left or CameraRotation.Right from the position the camera was at the start of the rotation. It would also be helpful if some direction is given on how to edit the SmoothFollow() method so that it follows the player with the camera still rotated. The problem is I'm not familiar with rotations and not sure whether to use Euler angles or quaternions so any tips would help. private void LateUpdate() if (GameManager. RotateCamera CameraRotation.None) SmoothFollow() else if (GameManager. RotateCamera CameraRotation.Left) transform.RotateAround(player.transform.position, Vector3.up, rotationSpeed Time.deltaTime) else if (GameManager. RotateCamera CameraRotation.Right) transform.RotateAround(player.transform.position, Vector3.down, rotationSpeed Time.deltaTime) Make the Camera follow the player smoothly private void SmoothFollow() Vector3 desiredPoistion player.position offset Vector3 smoothedPosition Vector3.SmoothDamp(transform.position, desiredPoistion, ref velocity, smoothSpeed) transform.position smoothedPosition transform.LookAt(player.transform) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.