_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | unity Tilt Android Device player Freeze When Die I attached tilt script to my Player to move player x and y Axis. Player have Rigidbody2D and also IsKinematic true. but the problem when the player can Die i want to stop tilting and player goes down to ground. here is my tilt Code public float Speed 20f void Update () if (PlayerControll.instance.isAlive) transform.Translate (Input.acceleration.x Speed Time.deltaTime, Input.acceleration.y Speed Time.deltaTime, 0) else PlayerControll.instance.PlayerRigidbody.isKinematic false I try to do that using disable tilt script when Player die and Iskinematic false but the problem is player can freeze to his position not goes down to the ground. I do that so many way but not done so what i do don't know then i post the Question. thanks in advance. |
0 | Best aproach to Ground level detection for spells skills I'm making a 3d Hero Defense Tower defense kind of game with unity3d. A made a skill system with scriptable objects that lets the Defender use skills on the terrain doing damage to enemies that can be damaged. Because of the complexity of the terrain in some parts (slopes going up or down) i made a function to detect ground level like this protected float GetGroundPosition(Vector3 position) LayerMask GroundLayer 1 lt lt GROUND LAYER RaycastHit hitInfo Physics.Raycast(position, transform.up, out hitInfo, GROUND DETECT DISTANCE, GroundLayer) if (hitInfo.collider ! null) return hitInfo.point.y else Physics.Raycast(position, transform.up, out hitInfo, GROUND DETECT DISTANCE, GroundLayer) return hitInfo.point.y Then i subdivided my raycast in several small ones like this protected void DealBaseDamageInALine(Vector3 cursorPosition, float slashSize) List lt GameObject gt alreadyHit new List lt GameObject gt () Vector3 startRaycast new Vector3(transform.localPosition.x, GetGroundPosition(transform.position), transform.localPosition.z) for (int i 1 i lt GROUND COLLISION RAYCAST NUMBER i ) Vector3 endRaycast startRaycast transform.forward (config.GetAoe() (i 2)) endRaycast new Vector3(endRaycast.x, GetGroundPosition(endRaycast), endRaycast.z) Debug.DrawLine(startRaycast, endRaycast, Color.blue, .5f) RaycastHit hits Physics.CapsuleCastAll(startRaycast, endRaycast, slashSize, Vector3.up) foreach (RaycastHit hit in hits) var hitObject hit.collider.gameObject var damageable hitObject.GetComponent lt HealthSystem gt () if (damageable ! null amp amp !alreadyHit.Contains(hitObject)) float damageToDeal config.GetDamage() damageable.Damage(damageToDeal, config.GetElementalType()) alreadyHit.Add(hitObject) startRaycast endRaycast I made a graph to better conceptualize what i made I use around 64 segments and a 50f raycast depth for the ground detection and it works performs quite well (i noticed a 3 4ms increase in my older PC though). But my question is are there better approches to this? maybe i overdid something that could be done more easily. |
0 | Unity 5 Error with code to make pitch changes based on distance I really need help. It's 2 00 AM here and my brain is half dead so I can't, for the life of me, find out what's wrong with this code anymore. It's supposed to find the distance between the game object to which it's attached (the target), and another game object (the player). Then, depending on the that distance, it should change the pitch of an AudioSource inside a child (in the player). However, the pitch only changes when I'm practically over the gameobject. So, for about 9 10 of the way, nothing changes in the pitch, but when I'm right there the pitch suddenly changes (but not to maximum value of Clamp function). What's going on? I want the pitch to, at first, stay at 0. But soon after you walk some steps in the right direction, the pitch must change gradually (and in a evenly manner), as (player) gets closer to (target). ps. The script is inside a instantiated prefab, that's why I used FindGameObjectWithTag and FindChild. Also, I'm using Unity 5. lt ! language lang cs gt four blanks using System.Windows.Controls more indented code using UnityEngine using System.Collections public class ProximitySensor MonoBehaviour public GameObject player private Transform playerTrans private Transform targetTrans public Transform beepTrans public AudioSource beepSound private float distanceCurrent void Start () targetTrans transform player GameObject.FindGameObjectWithTag("Player") playerTrans player.transform beepTrans playerTrans.FindChild ("beepController") beepSound beepTrans.GetComponent lt AudioSource gt () void Update () distanceCurrent Vector3.Distance (playerTrans.position, targetTrans.position) beepSound.pitch Mathf.Clamp ((1 distanceCurrent), 0.1f, 3.0f) |
0 | Get perpendicular vector from another vector I should clarify that I understand there is an infinite amount of 'perpendicular' vectors in 3D space. I am creating an electricity effect, and to do this the ability to have any number of perpendicular vectors is a good thing. The hard part is how to select any random one of these vectors how would I do that, given a base vector "direction" which has been normalised? Keep in mind that I want the resultant vector to be random, not just always up and down on the y axis or anything. |
0 | How can i instantiate empty gameobject to be position to existing already gameobject? When i click on keyboards for example dfrg i want that if i click on space it will add empty gameobject right after the letter g like a space for example drg hello So there is a space after the letter g and before the hello I want that the empty gameobject will be like space. So if i click space it should be always position after the clone. But not sure how to do it. The problem is that i instantiate the clone object after if i click on space key. And i also want the space to work for both side cases if i first click on space before i clicked and did any clones it should be for example dfrg There are many spaces before the dfrg using System.Collections using System.Collections.Generic using System.IO using System.Linq using UnityEngine public class Test MonoBehaviour public GameObject prefabs public int gap 50 public int offset 0 private GameObject go void Start() prefabs Resources.LoadAll("Prefabs", typeof(GameObject)).Cast lt GameObject gt ().ToArray() foreach (GameObject prefab in prefabs) if (prefab.name "testing") go prefab void Update() if (Input.anyKey) if (Input.GetKey(KeyCode.Space)) foreach (Transform child in go.transform) if (Input.inputString child.name) Transform clone Instantiate(child) clone.parent transform clone.transform.eulerAngles new Vector3(0, 0, 0) offset gap clone.transform.position new Vector3( offset, 0, 0) |
0 | Chroma depth shader unity I'm trying to reproduce a post effect with unity seen in the answer here. Chromadepth answer For the moment I just manage to reproduce the wave effect with a quick edge detection. I tried multiple textures but can't find one that fit do the same effect. I am using this texture The result for far. Shader "Unlit ChromaDepthEdge" Properties MainTex ("Texture", 2D) "white" Ramp ("Texture", 2D) "white" Threshold("Threshold", Float) 0.1 SubShader Pass ZTest Always Cull Off ZWrite Off CGPROGRAM pragma vertex vert pragma fragment frag pragma target 3.0 include "UnityCG.cginc" struct appdata float4 vertex POSITION sampler2D MainTex sampler2D Ramp Request camera depth buffer as a texture. Incurs extra cost in forward rendering, "just there" in deferred. sampler2D CameraDepthTexture float4 MainTex TexelSize float4x4 InverseViewMatrix float Threshold void vert ( float4 vertex POSITION, out float4 outpos SV POSITION) outpos UnityObjectToClipPos(vertex) fixed4 frag (UNITY VPOS TYPE screenPos VPOS) SV Target Convert pixel coordinates into screen UVs. float2 uv screenPos.xy ( ScreenParams.zw 1.0f) uv.y (uv.y 1) 1 Depending on setup platform, you may need to invert uv.y Sample depth buffer, linearized into the 0...1 range. float depth Linear01Depth( UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv))) float2 uvDist 3 MainTex TexelSize.xy float depthUp Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(0, 1)))) float depthDown Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(0, 1)))) float depthLeft Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2( 1, 0)))) float depthRight Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(1, 0)))) float mean ((depthUp depth) (depthDown depth) (depthLeft depth) (depthRight depth)) 4 Compressing the range, so we get more colour variation close to the camera. depth saturate(2.0f depth) depth 1.0f depth depth depth depth 1.0f depth return depth Use depth value as a lookup into a colour ramp texture of your choosing. fixed4 colour tex2D( Ramp, depth 6 Time.y 4) return lerp(colour, colour 6, mean gt Threshold) ENDCG What did I miss ? Thanks in advance. |
0 | Using single Triggers on multiple controllers in Unity After trying out a lot of stuff I finally need to surrender. Im having a project where I want to use the triggers of the Xbox Controllers seperately. To do so I added them as axis 9 and 10 in the input manager (see image). Now, when i have multiple controllers connected on project startup the triggers wont get recognized. I have to press the trigger on two controllers to get a value from it...prettty strange. If i reconnect the controllers after project launch everything works fine... Test script looks like this. Thanks! |
0 | 2d Raycast detection doesn't work I want to check if the position I generated has another object or not. I do this by using Raycast private void RandomOBS() Vector3 pos new Vector3(UnityEngine.Random.Range( 8f, 8f), UnityEngine.Random.Range( 4f, 4f), 0) while (Physics2D.Raycast(pos, pos).collider) pos new Vector3(UnityEngine.Random.Range( 8f, 8f), UnityEngine.Random.Range( 4f, 4f), 0) The code above doesn't work at all. I tested it with if statement and for some reason it cannot check that position. private void RandomOBS() Vector3 pos new Vector3(UnityEngine.Random.Range( 8f, 8f), UnityEngine.Random.Range( 4f, 4f), 0) while (Physics2D.Raycast(transform.position, transform.position).collider) pos new Vector3(UnityEngine.Random.Range( 8f, 8f), UnityEngine.Random.Range( 4f, 4f), 0) However when you check the transform.position instead of the pos, it works? How and why? All the game objects have the correct colliders amp stuff. |
0 | Calculate 2D tile map tiles within a "field of view" cone I need to calculate which tiles make up a "cone", originating at my player and extending outward for a specific tile distance. My player can only face North, South, East, West and I'm not sure yet on the angles I'll use for the cone. I've found several posts articles already covering this but they're trying to determine visibility and are a lot more complex than I need. I'm not lighting a room or calculating shadows occlusions. |
0 | Collision event function not running I am recreating flappy bird as a quick project to help me understand the ins and outs of unity. However I have hit a road block. When the bird collides with the pipe or ground it is not kicking off the void onCollisionEnter2D(Collision2D target) The Bird, the pole, and the ground are not triggers. They are all tagged correctly. Here is my code for the onCollisionEnter2D function. void onCollisionEnter2D(Collision2D target) Debug.Log("Entered 2D Collision") if (target.gameObject.tag "Ground" target.gameObject.tag "Pipe") if (isAlive) isAlive false anim.SetTrigger("Bird Died ") audioSource.PlayOneShot(deadClip) Even my debuging code is not being reached. So I am stuck as to why this function isn't being executed when the bird collides with the pole or ground. They both all have 2D collision boxes on them. |
0 | NullReferenceException Error For Respawning I am making an infinite runner game, and I am having issues with killing and respawning the player. I have a coroutine setup on the GameMaster objec which is the respawn and on the player I have a method that calls that coroutine. But when ever the player hits an enemy I get a Null Reference Exception and I am not sure why this is happining. Here is the entire error NullReferenceException Object reference not set to an instance of an object Player.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets Script Player.cs 32) Here is the line that when I double click on the error it goes to. This line is on the player. StartCoroutine(GetComponent lt GameMaster gt ().RespawnPlayer()) This is the method that the above line is in. This method is on the player. void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "Enemy") Debug.Log("HIT") Destroy(col.gameObject) StartCoroutine(GetComponent lt GameMaster gt ().RespawnPlayer()) Here is the coroutine that the above method is trying to call. This method is on the GameMaster GameObject and this object never gets destoryed or setActive false. public IEnumerator RespawnPlayer() player.GetComponent lt SpriteRenderer gt ().enabled false player.GetComponent lt BoxCollider2D gt ().enabled false player.GetComponent lt movemnt gt ().enabled false yield return new WaitForSeconds(respawnDelay) adMenu.SetActive(true) If anybody can give any suggestions that would be great! |
0 | Why is my Post Processing not working? I'm trying to get Post Processing working in my Unity Project, with URP enabled, but I'm not seeing it work. I've looked at a few tutorials and I've followed them exactly, but I never see any post processing happen. Here's the inspector window for my Camera And here's the inspector window for my Post Processing GameObject |
0 | How can I resize my Blender models when importing to Unity? I made a 3D model in Blender, but when put it in my Unity project and add an FPS camera the camera is bigger then my model. I used the measurements of Blender (that one cube is 1 meter in Unity). How can I fix this? |
0 | Anchored Unity text ...not anchoring! I've added some text to a unity UI and set both the achor and pivot to the top right corner as shown here When I start this in debug in unity the text looks fine What's weird is that when I build the app and run it as an executable as a host (this is a multiplayer networked game) the text also looks fine. But when I start a client instance the text doesn't appear. I debugged and paused the game in unity in client mode and noticed that the text object is miles away from where I'm expecting it to be (and as a result doesn't show on the camera). You can just about see the black line on the below image which is my level and the text anchored miles up and right of the level. It seems like I've done something stupid here but I can't work out what s EDIT Leo's answer was correct conceptually, but here's how I implemented the suggestion. Created an empty game object GameStateManager in the hierarchy Add a GameState script to the manager with a network identity Added my 'RemainingTime' property to the game state script and put the SyncVar attribute on it Put logic in the game state Update method to update the remaining time Added a ClientTimer script to the text object (mono behaviour), which retrieved the GameState from within the clients copy of the game state manager. In the update method of the client time, get a reference to the Text object and set the .text property to the value of the remaining time. I'm not sure if this is correct, but it does seem to work, and now the ClientTimer script isn't networked, which resolved the issues with placement of the text. |
0 | Sync a file across multiple devices How can a file be synced across multiple devices? I am able to store the data locally using binary serialization, but the user should have the ability to access it on any device at any time. Is this done automatically by the operating system? If the user logs into an Android phone using a Google account, would local data created by the application appear on every device that Google account is logged into or would I need to implement this functionality myself? I have considered using a remote database, but I am not so sure that is the best option. My target platforms are Windows Universal, Android, and iOS. The closest topic I found when I researched this is "Remote Settings" and "binary serialization", but neither help in my case. |
0 | Room based camera movement I'm trying to make a camera system where the camera never goes outside the edges of the current room (like Link to the Past or Mega Man, for example) This is what I have right now using UnityEngine using System.Collections public class CameraFollow MonoBehaviour public BoxCollider roomBounds public Player target Vector3 velocity float halfHeight,halfWidth void Start() halfHeight Camera.main.orthographicSize halfWidth halfHeight Camera.main.aspect void LateUpdate() Vector3 targetPosition target.transform.position if (targetPosition.x halfWidth gt roomBounds.bounds.max.x targetPosition.x halfWidth lt roomBounds.bounds.min.x) velocity.x 0 else velocity.x targetPosition.x transform.position.x if (targetPosition.y halfHeight gt roomBounds.bounds.max.y targetPosition.y halfHeight lt roomBounds.bounds.min.y) velocity.y 0 else velocity.y targetPosition.y transform.position.y transform.position velocity It works on a rudimentary level, but the problem is, whenever you're moving out from a wall after the camera's stopped, it snaps a little to the left or the right, and then goes back. Same vertically. Any idea as to what might be causing this and how to solve it? P.S. I know there have been a lot of threads about this kind of system (even one 21 hours ago), but none I've found helped me much. |
0 | Unity shader set to GameObject position I have a shader with acts like a magnifying glass that I downloaded and I have to attach to the camera scene. My issue with this I want it in the same fixed position as the sprite but being attached to the camera when I changed the screen size for different devices it wonders to the upper right of the screen. I am completely new to shaders so I and their scripts so I am not sure if this can be done. private void OnRenderImage(RenderTexture src, RenderTexture dest) if (mtrl null mtrl.shader null !mtrl.shader.isSupported) enabled false return if(Input.GetMouseButton(0) !detectMouseButtonDown) mtrl.SetFloat(" Radius", radius) mtrl.SetVector(" Mouse", new Vector4(740, 480, 0)) mtrl.SetFloat(" Distortion", distortion) mtrl.SetFloat(" ScaleArea", scaleArea) if(isMagnifyingGlass) mtrl.EnableKeyword("IS MAGNIFYING GLASS") else mtrl.DisableKeyword("IS MAGNIFYING GLASS") if(warpType WarpType.POW) mtrl.EnableKeyword("WARP TYPE POW") mtrl.DisableKeyword("WARP TYPE EXP2") else mtrl.DisableKeyword("WARP TYPE POW") mtrl.EnableKeyword("WARP TYPE EXP2") Graphics.Blit(src, dest, mtrl, 0) else Graphics.Blit(src, dest) Shader Shader "Hidden MagnifyingGlassFisheyeWarpImageEffect" Properties MainTex ("Texture", 2D) "white" SubShader Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma target 3.0 pragma multi compile WARP TYPE POW WARP TYPE EXP2 pragma multi compile IS MAGNIFYING GLASS include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float4 pos SV POSITION float4 scrPos TEXCOORD0 float2 uv TEXCOORD1 sampler2D MainTex float4 MainTex TexelSize float2 Mouse float Radius float Distortion float ScaleArea v2f vert (appdata v) v2f o o.pos UnityObjectToClipPos(v.vertex) o.scrPos ComputeScreenPos(o.pos) o.uv v.uv return o fixed4 frag(v2f i) SV Target float4 c 0 float2 uv i.scrPos.xy i.scrPos.w float2 mousePos Mouse.xy ScreenParams.xy float wh ScreenParams.y ScreenParams.x uv.y wh mousePos.y wh if(length(uv mousePos) lt Radius) uv mousePos if defined(IS MAGNIFYING GLASS) float newLength ScaleArea Distortion ScaleArea pow(length(uv) Radius, Distortion) else if defined(WARP TYPE POW) float newLength ScaleArea pow(length(uv) Radius, Distortion) endif if defined(WARP TYPE EXP2) float newLength ScaleArea exp2(length(uv) Radius Distortion) endif endif uv newLength uv mousePos uv.y wh c tex2D( MainTex, uv) return c ENDCG Here is what it looks like over the gold selector. It is in the correct position. Now if I change the screen size for a different device the magnifying effect has shifted to the right |
0 | 2D Infinite Runner how to manage background layers? First of all, sorry for this post, I guess this already has been discussed. I browsed stackexchange and the web but I couldn't seem to find a clear information for my case, with always mixed results. So I'm making a mobile game with Unity, and am re starting the development from the beginning in order to have smooth performances. The game is a 2D runner (Canabalt style). Though there will be two modes One story mode with about 12 levels precisely designed which will be always the same One arcade mode with randomly generated level (platforms). Main features Back and Foreground Parallax (5 6 layers totally, with different movement speed) Automatically running, manually jumping over holes and attacking ennemies So I have a few interrogations The classic question should I make it like a theadmill, having a fixed player position, and making the level move forward. Or should I be moving the character as the camera follows him ? Given the fact that I want multiple parallax background. Are there differences performance wise ? A linked question should I use the perspective camera and play with the Z axis ? or keep the orth camera ? I'm not sure how it affects the performances. Then, having read many topics, I guess I should try to move back the objects and backgrounds, instead of instantiating and destroying them all the time when doing a random level, right ? And for my pre designed levels (not random) should I split the background to display it step by step, in terms of performance ? I already know how to scroll my backgrounds, make a parrallax effect with my 5 6 layers, here I'm looking for tips to start clean with the smartest development style, especially in terms of performances and would like to have some hints on which are the best practices to follow Maybe you have other good practices to share with me... I'm hoping I'm not asking too much, thanks for any insights ! Have a good day |
0 | Polygon filling algorithm Share your methods or algorithms for painting areal objects, I will be very grateful. I have points List lt Vector2 gt or List lt Vector3 gt , there are textures with different settings And I need to fill the area. For example, I have 4 coordinates, I painted a square by clicking the button |
0 | How to display Textures, Buttons, Created with Unity's GUI (OnGUI()) to get displayed behind other objects in Scene I am making a game in which I am using OnGUI() to make Texture. I want this texture to display behind my Regular 3D objects like cube, spheres in the scene. I have tried and searched but I am unable to figure it out. Is this Possible? |
0 | Make a child sprite match the layer ordering of its parent I have my project settings set up to order the sprites' visual layering based on their y position. If I add a sword as a child to my character, the sword won't have the same order as the parent so things can look like Sword gt enemy gt player instead of enemy gt sword gt player (because I want the sword to be in front of the character) I thought of setting the pivot point of the sword sprite so when nested inside the parent sprite, it would be around the same height as the player's pivot point so they would have the same order. I feel like this wouldn't be the best solution because when I will animate the sword to attack, I wont be able to rotate it around the position I want.....unless I make it the child of an empty object? How can I solve this issue? |
0 | Why the while loop is not pausing the coroutine? I'm trying to find a way to pause the game the whole game. timeScale 0f is not working on coroutines. I have this script that pause the game on escape key using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class BackToMainMenu MonoBehaviour public static bool gamepaused false private void Update() if (Input.GetKeyDown(KeyCode.Escape)) gamepaused true Time.timeScale 0f And a script with a coroutine using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length var depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, clipLength)) postProcessingProfile.depthOfField.settings depthOfField IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) while(BackToMainMenu.gamepaused) yield return null playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings if (Time.timeScale 0) counter Time.unscaledDeltaTime else counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null But when I hit the escape key the freeze for a second or two but then the blurry effect in this script is keep on going then it also keep on running the game after this script part. It seems that the timeScale is not pausing the game at all but only for few seconds if at all. Or pausing only some stuff. What I want is to pause the whole game. Maybe I should use a game state somehow? I don't want to disable enable the gameobjects in the hierarchy. I checked again now. For example the player I can't move it with the keys but I can rotate the player looking around with the mouse while in pause mode. But other things are paused like other npc's I have they stopped moving(Not using animation). So some stuff is paused but some stuff not. |
0 | Collision in EdgeCollider Unity I want to make a collider for a line that I've drawn on the screen using mouse. so the detection should be cover the whole line that has drawn. What I've learned from edge collider is you can have collider if you assign the position of a certain point in col.transform.position (for example I can assign the startpos of my line and the collider works only for that point). the green line which is drawn by mouse in front of car is using the LineRenderer and requires EdgeCollider to be a road that car can drive on it's surface and my functions private LineRenderer line Reference to LineRenderer private Vector3 mousePos private Vector3 startPos Start position of line private Vector3 endPos End position of line public Material material void Update() On mouse down new line will be created if (Input.GetMouseButtonDown(0)) if (line null) createLine() mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 line.SetPosition(0, mousePos) startPos mousePos else if (Input.GetMouseButtonUp(0)) if (line) mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 line.SetPosition(1, mousePos) endPos mousePos addColliderToLine() line null else if (Input.GetMouseButton(0)) if (line) mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 line.SetPosition(1, mousePos) Following method creates line runtime using Line Renderer component private void createLine() line new GameObject("Line").AddComponent lt LineRenderer gt () line.material material line.SetVertexCount(2) line.SetWidth(1.1f, 1.1f) line.SetColors(Color.black, Color.black) line.useWorldSpace true Following method adds collider to created line private void addColliderToLine() EdgeCollider2D col new GameObject("Collider").AddComponent lt EdgeCollider2D gt () col.transform.parent line.transform Collider is added as child object of line col.points 0 startPos col.points 1 endPos Vector3 midPoint (startPos endPos) 2 col.transform.position midPoint setting position of collider object Following lines calculate the angle between startPos and endPos float angle (Mathf.Abs(startPos.y endPos.y) Mathf.Abs(startPos.x endPos.x)) if ((startPos.y lt endPos.y amp amp startPos.x gt endPos.x) (endPos.y lt startPos.y amp amp endPos.x gt startPos.x)) angle 1 angle Mathf.Rad2Deg Mathf.Atan(angle) col.transform.Rotate(0, 0, angle) btw i don't know what that col.points used for. I just found it from the unity documentation which won't make any collision |
0 | How to rewind time on just the main character? I have a 2D sidescrolling game and I want the character to be able to rewind time on him if he messes up. I don't want anything else to change, just the main character's position. Any idea how I can do this? |
0 | Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls) |
0 | Unity Ignore mouse click outside of the UI I am having a problem with my in game UI menus like the pause menu. When I hit the escape key the mouse cursor and pause UI is shown with 2 buttons "Continue" and "Exit". I have locked the player from moving when this UI is shown. But when I click outside of the buttons the mouse disappears and the player can move once again, the UI is still shown but it's lost focus or something. Is there a simple way to stop this? I've seen some scripts which seem to try to catch this behavior and ignore the click but I'm hoping there is a property on the canvas or something that I can use built into the engine. Thanks, Sam |
0 | Unity character vibrates during idle animation My player character vibrates in his idle pose for some reason. He has 3 animations (IdleState, WalkState, RunState) and the latter 2 run smoothly, but when I don't provide directional inputs and he enters his idle state, he looks like he had 100 espresso shots! 43 second video demo here https youtu.be QuHPrkjx T4 I am not using a blend tree for the moment and the animation used for IdleState was exported with only a single frame (frame 1) from Blender. Unity's FBX import panel has the animation listed as playing from frame 0 to 1. I have tried many different configurations for this animation in the importer, including looping, not looping, matching pose, setting animation length to 0. None of that fixed the jitters (the latter nullified the animation). I have restructured my scripts but have not found a solution for this yet. My character uses 2 scripts, one to control movement, and another to control animation. This one controls movement using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private float charSpeed public float walkSpeed private float runSpeed public float jumpForce public CharacterController controller public float gravityScale private Rigidbody rb public static Vector3 moveDirection Start is called before the first frame update void Start() controller GetComponent lt CharacterController gt () rb GetComponent lt Rigidbody gt () charSpeed walkSpeed runSpeed walkSpeed 2 Update is called once per frame void Update() if (Input.GetButton("Fire3")) charSpeed runSpeed else charSpeed walkSpeed Declare movement vector moveDirection new Vector3(Input.GetAxis("Horizontal") charSpeed, moveDirection.y, Input.GetAxis("Vertical") charSpeed) Set y axis movement conditions (jumping, grounded, free fall) if (Input.GetButton("Jump") amp amp controller.isGrounded) moveDirection.y jumpForce else if (!controller.isGrounded) moveDirection.y moveDirection.y Physics.gravity.y gravityScale Time.deltaTime else moveDirection.y 0 rotated 45 deg to align controls to camera instead of world space Vector3 rotated Quaternion.Euler(0, 45,0) moveDirection controller.Move(rotated Time.deltaTime) Vector3 lookDir new Vector3(rotated.x, 0, rotated.z) if (lookDir ! Vector3.zero) transform.rotation Quaternion.LookRotation(lookDir) ...and this one plays the animations using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.AI public class CharacterAnimator MonoBehaviour private Rigidbody rb Animator animator void Start() rb GetComponent lt Rigidbody gt () animator GetComponent lt Animator gt () void FixedUpdate() was Update(), no change if (Input.GetAxis("Horizontal") 0 amp amp Input.GetAxis("Vertical") 0) animator.Play("IdleState") else if (Input.GetButton("Fire3")) animator.Play("RunState") else animator.Play("WalkState") What is causing this jittery idle state bug? |
0 | Problem with repeating objects in array when already in the array When the player move forward then paint is instantiate and stored in the array, even if the paint is already in the array it will again be stored in the array. But I don't want to repeat any paint in the array. public GameObject array public GameObject paint int temp 0 private RaycastHit hit public float speed 10f public Text levelText public GameObject paint float maxdistance 0.51f Vector3 newtargetposition bool pos private void FixedUpdate() if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward,out hit, maxdistance)) if (hit.collider.gameObject.tag "Obstacle") move false if (move) PlayerMove() public void PlayerMove() if (move) vector3 positions transform.position new Vector3(0f, 0.5f,0f) when player move then paint instantiate y position array temp Instantiate lt GameObject gt (paint, position, Quaternion.identity) temp newtargetposition position Debug.Log("newtargetposiiton " newtargetposition) if (temp 150) if (newtargetposition position) what can i do here i dont want to paint here because position store in newtargetposition,it is repeat array temp Debug.Log("newtargetpositions " newtargetposition) temp gameOver.SetActive(true) SceneManager.LoadScene(1) when player move forward store position in array when player move back already fillup position again store in array |
0 | How to calculate Camera "correct" position and distance to Frame all my Scene? Consider I have N dynamic points on my Scene, I would like to "frame" all them, with my Camera. How can i calculate (at runtime) Vector3 Position to correctly frame all my scene ? This is my idea Calculate Avarage for all my points Move my Camera "up" to correctly "frame" all my points (i don't know how) Use Unity LookAt(myAvaragePoint) Thanks |
0 | Object Composition in the Unity Editor I'm trying to learn how to use Unity for my class composition, and I was wondering if you could help me. I'm trying to create a simple game where the player is trying to pop a bunch of balloons. However, any given balloon can only be popped if all of its conditions are met. Example conditions are The player color must match the balloon color The balloon must be popped in sequence (balloon A must be popped before balloon C) The balloon is only pop able during a certain time window And I'm sure you could think of more. Balloons can have 0 to many conditions associated with them, but they follow the 80 20 principle where 80 will fall into a specific category (e.g. color match only, or color and sequence only). My Initial Solution I created a "Balloon" class that contains a list of "ICondition" interfaces. When a collision occurs, the balloon loops through each condition to determine whether the balloon is pop able or not. I populate this list within a "BalloonFactory" class. For 80 scenarios I can just pass in the name of the balloon type I want. For 20 scenarios I can pass a list of conditions. This solution works, except for each new combination I need to change the factory code to include the new condition. What I'd Like to Do Instead of storing the balloon definitions in code, I'd prefer to create prefabs in Unity and use the editor to assign condition implementations to each balloon. My problem so far is that the Unity editor doesn't seem to like displaying a list of interfaces or abstract classes. Is there some way to do what I'm trying to do here? Or is there a third option which you would recommend? |
0 | 2D Platformer Methods to Implement a Whip Weapon I hope posting here isn't a faux pax, if it is please feel free to direct me to the correct location. Or, if there is a thread that already covered this I would love to be pointed in its direction. I've tried looking in quite a few different forums and I can't seem to find very much information about this. What I'm looking to do is implement a whip weapon for a character that's similar to that of Castlevania 4's whip. I have no idea where to start. I'm really just looking for any information. Things like how to program it, the idea of how it was done in the game, really just anything to help me figure out how to make a whip like Castlevania 4. I would appreciate any help. Thank you. |
0 | Unity 5 Check if an object's collider contains the mouse click point I am building a 2D turn based RPG battle scene with Unity 5. The enemies are represented as 2D sprites with box colliders. In my script, the relevant enemy class is defined as public class EnemyView MonoBehaviour public SpriteRenderer renderer public BoxCollider2D collider void Awake() renderer gameObject.GetComponent lt SpriteRenderer gt () collider gameObject.GetComponent lt BoxCollider2D gt () And I have the following code grouping the enemy sprites together public class MainGUIView MonoBehaviour public EnemyView enemyViews When a player clicks on an enemy, I would like to know the index of that enemy within the enemyViews array. I thought of implementing this within EnemyView class but that class has no information about its index, so I am thinking of implementing OnMouseDown() within MainGUIView where I could iterate through enemyViews to find the one whose collider contains the mouse click point, but I don't know how to write the code. Anyone can point me to some useful code snippet? |
0 | Getting distance between point of an object and another object in Unity First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development. I understand that I can find a distance between two objects using float dist Vector3.Distance(other.position, transform.position) However, how can I find the distance between a point of one object to other object? For instance let's say my object is this sphere Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5? Thank you for your patience and understanding |
0 | Unity or MonoTouch with XNATouch MonoGame? same price After figuring out the pricing of monoTouch and Unity, I've found that the pricing will be the same ( 800). With XnaTouch MonoGame for monoTouch I am able to port my games to droid apple. I am just curious if anyone has tried both XnaTouch and Unity and which one they prefer. I do mostly 2D games (if Unity had a 2d Engine I would be all over that) so xnaTouch seems that it might be better, but Unity seems better for more advance professional (more companies are using it, so if I ever wanted to do this for more than just myself I have more options, which I've thought about) (I also read somewhere that monoTouch is against the new apple term of agreement?) |
0 | How can I check if my object just stopped rotating this frame? using System.Collections using System.Collections.Generic using UnityEngine public class RotateRandom MonoBehaviour private void Update() if(Whilefun.FPEKit.FPEInteractionManagerScript.naviRotate true) transform.Rotate(0,0,100) else transform.eulerAngles new Vector3(0, 0, 0) I set the flag to true and false in another script. And here I want that each time the transform stops spinning, it should revert to looking forward once. But since I wrote transform.eulerAngles new Vector3(0, 0, 0) in the Update method, it will try to go back to facing forward every frame. I want it to do it only once each time it stops spinning. |
0 | Spotlights and Pointlights not working with Unity Render Pipeline? I'm experimenting with URP, Render Pipelines, and Shaders for the first time recently and have noticed something odd. In the scene I'm building, Point Lights and Spotlights don't work. No matter what I do, they do not affect the environment at all, for static and nonstatic objects. I can't even use a Halo component to visualize them. They exist in the scene but don't do anything and even Lightmaps don't seem to register them. I suspect that it's because of the render pipeline, but if I go to a blank scene and put a spotlight on an object, it works. I'm just very confused what's happening. Any idea what might be happening? |
0 | How can I make a chest that can be opened and shut in SteamVR? I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want. I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic. I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions. I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this. |
0 | How can i make all the scene dark night and spot a light on specific place area in the scene? I want to light the area of the 5 spheres. All the rest to be dark. What i have in the Hierarchy is Directional Light. I'm not sure if i need other lights objects and what to do to make it dark night environment and how to spot a light on the specific area. |
0 | How can I generate roads such as those in the game Twisty Road? Here is a link to see the gameplay https www.youtube.com watch?v 03PzsgO uAM How could I procedurally generate the path upon which the ball rolls in Unity C ? I know I could model distinct pieces of the road in Blender and import them into Unity as prefabs. My problem is, I genuinely have no idea where to start when it comes to programmatically generating the whole road out of those prefab sections in a cohesive manner, such that the road is built seamlessly and randomly with twists and turns in three dimensional space. I would appreciate any insight you could provide. Thank you. |
0 | How not to show ads to paid customers when I decided to make it free? I am planning to publish a paid game built with Unity. After a while I will update the game as free and will start showing ads. But I do not want my first paid customers to see the ads after installing update? How can I manage this? Game will be both on App Store and Google Play. Thanks |
0 | Is there a standardized way for creating a 2D ball physics movement method? Is there a standardized method for creating a 2D ball physics movement like you can see on gif below? |
0 | Unity3D WWW get HTML displayed in browser I currently have in a web page, on a localhost server, some information that I want to use in Unity. My problem is that this information are stored in some js variables. I tried to use the WWW class in a coroutine, but I only get the html source code. Is there a way to get the value of this variables inside Unity Editor ? Thanks ! |
0 | Things disappear in front of Canvas I'm trying to add some text to my Canvas but it seems to disappear in front of it? So does particle systems and other things? It is a child object of the canvas. |
0 | Unity Retrieve animation names from imported blend file I am just trying to generate a list from all animations within my Blender Asset file (see image) This is what I have so far using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DropDown MonoBehaviour public GameObject character public Dropdown dropdown Use this for initialization void Start () PopulateList() void PopulateList() TODO Read values from character List lt string gt names new List lt string gt () "idle", "cheering" , "jump" dropdown.AddOptions(names) The character is the actual blender asset (base character 29). The List names needs to be replaced with an array of my animations so I can populate a dropdown. I am using a humanoid rig so I am only having an "Animator" Component on my GameObject. I appreciate any kind of help, thanks in advance! |
0 | How to activate an object only when it's within the camera view I want to toggle an object's active state using the camera view when the object leaves the view it deactivates when the object enters the camera's view it activates I'm using this to control the activity of objects in a carousel like this I did this with a coroutine, but in my project the fps is falling a lot because of the coroutine. I've already used OnBecameVisible and isVisible but that's not it since they only work with a renderer. public void next() StartCoroutine(On(waitnext)) IEnumerator On(float waitnext) yield return new WaitForSeconds(waitnext) myArray Selecao .SetActive(false) Selecao if(Selecao gt myArray.Length 1) Selecao 0 yield return new WaitForSeconds(waitnext) myArray Selecao .SetActive(true) public void previous() StartCoroutine(On2(waitprevious)) IEnumerator On2(float waitprevious) yield return new WaitForSeconds(waitprevious) myArray Selecao .SetActive(false) Selecao if(Selecao lt 0) Selecao myArray.Length 1 yield return new WaitForSeconds(waitprevious) myArray Selecao .SetActive(true) |
0 | How to rotate sides of rubik's cube by mouse drag? I am trying to make a Rubik's cube simulator. I built the Cube by arranging 27 pieces in appropriate place. I wanna simulate the cube like This. This is what my cube looks like. I successfully wrote a simple script to rotate the whole cube while dragging the mouse on background. I was also able to rotate sides with key inputs like U, F etc. For this I created 6 empty game objects (UpLayer, FrontLayer etc.) and positioned them in centre of corresponding sides. I store every piece in an array. Now, when the user presses a key, suppose U, I Make all 9 pieces of upper layer child of empty game object UperLayer at runtime. Rotate the UperLayer object around its local y axis 90 degrees. Make required changes in the array. Un parent all the pieces. It works perfectly for every layer. But now, I wanna rotate the layer when user drags it with mouse (Check the above link). I can't think of any approach to do so. I need help. |
0 | My pixel art looks weird in the game view in Unity I am making my first 2D game in Unity and something has been bothering me. If I'm in the scene view, my game looks fine but when I go to the game view the pixels in the sprites aren't rendered correctly and everything looks distorted. Does anyone know an answer to this? |
0 | Fill all unallocated space with texture I have a system of bunkers underground, and I need to fill all the free space where there are no buildings with earth. Yes, I can manually add a ground texture to the plane, but I have procedural level generation. I thought there might be some kind of filter on the camera that I don't know about. Or maybe there are some other solutions? |
0 | Keep track of VoxelData NPC in parallel Level Background I'm tring to make a First Person Shooter Game in a Voxel World (Finit Size) with Unity3d. The Player has some kind of a Base that he has to protect against Enemy units. There are also one or more enemy Bases that the Player has to destroy, but in a different Level Map. The Game has multiple Levels that are connected through predefined Ports. So the Player and other Units can travel from Level to Level. There are a couple of Levels to explore. (Maybe there could be infinit Levels in the future.) At game start I create a LevelManager and all Levels as Children of them. They can spawn an manage the Units and Voxel Blocks independently. One ChunkManager renders always the current Level where the Player is in. He creates multiple Chunks which itself generate the Mesh from the current Voxel Data of the Level. This works all very well and I'm also able to travel between the Levels. (This runs all in one Scene.) At the moment I try to implement some kind of a Worm unit. They spawn from time to time anywhere in each level and can move randomly around and modify the Voxel World by eating the Blocks away... type of random enviroment event. Problem The problem I can't solve is how to simulate all the Worms in parallel Levels? And the Blocks they have eaten? Same problem would occur for the enemy bases if they grow and build new defences and so on. Because when the Player enter a Level there should be some differences since his last visit. My attempt All my Units and Buildings have already separated logic and rendering components. So they can work properly even when not rendered by the ChunkManager. Its working for maybe 3 Levels and a handfull of worms but if I increase the amount of Levels it gets starting to go laggy (4 10FPS). So this would not be the right way to go or is it and my code is crap? Has someone any suggestions for me how I can solve this? Edit I disable now all none active Levels and reactivate always the current Level where the Player is in. So I can better manage the objects that realy need computation time. The problem I get now is how can I simulate the progress in a Level since start? Example for the worm unit. He would have moved across the Level and left a path of removed voxels. Should I made a seperate method to calculate the path that would be made or the last X minutes or should I just call the Update method multipletimes to match the missed calls since last X minutes? This should then be made by all Objects that can modify the Level or produce something. |
0 | When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) |
0 | Keep track of VoxelData NPC in parallel Level Background I'm tring to make a First Person Shooter Game in a Voxel World (Finit Size) with Unity3d. The Player has some kind of a Base that he has to protect against Enemy units. There are also one or more enemy Bases that the Player has to destroy, but in a different Level Map. The Game has multiple Levels that are connected through predefined Ports. So the Player and other Units can travel from Level to Level. There are a couple of Levels to explore. (Maybe there could be infinit Levels in the future.) At game start I create a LevelManager and all Levels as Children of them. They can spawn an manage the Units and Voxel Blocks independently. One ChunkManager renders always the current Level where the Player is in. He creates multiple Chunks which itself generate the Mesh from the current Voxel Data of the Level. This works all very well and I'm also able to travel between the Levels. (This runs all in one Scene.) At the moment I try to implement some kind of a Worm unit. They spawn from time to time anywhere in each level and can move randomly around and modify the Voxel World by eating the Blocks away... type of random enviroment event. Problem The problem I can't solve is how to simulate all the Worms in parallel Levels? And the Blocks they have eaten? Same problem would occur for the enemy bases if they grow and build new defences and so on. Because when the Player enter a Level there should be some differences since his last visit. My attempt All my Units and Buildings have already separated logic and rendering components. So they can work properly even when not rendered by the ChunkManager. Its working for maybe 3 Levels and a handfull of worms but if I increase the amount of Levels it gets starting to go laggy (4 10FPS). So this would not be the right way to go or is it and my code is crap? Has someone any suggestions for me how I can solve this? Edit I disable now all none active Levels and reactivate always the current Level where the Player is in. So I can better manage the objects that realy need computation time. The problem I get now is how can I simulate the progress in a Level since start? Example for the worm unit. He would have moved across the Level and left a path of removed voxels. Should I made a seperate method to calculate the path that would be made or the last X minutes or should I just call the Update method multipletimes to match the missed calls since last X minutes? This should then be made by all Objects that can modify the Level or produce something. |
0 | Deal Damage to Player I have to make a simple "avalanche" game to show I know how to use the physics and creating terrain. But I actually wanted to go a little above and beyond and actually give the player health so there is a actual purpose to dodging the sphere objects. I found a very useful guide on how to set up player health, the only thing is I don't know how to set up the player taking damage when he collides with a sphere. Here is the code I have for the players health pragma strict public var health float 100f How much health the player has left. public var resetAfterDeathTime float 5f How much time from the player dying to the level reseting. public var deathClip AudioClip The sound effect of the player dying. private var anim Animator Reference to the animator component. private var playerMovement PlayerMovement Reference to the player movement script. private var hash HashIDs Reference to the HashIDs. private var sceneFadeInOut SceneFadeInOut Reference to the SceneFadeInOut script. private var lastPlayerSighting LastPlayerSighting Reference to the LastPlayerSighting script. private var timer float A timer for counting to the reset of the level once the player is dead. private var playerDead boolean A bool to show if the player is dead or not. function Awake () Setting up the references. anim GetComponent(Animator) playerMovement GetComponent(PlayerMovement) hash GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs) sceneFadeInOut GameObject.FindGameObjectWithTag(Tags.fader).GetComponent(SceneFadeInOut) lastPlayerSighting GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(LastPlayerSighting) function Update () If health is less than or equal to 0... if(health lt 0f) ... and if the player is not yet dead... if(!playerDead) ... call the PlayerDying function. PlayerDying() else Otherwise, if the player is dead, call the PlayerDead and LevelReset functions. PlayerDead() LevelReset() function PlayerDying () The player is now dead. playerDead true Set the animator's dead parameter to true also. anim.SetBool(hash.deadBool, playerDead) Play the dying sound effect at the player's location. AudioSource.PlayClipAtPoint(deathClip, transform.position) function PlayerDead () If the player is in the dying state then reset the dead parameter. if(anim.GetCurrentAnimatorStateInfo(0).nameHash hash.dyingState) anim.SetBool(hash.deadBool, false) Disable the movement. anim.SetFloat(hash.speedFloat, 0f) playerMovement.enabled false Reset the player sighting to turn off the alarms. lastPlayerSighting.position lastPlayerSighting.resetPosition Stop the footsteps playing. audio.Stop() function LevelReset () Increment the timer. timer Time.deltaTime If the timer is greater than or equal to the time before the level resets... if(timer gt resetAfterDeathTime) ... reset the level. sceneFadeInOut.EndScene() public function TakeDamage (amount float) Decrement the player's health by amount. health amount Thanks for the help guys, and helping me to learn unity. |
0 | How do I get the size of a Plane in pixels and set it multiplied by some factor to be the size of a Sphere? I am doing an attempt to make a 3D snake game, as an experiment but I am still a beginner. I have a Sphere that I wish to dynamically resize to be, let's say, the 20th part of the width of this Plane. How can I do this? I thought to find the size of the Plane first. I also thought to use Screen.width and Screen.height because in my actual project the Plane is almost the size of the screen, but from what I found the Transform class does not have a way to resize it to a specific dimension in pixels. Using the code below I do not get this work, but I also see that the Sphere becomes a black circle because of the only instruction in the Start method. Existing code using System.Collections using System.Collections.Generic using UnityEngine Attached to the Plane public class SphereResizer MonoBehaviour Start is called before the first frame update void Start() what should I put here? GameObject.Find("Sphere").transform.localScale new Vector3(1f, 1f) Update is called once per frame void Update() Screenshots Download the example Here is the GitHub repository. Thank you. |
0 | Strange artifacts in Unity Lightmaps I experienced this weird lightmapping bug in my game that causes some models to have glowing artifacts on their surface. These artifacts "move" around, when I edit the UVs of the model in Blender, so I assume that it has something to do with them. I took a few screenshots to hopefully clarify the issue. Engine used Unity 2019.1.4f1 3D Software Blender 2.79b If you need any other screenshots or something, let me know. Thank you in advance! Lightmap Bug (lights off) Lightmap Bug (lights on) Models without Lightmaps baked Unity Lightmapper Settings Tree model in Blender with UVs Model Configuration in Hierarchy Model Asset Configuration |
0 | How can I call two functions in a sequence with onclick? I'm learning Unity. I have two functions, one that transitions to a new scene and the other one is the button animation. I add both functions to the onclick of a given button. I assume it calls both functions at the same time and executes the transition without running the animation. I want the button to run the animation first (I'm using DOTWEEN) and once it's done to execute the transition. |
0 | Stuck on walls or sliding on top dilemma I'm making a 2.5D platformer game. I earlier had problem with my character getting stuck on walls when holding the forward button. I solved this problem by adding a physics material with zero friction to my colliders on the wall. So now when hitting a wall the character slides down, which is correct. My walls consits of 1 unit cubes tiled together, and box colliders are generated and merged at runtime. Now I've created a ladder and by pressing a button the player will rotate 180 degrees, and I also add some force along the y and z axis var force transform.forward Vector3.up force.y JumpOffForceY force.z JumpOffForceZ rigidBody.AddForce(force, ForceMode.Impulse) Now when the player lands on the top of the wall, which has the same box collider, and physics material, the player slides very jerky for a long time before coming to a halt. I understand why this happens, I've been trying to find a solution. One solution I'm thinking of is to change my algorithm that creates the box colliders and divide them so there is one box collider on the top with higher friction, and one for the walls with zero friction. Before I delve into that, is that a good solution? Or is there any other way? Have a nice day! |
0 | How do you have the clothing mesh hide the body mesh underneath? How do you have the clothing mesh hide the body mesh underneath, to prevent odd patches of body from sticking out in tighter modular clothing? Is there some sort of shader trick that can have the clothing always render quot in front of quot the mesh? |
0 | Screen boundaries seem randomly placed I have a strange issue in which the characters boundaries work fine, however are placed at four seemingly random edges outside of the game view as a result of (I'm assuming) my player boundaries script. The player actually stopping at the edges is working fine, the issue is just with the placement of those boundaries. I'm following a tutorial, and the code is pretty much just copy pasted, so I'm not sure what's going wrong. using System.Collections using System.Collections.Generic using UnityEngine public class PSBoundariesOrthographic MonoBehaviour public Camera MainCamera private Vector2 screenBounds private float objectWidth private float objectHeight Use this for initialization void Start () screenBounds MainCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, MainCamera.transform.position.z)) objectWidth transform.GetComponent lt SpriteRenderer gt ().bounds.extents.x extents size of width 2 objectHeight transform.GetComponent lt SpriteRenderer gt ().bounds.extents.y extents size of height 2 Update is called once per frame void LateUpdate() Vector3 viewPos transform.position viewPos.x Mathf.Clamp(viewPos.x, screenBounds.x 1 objectWidth, screenBounds.x objectWidth) viewPos.y Mathf.Clamp(viewPos.y, screenBounds.y 1 objectHeight, screenBounds.y objectHeight) transform.position viewPos Above is my boundaries script using System.Collections using System.Collections.Generic using UnityEngine public class controlPlayer MonoBehaviour public GameObject player public float speed 1000f public GameObject left bool isLeftHeld bool isRightHeld public void Update() var movement Input.GetAxis( quot Horizontal quot ) Ignore cases where neither both left and right are held at once. if ( isRightHeld isLeftHeld) Override the movement input from the keyboard joypad. if ( isRightHeld) movement 1f else movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed public void HoldRight(bool held) isRightHeld held isLeftHeld false public void HoldLeft(bool held) isLeftHeld held isRightHeld false My player controller. I should add that hold left and hold right are controlled by two buttons placed accordingly on the screen. |
0 | Unity inconsistent memory profiling when running same scene I'm in the making of a 2D silhouette style game where I'm trying basically 2 setups One where it consists only of sprites, One where it consists of a mix of sprites and meshes with NO texture. Now, I'm experimenting with the two as I wish to want the scenes to take up the least memory. I have these weird outcomes SPRITE SETUP Total 280 MB, Textures 155.5 MB, Meshes 1.7 MB Total 249 MB, Textures 151 MB, Meshes 4.1 MB Total 279 MB, Textures 151.0 MB, Meshes 10.8 MB SPRITE amp MESH SETUP Total 334.4 MB, Textures 188.2 MB, Meshes 1.8 MB Total 241 MB, Textures 148,0 MB, Meshes 2,3 MB Total 253.1 MB, Textures 157.7 MB, Meshes 4.2 MB Total 301.8 MB, Textures 157.7 MB, Meshes 8.4 MB Total 234.8 MB, Textures 145.3 MB, Meshes 1.9 MB Now, I find these result strange because It was checked on the exact same scene (the mesh setup had same amount of objects, just swapped the sprites for meshes) and the data is inconsistent, meaning there is about 100MB difference between the same mesh scene A scene of mostly mesh with zero textures uses more, or at least not less, textures than a sprite only scene?? By taking a look at the data above, I would require someone skilled to guide me through this. Shall I keep using those meshes or just go for sprites? What is really goind on here with this data? |
0 | Refactoring fighting game Movement class responsibilities I'm a web developer, new to C and trying to learn Unity. I've learned the C syntax, I understand how to write working code, although I'm having a hard time understanding when and to what classes should I split my code. At the moment I'm doing a simple 2D fighting game, similar to Mortal Kombat, I've started out with creating some basic sprites and basic scripts for the environment, like clouds spawning and moving (the action takes places on a rooftop), created a fighter character with animations and started with writing the movement script. At this point, the Movement script deals with moving, jumping, animations (also triggers for punches and kicks) and player input (I'm using the new Input System), also I want to make the game a two player game, so the Movement script also checks if the the fighter is controlled by player 1 or player 2 and everything is crammed in this little Movement script, not that it's too large, it's just funny that a Movement script is doing so much and furthermore I'll need to add health and attacks (not just animations). I think it's about time I refactor, my questions are Should I create a Character, CharacterController, CharacterManager or whatever script that inherits from MonoBehaviour and other scripts as simple C scripts, or should all of my scripts inherit from MonoBehaviour and be attached as components to my GameObject with references to each other? Should I have a separate script for my animations or should they be at their respective scripts as in Attack, Movement, maybe Jumping or Death, whatsoever? What would be the best way or what would be the ways of managing my Fighter GameObject to determine if it is controlled by player 1 or player 2 and if I'll plan to add an AI for example? Should I have a PlayerController AIController inherit from Character script, or have a separate AI class, or just have some variable to check against? My problem with various tutorials is that most of them don't give a larger overview of the whole picture, most of them just focus on a single subject movement, animations, spawning, pathfinding or some other concrete thing or term, etc. and don't show how they are intertwined together. |
0 | How can I record and replay axis input accurately for testing? I want to do integration testing for an old C Unity project. The project uses its own input system, so I can't use inputEventTrace or any other convenient Unity class. So I subscribed a new game object to the custom input system so that it records any input detected in each frame. But when I replay, because of the difference in frame times, the replays are not quite equal to the original playthrough (especially because of the axis input). My understanding is that input in Unity is not event based, so I can't think of any way to perfectly mimic the input given different frame times. Does anyone know of a way to do this? |
0 | Is It Possible To Reset UI To Initial State At Runtime Without Any Direct Assignments? Is it possible to reset UI to it's initial state (the state when game started) without directly reseting elements one by one? Thanks in advance. Edit I'm asking for runtime. (ResetToPrefabState doesn't work at runtime.) |
0 | Extending control remapping script to work with mouse buttons I have created a default key map for my game, however I have also included an option in the settings where the player can change the key bindings. My issue is if the player clicks on the button for shooting, which is defaults to mouse0, or aim on mouse1, then click on another key, they can never go back to mouse0 or mouse1. I am unsure of how to include all the mouse buttons scroll wheel into the viable buttons the player can choose from. Here is the part of my code that deals with the changing of the keys private void OnGUI() if(curKey ! null) Event e Event.current if (e.isKey) keyBinds curKey.name e.keyCode curKey.transform.GetChild(0).GetComponent lt Text gt ().text e.keyCode.ToString() curKey.GetComponent lt Image gt ().color normal curKey null |
0 | Restarting a level but with more time? So I'm trying to add a "Rewarded video ad" with the reward being more time to play in the next game. my RewardedAd.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.SceneManagement public class RewardedAd MonoBehaviour public static RewardedAd singleton private void Awake() if (singleton null) singleton this else if (singleton ! this) Destroy(gameObject) public void ShowRewardedAd() if (Advertisement.IsReady("rewardedVideo")) var options new ShowOptions resultCallback HandleShowResult Advertisement.Show("rewardedVideo", options) private void HandleShowResult(ShowResult result) switch (result) case ShowResult.Finished Debug.Log("The ad was successfully shown.") StartCoroutine(NewGameWithTime()) break case ShowResult.Skipped Debug.Log("The ad was skipped before reaching the end.") SceneManager.LoadScene(0) break case ShowResult.Failed Debug.LogError("The ad failed to be shown.") SceneManager.LoadScene(0) break IEnumerator NewGameWithTime() Debug.Log("NewGame Started") GameOverManager.singleton.GameOverAfterRewardAd() SceneManager.LoadScene(1) Timer.singleton.AddBonusTime(20) Debug.Log("NewGame Ended") yield return new WaitForSeconds(1) and my Timer.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement using UnityEngine.UI using System public class Timer MonoBehaviour public static Timer singleton public Text timeTF private float seconds 10f private void Awake() if (singleton null) singleton this else if (singleton ! this) Destroy(gameObject) private void Update() if (seconds gt 0f) seconds Time.deltaTime TimeSpan timeSpan TimeSpan.FromSeconds(seconds) string timeLeft string.Format(" 0 D2 ",timeSpan.Seconds) timeTF.text timeLeft TimeLeftCheck(seconds) public void AddBonusTime(float bonusTime) seconds bonusTime Debug.Log("New Timer script ") Debug.Log(seconds) private void TimeLeftCheck(float time) if ( time lt 5) Debug.Log("RunningOutTime sound") SoundManager.singleton.Sound RunningOutofTime() if ( time lt 2) Debug.Log("Out of Time sound") SoundManager.singleton.Sound OutofTime() if ( time lt 1) Debug.Log("Game Over") GameOverManager.singleton.GameOver() The video ad is playing fine and it's resetting my ad counter in my game over manager but I can't seem to figure out how to start the next game with more time (20 seconds to so) but ONLY if they've watched the ad. Also, I'm still learning so any suggestions or things I can improve, more than happy to take that criticism too! |
0 | Unity3D Multiple OnTriggerEnters are called before the first one could finish and destroy the object I'm working on a projectile which explodes when it reaches a destructible object and damages its voxels. (The projectile is a trigger) But the problem is that I use raycasting in OnTriggerEnter which makes it slow to finish. Which lets multiple OnTriggerEnter to be called before it could be finally destroyed. I fixed it by having a flag which lets only one call to be executed. But it feels a bit hacky, so I decided to ask you, maybe you have some better solutions. void OnTriggerEnter(Collider collider) if (!hit amp amp LayerMask.LayerToName(collider.gameObject.layer) "Destructible") hit true DoImpact() Destroy(gameObject) void DoImpact() Do 1 SphereCast RaycastHit hits Physics.SphereCastAll(transform.position, ExplosionRange, transform.forward, 0.0001f, 1 lt lt LayerMask.NameToLayer("Destructible")) Iterate through voxels foreach(var hit in hits) the parent object which manages its voxels var destructible FindDestructibleParent(hit.transform) Make some damage to that voxel based on the projectile, the voxel, and some "whole container parent object properties" destructible.TakeDamage(this, hit.transform.gameObject) |
0 | OnMouseDown() execute only once I have the following OnMouseDown() function private void OnMouseDown() Debug.Log("This turret is " thisTurret.ToString()) if (EventSystem.current.IsPointerOverGameObject()) return if (thisTurret ! null) buildManager.SelectTurret(thisTurret) which send to the following functions public void SelectTurret(GameObject turret) if(selectedTurret turret) Debug.Log("Selected turret is " selectedTurret.ToString()) DeselectTurret(selectedTurret) return selectedTurret turret Debug.Log("Selected turret here is " selectedTurret.ToString()) Debug.Log("Pasted turret here is " turret.ToString()) if (oldSelectedTurret null) oldSelectedTurret selectedTurret Debug.Log("Selected turret is " selectedTurret.ToString()) if (oldSelectedTurret ! selectedTurret) turretUI.Hide(oldSelectedTurret) Debug.Log("Old in if Selected turret is " oldSelectedTurret.ToString()) oldSelectedTurret selectedTurret Debug.Log("Current Selected turret is " selectedTurret.ToString()) turretToBuild null turretUI.SetTarget(selectedTurret) public void DeselectTurret(GameObject turret) if(turret ! null) Debug.Log("Turret to deselect is " turret.ToString()) turretUI.Hide(turret) selectedTurret null else Debug.Log("Turret to deselect is null!") it should deselect the turret if clicked twice but instead it select the turret on first click and don't execute on second click |
0 | MissingComponentException when using Animator I followed some tutorials to add WASD movement to a character I managed to set up the animator thing and it works in the bottom right corner viewport. Next I tried adding the following C script with basic movements using System.Collections using System.Collections.Generic using UnityEngine public class AppleInput MonoBehaviour private Animator animator Start is called before the first frame update void Start() animator GetComponent lt Animator gt () Update is called once per frame void Update() animator.SetFloat( quot Horizontal quot , Input.GetAxis( quot Horizontal quot )) animator.SetFloat( quot Vertical quot , Input.GetAxis( quot Vertical quot )) Configured like so But then I get the error message MissingComponentException There is no 'Animator' attached to the quot action10Prob normalsDONEyet quot game object, but a script is trying to access it. You probably need to add a Animator to the game object quot action10Prob normalsDONEyet quot . Or your script needs to check if the component is attached before using it. How do I solve this error? |
0 | Unity Instantiate an object respecting the prefab's default rotation Simple question, I hope. I've built a variety of prefabs for an isometric shooter game (hazards, enemies, health indicator bars, popup texts, shots, explosions). All of these prefabs were constructed with default rotations appropriate for the gameplay. My problem is that Instantiate() will overwrite the default rotation of the prefab with whatever is specified as the rotation parameter. So I'm left with hard coded rotations in my Instantiate() calls to get things oriented correctly in the X Z plane. (0,180,0) and (90,0,0) are common ones. I'd much prefer to Instantiate prefab gameObjects consistently with "no change to their default rotation," but I'm not sure how to accomplish this. Thanks for the help, Mike. |
0 | Unity3D Retry Menu (Scene Management) I'm making a simple 2D game for Android using the Unity3D game engine. I created all the levels and everything but I'm stuck at making the game over retry menu. So far I've been using new scenes as a game over menu. I used this simple script pragma strict var level Application.LoadLevel function OnCollisionEnter(Collision Collision) if(Collision.collider.tag "Player") Application.LoadLevel("GameOver") And this as a 'menu' pragma strict var myGUISkin GUISkin var btnTexture Texture function OnGUI() GUI.skin myGUISkin if (GUI.Button(Rect(Screen.width 2 60,Screen.height 2 30,100,40),"Retry")) Application.LoadLevel("Easy1") if (GUI.Button(Rect(Screen.width 2 90,Screen.height 2 100,170,40),"Main Menu")) Application.LoadLevel("MainMenu") The problem stands at the part where I have to create over 200 game over scenes, obstacles (the objects that kill the player) and recreate the same script over 200 times for each level. Is there any other way to make this faster and less painful? |
0 | Unity blue sprite always showing on top regardless of order I have 3 SpriteRenderer SpriteRenderer Green Sprite SpriteRenderer Blue Sprite SpriteRenderer Brown Sprite The problem is that the blue sprite always shows on top of the others. I even tried to keep the SpriteRenderer in the same order and change the images but no matter which SpriteRenderer I put the blue image into it always shows on top. I have the sorting layer set to 0 for all 3 and I cannot change them because I will have to change so many other objects in the game. |
0 | Unity Manually sync location of players from server to client I am new to Unity networking. I've set up my scene with NetworkManager and the Player prefab having NetworkIdentity. I originally had my players set up to sync with a NetworkTransform. This worked, but the objects were very choppy whenever they were children of a moving object. In order to fix this issue, I've replaced NetworkTransform with a class extending NetworkBehavior, using UnityEngine.Networking, and containing the following code to sync localPosition void Update () CmdSyncPos (transform.localPosition, transform.localRotation) Command protected void CmdSyncPos (Vector3 localPos, Quaternion localRotation) transform.localPosition localPos transform.localRotation localRotation This works really well! The only problem is that this is one way, the server now has the updated position of all clients but the clients only have the updated versions of themselves. How can I do this in reverse Manually sync the location of non local players from server to client? |
0 | Changing AnimationOverrideController "sometimes" fails Unity 5.2.1 I have the following code, in a menu where you can chose the armor and weapon of a character private List lt string gt armors new List lt string gt "armor1", "armor2", "armor2" private List lt string gt weapons new List lt string gt "weapon1", "weapon2", "weapon3", "weapon4", "weapon5", "weapon6", "weapon7", "weapon8", "weapon9" private int armor index 0 private int weapon index 0 public GameObject avatar body public GameObject avatar weapon void Update() if (Input.GetKeyDown(KeyCode.RightArrow)) nextArmor() else if (Input.GetKeyDown(KeyCode.LeftArrow)) previousArmor() else if (Input.GetKeyDown(KeyCode.DownArrow)) nextWeapon() else if (Input.GetKeyDown(KeyCode.UpArrow)) previousWeapon() else if (Input.GetKeyDown(KeyCode.Return)) loadLevel() void nextArmor() if (armor index lt armors.Count 1) armor index 1 else armor index 0 setArmor() setWeapon() void previousArmor() if (armor index gt 0) armor index 1 else armor index armors.Count 1 setArmor() setWeapon() void nextWeapon() if (weapon index lt weapons.Count 1) weapon index 1 else weapon index 0 setWeapon() void previousWeapon() if (weapon index gt 0) weapon index 1 else weapon index weapons.Count 1 setWeapon() void setArmor() avatar body.GetComponent lt Animator gt ().runtimeAnimatorController Resources.Load("AnimationControllers player " armors armor index " body" ) as AnimatorOverrideController void setWeapon() avatar weapon.GetComponent lt Animator gt ().runtimeAnimatorController Resources.Load("AnimationControllers player " armors armor index " " weapons weapon index ) as AnimatorOverrideController The problem is when I start switching between the weapons, sometimes the sprite showing does not update. Inspecting the GameObject, it is weird, because the Animator Component has successfully updated, but the Sprite Renderer still shows a fixed sprite from the last Animator. Here are 2 examples Here we see that the animator is set for the weapon Gladius, and that the Sprite renderer is looping through all the frames of that animation Here we can see that even though we have moved to the Flanged mace animator, the Sprite Renderer is still stuck on a sprite of Gladius The problem is hard to recreate, because it happens just SOMETIMES. If I were to switch back to gladius and then once again back to flanged mace... Now it works... but I didn't change anything. What is going wrong?? |
0 | How to wrap a components position using angles (i.e horizontal compass) I'm trying to make a horizontal compass. The compass is made up of UI components panel (with mask), with a child UI Image (the compass image). Here is the compass from Fallout As you turn around, so does the compass. I want to move the child based on the rotation of the player. I want to move the child by using transform.position so that any child components will also move (i.e way points). I found some code on the Unity forum. I got it to kinda work, however when it wraps around, it doesn't wrap to the correct position. See GIF. When I approach the South rotation, it wraps but not to the correct position. The compass image and code can be found here. I've made sure that the image is native size, and also tried various values in the "numberOfPixelsNorthToNorth" property. using UnityEngine using UnityEngine.UI using System.Collections public class CompassHandler MonoBehaviour public float numberOfPixelsNorthToNorth public GameObject target Vector3 startPosition float rationAngleToPixel void Start() startPosition transform.position rationAngleToPixel numberOfPixelsNorthToNorth 360f void Update () Vector3 perp Vector3.Cross(Vector3.forward, target.transform.forward) float dir Vector3.Dot(perp, Vector3.up) transform.position startPosition (new Vector3(Vector3.Angle(target.transform.forward, Vector3.forward) Mathf.Sign(dir) rationAngleToPixel, 0, 0)) I don't really understand how the code works in the Update method, as my Math knowledge is pretty poor. I looked up the methods used, but still was clueless. So I can't work out how to solve it. I would like to understand what is going on in the Update, but if that is too much, can anyone help fix the issue that is seen in the GIF? Edit Here is a GIF using the accepted solution. |
0 | C Network flooding I just created a simple MMO in unity3d, then me and my friends test it via LAN and the result is very smooth. But when I hosted it in public (100ms ping) the server became unresponsive and causes random disconnection. Host Setup 1gbps 32gb ram 256 ssd off firewall Server Setup max of 100 players every 100ms update no other updates, just only X and Y location of player by index c sockets w async Server Flow when 100ms tick reaches, server sends position of player base on index in a loop. ex. if (gtick gt 0.1f) for (x lt maxPlayers x ) check ifs couples of ifs here... send sendToWorld(x ... player x .posX ... player x .posY) somewhere, gtick 0, then counts up again... then the result is delay, unresponsive, and random disconnection. maybe it flooding itself, I don't know. but when we test it locally (10 players), it is very smooth and no problem at all. My question is, How can I update all players every 0.1 without server flooding itself? |
0 | How can I switch between texture atlases based on the iOS version? How can I switch between atlases (with different resolutions) in Unity based on the runtime iOS version? |
0 | How to import character from Blender to Unity? I am trying to import a character into Unity from Blender. I exported the model (which has actions animations) from Blender as a FBX file and dropped in into my Unity project s Assets folder. The model with all of its components (mesh, armature, animations) appears in the project window however, Unity doesn t immediate associate the animations with the model when I drag an instance of the model into my scene. I have also imported a Blender default model ( Constructor a man with red overalls and a wrench), and have been comparing the settings of my model to the Blender model in order to find discrepancies. 3 observations I have made Blender s model is automatically assigned an Animation window in the Inspector panel (image 1), while mine is assigned an Animator window (image 2). Since the former window is the one where the animations are listed and you assign the default animation, it seems like this one is crucial. How do I import my model such that the Animation window appears in its Inspector window? (I ve tried adding an Animation window myself, but it doesn t recognize the model s animations as the Blender model s Animation window does. In Unity, my model s animations all begin at 1.0 (even though they begin at keyframe 0 in Blender) (image 3). For each animation, I get the message, The clip range is outside the range of the source take. I get this message even when I move the animation forward several keyframes in Blender and re export the file to Unity as a FBX. I compiled several of my actions into an animation that I then exported as a .mov file, and this is the sequence of actions that begins when I press Play in Unity. When I deleted this animation from Blender (as I thought this was the issue), my model now does nothing when I press Play. I am using Blender 2.67 and Unity 4.1.5f1 My actual question How do I import my character into Unity such that it is automatically assigned an Animation window? I have been struggling with this issue for several hours now, and none of the online tutorials or forums seem to address it. |
0 | How to disable an object after it goes outside camera's viewport? I have a gameobject at a certain position in the game. I want the gameobject to be disabled once it is outside the camera's viewport, and it should become visible only when the camera focuses at that position. |
0 | Is there a way to identify, within a shader, the current GPU thread ID? My question is rather simple within a shader, is there a way (that works both in DirectX and OpenGL) to retrieve the ID of the given GPU thread being executed at the given iteration? I am using Unity 5.3.4, if that helps. But I guess this is actually quite a platform agnostic question. I have searched quite a bit for it, but found nothing satisfactory. |
0 | Export selected region of Unity tilemap to c array? I have a small region of the map selected with the quot Select an area of the grid quot tool from the tile palette. I'd like to be able to copy and paste this area for usage elsewhere in a programmatic way. Since the location this region will be placed is determined via scripts, it's not sufficient to just directly copy and place these tiles down elsewhere I think they need to take the form of a c array so I can read through that and then use it elsewhere when the time comes. How can I achieve this? |
0 | How to implement ECS architecture in C ? As C is a strongly typed language, I'm having great difficulties associating all my data types together so that I can have a clean, if not performant, game loop. Example 1 Keeping Components Together Keeping components together means I need an interface or base class to store them in an array, which would require keeping track of each type separately so that it can be converted back to the derived type before being consumed. The constant type conversion seems like a bad idea in an ECS? To compound the problem, I would prefer to use structs instead of classes for my components, which when cast to an interface will cause boxing. In some simple stop watch tests I've run it seems the casting boxing is 16x slower than just looping over the raw type. (Pseudo code below) IComponent sprite new SpriteComponentStruct() boxing for(int i 0 i lt iComponents.Length i ) var type GetComponentTypeByIndex(i) var system GetSystemWithType(type) SpriteComponent sprite Convert.ChangeType(...) system.Execute(sprite) Example 2 Keeping Components Separate To keep components separately in their own classes managers systems I would likely need a generic class to cut down on the code duplication. The problem I run into here is that looping over each class will require a base class or interface, which at the very least would force me to cast the component types again. (Pseudo code below) ComponentManager lt T gt () where T struct T components can't use with non generic interface to put manager into a list public void AddComponent(T component) ... won't compile type "T" will not cast to type "T" public void AddComponent lt T gt (T Component) ... requires casting and or boxing, which defeats the purpose of keeping components separate public void AddComponent(object component) ... It seems every which way I try to implement a ECS in C ends with hacky non performant code, that's assuming I can get it to compile in the first place. From studying other ECS systems around the net, it seems some side step these issues by using void int pointers or storing component bytes directly in memory (like I believe the new ECS in Unity 2018 does). Either way those are unsafe operations in what's supposed to be a managed memory language. So is C the wrong tool for the job? Am I approaching this incorrectly? I'd love to hear some opinions as this just seem impossible... |
0 | Animation playing incorrectly when controlled through player I have a 2D simple directional blend tree with 2 inputs, X and Y, for movement. If i move the red dot in the inspector, the animations blend nicely. Same if i move the 2 input parameters in the animator. But if i press play and move the character with arrows, i can see the 2 parameter inputs in the animator screen moving same as when i moved them with mouse, but the animation that is playing stays the same and the red dot that represents parameters in the inspector stays in the center (even though the parameters in the animator are moving). I also tried using just 2 animations and blending between them, but turns out that doesn't work ether, even though animator shows that the correct animation should be playing. (if i press forward animator shows that forward animation is playing, but on scene the animation that is playing is like a blend at parameter value in the middle. The animations were made in Blender as actions (if that's important). |
0 | Add single color background to texture using shader I want to add a single color background to my texture. In my case, in Unity UI, I can simply create two Image components, one on top of another, and use the one on the bottom as a single color background. However, I would like to do it in a single draw call, using a shader. This is the shader that I use Shader "UI Background Tinted" Properties PerRendererData MainTex ("Sprite Texture", 2D) "white" BgClip ("Offset Mask", Range(0,0.1)) 0.025 StencilComp ("Stencil Comparison", Float) 8 Stencil ("Stencil ID", Float) 0 StencilOp ("Stencil Operation", Float) 0 StencilWriteMask ("Stencil Write Mask", Float) 255 StencilReadMask ("Stencil Read Mask", Float) 255 ColorMask ("Color Mask", Float) 15 Toggle(UNITY UI ALPHACLIP) UseUIAlphaClip ("Use Alpha Clip", Float) 0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" "PreviewType" "Plane" "CanUseSpriteAtlas" "True" Stencil Ref Stencil Comp StencilComp Pass StencilOp ReadMask StencilReadMask WriteMask StencilWriteMask Cull Off Lighting Off ZWrite Off ZTest unity GUIZTestMode Blend SrcAlpha OneMinusSrcAlpha ColorMask ColorMask Pass Name "Default" CGPROGRAM pragma vertex vert pragma fragment frag pragma target 2.0 include "UnityCG.cginc" include "UnityUI.cginc" pragma multi compile UNITY UI CLIP RECT pragma multi compile UNITY UI ALPHACLIP struct appdata t float4 vertex POSITION float4 color COLOR float2 texcoord TEXCOORD0 UNITY VERTEX INPUT INSTANCE ID struct v2f float4 vertex SV POSITION fixed4 color COLOR float2 texcoord TEXCOORD0 float4 worldPosition TEXCOORD1 UNITY VERTEX OUTPUT STEREO fixed4 TextureSampleAdd float4 ClipRect float BgClip v2f vert(appdata t v) v2f OUT UNITY SETUP INSTANCE ID(v) UNITY INITIALIZE VERTEX OUTPUT STEREO(OUT) OUT.worldPosition v.vertex OUT.vertex UnityObjectToClipPos(OUT.worldPosition) OUT.texcoord v.texcoord OUT.color v.color return OUT sampler2D MainTex fixed4 frag(v2f IN) SV Target half4 main tex2D( MainTex, IN.texcoord) float mask 1.0 main.a half4 bg IN.color bg.a mask half4 color main (bg mask) return color ENDCG With two Images component everything is fine. However, with single shader approach I encounter sharp edges near image alpha boundaries. Using 2 images, looking fine Using single shader, jagged edges How do i fix that, using a single shader approach? |
0 | Unity2D Collision Issue I have a crate setup (in pic below) with a rigid body component, box collider and 3 circle colliders(they allow me to push the crate most of the time without getting stuck on the floor textures which are normal box colliders) As you can see in the pic there are collisions detected between the crate and floor even though they are not physically touching. How can i make the collisions more precise as my crate gets snagged on the floor textures when there is minuscule difference between the floor box colliders? |
0 | How to build a hidden 3D snapping grid effect? Looking to build a 3D grid similar to the image below taken from Google Blocks. Seems like it consists of these main components A set of spheres that can go transparent. A stencil that follows the controller's location. When stencil overlaps with spheres, they show up, otherwise, alpha fades to zero. Any advise on how to approach building this? |
0 | theoretical solution for "drawing" with mask So am trying to create a make up game and i need to have a basic drawing solution, and so far i have made a good progress with the help of the DepthMask solution My approach was like this suppose we want to edit the eyelash color (texture) 1 in the beginning there is an eyelash object at a layer named old 2 after choosing the new color that we will draw with, a new game object is created under the first eyelash, which mean it's invisible for the moment 3 then when we start drawing, we are actually creating little circles above the old eye lash, these circles contain the depthMask shader which effect the old eyeLash and give the impression that we are drawing with the new color So far, everything is going great, my problem is that i cannot use this approach to use a 3rd color, suppose the player want to create an eyelash with mixed color, how can i do that with the previous solution ? or is it impossible to do ? EDIT I already thought about adding new layers with each new color, and it works, but since unity is limited to 31 layers, this solution can never be a good one. I really hope someone can answer this, and if you know a better way to do it then please don't hesitate to tell me. EDIT2 After a couple of hours, i've reached a pretty cool result, and i think that this can be the good way to reach my goal, this script allow to replace a specific pixel in a material texture with another chosen texture (target texture must be in the same size, and readable) the texture that i will paint with public Texture2D targetTexture temporary texture Texture2D tmpTexture void Start () setting temp texture width and height tmpTexture new Texture2D (targetTexture.width, targetTexture.height) for (int y 0 y lt tmpTexture.height y ) for (int x 0 x lt tmpTexture.width x ) filling the temporary texture with the target texture tmpTexture.SetPixel (x, y, targetTexture.GetPixel (x, y)) Apply tmpTexture.Apply () change the object main texture renderer.material.mainTexture tmpTexture Now i think that the problem will only be, "how to know which pixel i should replace based on mouse position over the object ?" Thank you very much and have a great day. |
0 | Is Time.deltaTime framerate dependent? I have a game that calculates your score via Time.deltaTime (the more time the more score). On my PC I get about 1200 points if I just idle the game while on my phone I only get about 400 points. I believe my code must be FPS dependant and that's why my phone is getting a lower score for the same time. Here's the code void Update () time Time.deltaTime score (int)time timerLabel.text score.ToString() Sorry if it's something very obvious. I'm quite new at c . Can't seem to get the solution to work. It just stays at 0 Full Code using UnityEngine using UnityEngine.UI using System.Collections using UnityEngine.SceneManagement public class EndGame MonoBehaviour public Text textWin public Text timerLabel public GameObject retryButton public GameObject points private Vector3 offset private float time private float score void OnTriggerEnter (Collider col) if (col.gameObject.name "Player") setWinText () retryButton.SetActive (true) points.SetActive (false) void setWinText () textWin.text "Final score " score.ToString() void Update () time Time.deltaTime if (time gt 1.0f) score score 1.0f timerLabel.text score.ToString() |
0 | In 2D, how can I improve character rotation using raycasts when dealing with sharp convex edges? Edit After making some edits to my polygon collider (based on Alex F's suggestion), I can indeed confirm that sharp, convex corners are causing the buggy rotation. For now I've decided to only rotate my character if its moving, so standing on a corner when velocity.x 0 won't cause my collider to rotate rapidly. However, this seems like a band aid fix, and I'm still wondering if there's a better way to handle these edges. Resuming movement after idling on a corner still causes some buggy behavior, and I'm concerned that this will compound once my rotations become more complicated or frequent Original question I'm quite inexperienced with quaternions and rotating, so I'm not entirely sure if this issue has to do with my code, the collisions shown in this question, or my game design. What I'm trying to achieve is "smooth" rotation of my character's collider based on the normal of the current surface. I've been creating a custom raycast controller in 2D from the ground up, and already know how to find all kinds of information from rays, such as the current angle of a sloped surface. My controller is coming along quite nicely, and rotation is one of the last things I'd like to tackle. It should be able to handle sloped box colliders, but also irregular ground shapes that require something like a polygon collider. I've been somewhat successful, having learned that I shouldn't set my character's z rotation directly, but instead update my entire transform.rotation with a method like Quaternion.Lerp. This has worked generally well, but I'm running into issues on irregular ground, and on corners. Notice the smooth transition from flat to sloped surfaces, but that my collider rotates rapidly when the raycast hits a corner Movement is still somewhat smooth on irregular terrain, but there is a noticeable shakiness at times. Sometimes my character's collider rotates rapidly as well (end of gif) I suspect that the shakiness on the irregular terrain is just my collider getting "caught" on the many edges that the polygon collider creates. I just don't know if this is happening because I could be doing something differently in my code, or if I need to edit the polygon collider, or is caused by something else entirely. Perhaps raycasting isn't the best way to achieve my desired behavior. SerializeField private float speed 5 SerializeField private float gravity 20 SerializeField private LayerMask collisionMask private BoxCollider2D boxCollider private Vector2 velocity private Vector2 groundNormal private void Awake() boxCollider GetComponent lt BoxCollider2D gt () private void Update() float playerInput Input.GetAxisRaw("Horizontal") velocity.x playerInput speed velocity.y gravity Time.deltaTime MoveCharacter(velocity Time.deltaTime) private void MoveCharacter(Vector2 velocity) Rotate the character Quaternion targetRotation Quaternion.FromToRotation(Vector2.up, groundNormal) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, 0.5f) groundNormal Vector2.zero CollideBelow(ref velocity) transform.Translate(velocity) private void CollideBelow(ref Vector2 deltaMovement) float rayLength 1 Vector2 rayOrigin transform.position RaycastHit2D hit Physics2D.Raycast(rayOrigin, transform.up, rayLength, collisionMask) Debug.DrawRay(rayOrigin, transform.up rayLength, Color.red) if (hit) velocity.y 0 deltaMovement.y (hit.distance boxCollider.size.y 0.5f) groundNormal hit.normal |
0 | Fixing text on the screen for Oculus Rift I would like to fix text to the screen for an Oculus Rift in Unity. The text should say something like "get comfortable and then press any key". It seems like OVRGUI.StereoBox should work for this and I've tried to copy an example I found on Github, like so public class TargetScript MonoBehaviour void OnGUI() Debug.Log("Drawing Recenter dialog.") string loading "LOADING..." OVRGUI guiHelper new OVRGUI() guiHelper.StereoBox(300, 300, 300, 300, ref loading, Color.white) Debug.Log("Stereo Box should be visible.") Debug.Log (guiHelper) The log messages indicate that this code block is definitely being hit, but no text is visible on screen. What am I doing wrong? |
0 | Tile Palette problem in Unity I am working on isometric tilemap in Unity 2019.4.8f1. In the Tile Palette panel, the selection is always 1 block away. Please see this screenshot In the screenshot, apparently I selected an empty tile, but in fact I am select the green tile with flowers. How come? Every selection is one tile away. The same issue happens in the Tilemap selection mode too. I have to select the adjacent tile in order to select the tile I want. How do I fix it? It's quite annoying. UPDATE I have added the settings of Grid, Tilemap as well as the import settings of the tile sprite sheet below. UPDATE 2 Changed the Pivot in Sprite Editor to Bottom Center Recreated the Tile Palette, and it looks like hovering 0.5 unit up. |
0 | Getting world space vertex coordinates in Unity I'd like to get world space coordinates for a specific mesh vertex. Transform.TransformPoint() seems to be what I need however I'm unable to get the correct position. In the scene I have an object called "head" at Pos (0, 0, 0) Scale (0.03, 0.03, 0.03) and I'm trying to get the position of vertex id 590 in order to spawn another object at that specific location. Mesh mesh GameObject.Find ("head").GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 newPos transform.TransformPoint (vertices 590 ) Debug.Log (newPos) The value of newPos is not on the head object. |
0 | Press and hold camera movement with mouse in new Input System? I am transitioning to the new movement system and am having trouble figuring out how to move the camera when a mouse button is pressed and held. Here's how I did it before private void Update() Get the position of the mouse when a middle click occurs if (Input.GetMouseButtonDown(2)) dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) If the MMB is still held down, calculate the distance and move the camera if (Input.GetMouseButton(2)) Vector3 difference dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) cam.transform.position difference I have tried doing something similar in the new input system but it doesn't work public void OnMMB(InputAction.CallbackContext context) if (context.phase ! InputActionPhase.Started) Get the position of the mouse when a middle click occurs dragOrigin cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) else If the MMB is still held down, calculate the distance and move the camera Vector2 newPosition cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) Vector3 difference dragOrigin newPosition cam.transform.position difference Here is how I set this up inside the Input editor The Action Type of the action is Button. |
0 | Get the dropped object using IDropHandler.OnDrop In Canvas, I drag some UI objects to a panel using this code public void OnDrag(PointerEventData eventData) Vector3 screenPoint Input.mousePosition screenPoint.z 10.0f Item2Drag.position Camera.main.ScreenToWorldPoint(screenPoint) But what I can't figure out is when I dropped an object on the panel, how can I get the gameObject which has been dropped? |
0 | Unity getting Input from UI So I'm trying to get a script of mine to pass information to another static class being used for saving files as I've been told I wouldn't want that script to be instantiated. So I used a separate script to get input field text. However, I seem to be encountering a problem whenever I want to save the file. I keep getting the error "Object reference not set to an instance of the object", I have made done this though. (See code below) The class to get the name of the file public class SaveInputField MonoBehaviour public static string saveName public GameObject inputField public void getFileName(string saveName) saveName inputField.GetComponent lt Text gt ().text Debug.Log("Save file name " saveName) SaveFile.saveName saveName called whenever its been edited The static class public static class SaveFile public static string saveName public static void SaveData(Deck deck) BinaryFormatter formatter new BinaryFormatter() string path Application.persistentDataPath " " saveName ".dd" FileStream stream new FileStream(path, FileMode.Create) Debug.Log("Stream Opened") DeckData data new DeckData(deck) formatter.Serialize(stream, data) stream.Close() Debug.Log("Stream Closed") |
0 | How can I display Unity games in Flex? We have tried the following methods to upload sample Unity3D build to a desktop application in Flex HTML Loader, NavigateToURL, iFrame and resolvePath. But we only see the text content, not the 3D content. What is the solution for that? How can I host a Unity game inside Flex? |
0 | How do I reference a particular UI Image or Sprite in my assets folder? I have an Item class, and I want to associate an Image class with it. How do I get a reference to the intended Image, from my assets folder, in order to provide it as a reference to a constructor for Item? Here is my code using System.Collections.Generic using UnityEngine using UnityEngine.UI public class ItemData MonoBehaviour private List lt Item gt items void Start() items new List lt Item gt () Item sword new Item(0, "Sword", What goes here? ) items.Add(sword) Item hammer new Item(0, "Hammer", What goes here? ) items.Add(hammer) public class Item public int itemID public string itemName public Image itemImage public Item(int newItemID, string newItemName, Image newItemImage) itemID newItemID itemName newItemName itemImage newItemImage |
0 | Why my Edit Collider in Unity2D has no point to adjust size? Why when I clicked to Edit Collider of Box Collider 2D component, is not showing points for me resize the collide box? |
0 | How to make unitypackage from allseen alliance's android sdk? Im making an offline multiplayer for Android device by Unity and I found only one way to do this is the allseenalliance sdk. After download its from here I found that to use it I need to create an .unitypackage file but I cant understand the tutorial they give gt Open a CMD window. gt Add the path to Unity.exe (the Unity IDE) to your PATH, if it is not there already. gt For example, set PATH PATH C Program Files Unity Editor gt CD to each quot unity quot folder in the SDK, and run the following command in each location gt Unity.exe batchmode nographics quit projectPath CD exportPackage Assets AllJoyn.unitypackage gt This command creates the AllJoyn.unitypackage file. Please give me a noob tutorial for this or the package file, thanks. p s Is there another way to connect mobile device without internet in unity3d? |
0 | How to temporarily increase the speed of a character in a Unity game As the title would suggest, I want to give a character a speed boost for x amount of seconds, while increasing their Gameobject's mass. During this little speed boost, I also want to add a script to another player that disappears when the speed boost dies out I am new to C , and Unity in general, any help would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerAddMass MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKey(KeyCode.Q)) rb GetComponent lt Rigidbody gt () rb.mass 10 rb GetComponent lt Rigidbody gt () rb.speed 5 The code above was found on a unity website of some sorts, and I modified it to set the speed and mass numbers (I changed the 0s into a 10 and a 5) The errors I get are "rb does not exist in the current context" x 4 |
0 | Problem with Animating on local position Unity Currently, I am having a Cube that needs to be animated to roll on its edge. Using unity built in animation feature, I created 4 animations (RotateUp, RotateDown, RotateLeft, RotateRight). At the end of each animation I would put an Event to call a method on my script. To be able to move the object every time the animation is played, I put the cube with animator attached inside a parent object. Below is the script attached to my cube. using System.Collections using System.Collections.Generic using UnityEngine public class RedCubeBehavior MonoBehaviour Animator anim bool isMoveTriggered false void Start() anim gameObject.GetComponent lt Animator gt () void Update() if (Input.GetKeyDown(KeyCode.UpArrow)) MoveUp() else if (Input.GetKeyDown(KeyCode.DownArrow)) MoveDown() else if (Input.GetKeyDown(KeyCode.LeftArrow)) MoveLeft() else if (Input.GetKeyDown(KeyCode.RightArrow)) MoveRight() if (isMoveTriggered) if (IsBackToIdle()) transform.parent.position transform.position transform.localPosition Vector3.zero isMoveTriggered false void AnimationFinished() anim.Play("IdleState") public void MoveUp() if (isMoveTriggered) return else Debug.Log("MoveUp") isMoveTriggered true anim.Play("RotateUp") public void MoveDown() if (isMoveTriggered) return else Debug.Log("MoveDown") isMoveTriggered true anim.Play("RotateDown") public void MoveLeft() if (isMoveTriggered) return else Debug.Log("MoveLeft") isMoveTriggered true anim.Play("RotateLeft") public void MoveRight() if (isMoveTriggered) return else Debug.Log("MoveRight") isMoveTriggered true anim.Play("RotateRight") bool IsBackToIdle() return anim.GetCurrentAnimatorStateInfo(0).IsName("IdleState") Every time the arrow key is pressed the object would rotate but in the end when AnimationFinished() is called, the cube would just roll back to its starting position (because of playing IdleState). It will only work (the object didn't return to its starting position) if I pressed the arrow twice quickly. I've tried to not call the IdleState (which is only an empty state), but what happens next is it just won't play another animation again when triggered. What should I do in order to get it work without having to press the key twice? |
0 | Adding hotbar to inventory? I have a inventory and I need to add a hotbar to access certain items. What this hotbar needs to do is when in the inventory "Menu" you add items to it and when you close the menu the hotbar moves to the bottom of the screen and you select and item, weapon, food ect, and can use it (like in Minecraft). My problem is I don't know whether I should Keep track of which items are in hotbar "spaces" of the inventory and use them accordingly, or Make a separate list for hotbar items and move them between the inventory and hotbar lists when needed or a third way I did not even think of. My inventory works by having items in a list. The item class has values such as dmg, uses, name, etc. I have an item data class I put on GameObjects that has a public item variable. I have an inventory UI class that takes the inventory list and displays them. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.