_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Wrong Second position of LineRenderer I'm drawing some kind of bullet trace effect with LineRenderer in my 2D Game Project with Unity. At some position, setting position of LineRender result weird In the above screenshot, you can see two types of lines are exists. Pure red lines are result of Debug.DrawRay which is only renders in Scene view, not actual game play, and another lines which has yellow to red gradient are actual line renders I want to draw. I used exactly same code for rendering both two, Debug.DrawRay() and LineRenderer.SetPosition(), but as you can see only DrawRay works as I expected and LineRenderers are cutted and pointing wrong direction. Here's the code I'm trying void Fire() Vector3 shootDirection m ShootPoint.right RaycastHit2D hit Physics2D.Raycast(m ShootPoint.position, shootDirection, m Range) Debug.DrawRay(m ShootPoint.position, shootDirection.normalized m Range, Color.red, 20) On Hit, set end position where it hits if (hit) CreateBulletTrace(m ShootPoint.position, hit.point) Otherwise, render straight until it's range else CreateBulletTrace(m ShootPoint.position, shootDirection.normalized m Range) void CreateBulletTrace(Vector3 startPos, Vector3 endPos) GameObject bulletTraceObj Instantiate(m BulletTraceLineRendererPrefab) LineRenderer bulletTraceLineRenderer bulletTraceObj.GetComponent lt LineRenderer gt () bulletTraceLineRenderer.useWorldSpace true bulletTraceLineRenderer.SetPosition(0, startPos) bulletTraceLineRenderer.SetPosition(1, endPos) Destroy(bulletTraceObj, 0.1f) Note that LineRenderer checked use world space to true. What am I missing? Using Unity 2019.1.0f2. |
0 | A canvas to let through a given layer I have two canvases, both of them having a UI element on them. At some point, both canvases will be active in the game (I just act like so, I want to make sure that my game works even if that's the case) and I want one of them to never block the other canvas's layer. These two, let's say Canvas1 is on layer UI and is responsible for character jumping. Canvas2 is on layer toggle time scale and it's job is to switch between timescale 0 and 1. I want Canvas2 to be ALWAYS accessible, so its layer, toggle time scale is NOT blocked by the first canvas. I tried messing around with the Blocking Mask but that didn't help, sometimes the ray still gets blocked out. How to set up those Blocking Masks for my canvases to work? |
0 | How can I prevent picking up health items when I'm already at max health? This is what I have so far.. public class Per10HealthCollect MonoBehavior void OnTriggerEnter(Collider other) if (GlobalHealth.healthValue gt 91) GlobalHealth.healthValue 100 else GlobalHealth.healthValue 10 GetComponent lt CapsuleCollider gt ().Enabled false this.gameObject.SetActive(false) |
0 | Do realtime reflection probes and precomputed GI work on iOS in Unity 5? Seems they don't from my tests but just to double check. My setup is made up of a few objects marked as static, all sharing a standard shader material with some emissive color, GI set only to precompute and a realtime reflection probe (set to render on every frame) attached to the player, which is the object that moves and passes near the emissive objects. The player has a metallic material, also standard shader based. In the editor, this generates reflections on the player as it passes near an emissive object, as you'd expect. On iOS, the player looks dull, very dark, and no reflections appear on its surface. I also tried setting instead the probe to Custom and tell it to render from within a script, since I can't just pre bake the probes, because the static objects are brought in at runtime. This doesn't seem to work either the probe doesn't seem to render anything. Any ideas? |
0 | Objects rendering only on editor, but not on build (they get invisible) Everything works fine in the editor, but when I build the game, none of the objects in the scene are rendered, and only the skybox and UI text is visible. But although they aren't appearing, they are working as normally (i.e. these objects' triggers work normally when the determined event occurs, like for example, colliding to a specified object, or in other words, they are invisible). I searched for this issue but didn't found any answer. Could it be my cheap computer's fault (Intel Celeron without an external graphics card)? In editor game mode In buit game I ran both the editor and the built game in the same quality, and also tried to run it in Fastest quality, but no, it made no difference in the built game. Also, there is no object tagged with "Editor only", only one have a custom tag and all the others are "Untagged". And the camera's culling mask is set to "Everything". The result is the same either for web or Windows. Edit OK, I built for Android and the objects render normally. So, I'm not completely sure, but probably it's my PC that can't render the objects, because both building for web plugin and desktop have this disappointing result, but for Android it works perfectly (even the shadows, which wasn't being cast in the editor), so... |
0 | why command is not executing on local player I am getting very strange behavior, if my player instantiate as host (Server Player) then my command function runs perfectly and certain object become instantiate but if I join the host then my Command doesn't execute on my local player but runs on all other clients. void Start() if (isLocalPlayer) Debug.Log("It is VR Player spawn Start") SetVRLocalPlayerSetting() InstantiateMimicVRHeadAndController() CmdInstantiateMimicVRHeadAndController() else Debug.Log("It is not vr Player its not isLocalPlayer") DisableSelectedMonobevaiourScripts() Command This function have a problem public void CmdInstantiateMimicVRHeadAndController() Debug.Log("instantiateing the controller and head object") vrHeadCopyObj (GameObject) Instantiate(vrHeadObjPrefab) vrRightCtrlCopyObj (GameObject) Instantiate(vrRightCtrlPrefab) vrLeftCtrlCopyObj (GameObject) Instantiate(vrLeftCtrlPrefab) spawn the bullet on the clients NetworkServer.Spawn(vrHeadCopyObj) NetworkServer.Spawn(vrRightCtrlCopyObj) NetworkServer.Spawn(vrLeftCtrlCopyObj) |
0 | How do I draw a tilemap within unity3d? I'm pretty new to Unity and after a bit of googling around I have come up with this code to draw my tilemap (the script is attached to my camera). I am simply trying to use nested for loops to draw a grid of grass tiles, here is my code public class DrawMap MonoBehaviour Use this for initialization void Start () Sprite grass (Sprite)Instantiate(Resources.Load("Grass")) float x, y for (int i 0 i lt 20 i ) for (int j 0 j lt 20 j ) x i 1.28f y j 1.28f Instantiate(grass, new Vector3 (x, y, 0f), Quaternion.identity) Update is called once per frame void Update () I keep getting an error where I initialize "grass" saying the it cannot cast the source type from the destination type. I created "grass" to be a prefab from a slice of a spritesheet that i imported. Any help would be greatly appreciated |
0 | Unity2D How to destroy spawned object once it exit out of camera's view? I'm trying to destroy spawned objects once it exit out of camera view automatically straight away. You see I'm trying to make a flappy brids type of game but things also comes in from the bottom and if they get a really high score then things will be spawned in from above and from the left side. So, so far this is what my game looks like (I'm still working on it). However I'm having problems with deleting spawned objects once it exit out of camera's view, I tried all sorts of things like private var hasAppeared boolean function Start () hasAppeared false function Update() if (GetComponent. lt Renderer gt ().isVisible) hasAppeared true if (hasAppeared) if (!GetComponent. lt Renderer gt ().isVisible) Destroy(gameObject) But with this script, it doesn't destroy the game object quickly enough that and only some of them is being deleted. I also tried this method public void OnBecameInvisible() Destroy(gameObject) But not all of them is being deleted as well and it also takes a long time for any of my game objects to be destroyed. My last result was this script, it destroys the game object straight away once it exit out of the camera's view (which is what I want) but only these sides works where as the other's don't, I think it destroys my enemies (spawned objects) before it has even entered the camera's view. How do I get the script to work on this side? This is my script void Update () DestroyAllEnemy () public void DestroyAllEnemy() GameObject enemies GameObject.FindGameObjectsWithTag ("enemy") if ((enemies.Length gt 0) amp amp (camera ! null)) for (int i (enemies.Length 1) i gt 0 i ) just a precaution if ((enemies i ! null) amp amp ((camera.WorldToViewportPoint (enemies i .transform.position).x gt 1.03f) (enemies i .transform.position.y lt 6f))) Destroy (enemies i ) Thank you ). |
0 | Getting neighbors of hex tiles in 3D space I have a hex tiled model like attached below. Each of the hex tiles are separate objects meaning I can access each of the hex tiles individually inside Unity Now in my program I want to be able to get the 6 neighboring tiles of the selected tile. At first I thought I would get the 6 edges of the current tile and then check to see if any of the remaining tiles have those edges in common but that would be very expensive if I want to compute neighbors of all the tiles. Any ideas?? |
0 | Unity Editor Get Mouse coordinates on left click on Scene Editor I need a simple script which does the following When I left click somewhere in the Editor Scene (doesnt matter if there is an object under the cursor or not) Do NOT deselect the current selection in the Inspector. Do not select the object under the cursor. and Just print the mouse X and Z interception with the Y Plane in the Debug.Log() i stumbled on many solutions but somehow i couldnt get this to work. i tried HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) and Tools.current Tool.None both seem to do nothing ..... X.x EDIT Happens that "HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) " needs to be inside public void OnSceneGUI() and called every frame to "block" the mouse clicks on the editor. i thought it toggles it off. still the problem of the mouse coordinates persists. |
0 | Why is Particle System Not Visible Without Scene Window Viewing the Origin? I have a particle system, which is supposed to be highlighting an important game object, but the Particle System doesn't show on the game window unless the Scene window camera has the Origin (0,0,0) in view. The origin is at the corner of my UI canvases, in which you can see the two white lines marking the edges. Take a look at these screenshots. On the 1st screenshot, the particle system is not visible. The 2nd screenshot was taken just moments later and the particle system is completely visible (and the number of particles is as if it had already been emitting the whole time.) The only difference is that I slightly rotated the camera of the Scene Window in between screenshots. The camera was rotated down just a tiny bit to put the origin visible in the scene view. The particle system immediately becomes visible on the game window as soon as I rotate the SceneView camera so that the Origin is in view. This is Unity version 5.6.0f3. There are other questions about particle systems not working, but the cause and solutions appear to be very different. Here are things I've already tried The particle system is already set to "Play on Awake" both before and after rotating the camera. I've ensured that all of components and game objects are visible and enabled both before rotating toward the origin and after. All of the particle settings (size, etc.) are correct both before rotating to the origin and after. Why is the particle system not visible without the origin in the scene view? |
0 | 360 Orbital Camera Controller I have a stationary cube in my scene that I'm orbiting a camera around. I have my MainCamera nested under a GameObject that I'm calling 'OrbitalCamera'. I setup the script so that a click (or tap) and drag will rotate the camera around the object in space so it feels like you're rotating the cube (ie if I click the top of a face on the cube, and pull down, I'm rotating the X value) but you'll actually be rotating the camera. For the most part, my script works. However, after rotating the Y so much, the camera is upside down and the X gets inverted. Here's my script public class OrbitalCamera MonoBehaviour public bool cameraEnabled SerializeField private float touchSensitivity SerializeField private float scrollSensitivity SerializeField private float orbitDampening protected Transform xFormCamera protected Transform xFormParent protected Vector3 localRotation protected float cameraDistance void Start () cameraEnabled true xFormCamera transform xFormParent transform.parent cameraDistance transform.position.z 1 void LateUpdate () if (cameraEnabled) TODO FIX PROBLEM WHERE WHEN CAMERA IS ROTATED TO BE UPSIDEDOWN, CONTROLS GET INVERSED if (Input.GetMouseButton(0)) if (Input.GetAxis("Mouse X") ! 0 Input.GetAxis("Mouse Y") ! 0) localRotation.x Input.GetAxis("Mouse X") touchSensitivity localRotation.y Input.GetAxis("Mouse Y") touchSensitivity Quaternion qt Quaternion.Euler(localRotation.y, localRotation.x, 0) xFormParent.rotation Quaternion.Lerp(xFormParent.rotation, qt, Time.deltaTime orbitDampening) Is there a good method to achieve this type of 360 camera? I'd like dragging from right to left to always move the camera left and dragging left to right to always move the camera right no matter how the camera is oriented. |
0 | Too Low Amount of Tris in Statistics Window, Only in the Tens (Unity) I'm working on a mobile game, and for optimization it would be useful to see the correct amount of polygons rendered. However in the Statistics window the amount of polygons displayed are suspiciously low, only 62. Getting the poly count this low would be quite an achievement. I'm using the Universal Rendering Pipeline. Would there be a way to fix this? |
0 | Top down off screen indicator, Unity3D C I'm working on a top down 3D game where things spawn off camera. Movement only occurs on 2 axis (x and z). Rotation is about y axis. The player is in the center of the camera and needs to have indicators at the edge of the screen to show where the item is relative to the players location. I've managed to figure out the distance from my player to the target just using the distance between 2 Vector3 points. However, I can't figure out how to translate this into a direction angle for an indicator arrow that I have instantiated as a child of the canvas UI and make it point to the edge of the screen. |
0 | How to divide sprite sheet, but keeping the in same png? first post here, but couldn't find an exact answer in your database, so guess I'll have to ask. I want to know how it is possible to create a ".META" file for a .png so you can extract individual sprites in a spritesheet without having to save all the sprites in individual .png's. I know it's possible since the developer in the tutorial HERE is using a spritesheet like that. Thank you very much in advance. |
0 | Unity Change Text with Time (Text Flashes) I am trying to display instructions within the Unity game. The idea is to have the instructions appear over time. For example, "instruction 1" then wait 5 seconds and show "instruction 2" instead of instruction 1 (on the same spot, in this case, I am changing the "message" variable in the code to change the instructions). This code does change the instructions but the problem is that it does it in a haphazard fashion. It appears that "instruction 1" is replaced with "instruction 2" and then it reverts back to "instruction 1" within a second and then back to "instruction 2" so instead of just 1 appearing 1 disappearing 2 appearing etc in a smooth fashion, it does this weird flashing thing before proceeding to the next instruction. How could I fix this? using UnityEngine using System.Collections using UnityEngine.UI public class Growing MonoBehaviour public Text instructions public string message void Start () instructions.text message void Update () Instructions() other code to begin moving a game object IEnumerator Instructions() run instructions message "GET READY FOR YOUR FOCUSED BREATHING EXERCISE" yield return new WaitForSecondsRealtime(5) message "MAKE SURE YOUR BODY IS COMFORTABLE" yield return new WaitForSecondsRealtime(5) |
0 | Objects with custom shaders cast grayscale shadows when lightmapped Unity 5 seems to be able to calculate colored shadows from objects mapped with standart shader and legacy shaders. What should I do to make my custom shader to cast colored shadows as well? |
0 | Get object length and width divided by two? I have googled and found a script for the following task Make the camera move to touched position. However, this script will jump to x and y positions on an object, while i would like for it to move to the middle of the object, and then only be able to jump to others. using UnityEngine using System.Collections public class TapToMove MonoBehaviour flag to check if the user has tapped clicked. Set to true on click. Reset to false on reaching destination private bool flagTouchCoords false destination point private Vector3 cameraDestination alter this to change the speed of the movement of player gameobject public float duration 100.0f vertical position of the gameobject private float yAxis void Start() save the y axis value of gameobject yAxis gameObject.transform.position.z Update is called once per frame void Update() check if the screen is touched clicked if ((Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) (Input.GetMouseButtonDown(0))) declare a variable of RaycastHit struct RaycastHit hit Create a Ray on the tapped clicked position Ray ray for unity editor if UNITY EDITOR ray Camera.main.ScreenPointToRay(Input.mousePosition) for touch device elif (UNITY ANDROID UNITY IPHONE UNITY WP8) ray Camera.main.ScreenPointToRay(Input.GetTouch(0).position) endif Check if the ray hits any collider if (Physics.Raycast(ray, out hit)) set a flag to indicate to move the gameobject flagTouchCoords true save the click tap position cameraDestination hit.point as we do not want to change the y axis value based on touch position, reset it to original y axis value cameraDestination.z yAxis Debug.Log(cameraDestination) check if the flag for movement is true and the current gameobject position is not same as the clicked tapped position if (flagTouchCoords amp amp !Mathf.Approximately(gameObject.transform.position.magnitude, cameraDestination.magnitude)) amp amp !(V3Equal(transform.position, endPoint))) move the gameobject to the desired position gameObject.transform.position Vector3.Lerp(gameObject.transform.position, cameraDestination, 1 (duration (Vector3.Distance(gameObject.transform.position, cameraDestination)))) So this is how the game looks. The script moves correctly, but will jump at different positions when it hits the collider on the lily pads. I could reduce the collider, but I feel like there should be an easy way to get length and width of a collider, and reduce it by 2 to make the camera move directly in the middle. Anyone care to help? Thanks in advance. ) |
0 | In Unity, how to get reference of descendant? I'm trying to get descendant game object, not a child. Let's assume that I have a GameObject and it's hierachy looks like this Weapon Hands metarig upper arm.L upper arm.R forearm.L.001 hand.L.001 weapon.L.001 AttackDetection(!) Sword I want to access "AttackDetection" from Weapon(Root) in script. But when I try this void Start() attackDetectionGObject this.transform.Find("AttackDetection").gameObject It fails with this NullReferenceException Object reference not set to an instance of an object Looks like transform.Find just looking up it's own child, not descendant. I try to find way to solve this problem, but there's nothing I found. Any advice will be very very appreciate it. |
0 | Handling an item database with procedurally generated items? Let's say you have an item database which has every item in your game. This works fine for regular items like a Health Potion, a normal Iron Sword etc, because these items have ItemID's so we can get an exact copy of this item. But what if we have an Iron Sword with an enchantment ' 5 Fire Damage'? (or whatever) If you were to save that item to a player's inventory, exit the game and load the game, the item will load as a regular Iron Sword, because it still has that ID. Specifically, how would you save that item to a file? I'm using Unity, so to save the Player's inventory, I use PlayerPrefs.SetInt("Inventory " i, inventory i .ItemId ) Would you create a custom item ID for every item with enchantments or is there a better way around this? |
0 | Rotating a gameworld using quaternion I'm a hobbyist programmer at best and I had an idea I wanted to test in Unity, I wanted to rotate the game world around 90 degrees, to this end I've been learning a tiny bit about quaternions, in this simple test I have a empty game object at position 0,0,0 and 2 cubes placed so only one will be in the foreground at once (both children of the empty game object). I simply want to rotate the parent object on a mouse up like so. if (Input.GetMouseButtonUp(0)) Quaternion newrot Quaternion.Euler (0,90,0) transform.rotation Quaternion.Slerp (transform.rotation,newrot,0.05f) The problem I am having is that this does not do the rotation in a single click and never reaches 90 degrees, it only ever tends towards 90 (for fun I decided to click for 2 minutes and only got up to 89.99999 ... well you get the picture). Can someone tell me what I am doing wrong and if there is a better way of doing this? |
0 | How can I make outline shader like "Life is Strange"? I want to make sketch shader like life strange. shader has two part 1.animated dashed line 2.noisy outline I like to know how can I make noisy outline? see outline of objects First I tried to make outline by copying of incoming vertex data and scaled according to normal direction then Cull Back.but I think it's something like Image effect because outline sometimes move inside of object. anyway I will appreciate if someone help me to Implement this shader ) What I tried I used edge detection and animate it by vertex shader but this isn't good like above gifs. |
0 | How can I tell if a Gameobject is currently touching another Gameobject with a specific tag? I've seen similar questions to this here on Stack Exchange Game Development, but none of the answers to them have helped my problem. I am working in Unity 2019.2.18f1 with Visual Studios 2019 Community. What I want to know how to tell when one Gameobject (the player) is currently touching another game object with a tag name of "Block". When the player collides with a "block" I want it to set jumpPossible true But when it leaves the block (by jumping or falling off) jumpPossible false What I currently have in my PlayerController script (the important stuff anyways) private void OnCollisionEnter(Collision collision) if (collision.gameObject.CompareTag("Block")) jumpPossible true private void OnCollisionExit(Collision collision) if (collision.gameObject.CompareTag("Block")) jumpPossible false The problem I am having is when the player is currently on a block and then touches another block. When it leaves the one of the blocks, it will set jumpPossible false and so you can't jump. What I want for this script to do is whenever the player is touching any Gameobject with a tag of "Block" it should allow it to jump. |
0 | fading from one scene to another not working I am using the following code to fade from one scene to another, but it doesn't fade. It just loads the next scene without fading. I suspect there's something wrong with the image I'm using. I used a black .png image with dimensions 425 344 that I downloaded from Google. How can I solve this issue? Fading.cs (I added this to an empty game object) public Texture2D fadeOutTexture public float fadeSpeed 0.8f private int drawDepth 1000 private float alpha 1.0f private int fadeDir 1 void onGUI () alpha fadeDir fadeSpeed Time.deltaTime alpha Mathf.Clamp01(alpha) GUI.color new Color (GUI.color.g, GUI.color.b, alpha) GUI.depth drawDepth GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture) public float BeginFade (int direction) fadeDir direction return (fadeSpeed) void onLevelWasLoaded() BeginFade ( 1) In the script of the trigger object IEnumerator gameScene2() float fadeTime GameObject.Find ("FadeObject").GetComponent lt Fading gt ().BeginFade(1) yield return new WaitForSeconds(fadeTime) Application.LoadLevel("Scene2") These are the image settings for the black .png image |
0 | ToonRamp Shader Normal Maps How to keep strict lighting bands? I'm trying to achieve a shading similar to the one on this image Image 1 https imgur.com a eTTvSCD To get something similar to this I wrote a toon ramp shader (similar to the one in the Standard Assets) with normal maps. The shader works, and without a normal map you can see the lighting bands strictly defined, with visible seams separating them (Image 2). But once you add a normal map, the toon bands won' t have well defined seams anymore, and will blend smoothly all across the mesh (Image 3). Image 2 amp 3 https imgur.com a SI3BxED This is my current shader Shader "Custom ToonRampWithNormals" Properties Color ("Color", Color) (1,1,1,1) MainTex ("Albedo (RGB)", 2D) "white" BumpMap("Bumpmap", 2D) "bump" Ramp("Toon Ramp", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Ramp Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D Ramp half4 LightingRamp(SurfaceOutput s, half3 lightDir, half atten) half NdotL dot(s.Normal, lightDir) half diff NdotL 0.5 0.5 half3 ramp tex2D( Ramp, float2(diff,diff)).rgb half4 c c.rgb s.Albedo LightColor0.rgb ramp atten c.a s.Alpha return c struct Input float2 uv MainTex float2 uv BumpMap sampler2D MainTex sampler2D BumpMap half Glossiness fixed4 Color UNITY INSTANCING BUFFER START(Props) put more per instance properties here UNITY INSTANCING BUFFER END(Props) void surf (Input IN, inout SurfaceOutput o) Albedo comes from a texture tinted by color fixed4 c tex2D ( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Normal UnpackNormal(tex2D( BumpMap, IN.uv BumpMap)) o.Alpha c.a ENDCG FallBack "Diffuse" So, what have I done wrong? How can I have well defined lighting bands and have normal mapping? If you can think of a better way to achieve something similar to the reference or have any thoughts about it please share, any contribution is much appreciated. |
0 | Animator Component gets removed automatically Unity I am creating a simple scaling animation on image (in Unity). When I play game in unity editor, the animator component get removed automatically. Here I am copying snapshop of Inspector of Image. What should I correct? |
0 | How to add a fluorescent effect on an image in Unity I have recently been attempting to create a true on screen representation of a fluorescent orange colour on an image. Whereby, I believe post processing with unity will deliver the best results. Thus, I was wondering if someone could kindly guide me through the steps to add a fluorescent effect to my image? As a reference I would like to try match pantone 804c on screen. Image in question I have tried to follow tutorials like this, but unfortunately they all are working on 3D scenes. I have a pre existing jpg image that I want to modify. |
0 | How to FindGameObjectsWithTag then cast the array of GameObjects to an Array of Interfaces I have a few GameObjects that implement a common Interface IsTree. I need to call the function doTreeThing() on each of those IsTrees after getting a reference to each of them via FindGameObjectsWithTag("tree"). This line complains that it cannot implicitly convert from GameObject to IsTree IsTree trees GameObject.FindGameObjectsWithTag("tree") So then I tried to leave the GameObject an iterate over it to convert each individual object inside to an IsTree. GameObject trees GameObject.FindGameObjectsWithTag("tree") foreach (GameObject tree in trees) IsTree isTree (IsTree)tree isTree.doTreeThing() But this complains that it also cannot convert GameObject to IsTree. Then I got a little desperate and tried to make my IsTree into a GameObject. public class IsTree GameObject public System.DateTime getAge() return null GameObject is a sealed type. (I don't really know what that means besides that this does not work) So how do I get this array of GameObjects into an array of SomeInterface? |
0 | Adding Score to score canvas after collision Simply a player has to move through pipes falling down, once the player moves through the gap it should add a score and increase the scoring after each pipe the player goes through, pretty basic. I have made a prefab object and it is a block with a collider on it and another collider that acts as a trigger behind it stretched out so it can be accessed on both sides. I then added to the main scene canvas textmeshpro added a script with the following code however, when the player hits the collider the score does not increase in the scene. But if I remove the GetComponent then it increases by increments of 4 in the inspector. using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() GetComponent lt UnityEngine.UI.Text gt ().text Score.ToString() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score |
0 | How to do camera follow without drag and drop in Inspector in Unity? How to do camera following an object with special tag without drag and drop into Inspector? I have 2 prefab model they are not into hierarchy for the moment when player start play. To load selected model into scene I'm using the below code. public GameObject players void Start () LoadPlayer () private void LoadPlayer() GameObject player Instantiate(players PlayerPrefs.GetInt(MyModel") ) Because in other scene I can change my player model but I can't follow it using in c script for camera public Transform cause of I can't drop it in that place in Inspector. So in what way I can find current player object when game start to follow it by camera? |
0 | How can I do unit testing in Unity? How to implement Unit Test at Unity3D. I wonder if it would be possible to extend the Unity editor to have some sort of testing framework in it. Is there any guideline to implement it? Any reference like book, blog? Any working example or project? |
0 | Surface Depth Intersection Shader I recently asked a question about the creating an accurate Depth Intersection Shader. When creating this in a fragment vertex shader it could be achieved by the following code SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" Pass CGPROGRAM pragma target 3.0 pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 float3 normal NORMAL struct v2f float2 uv TEXCOORD0 sampler2D MainTex float4 MainTex ST sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength v2f vert(appdata v, out float4 vertex SV POSITION) v2f o vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag (v2f i, UNITY VPOS TYPE vpos VPOS) SV Target float2 screenuv vpos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(vpos.z) float intersect 0 if(diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) return fixed4(lerp(tex2D( MainTex, i.uv) Color, GlowColor, pow(intersect, 4))) ENDCG However, when I try to put the same logic into a surface shader, the result does not show any depth intersections. SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows alpha fade Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex struct Input float2 uv MainTex float4 screenPos float eyeDepth half Glossiness half Metallic sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. See https docs.unity3d.com Manual GPUInstancing.html for more information about instancing. pragma instancing options assumeuniformscaling UNITY INSTANCING CBUFFER START(Props) put more per instance properties here UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float2 screenuv IN.screenPos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(IN.screenPos.z) float intersect 0 if (diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) fixed4 col fixed4(lerp(tex2D( MainTex, IN.uv MainTex) Color, GlowColor, pow(intersect, 4))) o.Albedo col.rgb o.Alpha col.a o.Metallic Metallic o.Smoothness Glossiness ENDCG |
0 | RTS Unit AI When to let the unit stop (due to local avoidence) I am developing an RTS like game, that have units that move and attack. I implemented path finding and local avoidance. One problem is when multiple units being ordered to the exact same position, they can never reach the position due local avoidance and collision. Only this will make the units scratch each other, this will also cause the unit not able to STOP, as the unit might be still far from the target position. And whether stopped or not is important for battle (unit can only attack when stopped). I studied how SC2 handles this, it appears that the units will stop after a few seconds of scratching. PS, I have used group formation to avoid the situation, but it can not be avoided, when the group are ordered to goto some impossible position, and they would cluster at the edge of the valid navmesh. |
0 | How to make a script's Gizmo toggleable in the Gizmos menu in Unity3D? I've implemented Gizmos for a few behaviours, and I'd like to make them toggleable in the Gizmos menu, just like the built in ones. Is this achievable? |
0 | Move a ball horizontally left and right but restricting forwards and backwards motion unity 2d I am trying to develop an endless runner where there is a sphere as the player and it is moving left and right following the position of a finger on a touch screen. However, when I try to do this I cannot get the player to lock on the Y axis. I want a constant force that speeds up overtime which I have using the constant force 2d supplied by unity. I have two versions of code, the first follows the finger but the player is able to move up and down as well using UnityEngine using System.Collections public class Test MonoBehaviour public GameObject character public float speed 500.0f void Start() Input.multiTouchEnabled false void Update() if (Input.touchCount 1 amp amp Input.GetTouch(0).phase TouchPhase.Moved) Vector2 target Camera.main.ScreenToWorldPoint( new Vector2(Input.mousePosition.x, Input.mousePosition.y)) character.transform.Translate(Vector3.MoveTowards(character.transform.position, target, speed Time.deltaTime) character.transform.position) The second code I have allows the player to move left and right by tapping rather than following but is still sloppy using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody2D rb public float sidewaysForce 500f Start is called before the first frame update void Start() rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update() foreach (Touch touch in Input.touches) if (touch.position.x lt Screen.width 2) rb.velocity new Vector2(sidewaysForce 1, rb.velocity.y) if (touch.position.x gt Screen.width 2) rb.velocity new Vector2(sidewaysForce 1, rb.velocity.y) Any help on this would be awesome Thanks!!! |
0 | How can I prevent the knob from resizing when I use the Slider? I am using the Unity Slider component. I have a custom background and custom knob. But whenever I move the slider, my knob's size becomes distorted. It is 100x100 pixels, and when I set it to its native size, it does so. But I soon as I move the slider, it cuts its height in half. How can I prevent this from happening? |
0 | Simple Line Formation I'm working on the first formation for my game's troops. These should simply stand on land, facing the same direction. To achieve this, I tried to create offsets towards a pivot unit, that is approximately the unit in the center of the formation. The units are (temporary) elements of a squad list withing the Squad class. I divide the List by 2 and get the closest integer, that should be the pivot point of the formation. Now I generate offsets for all units on the left side (Unit 1 to pivot 1) and right (pivot 1 to last unit) based on the distance gaps. This is the code for the line formation. Sadly, the units are only forming a very stange line with no visually detectable system int count (int)(squadMembers.Count 2) pivot squadMembers count center pivot.transform.position switch (type) case FormationType.Line int space 5 for (int i 0 i lt squadMembers.Count i ) Unit tmp squadMembers i int dist 0 if (i gt count) dist (count 1) space center.x dist if (i lt count) dist (count 1) space center.x dist tmp.StartMove(center) break It also appears that this only works along the x axis, any idea how i can realize this with the walking facing direction ov the pivot? Is there any (obvious) error? How can I improve this script? PS Any idea, how I can transform this into a double line (2 Lines behind with half spacing) |
0 | Line renderer's baked mesh not moving correctly with the line I used LineRenderer' Bakemesh to create a mesh around the line drawn, it is placed exactly, but when the line moves, the mesh is not following its movement. |
0 | How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d? I have two character in my game enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way void FixedUpdate() if (CanMove) transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) public void StartMove(bool canMove) CanMove canMove TargetPlayer GameObject.FindGameObjectWithTag(Tag).transform rigidbody2D.gravityScale 0 This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good looking? Edit I need to make good looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the current player position. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air(( Edit 2 I was thinking about destroying that object anyway, but to my mind this will not look good the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself. |
0 | Unity UI Input Field suddenly malfunctioned I'm using Unity 5.0.1f1, and my UI Input Fields are not working as they are supposed to. I have an Input Field that is placed in a Panel and inside a Canvas. It has a Text component in which I can set text that the Input Field will display. When I change value of this Text component, the changes are not reflected on the Input Field, it seems to be reset to the value of Input Field (Script) Text of the Input Field. If I enter Play mode, I can input text normally but when I build and run on my Android phone, I cannot input anything. Has anyone encountered this problem? How can I solve this? |
0 | Get rotation of camera in Google VR I'm trying to move child of camera object smooth. To implement that, I need to know the movement of x and y axis, like Input.GetAxis in general PC platforms. I saw the documentation and examples of Google VR, but there's not much explained well. One thing I found is GvrControllerInput.Gyro, but it's said it's deprecated and use GvrControllerInputDevice.Gyro instead, but there's no Gyro value in GvrControllerInputDevice. Seems like basic usage is totally changed, so they are not providing static methods, and force to using internal method of the object, but couldn't find any related information about this. So, how do I get gyro from GvrControllerInputDevice? Or is there an alternative way to make child object rotate smooth from their parent? Any advice will very appreciate it! |
0 | Set Layer of UI Object being Dragged In my game, I have an inventory system with slots and images in those slots. The images are by default disabled, but when an item is added to the slot, the image component becomes enabled. I have implemented a very simple drag and drop system for moving objects around in the inventory using IBeginDragHandler, IDragHandler, and IEndDragHandler. As I am dragging an item from one slot to another, I want the item image to be rendered in front of the slots and the rest of the inventory. Currently, when dragging an item image, it renders behind the empty slots. I don't want to use hierarchy order to organize the layers of these slots because moving items around is very dynamic and the hierarchy order of the slots changes seemingly randomly when I press play. Is there another way to ensure that the item image being dragged is "closer to the camera" or in front of the rest of the inventory? Thanks. |
0 | How to revert to MonoDevelop's old "ctrl tab" behavior? I believe MonoDevelop (bundled with Unity3D) has changed its ctrl tab and ctrl shift tab behavior and I would like to get back to the old behavior, as the new way frustrates my workflow. Ctrl tab (and ctrl shift tab) previously (and ought to) go to the "last viewed tab", in a similar way to how alt tab works on Windows. Unfortunately there seems to have been a change and now it goes to the "tab on the left of the current one". An example of why this is frustrating quickly looking at a class definition, you hit F12 to load the definition (perhaps in a new tab), and then you want to go back to the code you were working on. Previously you could hit ctrl tab and you'd be back there. Now you can't do that and you have to actually remember what you were doing, which isn't good for my workflow (read ailing memory). I'm not sure when the change happened, or if it's a setting somewhere (I can't find it). I'm running Unity 5.1.2p2 and its bundled MonoDev 4.0.1. Noticed it after a clean install of Windows 10. How can I fix this to revert to the old behaviour, or is there some other method to jump back to the last viewed tab? It seems pedantic but it has a major impact on my productivity. |
0 | Using unity Rigidbody 2D gravity, how to add to velocity? I am creating a top down game, and have an object I want to create a small bouncy illusion for. Since I dont have anything to collide with I'll have to do it with Scripts. Without Unity I would probably do something like function fall () this.vertical speed this.vertical speed GRAVITY if (this.vertical speed gt TERMINAL VELOCITY) this.vertical speed TERMINAL VELOCITY this.vertical position this.vertical position this.vertical speed However in Unity we have the Rigidbody 2D, so I want to somehow use that for this. if I set rigidBody.velocity new Vector2(1, 0) speed delta , it gets a constant speed, and ignores gravity. How can I add gravity? i.e I want to create a curve like |
0 | How to create a standard pbr material with shader graph? I want to create a standard pbr material that is editable with the shader graph, but when I install the package and go the Create gt Shader tab, I only have 2 graph options Empty Shader Graph, and Sub Graph. Isn't there a shader graph that starts me off with a basic pbr material with color and reflections? I'm using unity 2020, and the default render pipeline. Do I need to switch to ldrp or hdrp? |
0 | How to Handle Lighting from a 3D Game Engine with a Roguelike Game using Shadowcasting Normally the shadowcasting will, from the player position, set a brightness amount to each relevant tile. Yet I'm making a roguelike with a 3D map, and Unity has lighting. Currently I have the player piece with a point light, and game objects that haven't been seen yet are set to inactive. but it doesn't have the same effect. Has anyone resolved this situation? Any suggestions? Addendum Screen shots I somewhat like the effect as it is in the screenshots I'd like to be able to control the amount of light in each 'tile' if possible. |
0 | Unity Disable push on dynamic Rigidbody2D objects I have a player, and several NPCs. I also have several static colliders in the world (trees, water, fence, etc), I want my NPCs to collide with this, so the Rigidbody2D needs to be dynamic, since kinematic does not collide with static colliders (colliders without a rigidbody). My problem is that since both player and NPC have dynamic rigidbodies, they push each other when they collide. I could disable this by setting the following in the NPC script void OnCollisionEnter2D(Collision2D other) if (other.gameObject.name "Player") isMoving false myRigidBody.isKinematic true However, the NPC still gets pushed a few pixels before it stops, its barely noticable, but it is noticable, and if you keep colliding with the NPC you could move it as far as you wanted (tedious, but possible). I've spent a few hours looking and cannot find a good solution to this. I want my NPC to collide with static colliders, but I don't want them to get pushed by the player. How can I solve this? |
0 | Using PlayerPrefs to save audio volume throughout scenes in Unity I have game that plays music. I have a mute toggle button that will mute my game music when you press on it, it will also un mute it when you press it again. I'm having problems with saving the audio volume when a scene is loaded. (I tried using DontDestoryOnLoad but my mute script is attach to my main menu canvas so its saving the canvas as well, which I do not want. I find using playerprefs a lot easier). For example, when I click on my mute button, it mutes my game, I play the game, die, restart the game and the volume is being restarted as well. Even though I used playerprefs to try and solve the problem it didn't work, it still did the same thing. Anyway this is my script public bool mute public static Vector3 target void Start () PlayerPrefs.GetFloat("mute") void Update() PlayerPrefs.GetFloat("mute") private void Muted () mute !mute if (mute) gameObject.GetComponent lt AudioSource gt ().volume 0 PlayerPrefs.SetFloat("mute", 0) else gameObject.GetComponent lt AudioSource gt ().volume 1 PlayerPrefs.SetFloat("mute", 1) |
0 | Elongated and straight terrain perlin noise Why am I getting this kind of results with my perlin noise ? The terrain is wide or elongated or straight at the variations of the noise function. This is the way I generate terrain public void GenTerrain() for (int x 0 x lt this.size.x x ) for (int y 0 y lt this.size.y y ) float xCoord (float)(x offsetMirror origin.x) this.size.x scale float yCoord (float)(y offsetMirror origin.y) this.size.y scale float noise Mathf.PerlinNoise(xCoord, yCoord) if (noise gt 0.6f) this x, y .terrainType TerrainType.Grass else if(noise gt 0.5f) this x, y .terrainType TerrainType.Sand This is the way I add chunks of terrain void Start() maps new Dictionary lt Vector2Int, Map gt () Res.LoadMaterials() void AddNeighbours(Vector2Int position) int length 32 for(int x length x lt length x ) for(int y length y lt length y ) Vector2Int addPos new Vector2Int((x size) position.x, (y size) position.y) CheckAndAddMap(addPos) void CheckAndAddMap(Vector2Int addPos) if (!maps.ContainsKey(addPos)) AddMap(addPos) void AddMap(Vector2Int origin) Map map new Map(new Vector2Int(size, size), origin) maps.Add(origin, map) MapMesh mapMesh new MapMesh(map) foreach (KeyValuePair lt TerrainType, MeshData gt kv in mapMesh.meshes) MeshData meshData kv.Value TerrainType terrainType kv.Key GameObject go new GameObject( quot Mesh quot ) go.transform.SetParent(this.transform) go.transform.localPosition new Vector3(mapMesh.map.origin.x, mapMesh.map.origin.y, (int)kv.Key) MeshFilter meshFilter go.AddComponent lt MeshFilter gt () meshFilter.mesh meshData.mesh MeshRenderer mr go.AddComponent lt MeshRenderer gt () mr.material Res.mats terrainType.ToString() Update is called once per frame void Update() Vector2Int playerPosition ConvertPlayerPositionToTiles(ShootBehaviour.PlayerInstance.transform.position) AddNeighbours(playerPosition size) private Vector2Int ConvertPlayerPositionToTiles(Vector3 position) Vector2Int result new Vector2Int() result.x (int)position.x size result.y (int)position.y size return result |
0 | Unity Smooth collision I'm making a topdown 2D RPG in Unity. All moveable objects have Rigidbody2D components with gravity set to 0, linear drag set to 5 and different masses. Walls are stationary boxes with BoxCollider2Ds. Here's my problem http a.pomf.se nifmcn.webm The rock is not particularly easy to see, but if you watch when I'm trying to walk into a wall, the player kind of jags in and out of the wall. Of course, this is because I'm moving the player by moving it's Rigidbody2D, for example rigidbody2D.transform.position Vector3.up Time.deltaTime speed The box then throws the player in the opposite direction of what he was going. What's a good way of stopping a player from moving in the direction he's trying to go? More specifically, how do you detect which way he's going? Do you find the angle between the player and the object wall? This is kind of an open question, but I think it's extremely important. |
0 | 2D physics without "rebound" I'm trying to get my 2D top down shooter to use some physics. I want the player and enemies not be able to exist in the same position, in other words, use collisions. My first attempt was to use a CharacterController, but I could not get my other game objects to collide with my player, even though I had a RigidBody2D and a BoxCollider2D on them. Obviously, due to using a CharacterController, I was not able to add these components on my player. Going one step back, I removed the CharacterController, and rather opted to go the Rigidbody2D route. This worked partially. I now get collisions on my player when he walks into other gameobjects (with RB2D and BC2D on them), but there seems to be a quot rebound quot anomaly occurring my player moves around after collision. I've tried playing around with the settings on the RigidBody2D on the player, but it does not seem to have any effect. This is my PlayerMovement script void Update() HandleRotation() HandleMovement() void HandleRotation() var mousePos Input.mousePosition mousePos.z 5.23f var objectPos Camera.main.WorldToScreenPoint(transform.position) mousePos.x objectPos.x mousePos.y objectPos.y float angle Mathf.Atan2(mousePos.y, mousePos.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(new Vector3(0, 0, angle)) void HandleMovement() float horizontal Input.GetAxisRaw(Constants.Axis.Horizontal) float vertical Input.GetAxisRaw(Constants.Axis.Vertical) Vector3 direction new Vector3(horizontal, vertical, 0f).normalized if (direction.magnitude gt 0.1f) var speed (Input.GetKey(KeyCode.LeftShift) Input.GetKey(KeyCode.RightShift)) ? mobileController.runningSpeed mobileController.walkingSpeed var moveVector (direction speed) transform.position mobileController.rigidbody2d.MovePosition(moveVector) var camPosition new Vector3(mobileController.transform.position.x, mobileController.transform.position.y, 10) cam.position camPosition The settings on my Player I would like my player to stop dead in his tracks when colliding with another RigidBody2D. Is this possible? And if so, how would I go about doing that? |
0 | Unity3D Facebook login into the game Verification on Server Side I don't need to know the specific code required for that, but I want to understand at high level how can I implement that and what SDKs I have to use to achieve that. Facebook PHP SDKs Ok If I want to perform login with Facebook into my web page. Unity3D's Facebook SDK Ok If I want to perform login inside my App without a server (apart Facebook's servers of course). What I want to achieve is User login into facebook from the App (just once, and eventually the option to log out on request of user, or to relog if login data expires) Login is verified by my Server (actually a user should really have a facebook account) Do not embed stuff like Facebook App ID in my App source code. My server will store some data for each user and to identify users I need to be able to use some unique data provided by Facebook like session token etc. Of course the session token may change so I need anyway to be able to identify the user (to avoid losing memorized data). |
0 | How to start simple game development with Unity 5 I want to start developing games with Unity because it's easy to learn, but I don't know where to start. My questions are Which preparations should I make for a game? Are there any tips and tricks for efficient work? Do I need special equipment? Thank you for your response! |
0 | Create prefab asset from object without creating object in the scene I am writing an editor tool that is supposed to generate prefab objects from a parsed TMX file. Since this is a special case because I don't want to instantiate objects, but rather create them there are not much documentation on how to do this. I have come up with a way that actually creates an .prefab file from a gameobject. But the problem is that when I do this, the gameobject itself is created and put into the hierarchy. I only want the .prefab asset file. This is they way I am doing it now. static void ConvertFile(string filepath) This function returns a "new GameObject()" with attached components However, this function still puts the new game object in the scene amp hierarchy which is not what I want GameObject mapObject mapLoader.fromFile (filepath) string filename System.IO.Path.GetFileNameWithoutExtension (filepath) Create prefab file from an object PrefabUtility.CreatePrefab ("Assets " filename ".prefab", mapObject) public GameObject fromFile(string filepath) Removed code that parses file for easy read GameObject gameObject new GameObject () return gameObject |
0 | Unity 2d, Place object nearest to a coordinate without overlap? I am working on a game similar to Pool (Carrom actually). I need to place coins at the center of the board or nearest possible to it without overlapping any other coins. This is a 2d game. |
0 | How to make a character that moves like a slinky? I have a school assignment to make a 2D platformer game, with a character that moves like a slinky (Animated example from the assignment linked above) At first, the character needs to grow in height over time When the player presses a button, the character starts to bend toward the next platform Its height when you press the button determines whether it will hit the next platform After that it must shrink to its initial size, and it goes over again. How can I approach this? |
0 | Causing Update loop with Coroutine Unity Total Noob Alert! lt 7 days with C and Unity My Win Game screen becomes SetActive and my Player is SetActive false when you are standing in a trigger and crouch. That all works fine except you cant see the crouch animation because he is IMMEDIATELY SetActive false. I tried to delay this by creating a coroutine. The problem with that is this is all happening in the Update function (or whatever it's called) because of the getkeydown for crouch. That gets called once per frame so my coroutine is trying to go off once per frame. I tried creating a bool called isCoroutineStarted and set it to false and then set it to true in the Coroutine to break the loop but that didn't work either. Don't know what to do so I reverted it back to before where it doesn't show my crouch animation. Here's my script (It's attached to a Game Object with the trigger) using System.Collections using System.Collections.Generic using UnityEngine public class xxxxxx MonoBehaviour public bool xxx false SerializeField private GameObject youWinUI SerializeField private GameObject player Determines whether or not the player is standing on the xxxxx void OnTriggerEnter2D (Collider2D other) xxx true void OnTriggerExit2D (Collider2D other) xxx false Turns on Win screen and makes player disappear when crouch on xxx void Update () if (Input.GetKeyDown (KeyCode.S) amp amp xxx true) youWinUI.SetActive (true) player.SetActive (false) P.S. ignore the x's no stealsies lol. Also this piece of script works as intended I just want a delay so you can see the crouch animation. |
0 | Collision2d Unity To Change Another Scripts Int Value I am looking to decrease the value stored in my script "progress" which takes 1 away from a value curHealth, when the Player sprite to which this script "collision", is attacked touching the Enemy 2d box collider. The decreasing of the value doesn't happen when the two objects touch. Both the Player and the Enemy have 2dbox colliders and other shape 2d colliders. using System.Collections using System.Collections.Generic using UnityEngine public class collision MonoBehaviour public progress Progress GameObject.FindGameObjectWithTag("HealthBar").GetComponent lt progress gt () void OnCollisionStay2d(Collision2D coll) if (coll.gameObject.name "Enemy") Progress.curHealth 1 |
0 | The name 'txt' does not exist in the current context I am getting the error The name 'txt' does not exist in the current context and I am unsure why this is happening. I am very new to programming in C so sorry if the answer is obvious. I am trying to make my ammo count change on screen and have been told to use txt.GetComponent lt UnityEngine.UI.Text gt ().text ammo.ToString() but that gives me the error and I am unsure why. This code is supposed to spawn in bullets for my gun but that part of the script is not important. The problem is that error. If you could tell me what the problem is that would be greatly appreciated. Here is my code using System.Collections using System.Collections.Generic using UnityEngine.UI using UnityEngine public class PL MonoBehaviour public GameObject bulletPrefab public Camera playerCamera private Coroutine hasCourutineRunYet null public int ammo 165 65 enemies in total, needs tons of ammo public GameObject axe public Text Ammmo Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) if (hasCourutineRunYet null) hasCourutineRunYet StartCoroutine(BulletShot()) if (ammo 0) GameObject.Find( quot wp shotgun quot ).SetActive(false) axe.SetActive(true) txt.GetComponent lt UnityEngine.UI.Text gt ().text ammo.ToString() IEnumerator BulletShot() GameObject bulletObject Instantiate(bulletPrefab) bulletObject.transform.position playerCamera.transform.position playerCamera.transform.forward bulletObject.transform.forward playerCamera.transform.forward yield return new WaitForSeconds(1.0f) hasCourutineRunYet null ammo |
0 | The rightmost part of the game screen is truncated in HTML I created a game that, when I play it in Unity, looks like this But when I build it in WebGL, the rightmost part of the screen (with the red player character in it) is truncated Play it in browser on itch.io to confirm. It looks the same when I open the HTML file locally, so the problem is with the WebGL version and not with itch. Only when I click the "full screen" button, the rightmost part is shown. What am I doing wrong? |
0 | "Hold to jump higher" suddenly outputs a much higher jump I'm programming my first game in Unity and I'd like to make a very controllable jump. The idea is to apply an upward force while the player is still pressing the jump button, and then after some time ignore jump input. Kinda like how Mario and Mega Man jump. Problem is, somehow, my character occasionaly jumps much higher than it normally does. I set three variables on the inspector jumpImpulse the initial speed after pressing the jump button riseAcc the acceleration applied to the character while holding the jump button maxJumpHoldTime the longest possible time one might hold the button while still rising. if ((onGround onPlatform) amp amp Input.GetButtonDown("Jump")) GetButtonDown prevents holding jump and keeping jumping rb.AddForce(Vector2(0,(jumpImpulse rb.mass)), ForceMode2D.Impulse) force that starts the jump itself. rb.mass makes F ma into F ma m gt F a, so "Force" is actually acceleration. This is to better control mass and jump mechanics. jumping true DEBUG debugJumped true if (jumping amp amp Input.GetButton("Jump")) rb.AddForce(Vector2(0,(riseAcc rb.mass)), ForceMode2D.Force) first acceleration jumpHoldTime Time.deltaTime if (jumpHoldTime gt maxJumpHoldTime) jumping false else jumping false jumpHoldTime 0 Made this so I know how high the character jumps. if (debugJumped amp amp (!onGround) amp amp rb.velocity.y lt 0) Debug.Log ("Jump height is " transform.position.y) debugJumped false In the console, the jump height is listed normally as 2.376213, but sometimes it appears as 5.008272. It appeared once as 2.377432. Also, this variation seems to appear more frequently when I'm also moving the character left or right. And I'm not sure if this is related, but there are many times when I press the jump button and the character simply doesn't jump. Also, I put everything here under the FixedUpdate function. |
0 | How do I make an object not appear grey regardless of distance? My moon texture is on a plane 500m away and I would like to know if there is a way to keep displaying the texture As opposed to it turning grey as pictured here regardless of the distance it is from the camera. Any help is greatly appreciated, Thanks. |
0 | Loading a web page in unity Hello I need to open a page in unity and save some of it's contents but I have absolutely no idea how I should do it. Thanks for help. |
0 | Non invocable memeber 'Text.text' can not be used as a method Trying to change text in a text box, and have multiple lines on it, i found something online talking about quot n quot but this came up. Non invocable memeber 'Text.text' can not be used as a method. This is my code private void Start() if (creditEnding) startText.text( quot You, died? n well you should get some sleep anyways quot ) |
0 | Unity Capture And Display Live Camera Feed I want to display the video using the device camera on specific part of the screen on iOS, android and Editor. I was able to find the WebCamTexture which display the camera video on the Quad (3D Object). Now I want to record the video and save it on the disk. Is there are way to do that ? Or is there a better way to do that using unity or through plugin ? |
0 | When when pressing on the G key one of parts is scaling slower then the other? Each Prefab is built with canvas and two panels childs of the canvas. I'm scaling the two panels. The automatic mode part is working fine. The problem is with the G key. When I press once on G it's scaling both panels up to maxSize then when pressing on G once again it's scaling the panels back down to minSize. But when I press on G quick in the middle while it's scaling them it should turn the scaling side in the middle. For example if I press G and both panels start scaling to maxSize if in the middle I press on G again it should scale them both to minSize without getting first to the maxSize. But in this case one of panels is keep scaling to maxSize a bit and then move back to minSize. But they both should turn side in the middle at once. It seems like one of them have a lag he turn sides a bit after the first one. using System.Collections using System.Collections.Generic using UnityEngine public class Scaling MonoBehaviour public GameObject Prefab public int numberOf 1 public float duration 1f public Vector3 minSize public Vector3 maxSize public bool scaleUp false public Coroutine scaleCoroutine public bool automatic false public bool coroutineIsRunning false private List lt GameObject gt parts new List lt GameObject gt () private void Start() for (int i 0 i lt numberOf i ) GameObject objecttest Instantiate(Prefab) foreach (Transform child in objecttest.transform) parts.Add(child.gameObject) private void Update() if (automatic) if (!coroutineIsRunning) Scale() else if (Input.GetKeyDown(KeyCode.G)) Scale() private void Scale() scaleUp !scaleUp if (scaleCoroutine ! null) StopCoroutine(scaleCoroutine) for (int i 0 i lt parts.Count i ) if (scaleUp) scaleCoroutine StartCoroutine(ScaleOverTime(parts i , maxSize, duration)) else scaleCoroutine StartCoroutine(ScaleOverTime(parts i , minSize, duration)) private IEnumerator ScaleOverTime(GameObject targetObj, Vector3 toScale, float duration) float counter 0 Vector3 startScaleSize targetObj.transform.localScale coroutineIsRunning true while (counter lt duration) counter Time.deltaTime targetObj.transform.localScale Vector3.Lerp(startScaleSize, toScale, counter duration) if (counter gt duration) coroutineIsRunning false yield return null |
0 | Unity sprites are no longer batched after the object rotates moves With Unity 5 and access to the profiler, I'm running our game through some stress tests so I can find where our performance issues are. While testing having 1024 units on the screen with 4 selection box corners each I ran into an odd problem. When I select all the units, 4096 selection box objects come into existence, my draw calls go from 25 to 50 with 50 batches. Now when I tell the units to move, they rotate and the number of batches climbs up to 2090 and the draw calls climb to 2090 and stay there even after the units stop rotating or moving. If I then reselect all the units, the selection boxes are destroyed and re instantiated (I know, not the best way) and the batches and draw calls go back down to 50 from 2090. What is causing this, and how would I go about fixing it? After Selecting All Units After having them rotate and move After Re selecting Them All |
0 | Check if all gameobjects are destroyed I am making a shooting game, where I have a countdown as I destroy enemies. I want to implement logic when all the game objects are destroyed within the given time, and the countdown reaches zero. How do I do that? |
0 | How to optimize two pass operations on an array with Unity Coroutines I am working on simulating vacuum decompression in a 2D top down environment. I have 2 2 dimensional arrays one that stores the pressure at a location, and one that stores the vector of fluid flow. The algorithm looks likes this private void Flow() Diffuse() Vectorize() private void Vectorize() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... Vector2 flowVector calculate the resultant vector from the pressure differentials O(1) op ... vector x,y flowVector private void Diffuse() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... float newPressure calculate the new pressure from the pressure differentials O(1) op ... pressure x,y newPressure The problem is that as the area of the simulation space increases, the performance continues to drop off as the iteration steps block the update loop. I want to convert these to Coroutines in such a way that both yield but more or less maintain a lockstep appearance. Since flow is dependent on pressure differential, and pressure differential is partially dependent on flow, if an order has to be enforced, then Diffuse should take precedence. My initial attempt followed the following form IEnumerable Flow() StartCoroutine(Diffuse()) yield return null StartCoroutine(Vectorize()) IEnumerable Vectorize() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... Vector2 flowVector calculate the resultant vector from the pressure differentials O(1) op ... vector x,y flowVector yield return null IEnumerable Diffuse() for(int x 0 x lt xRange x ) for(int y 0 y lt yRange y ) float myPressure pressure x,y ... float newPressure calculate the new pressure from the pressure differentials O(1) op ... pressure x,y newPressure yield return null This tended to cause a jittery simulation. Even on a small 20x20 simulation field, there was noticeable difference between the first and second solutions. Are there any tricks to coroutines that will allow a more lockstep simulation that scales well? Any suggestions on optimization is welcomed as well. |
0 | How can I have cutouts in a texture? I want to be able to have a gameobject that's basically just a black box on top of everything else. Then I want to be able to place other gameobjects which are just gradients on top of that and they should "cut out" of the black texture like this How can I achieve this sort of effect? Please keep in mind that I have pretty much no experience with shaders ) Here's a video that might help explain what I'm trying to achieve https www.youtube.com watch?v L1dd4fkVSAM |
0 | How to make AI detect a target behind a wall, who is only partially exposed? I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger. So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed. I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target? |
0 | Unity right mouse drag turn How would I use my right mouse button to turn a player character in unity, while only turning in the direction and speed of the drag? Not sure if I'm meant to post this here or stackoverflow. EDIT game is 3D EDIT2 Hold right click and drag to turn the camera Edit3 Got this code using System.Collections using System.Collections.Generic using UnityEngine public class Control MonoBehaviour public int speed public Transform tf Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButton(1)) tf.eulerAngles new Vector3 (0, Input.GetAxis("Mouse X") speed, 0) Code works, but after moving the mouse in the specified direction the character jumps back to its original position and kinda does this glitchy turn while moving the mouse (keeps jumping back to original position) nevermind, I think that I figured it out |
0 | How to blend motions with Mecanim I'm struggling with Mecanim. My concern is to blend straight turning animations with strafe animation for a humanoid character. I downloaded a SampleAsset from unity and took Ethan character as example. The animator uses a blendtree which naturally blend idle walking running animations with a smooth turning left right animations. In this case the Ethan character cannot strafe. I'm trying to understand how to blend strafe movement with it's actual straight turning blending motion. Was I somewhat clear? |
0 | Detecting mouse clicks in Unity UI Beta I want my game script to detect mouse clicks everywhere on my screen, except one corner where I have a pair of buttons to control the sound and will be handled separately. To help identify this corner, I've created a soundPanel object with the Rect Transform component (available in the Unity 4 Beta 17 ) and have sized positioned it appropriately in the editor in my UI layer. In my game's script, I have passed in this corner object, and tried using it in the following way bool tap (Input.GetMouseButtonDown(0) Input.GetMouseButtonUp(0)) amp amp !soundPanel.rect.Contains(Input.mousePosition) Clicking in the soundPanel still triggers a tap. I figured this is because the mouse position and soundPanel.Rect are not in the same coordinate space. Since the documentation on the new Unity Beta UI is a bit lacking hard to find, I tried converting the mouse coordinates to everything I could if (Input.GetMouseButtonDown(0) Input.GetMouseButtonUp(0)) if (soundPanel.rect.Contains(Input.mousePosition)) print("Raw") if (soundPanel.rect.Contains(camera.ScreenToViewportPoint(Input.mousePosition))) print("ScreenToViewportPoint") if (soundPanel.rect.Contains(camera.ScreenToWorldPoint(Input.mousePosition))) print("ScreenToWorldPoint") if (soundPanel.rect.Contains(camera.ViewportToScreenPoint(Input.mousePosition))) print("ViewportToScreenPoint") if (soundPanel.rect.Contains(camera.ViewportToWorldPoint(Input.mousePosition))) print("ViewportToWorldPoint") if (soundPanel.rect.Contains(camera.WorldToScreenPoint(Input.mousePosition))) print("WorldToScreenPoint") if (soundPanel.rect.Contains(camera.WorldToViewportPoint(Input.mousePosition))) print("WorldToViewportPoint") print(" ") When I click with the above code, "ScreenToViewportPoint" and "ScreenToWorldPoint" print no matter where I click, and no others trigger. I suspect I need to transform the soundPanel somehow. Here is the Hierarchy, Scene, and Inspector. The selected rect is the soundPanel, and it is in the bottom right of the UI Canvas |
0 | Canvas enabling is not working I have a canvas with two buttons in it and I want to enable it on the button click, but when I try to enable it, it doesn't work. However, when I try to disable it on button click it does work. Here is my code public GameObject mycanvas public void onClick() mycanvas.SetActive(true) Can someone please tell me what I am doing wrong? |
0 | Destroy the enemy only if the animation is played and touch the enemy I am using Unity. I want to attack an enemy with a knife. So I created an object (the knife) and put an attacking animation to it. Now I want to destroy the enemy only if the attacking animation is played and the knife touches the enemy. And if the animation is not played and the knife touches the enemy it should show a game over screen. |
0 | How do I detect if my object is grounded? I am trying to detect when an object is grounded. My script right now is using System.Collections using System.Collections.Generic using UnityEngine public class playermovement MonoBehaviour public CharacterController2D controller public Rigidbody2D rb float horizontalMove 0f public float runSpeed 40f Vector2 forceapplied public bool isGrounded public float NumberJumps 0f public float MaxJumps 2 public float jumpHeight 7f public CircleCollider2D bc void Start() forceapplied new Vector2(0.0f, 30f) void Update() if(bc.gameObject.name quot Grid quot ) isGrounded true NumberJumps 0 horizontalMove Input.GetAxisRaw( quot Horizontal quot ) runSpeed if (NumberJumps gt MaxJumps 1) isGrounded false private void FixedUpdate() if (isGrounded) if (Input.GetButtonDown( quot Jump quot )) rb.AddForce(Vector2.up jumpHeight) NumberJumps 1 controller.Move(horizontalMove Time.fixedDeltaTime, false, false) In the inspector it always says that Isgrounded is false. Can someone please help? |
0 | OnTriggerExit() called when game object with collider component gets re parented I have an object Hand, with a rigid body attached to it. In every Update() call, the user's hand controller rotation and position are tracked. In my scene, there is an object Pin, with a mesh collider attached to it. In OnTriggerEnter() (inside the Hand class), Pin becomes re parented to Hand. (Pin's original parent is something else.) My scene also contains other objects with colliders. However, these other objects do not get re parented only Pin does. Once this re parenting takes place, OnTriggerExit() (in the Hand class) is called immediately. This is surprising to me I had expected OnTriggerStay() (in the Hand class) to be invoked instead, since Hand is still in contact with Pin. Is such behaviour by design? Is there an elegant way of working around such behaviour? UPDATE In response to this comment Does the pin object have a parent before it becomes a part of the hand? Yes. As mentioned in my post, Pin's original parent is something else. Or is it placed inside another collider? And does the pin leave any of these collider areas when the parenting takes place? As mentioned in my post, Pin itself has a mesh collider component attached to it. Perhaps I am not understanding the question correctly... You can prevent the hand's script from getting this OnTriggerExit by adding a seperate rigidbody to the pin. I added a separate rigid body to the pin (setting isKinematic to true), but OnTriggerExit() inside the Hand class is still called immediately after Pin gets re parented. MORE INFORMATION Pin's original parent (before it gets re parented to Hand) does not itself have a collider component. When OnTriggerExit(Collider collider) gets called immediately after the re parenting takes place, the collider argument passed to the method is the Pin itself. |
0 | How to file down a fingernail mesh? I am creating a nail salon 3D game where I need to implement nail filing mechanics. I have tried out approaches including mesh deformation but I'm concerned about performance as I am targeting mobile platforms. How can I shape a nail efficiently for mobile devices? |
0 | Is a custom coordinate system possible in Unity Is it possible to create a custom coordinate system (i.e the one using double for coordinates or the one dividing the world into 'chunks' of safe size) not constrained by the floating point precision limitations in Unity, and make systems using the built in coordinate system use that one instead somehow? Thanks! |
0 | How to display full website in Unity WebGL? I want to display the complete website within the WebGL in Unity. I have tried Awesomium plugin but it doesn't work in WebGL. Please tell me is there any way to display the webpage. Thank you. |
0 | Load a specific sprite by name from a SpriteSheet with Resources.Load I want to avoid loading all the sprites from a sprite sheet into a dictionary. Is there a way to access the specific sprite inside the sheet. Right now I'm using this code prefabImage.sprite Resources.Load lt Sprite gt (spritePath spriteName) But this loads a single sprite. Can I change spritePath to somehow point inside the sprite sheet? |
0 | Unity Setting up the Universal Rendering Pipeline for Layer Masking I've been watching this video about Field of View (Player) by CodeMonkey which explains on how to set up a scriptable rendering pipeline for the layer unmasking masking of objects. However, the interface changed with the latest updates. There's an Opaque Layer Mask and there's a Transparent Layer Mask. I've followed the Render Features as described in the video but I wasn't able to get the masking done correctly as there's these two options that I can't seem to figure out what it does. I tried toggling to and from layers to see which one is meant to be in the other one but this is the best I could get For simplicity's sake, these are the layers that I am using Characters (things I want to see when the Field of View mask is over them) player enemy friendly dead Field of view (the unmasking layer) Fog of war (the thing that makes everything have a black transparent fog) UI (the layer that I want to see regardless of the where the Field of view mask is) As of right now, I could see the Field of View and the UI. Everything else is missing. I have asked in their own community however, no one reached out to me. Let me know in the comments if you need more info. edit 1 to reproduce create the following layers (Player, Enemy, FogOfWar, FieldOfView, Wall, UI) Set a game object with sprite component to player, enemy. Set them to the Player and Enemy respectively. This one, we want to see if the field of view layer is on top of it. They will be invisible if the field of view is not on top of it. Place a Sprite Renderer (a square) and set it to the Wall. This one, we want to see regardless if it's masked or not. If the field of view layer is not on top of it, this should be darkened by the fog of war. Set a Mesh Renderer (A simple plane would do) to Field of view and set it above the player and enemy. Make sure the face of the plane is facing the camera. This object would reveal or hide the Player and the Enemy layer. If this is on top of the FogOfWar, the area that the FieldOfView is upon will be invisible. That way, the sprites underneath it is not darkened. Have a sprite renderer (A square) and set it to black with 50 opacity and make it cover the the Player, Enemy, and FieldOfView. Set this to FogOfWar Create a button, and set it to UI layer Create a universal rendering pipeline. head over to the options and add the settings (keep in mind, I don't know what to set here. The Opaque and Transparent Layer Mask are my problem.) a. Opaque Layer Mask Wall, FogOfWar, FieldOfView b. Transparent Layer Mask Player, Enemy For the render features, add these three Behind Masks contain Player amp Enemy edit 2 I forgot. I have three cameras. All orthographic. They only render a specific layer. Main Camera Culling Mask is Wall Character Camera Culling Masks are Player and Enemy UI Camera Culling Masks is UI Character and UI camera have a depth. UI Camera's depth is 0. Character Camera's depth is 1. I want to render the UI below the characters. Hence, I separated them into their own camera. |
0 | Unity3D Blender Bounding box rotated on import For some reason my bounding box is always tilted when i import to unity. I've checked for loose geometry and everything but there's nothing. |
0 | Disable global fog from camera Does anyone know how to disable global fog from a particular camera? I have two cameras in my scene one is a mini map camera, where I need to disable global fog. I have checked this answer and the wiki, but have found nothing that works. |
0 | Same dimension feel no matter what FOV Does anyone know a formula, way, ... to make a FPS player feel like an object has the same size on different FOVs (given that it's at the same distance of the player, of course)? I know that this can't be done perfectly, because of the distortion various FOVs cause and the position of the object (near the edges of the FOV more distortion). Let's ignore these distortions, and aim for a same size feel for objects that are directly in front of the player (so in the exact center of the FOV). To clarify things a bit further I want 1 object in my game to have the same scale feel on different FOVs, not my entire game world. I've tried giving it a percentage of the frustrum height, but that doesn't seem to give me consistent results. Note I'm using vertical field of view in my game. |
0 | Unity3D C Drag object smoothly on it's x axis that's already bouncing In my scene, I have a bouncing ball that collides with a cube. On each collision the ball returns to the same height. How can I get the ball to smoothly move along the x axis by dragging my finger across the screen, while at the same time having no effect on the y or z values? The y position is changing every frame depending on the state of the jump, so setting it's y position to transform.position.y in the Update function causes the movement to be jittery if the frame renders when it isn't caught up with the position of the ball. Also, I set the interpolate value of the rigidbody to interpolate to get a smoother jumping motion, not sure if this is relevant to my problem or not. Here is where I am at so far with little success. A few mobile games that replicate what I'm trying to achieve in terms of ball movement are Hop, Color Hop, and Splashy! void Update() if (Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Moved) Control sliding using touch input. Vector2 touchDeltaPosition Input.GetTouch(0).deltaPosition transform.Translate(touchDeltaPosition.x slidingSpeed, 0, 0) transform.position new Vector3 (Mathf.Clamp(transform.position.x, xPosLimit, xPosLimit), transform.position.y, transform.position.z) |
0 | How do I calculate sprites frame usage on my platform's ram? I plan on building a 2d game for mobile and possibly pc. I also plan on using sprites frames for the animation of my 2d game. What's stopping me from doing so is because I can't figure out if the sprites frames containing the animation is gonna use up a lot of RAM on my device. Does anybody here know what I'm talking about? |
0 | Unity Android Button Select (Highlight) by touch, before clicking I have a multiplatform game with dozens of buttons in many menus. I used the animated buttons setup to have a normal state and highlight state. Highlight will most of the time resize the button with a nice anim AS WELL as make a dedicated text box appear with extra information. So far so good. Everything works perfectly on PC. However, as I am testing my build on android, I cannot find how to access the "highlight" state since touching the screen click and it execute the on click () associated. What I need is a way to select a button when it is first touched, since selected highlight (somewhat) then if it is touched (clicked) a second time while selected then to do the on click ( ) function. I have a few theory on how to do it, but it would require recreating every of my 80 or so buttons as well as changing everything from using the Unity GUI system to make my own C version which would take weeks. I am also trying a few other way to achieve the same thing. One of which is using the "button.select()" to select the button on its first click. That works. problem is I cannot seem to write a way to do "if (thisbutton.IsSelected true)" that just refuses to work. |
0 | Unity stats framerate vs Time.deltaTime Googling around, a way for calculating framerate and displaying it as text ingame is using 1 Time.deltaTime. However, comparing this against unity stats FPS shows 2 different FPS. Which of it is incorrect? If 1 Time.deltaTime is incorrect, how does one go about calculating FPS? Below is a screenshot of the FPS difference, as seen in the profiler, fps is well below 100 FPS whereas calculated FPS stays around 60. |
0 | Unity How to don't ignore a layer when Raycasting? For example Physics.Raycast(ray, out hit, range, layerMask), let's say layerMask groundMask. What I want to do is only return true if it didn't hit a ground mask. Like what I mean is like quot Ignore raycast except groundMask quot . Is there anyway to do this? Some example origin (groundmask) (other mask) return false because there is a ground mask in a range origin (other mask) return true because there is no ground mask in a range |
0 | Preventing character's movement if it won't fit(Unity2D) I'm creating a pacman game copy and I set up my movement. But there's a problem. My character can try to go up whenever I press but in the original you cannot go if there's a wall above you or your character won't fit. For example in this situation you can still go up but you'll bounce off wall. So my question is how to prevent character from movement if there's a wall or it won't fit there. |
0 | Flare fading when moving camera I have been trying to do a sun in Unity 3D. I have used a sphere with a texture and a flare. The problem is that when I move the camera the flare fades until it disappears when the sun is almost out of view, as shown in the image I've tried changing the fade value fron the flare but I can't see any difference. Does anybody know if this is a normal behaviour or if it can be fixed so the flare is always the same as long as the sun is in view? Thank you! |
0 | Does pixels per unit property affect performance of the game in Unity? The Sprite import inspector has a Pixels Per Unit setting that controls the size of the sprite objects when they're added to the scene Will Unity resize the sprite at run time or will it be resized after me changing the property and saved for the future? |
0 | What determines the hit detection ordering for graphic elements in Unity (2d game)? I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated. Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered. How do you control the order in which buttons are registered by the mouse? |
0 | How to create a 3D grid in Unity3D? What is a easy way to generate a 3D "hollow" and square grid around a central point, more like a cube (that can vary in size), with each cell being evenly spaced (based on a value)? Note I know how to make a 2D grid but not a 3D one. Edit I'll try to explain it more I'm looking for a way to create a grid at every face of a cube (6 faces) at runtime, that lets suppose is 3x3x3m, and each cell being every 1 meter apart from each other. Something like that |
0 | How to make the capsule collider that comes with character controller follow the animations I'm making a 3D endless running game like subway surf. When I swipe press down arrow the slide animation starts but the capsule collider isn't following along as it doesn't slides along with the character. Searched a lot on this on the forums, one possible answer is to attach the collider with some bone. I tried doing so, but couldn't make it. As I'm fairly new to Unity please provide some insights to how to overcome this situation. Here are the screen shots of the collider not following the sliding animation |
0 | How can I reduce a bezier curve using a slider till all points converge to it's original midpoint I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet). I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves. I would like achieve this using a float slider (with values from 0 to 1) in editor mode. |
0 | Can I detect collision on specific collider? I'm a beginner with Unity and I'm developing my very first 2D game. My game character needs to have an automatic right left movement but I'm struggling with the colliders on the walls (I made a tilemap object and set a collision for each wall on it). I need my character to detect the collision on the Right wall and turn to the left but I just can't find a way to name (I don't even know if you can do this) and detect a specific collider collision so I can make an if statement on the player script. How can I detect a specific collision collider and refer this on my player script? Here is the code I'm using for it (it isn't working) void OnCollisionEnter2D(Collision2D collision) if (collision.collider.gameObject.name "Right Facing Wall") runForwards false else if (collision.collider.gameObject.name "Left Facing Wall") runForwards true |
0 | I have a problem rotating a 2D game object after collision I'm developing a simple flip game where a cube flips and the bar a it collides with should start rotating after collision. Most snips involve destroying an object, but that's not my case. Here is my code using UnityEngine public class CheckI MonoBehaviour float x public Rigidbody2D rb2d void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "bar") x Time.deltaTime 10 transform.rotation Quaternion.Euler(0, 0, x) How do I start rotation after collision? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.