_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
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 | How do I change a background in movement in Unity? I'm developing a game and the background is moving and I wanna change to another image without losing the current speed of the movement. File public class BackgroundMovement MonoBehaviour Material material Vector2 offset GameManager gameManager UIManager uiManager SpawnManager spawnManager public float speed 0.3f private void Awake() material GetComponent lt Renderer gt ().material gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () uiManager GameObject.Find( quot Canvas quot ).GetComponent lt UIManager gt () spawnManager GameObject.Find( quot SpawnManager quot ).GetComponent lt SpawnManager gt () Update is called once per frame void Update() offset new Vector2(speed, 0) if(gameManager.gameOver false) GameSpeed() material.mainTextureOffset offset Time.deltaTime In Unity, I added to the material of the background a shader quot unlit transparent quot and added the background in it. The object that this material is in, is a quad. I tried to change creating a list of background images that I wanted on the game. One of the times I tried, I managed to change the background, but the image didn't move, only the first. This is the inspector of the background. |
0 | Unity doesn't change particle color when render is set to mesh? I've got a particle system with Render Mode set to Mesh. Then I applied a material to it, which is just white with the default shader. Now I can't change the start color nor the color over lifetime etc. As far as I know that shouldn't happen, right? I'm using Unity 5.5.0f3 This is what my PS looks like with the material This is what I achieved with 3 particle systems with 3 different materials, but actually, I don't want these materials. Instead, I want to set the start color property of the particle system to apply some color. The material solution restricts me in terms of random start color and stuff like this. |
0 | How do I calculate a new position from current and target position for intuitive non instant dragging? I have a simple 2D game where I can move an object using the mouse. I've been improving on the 'feel' of the movement gradually, however it still doesn't behave as you'd expect if the object were to be moved by human hands in a real world scenario. My improvements were as follows New position mouse position Sharp unrealistic movement. No max speed. Cap the maximum speed Nicer. Still stops abruptly. Doesn't accelerate smoothly Add 'inertia', recording last change in position and applying it to subsequent moves Vastly improved, however... Object is dragged as if on elastic, slow to accelerate, very slow to stop. Once moving, object oscillates or orbits around a stationary mouse position. I'm looking for suggestions on how to make the movement more intuitive Moving an object from A to B a human would rarely overshoot A user shouldn't need to correct against inertia to stop an object I'd like to be able to adjust the weight of the object so that heavier things are harder to get moving My current code is as follows float maxInertiaChange 0.1 Vector2 lastPosition Vector2.negativeInfinity Vector2 inertia Vector2.zero private Vector2 InterpretPosition(Vector2 mousePosition) Vector2 newPosition if (lastPosition.x ! float.NegativeInfinity) newPosition lastPosition (inertia Time.deltaTime) newPosition GetPointTowardsTargetWithMaxDistance(newPosition, mousePosition, maxInertiaChange) inertia (newPosition lastPosition) Time.deltaTime else newPosition mousePosition lastPosition newPosition return newPosition private static Vector2 GetPointTowardsTargetWithMaxDistance(Vector2 startVector, Vector2 targetVector, float maxDistance) float lerpScale maxDistance Vector2.Distance(startVector, targetVector) return Vector2.Lerp(startVector, targetVector, lerpScale) Thanks in advance! |
0 | How can I make tree foliage work with baked lighting? I have an issue in Unity where my trees are black and it seems to be due to the fact that I'm using baked lighting in my scene. Luckily, it seems that I'm not the only one who's experienced this. I found a post on the unity3d subreddit which goes into more detail about basically the same problem. I'll repost it here for convenience So, I have some custom trees using the "Nature Tree Soft Occlusion" shaders and they looked great before baking a lightmap. However, now that I have baked the lightmap, the trees have turned black. Or rather, when I tried baking with the trees set to static, they turned invisible, and now that Ive tried without, they're black. Also, they're not casting shadows. Anyone know how to fix this issue? Perhaps I need to use light probes? http imgur.com a 21At5 before and after (fyi the bark is not using the nature occlusion shader. The shader definitely seems to be the root of the issue, but Im just not sure how to fix it without using a different shader) Ultimately, the author of this post eventually "solved" his problem by just switching to realtime lighting instead of baked lighting. Unfortunately, this is not an option for me. However, the author did receive some useful comments before giving up. One of the comments asks if the leaves have properly laid out UVs. The commenter goes on to say that the leaves all need to have their own unique space in the UV grid. I think this makes sense because I enabled the Generate Lightmap UVs option on my tree model in Unity. But it did nothing. The author apparently also had no luck with that option. In any case, Maya was suggested (among other software) to check these leaves' UVs. Unfortunately, I've never used Maya and I absolutely can't make heads or tails out of it. I'm just using a borrowed copy from a friend so I've never gone through any tutorials or anything for it. I'm just trying to check this one thing, but I am really at a loss. EDIT According to some comments from DMGregory, he suggests that since trees get spawned and varied dynamically, there's no single mesh to pull apart and check its UVs. His logic seems to make sense, so perhaps Maya is not the solution that I'm looking for. Now, though I'm having trouble with figuring out how to get my tree shaders to work with lightmapping. Details are in the comments. |
0 | Unity IUnityLifecycleManager already exists I followed this tutorial https www.youtube.com watch?v OElh7wda4Qc in Unity version 2019.3.1f.1 Personal Edition, but I got 6 errors like this in the console, also I updated to version 3.4.4 via the package manager, because it said that the asset store version was not compatible anymore. Library PackageCache com.unity.ads 3.4.4 Runtime Monetization AndroidPlacementContentOperations.cs(55,40) error CS0433 The type 'IUnityLifecycleManager' exists in both 'UnityEngine.Advertisements.Editor, Version 3.4.2.0, Culture neutral, PublicKeyToken null' and 'UnityEngine.Advertisements, Version 3.4.2.0, Culture neutral, PublicKeyToken null' This is the code I am using, its the same as the code in the official website, but personalized to my project. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.UI public class adsController MonoBehaviour, IUnityAdsListener public bool testMode true public Button rewardedAd private string storeID "3509232" private string rewardedVideo "rewardedVideo" private void Start() rewardedAd.interactable Advertisement.IsReady(rewardedVideo) rewardedAd.onClick.AddListener(ShowRewardedVideo) Advertisement.Initialize(storeID, testMode) private void Update() private void ShowRewardedVideo() Advertisement.Show(rewardedVideo) Implement IUnityAdsListener interface methods public void OnUnityAdsReady(string placementId) If the ready Placement is rewarded, activate the button if (placementId rewardedVideo) rewardedAd.interactable true public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) Define conditional logic for each ad completion status if (showResult ShowResult.Finished) Reward the user for watching the ad to completion. Debug.Log("Reward") else if (showResult ShowResult.Skipped) Do not reward the user for skipping the ad. Debug.Log("Not Reward") else if (showResult ShowResult.Failed) Debug.LogWarning("The ad did not finish due to an error.") public void OnUnityAdsDidError(string message) Log the error. public void OnUnityAdsDidStart(string placementId) Optional actions to take when the end users triggers an ad. EDIT Looks like I forgot a line in the code and reinstalling the unity ads package now it runs but still gives this warning. Please consider upgrading to the Packman Distribution of the Unity Ads SDK. The Asset Store distribution will not longer be supported after Unity 2018.3 |
0 | Texture2D GetPixels Finding pixels that are not transparent. Problem as finding more than expected I am trying to make a level design system where I use a low resolution png file with certain pixels filled. My code will turn this location of the pixel in the image into placement of platforms in my game. But I test the following code with a png i made with only 1 pixel in it (the rest are transparent). But the result is it finds 4 every time. Is it possible there is a discrepancy between the Gimp png and the texture that Unity sees. (In GIMP I used pencil 100 hardness 1px width. There are also settings for 'resolution' of the image, which i left at defaults) public class LevelBuilder MonoBehaviour public Texture2D sourceTex Color32 pixels int pixelsFound 0 private void Start() pixels sourceTex.GetPixels32() for (int i 0 i lt pixels.Length i ) if (pixels i .a ! 0) Debug.Log("found colored pixel. total " pixelsFound) |
0 | How to make a visible area in unity3d the simple way to explain it is an image I want to have a black background and to show only a small area around player. Which way I have to look? I have no clue where to start searching ) Thanks. |
0 | How does Unity know that you make more than one hundred thousand dollars on the Personal plan? How do they check if you make more than 100k? That is really puzzling me. |
0 | Scale object based on another object's position Despite an hour or so of Googling I can't seem to figure out how to calculate the scale factor based on distance. Here's the illustration of my problem. I've tried manipulating the x values and such, but until now I still cannot figure it out. Here's the snippet Vector3 v3Scale frontWall.transform.localScale frontWall.transform.localScale new Vector3(v3Pos.x 2.0f , v3Scale.y , v3Scale.z) Any ideas? Thanks in advance! UPDATE if(getTarget.CompareTag("LeftRightWall") amp amp getTarget.transform.childCount 1) float translate getTarget.transform.position.x getTarget.transform.GetChild(0).gameObject.transform.position.x Debug.Log("value " translate) foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall")) Vector3 v3Scale frontWall.transform.localScale float scaleFactor translate frontWall.transform.localScale.x frontWall.transform.localScale new Vector3(translate , v3Scale.y , v3Scale.z) v3Pos.z getTarget.transform.position.z v3Pos.y getTarget.transform.position.y getTarget.transform.position v3Pos getTarget.transform.GetChild(0).gameObject.transform.position new Vector3( v3Pos.x, v3Pos.y, v3Pos.z) The LeftRightWall is the ones that I drag on the picture, with another vertical line as its child. The FrontWall is the horizontal line that is stretched when the LeftRightWall is dragged. Hope its clear enough. Thanks UPDATE This is the closest one from what I'm trying to achieve... (( Here's the code float translate getTarget.transform.position.x getTarget.transform.GetChild(0).gameObject.transform.position.x Debug.Log("value " translate) foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall")) Vector3 v3Scale frontWall.transform.localScale frontWall.transform.localScale new Vector3(translate v3Pos.x, v3Scale.y , v3Scale.z) UPDATE This is what I'm able to do so far, thanks to the answer below. However I still don't know why the other side of the panel is behaving like that. The scale of horizontal lines also shrinks when I click on the vertical line. This is the updated code ray mainCamera.ScreenPointToRay(Input.mousePosition) float dist plane.Raycast(ray, out dist) Vector3 v3Pos ray.GetPoint(dist) if(getTarget.CompareTag("LeftRightWall") amp amp getTarget.transform.childCount 1) float translate getTarget.transform.localPosition.x getTarget.transform.GetChild(0).gameObject.transform.position.x Debug.Log("value " getTarget.transform.GetChild(0).gameObject.transform.localPosition.x) foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall")) Vector3 v3Scale frontWall.transform.localScale float scaleFactor (translate v3Scale.x) frontWall.transform.localScale new Vector3(v3Scale.x scaleFactor, v3Scale.y, v3Scale.z) v3Pos.z getTarget.transform.localPosition.z v3Pos.y getTarget.transform.localPosition.y getTarget.transform.localPosition v3Pos getTarget.transform.GetChild(0).gameObject.transform.position new Vector3( v3Pos.x, v3Pos.y, v3Pos.z) |
0 | Project vertex on a line V,A and B are 3 points in 3D space and We have d0 (distance of V from (AB)line). I want to calculate question mark point in the image above! |
0 | Understanding pixel art in Unity 2d I am struggling to understand the basics behind pixel art in Unity. I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16. Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)? What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game? The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite. So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non square value, when my tiles are 16x16 |
0 | Unity Non Power of 2 Textures I have a texture that is 1024x900. Should I resize it in Photoshop to be 1024x1024 or leave it as it is? What about a texture sized 1000x900? |
0 | How to set a specific face's texture color in Unity? First off, let me describe my situation... So I'm building a voxel engine based on this tutorial. I'm using my own texture tilesheet. Most of the tiles have their own color except grass, leaves, and a few others. These specific ones are meant to be colored based on the temperature and humidity of the location. AlexStv (the author of the tutorial linked above) said the mesh colors array could be set, but I tried that and nothing happened. I probably did it wrong though, not sure. But he also said "you may need a shader that render vertex colors, not sure if the standard shader does that anymore" so that could also be the issue. So... Do I need a custom shader? If not how do set the face's colors? EDIT, Note I just tried a custom shader called UnityVC, it still didn't work so I guess I must be doing the color thing he suggested wrong. |
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 | Playing a video in AR using Vuforia and Unity 5 I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon. |
0 | Finding the "top" of a mesh representing the terrain I'm generating a low poly mesh for terrain, and for a given world coordinate I'd like to know where the "ground" is. My game uses fairly standard infinite terrain I generate noise values for world coordinates and use them to generate this mesh procedurally. This is done in chunks of 16x16. I'm planning to begin decorating the terrain with plants and such and I need a good way to determine how high the ground is. So for example, if I want a rock at x 5, z 5, what's the best most efficient way to figure out the "height" of the ground at that location? I've considered trying to inspect the mesh vertices, or maybe using a top down ray cast and picking the collision point, but I'm looking for advice before I begin. I've tried the raycast method, and it works perfectly, I'm just not sure how efficient that is. I'll profile if any alternatives seem worth comparing. |
0 | Is it possible to move a parent object independent of the child object I need to be able to move a Parent Object without moving the Child Objects. |
0 | Get a point inside an ellipse So I have a sprite of an ellipse ( it is a 2D game). I would like to get a point inside this ellipse so I can instantiate something. How would I do that? Sprite won t be changing the scale, so uniform scale. The point shouldn t be on the edge and a bit further away from the edge |
0 | Unity Android Button Select (Highlight) by touch, before clicking I have a multiplatform game with dozens of buttons in many menus. I used the animated buttons setup to have a normal state and highlight state. Highlight will most of the time resize the button with a nice anim AS WELL as make a dedicated text box appear with extra information. So far so good. Everything works perfectly on PC. However, as I am testing my build on android, I cannot find how to access the "highlight" state since touching the screen click and it execute the on click () associated. What I need is a way to select a button when it is first touched, since selected highlight (somewhat) then if it is touched (clicked) a second time while selected then to do the on click ( ) function. I have a few theory on how to do it, but it would require recreating every of my 80 or so buttons as well as changing everything from using the Unity GUI system to make my own C version which would take weeks. I am also trying a few other way to achieve the same thing. One of which is using the "button.select()" to select the button on its first click. That works. problem is I cannot seem to write a way to do "if (thisbutton.IsSelected true)" that just refuses to work. |
0 | AddForce results in stuttering movement I'm currently developing a simple breakout arkanoid mobile game. Now, I noticed that my ball movement is noticably stuttering. I've read various approaches about how to make the ball move and decided to go for AddForce so I don't have to do any physics calculations myself. The only thing im currently doing is using AddForce on my ball's rigidbody2D and have it collide with the walls and blocks. There's nothing done manually in Update or FixedUpdate and there are no other scripts running while the ball is moving. The scene is pretty empty actually. Things I have tried so far without success Disable V Synch Increase the velocity iterations (I tried values 15 500) Set the RigidBody2D's interpolation mode to Interpolate Extrapolate Using different mass values and force values in AddForce Checking, whether it's just an optical illusion (it seems to run more smoothly in editor and other breakout arkanoid games don't have that problem on my Galaxy S7) RigidBody settings of the ball Body Type Dynamic Material Friction 0 Bounciness 1 Mass 0.025 Linear Drag 0 Angular Drag 0 Gravity Scale 0 Collision Detection Continous Sleeping Mode Start Awake Interpolate Interpolate The walls and blocks are simple BoxCollider2D components. And I'm calling AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) on the ball's RigidBody2D. Edit public void OnPointerUp(PointerEventData eventData) if(! ballStarted) PaddleController.ShootStickingBalls() ballStarted true public void ShootStickingBalls() int stickyBallsAmount stickingBallsRigidBody2D.Count for (int i 0 i lt stickyBallsAmount i ) stickingBallsRigidBody2D i .AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) stickingBallsRigidBody2D i .transform.SetParent( nonStickyBallsTransform) Sticky false |
0 | How can I make the objects to move at the same speed as the lines? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) Vector3 endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, counter 500f speed) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) The lines are LineRenderer. void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.tag "FrameLine" myLine.name "FrameLine" myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () myLine.GetComponent lt EndHolder gt ().EndVector end LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace false lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, start) So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed. Now I want to move the instancesToMove (GameObject ) with the same speed as the lines but the instancesToMove are moving much slower then the lines. I tried instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed) Then instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed Time.deltaTime) But it's never moving with the same lines speed. |
0 | Selecting all GameObjects in Unity I want to rotate all my GameObjects by 90 degrees. To do that I need to select all my GameObjects, how can I do so? |
0 | I am getting different results when using 'Maximize on play '? so i'll be straight to point. when i move my character without using 'max on play' it works fine just as i wanted it to be. but when i switch to 'max on play' my character moves very fast. i am using addForce() to make me character move in Update(). after some googling i found that as i am working with physics i need to use FixedUpdate() But when i tried with fixed update i felt like it was not registering the keystrokes as it would in Update(). i would really appreciate if someone would help me out here. Edit Movement Script Added using UnityEngine public class PlayerController MonoBehaviour SerializeField float jump speed SerializeField float walk speed SerializeField float max speed Rigidbody2D rb int jump counter Animator animator void Start() rb GetComponent lt Rigidbody2D gt () animator GetComponent lt Animator gt () jump counter 0 animator.SetBool( quot isIdle quot , true) animator.SetBool( quot isWalkingLeft quot , false) animator.SetBool( quot isWalkingRight quot , false) void Update() if (Input.GetKeyDown(KeyCode.Space) amp amp jump counter lt 1) rb.AddForce(transform.up jump speed) jump counter else if (Input.GetKey(KeyCode.D)) rb.AddForce(transform.right walk speed) PlayWalkingRightAnimation() else if (Input.GetKey(KeyCode.A)) rb.AddForce( transform.right walk speed) PlayWalkingLeftAnimation() else if(jump counter lt 0) PlayIdleAnimation() void FixedUpdate() rb.velocity Vector2.ClampMagnitude(rb.velocity, max speed) private void OnCollisionEnter2D(Collision2D collision) jump counter 0 void PlayWalkingLeftAnimation() animator.SetBool( quot isWalkingLeft quot , true) animator.SetBool( quot isWalkingRight quot , false) animator.SetBool( quot isIdle quot , false) void PlayWalkingRightAnimation() animator.SetBool( quot isWalkingRight quot , true) animator.SetBool( quot isWalkingLeft quot , false) animator.SetBool( quot isIdle quot , false) void PlayIdleAnimation() animator.SetBool( quot isWalkingLeft quot , false) animator.SetBool( quot isWalkingRight quot , false) animator.SetBool( quot isIdle quot , true) I have added whole script hope this helps understand my problems. |
0 | Why does my first person camera attached to a rigid body vibrates? I'm trying to make a first person character with a rigid body. I need a rigid body because I want to add areas where the gravity comes from different directions so I also need to rotate the character accordingly. And as far as I know you cant rotate a character controller. So I wrote a script for movement and camera rotation. The problem I now face is that the camera vibrates. I recorded this video to show it. Why do I get this and how do I fix this? Movement code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovementRigidBody MonoBehaviour public float speed 10.0f public Rigidbody rb public LayerMask groundLayers public float jumpForce 7 public CapsuleCollider col float transelation float straffe Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked rb this.GetComponent lt Rigidbody gt () col GetComponent lt CapsuleCollider gt () Update is called once per frame void Update() transelation Input.GetAxis("Vertical") speed straffe Input.GetAxis("Horizontal") speed bool jumping Input.GetKeyDown(KeyCode.Space) transelation Time.smoothDeltaTime straffe Time.smoothDeltaTime if (IsGrounded()) rb.useGravity false else rb.useGravity true if (IsGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) rb.AddForce(Vector3.up jumpForce, ForceMode.Impulse) if (Input.GetKeyDown("escape")) Cursor.lockState CursorLockMode.None void FixedUpdate() transform.Translate(straffe, 0, transelation) private bool IsGrounded() return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius .9f, groundLayers) Mouse look code using System.Collections using System.Collections.Generic using UnityEngine public class MouseLookRigidBody MonoBehaviour public float mouseSensitivity 100f public Transform playerBody Rigidbody rig float xRotation 0f Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked rig this.transform.parent.gameObject.GetComponent lt Rigidbody gt () Update is called once per frame public void Update() float mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime float mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX) |
0 | I need my timer to go up every 30 seconds I wrote code for a jackpot to increase from one date to the next, and it works beautifully. The client wants the numbers to stay put for a while, and then increase. This is the code if (timerRunning1) timerValue1 Time.deltaTime 14.4 (timerValue1F timerValue1) (finish1 start).TotalSeconds Jack1.text timerValue1.ToString ("F2") PlayerPrefs.SetFloat ("Jackpot1", float.Parse(Jackpot1.text)) PlayerPrefs.SetFloat ("Jackpot1f", float.Parse(Jackpot1F.text)) if (timerValue1 gt (timerValue1F 0.1)) timerRunning1 false print ("ALTO") PagPrincipal.SetActive (false) Victoria.SetActive (true) Debug.Log ("FUNCIONA!!!") Invoke ("apagavictoria", 10f) I tried WaitForSeconds(30f), and it didn't work. How can I make my timer go up every 30 seconds? |
0 | Alternatives to Camera.main.ScreenToWorldPoint in Unity What are alternatives to Camera.main.ScreenToWorldPoint in Unity? So, here is my code (just the piece which is relevant for the question) void sendPointerMove(ref Vector3 mousePosition) lastMousePosition mousePosition Vector3 mousePositionInWorld Camera.main.ScreenToWorldPoint(Input.mousePosition) PointerData pointerData new PointerData( mousePositionInWorld mousePositionInWorld ) void FixedUpdate() Vector3 mousePosition Input.mousePosition if (needToSendPointerMove(mousePosition)) sendPointerMove(ref mousePosition) I am using JetBrains Rider to develop for Unity. And the ide suggests me the following about my sendPointerMove function invocation inside the FixedUpdate Expensive method invocation I am sure that the issue is due to the Camera.main.ScreenToWorldPoint because when I comment out the part the warning disappears. Thank you. |
0 | How can I spin a child capsule of a cube parent? I have a parent cube and to make it like a surface I had to change the rotation of the cube on the X to 90. and as a child, I added a capsule, and to make the capsule like standing I had to change the capsule X also to 90. The result is The reason I put the capsule child of the cube is that I want the capsule to move with the cube. The capsule rotation on the X is also 90 Then in a script at the top, I added speed and index variables for the rotation private int index 0 private int rotationIndex 0 In the Update RotateTo() And the method curvedLinePoints is a List private void RotateTo() var distance Vector3.Distance(capsule.position, curvedLinePoints rotationIndex .transform.position) if(distance lt 0.1f) rotationIndex Determine which direction to rotate towards Vector3 targetDirection curvedLinePoints rotationIndex .transform.position capsule.position The step size is equal to speed times frame time. float singleStep rotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards(capsule.forward, targetDirection, singleStep, 0.0f) Draw a ray pointing at our target in Debug.DrawRay(capsule.position, newDirection, Color.red) Calculate a rotation a step closer to the target and applies rotation to this object capsule.rotation Quaternion.LookRotation(newDirection) The problem is that because the capsule is a child when I rotate the capsule it looks like the capsule changes its shape and not spinning around itself. If I remove ut the capsule from the prefab and will rotate it on its own it will spin fine but when it's a child of the cube the result is I tried before running the game to play with the capsule rotation in the editor in the inspector changing the Y and Z values and the result is like in this screenshot. but I want to spin it around itself but because it's a child of the cube it's not spinning but looks like it's changing its shape. The workaround I found is to create an empty GameObject at 0,0,0 and put both Platform and Capsule as a child of it. Then I added this part to the script above private void LateUpdate() capsule.localPosition transform.localPosition new Vector3(0, 1.4f, 0) This way the Capsule is following the Platform. The empty GameObject is just to put them both together. and for testing I just did in the Update capsule.Rotate(0, 10, 0) and it's working fine. Now I have to figure out how to make this rotation with the code in the RotateTo method. |
0 | Unity Animation Tracking Background I've recently reached a bottle neck in my game's code that forced me to completely decouple the logic networking from the graphics. Thanks to the nature of my board game, I was able to build the following architecture Logic update loop gt wait for event gt process event gt dispatch graphic events Graphics update loop gt wait for event gt process event gt wait for animation Question From the previous design, tracking animation timing and knowing when they end is crucial, since that marks the end of the third phase in the graphics loop, allowing us to proceed to the next phase. I'm using Unity, and I am not sure how to go about this. I am using Unity's animation system as well as LeanTween to perform animations on the 2D NGUI level as well as the 3d game scene level. Proposed Solutions Solutions that have occurred to me so far are Callbacks Pass on a callback, and make the animation system trigger that callback when the animation finishes. This has proven to be high maintenance and redundant, as I have to manage passing data back and forth maintaining the overall animation state somehow (if multiple animations were triggered). Global Monitor Animations register under a global monitor, and I can emit a signal when the monitor becomes empty, triggering the end of the animations phase. I must make sure animations are registered immediately at the beginning of the animation phase, which I should be able to do. I should also maintain a list of animation IDs or a simple "anonymous" counter, which animations increment and decrement. Kinda like manual memory management. I might do this. Any of those seem viable? Am I overlooking details about this system? Any better alternatives come to mind? |
0 | How can I clean this if Statement up? I am busy working on a full solo project with no assistance from tutorials or guides. But I have created a monstrosity of an If statement. How could I clean this up and save on memory since I'm calling this in my Update() method and the game is for android? the hp1 to hp5 are images used as health bars on the hud, I need to deactivate the ones that are not in use when the hp value decreases. if(hp gt 81) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled true hp5.enabled true else if(hp gt 61) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled true hp5.enabled false else if(hp gt 41) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled false hp5.enabled false else if (hp gt 21) hp1.enabled true hp2.enabled true hp3.enabled false hp4.enabled false hp5.enabled false else if (hp gt 1) hp1.enabled true hp2.enabled false hp3.enabled false hp4.enabled false hp5.enabled false else if(hp lt 1) hp1.enabled false hp2.enabled false hp3.enabled false hp4.enabled false hp5.enabled false |
0 | Unity Make sprite visible only to shaders I have made a shader for my UI buttons, the sprites should be black and white, so they can be used as a mask when blending. They should allow for the image behind them to pass through the whiter pixels and be blocked by the darker ones. I want to use this effect for my menu, have a black background and a colored one (like a gradient or a pattern), let the colored one pass only through the buttons and the black one everywhere else. My shader does just that, but with one problem. I can't hide the colored background from the camera. If I change it's layer it is useless (I guess because it is the child of a canvas), and if I use a regular sprite (non UI) it is just ignored by the camera and the buttons don't pick up the color. How can I achieve this effect, having the sprite be invisible to the camera but visible to the shaders of the buttons. |
0 | How can I debug a GameObject's rotation? I have a model of a dragon, with an animation of it flying. When I play the animation in the Animator's preview, the dragon flies in a straight line, but when I run it in game, it flies around in circles about 10 units in diameter. If the turning isn't coming from the animator, it has to be coming from somewhere else, but I have no idea where. There aren't any scripts on the dragon that would influence it like that. Is there any way to discover what's causing my dragon to turn? (It's times like this that I really miss the ability to set a memory breakpoint on an object when working in .NET. That would make this trivial!) |
0 | Unet how to control child gameobject? I'm currently getting into the Unity networking system called unet. I have a child of the local player authority, the weapon. The weapon (PlasmaCannon left and right) have a script handling firing, because weapons can be replaced, and have different firing intervals, this seemed to me to be the easier way. However, they won't fire. Hierarchy (simplified) Weapon Code public void Start() Debug.Log("Weapon Spawned.") if (isLocalPlayer) Debug.Log("Weapon set as local player") public void Update() if (isLocalPlayer) if (firingTimer lt firingInterval) firingTimer Time.deltaTime if (firingTimer gt firingInterval) if (Input.GetButton("Fire1") amp amp firingMode FiringMode.Primary) CmdFire() if (Input.GetButton("Fire2") amp amp firingMode FiringMode.Secondary) CmdFire() Command public void CmdFire() Debug.Log("Firing Bullet.") I am getting the "Weapon Spawned." log message, but nothing inside isLocalPlayer conditions is happening even though I have added a networkidentity component and set Local Player Authority to true. Like I said, I'm still learning so I have no clue what's going wrong here. |
0 | How can I return the class as a Transform in the array instead of each property? public class TransformInfo public string sceneName public string name public Transform parent public Vector3 pos public Quaternion rot public Vector3 scale Then the method public static TransformInfo LoadTransformInfo() string jsonTransform File.ReadAllText( "d json json.txt") if (jsonTransform null) return null TransformInfo savedTransforms JsonHelper.FromJson lt TransformInfo gt (jsonTransform) return savedTransforms The return is But then when using it var test TransformSaver.LoadTransformInfo() Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info. So I can do for example Transform test1 test 0 Instead make a loop and assign each property from the Test to the new Transform test1. |
0 | Is it possible to prevent the collider 2D outline from hiding in Unity? Is it possible to prevent the collider 2D outline from hiding in Unity? I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation. In my case the collider outline is red I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow? |
0 | Do I lose any functionality using Visual Studio for Unity 3d? MonoDevelop has always had a strange tendency to stop functioning in basic ways ... autocompletion, copy paste clipboard, error detecting, and other silly things. I routinely fix this by running clean rebuild all, then restarting MonoDevelop. But this is time consuming. I've read that Monodevelop has issues... If I switch to Visual Studio will I lose anything at all that I rely on with Monodevelop's integration to unity? Or will I in fact gain? |
0 | Unity Custom EventManager, multiple arguments, and order I have some hard question for me... I have a nice EventManager, who handle multiple arguments. (no argument, one int, one bool, a GameObject and a bool... but for each sort, I have to create a special dictionnary for this... public class EventManager SingletonMono lt EventManager gt here I have many, many class who handle all sorte of different arguments... private class UnityEventInt UnityEvent lt int gt here definition of all dictionnnary for each class... private Dictionary lt GameData.Event, UnityEvent gt eventDictionary private Dictionary lt GameData.Event, UnityEventInt gt eventDictionaryInt private void Awake() Init() void Init() here initialise all dictionnary if (eventDictionary null) eventDictionary new Dictionary lt GameData.Event, UnityEvent gt () if (eventDictionaryInt null) eventDictionaryInt new Dictionary lt GameData.Event, UnityEventInt gt () ... One of the startListening public static void StartListening(GameData.Event eventName, UnityAction lt int gt listener) if (!Instance) return UnityEventInt thisEvent null if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent)) thisEvent.AddListener(listener) else thisEvent new UnityEventInt() thisEvent.AddListener(listener) Instance.eventDictionaryInt.Add(eventName, thisEvent) one of the stop public static void StopListening(GameData.Event eventName, UnityAction listener) if (EventManager.Instance null) au cas ou on a d ja supprim l'eventManager return UnityEvent thisEvent null si on veut unregister et que la cl existe dans le dico.. if (Instance.eventDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.RemoveListener(listener) and one of the trigger public static void TriggerEvent(GameData.Event eventName, int param1) if (EventManager.Instance null) au cas ou on a d ja supprim l'eventManager return UnityEventInt thisEvent null if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent)) thisEvent.Invoke(param1) And... when I want, in some script I do EventManager.StopListening(GameData.Event.PlayerAddScore, SomeFuncntion) EventManager.StartListening(GameData.Event.PlayerAddScore, SomeFuncntion) EventManager.TriggerEvent(GameData.Event.PlayerAddScore, 1) here SomeFunction take 1 argument, but if i wanted to have 2... i have to hard code the case in my EventManager So... My question is... how can I make that dynamic ? with only one Dictionary ? with only one list ? with good OOP or something ? And secondly, how can I handle order or the call ? Let's say 2 functions are listening for PlayerAddScore from 2 different script, how can I handle an order between the 2 function ? Thanks you for help. |
0 | Wrong contineous rotation to car In my 2d game, I want to rotate car face based on collision detected. But at present after 3 to 4 collision its doing continuous rotation only rather than moving straight after collision. Here is my straight movement related code myRigidbody.MovePosition (transform.position transform.up Time.deltaTime GameManager.Instance.VehicleFreeMovingSpeed) For better collision purpose, I have used Rigidbody position change approach. Here is my collision time code public void OnCollisionEnter2D (Collision2D other) if (other.gameObject.CompareTag (GameConstants.TAG BOUNDARY)) ContactPoint2D contact contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (transform.up, contact.normal) direction reflectedVelocity if (direction ! Vector3.zero amp amp pathGenerator.positionList.Count lt 0) float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg Quaternion targetRot Quaternion.AngleAxis (angle 90f, Vector3.forward) transform.rotation Quaternion.Slerp (transform.rotation, targetRot, 0.1f) if (Quaternion.Angle (transform.rotation, targetRot) lt 5f) transform.rotation targetRot direction Vector3.zero Rotation get applied within other code so that car was changing its face correctly and that method not affecting here that I have checked by placing debug statement. Share you side thought for this. |
0 | Implicit conversion error why is this code trying to convert a 'World' to an 'int'? using System.Collections using System.Collections.Generic using UnityEngine public class World Tile , tiles int width int height public World (int width 200, int height 200) this.width width this.height height tiles new Tile width, height for (int x 0 x lt width x ) for (int y 0 y lt height y ) tiles x, y new Tile this, x, y public Tile GetTileAt(int x, int y) if (x gt width x lt 0 y gt height y lt 0) Debug.LogError ("Tile (" x ", " y ") is out of range") return null return tiles x, y anyone see anything wrong with this code because on line 18 of my code i get this error "cannot implicitly convert type 'World' to 'int' and i don't know what is going wrong. |
0 | Rotate an object smoothly by using Accelerometer Input in Unity There is a simple script where the object orientation is equal to the mobile devices orientation. it works but the object doesn't rotate smoothly. void FixedUpdate() float accelx Input.acceleration.x float angle Mathf.Asin(accelx) Mathf.Rad2Deg transform.eulerAngles new Vector3(angle , 0, 0) How to rotate an object smoothly by using Accelerometer Input ? |
0 | How to make game scene bigger in 2d platformer? Hi i am current making a 2D platformer game but after i reach an end of screen then it doesn't move forward how to increase the game play screen area so that i will be able to go in vertical direction i am pasting an image of the problem i am new to unity please help me! 1 |
0 | How to destroy an object, and then instantiate it again later? I'm creating an enemy spawner in Unity (2D). At long last, I have something that is quite close to working, but the problem is that I want it to destroy all instances of the enemy when the player can no longer see the spawn area. That is, the player happens upon the spawn area to find several enemies, but if they move so that the camera can no longer see the spawn area, I want those enemies to be deleted and then a different set of the same enemies to be instantiated when the player (camera) happens upon the spawn area again. But when I attempt this initial delete, the script component no longer has an object to instantiate when the player returns. Here's a snippet of what I have if (!notOnScreen amp amp spawned false) int numberOfEnemies Random.Range(1, enemyMax) for (int i 1 i lt numberOfEnemies i ) spawnX Random.Range(minX 1, maxX 1) spawnY Random.Range(minY 1, maxY 1) Vector3 spawnpoint new Vector3 (spawnX, spawnY, 0) if (enemies.Length 1) typeOfEnemy 0 else if (enemies.Length gt 1) typeOfEnemy Random.Range(0, enemies.Length) else typeOfEnemy 1 Instantiate(enemies typeOfEnemy , spawnpoint, Quaternion.identity) spawned true if (notOnScreen) spawned false currentEnemies GameObject.FindGameObjectsWithTag("Enemy") for (int i 0 i lt currentEnemies.Length i ) Destroy(currentEnemies i ) I'm sure there's a way to preserve an instance of the enemy so that they can be instantiated again later, but I'm not sure how (sorry very new to this). I thought about cheating and having one enemy remain at a different z coordinate behind the map (as this is a 2D game), but that doesn't seem like an appropriate solution. Any thoughts or advice? |
0 | Texture atlasing in Unity I'm researching new ways to optimize games for better performance. Currently I am working on texture atlasing, which is giving me a hard time. I made the atlas using Texture2D.PackTextures and saved the offset and height and width values to a text file. Now when I insert the values to a material the texture is shown correctly, but since batching requires that the same material is used how I can I use the same material with different offsets? Picture All the cubes use the same texture. Only the two on the right batch as they use the same material. |
0 | Unlit Node Shadow Shader Graph How to make unlit node cast shadows? Is is possible with the current state of Shader Graph in LWRP? In this great article Toon Shader OP grabs pass from VertexLit shader. Is something similar achievable with Shader Graph? |
0 | Declaring Keycodes as strings How do I declare the keycodes as strings instead of selecting the keys from a list? Such that the user can input a key in inspector window and it will be read? public string StringKey quot a quot void Update () if (Input.GetKeyDown (KeyCode.StringKey)) |
0 | How to access random material in a renderer besides first without cloning any materials except accessed one? Clones only first material renderer.material Clones all materials in the same renderer renderer.materials 0 |
0 | Why does my material look blotchy on this mesh? This is a generative mesh wireframe looks like this Here's the material But the shaded object looks like a tie dye tshirt I've no idea what settings are causing it to look like this. These are the settings of the mesh renderer |
0 | How can I prevent my bullet from influencing other players when colliding with them? So when my bullet which is a Rigidbody is hitting another player which is also a Rigidbody, the bullet is getting destroyed immediately. But it seems that this isn't enough to prevent the physics to be applied. I guess that's why my player is getting pushed backward all the time when he is getting hit. I don't want this behaviour, so I tried to fix it I tried to lower the mass of the bullet which didn't help. I also tried to change the bullet behavior to a trigger, but the collision detection failed very often. |
0 | How does Unity's execution order work? I wonder how Unity's execution order really works. There's an ordered list at https docs.unity3d.com Manual ExecutionOrder.html, but how does this work when there are different gameobjects involved? Will Unity first run the specific function for all the monobehaviours in the scene before it proceeds to the next function? Or will each monobehaviour go through that specific order of functions before Unity goes to the next monobehaviour? Or is it more complex? It isn't really clear to me from the documentation. For example, normally Start() gets called before Update(), however when I was debugging, Update() on my Avatar prefab got called before Start() of my Camera child object. Is this supposed to happen? |
0 | How can I make the y extent height also to be random when instantiate new objects? With the script I instantiate random objects above the terrain. But the random was only on x and z. Now I want the height of the objects to be random as well. The terrain position is X 250, Y 0, Z 250. So I changed the line var y Extents.y To var y Random.Range( Extents.y, Extents.y) But now half of the objects above the terrain and half below the terrain, and I want them all to be above the terrain thus the random height should be above the terrain. My full code for reference using System using UnityEngine using Random UnityEngine.Random ExecuteInEditMode public class SphereBuilder MonoBehaviour for tracking properties change private Vector3 extents private int sphereCount private float sphereSize lt summary gt How far to place spheres randomly. lt summary gt public Vector3 Extents lt summary gt How many spheres wanted. lt summary gt public int SphereCount public float SphereSize private GameObject parent private void Start() parent GameObject.Find("Target Builder") private void OnValidate() prevent wrong values to be entered Extents new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z)) SphereCount Mathf.Max(0, SphereCount) SphereSize Mathf.Max(0.0f, SphereSize) private void Reset() Extents new Vector3(250.0f, 20.0f, 250.0f) SphereCount 100 SphereSize 20.0f private void Update() UpdateSpheres() private void UpdateSpheres() if (Extents extents amp amp SphereCount sphereCount amp amp Mathf.Approximately(SphereSize, sphereSize)) return cleanup var spheres GameObject.FindGameObjectsWithTag("Target") foreach (var t in spheres) if (Application.isEditor) DestroyImmediate(t) else Destroy(t) var withTag GameObject.FindWithTag("Terrain") if (withTag null) throw new InvalidOperationException("Terrain not found") for (var i 0 i lt SphereCount i ) var o GameObject.CreatePrimitive(PrimitiveType.Sphere) o.tag "Target" o.transform.localScale new Vector3(SphereSize, SphereSize, SphereSize) o.transform.parent parent.transform get random position var x Random.Range( Extents.x, Extents.x) var y Extents.y sphere altitude relative to terrain below var y Random.Range( Extents.y, Extents.y) var z Random.Range( Extents.z, Extents.z) now send a ray down terrain to adjust Y according terrain below var height 10000.0f should be higher than highest terrain altitude var origin new Vector3(x, height, z) var ray new Ray(origin, Vector3.down) RaycastHit hit var maxDistance 20000.0f var nameToLayer LayerMask.NameToLayer("Terrain") var layerMask 1 lt lt nameToLayer if (Physics.Raycast(ray, out hit, maxDistance, layerMask)) var distance hit.distance y height distance y adjust else Debug.LogWarning("Terrain not hit, using default height !") place ! o.transform.position new Vector3(x, y, z) extents Extents sphereCount SphereCount sphereSize SphereSize |
0 | Unity Ball moving inside the surface My ball is jumping on a 3d cylinder, and sometimes the ball gets stuck inside the cylinder. The ball has a rigid body and it's continuously dynamic. The circle also has a mesh collider. Here is the code to make the ball jump void Update () if(Mathf.Sign(rg.velocity.y) 1) isforceApplied true void OnCollisionEnter(Collision collisionInfo) if(isforceApplied true) isforceApplied false rg.AddForce(transform.up forceAmount,ForceMode.Impulse) |
0 | Reusing tilemap segments I'm wondering how I can incorporate reusable tilemap segments in my workflow. For example I construct a room out of my tile palette, and I want to reuse this room in multiple places. Is there some way to "prefab" a section of a tilemap? I haven't found such a thing. Or perhaps I should just prefab the whole tilemap, and use multiple tilemap objects within one grid? Won't that introduce significant overhead? What if I want to prefab a section of a tilemap with some additional, non tilemap objects? |
0 | Unity Free Inverse Depth Mask? How would it be possible to create an inverse depth mask? In this case, I refer to a depth mask as a shader attached to a mesh that 'pokes a hole' through the current camera layer to let you see the camera render layer one depth down, usually by using ColorMask 0. What I want is for, instead, the mesh to determine what ISN'T cut out, without everything that is NOT seen through the mesh being cut out. |
0 | How does Aspect Ratio and Resolution work in Unity? I am trying to make progress in Unity on understanding how aspect ratios and resolution work. I can't quite wrap my head around the topic. For example, I am trying to make a simple breakout style game, but in order to do that, I need to consider the world units and how each brick would fit into the scene. From what I have read, world units are dependent on screen resolution and aspect ratio. How would I be able to make something like this if mobile games are played on different devices (and ones with notches nonetheless). Also I'd like to know how to achieve this without using the tacky black bars that some games use. Any information regarding this would be extremely appreciated. |
0 | Fade a texture effect as it nears the end of a cylinder mesh In my game I have a laser beam that travels for about 15m, but abruptly stops due to the mesh the texture is attached to. How can I setup my shader graph so that the end of the texture fades away? I can't find anything similar to this anywhere online, and have tried multiple things (gradient colors with lerp attached to alpha) but just can't figure it out as I'm too new to the whole shader graph thing. Anything helps, thank you. Note The texture is 'animated' and scrolls along the path of the beam using the shader graph |
0 | Select Unity Prefab from enum choice After a couple tries, I still haven't found any solution to this problem of mine. Currently, I have a script inheriting from MonoBehavior which creates a map with Perlin Noise. Let's call it mapGenerator. It instantiates a HexTile object from another script, which does not inherit from MonoBehaviour, that contains a refere to my terrain prefab and an enum value which says its type (so water, grass, wood, etc.). There is an array declared at the beginning of the script that I manually change as I'm adding terrains. Everything works fine except when tweaking the map generation, If I want to change some values for perlin intervals, I might have to add another value to my HexTile and then drag my terrain prefab and set the enum value. What I want is to know if there is a way to make the script select a prefab depending on the value the enum was set to. Here is the code (simplified) public class ProceduralTerrainGenerator MonoBehaviour public bool regenerateMap true public Hextile hexTiles void Update() CreateMap() private void CreateMap() Some code for Perlin Noise generation inside perlinMap , for (int i 0 i lt mapLength i ) for (int j 0 j lt mapHeight j ) Setting up position from i and j index foreach (HexTile hexTile in hexTiles) if (ValueInRange(perlinMap i,j , hexTile.LowLimit, hexTile.HighLimit) Instantiate lt HexTile gt (hexTile.tile, position, Quaternion.Euler(0f, 0f, 0f), this.transform) and my other script System.Serializable public class HexTile public GameObject tile public HexMetrics.HexType hexType public float perlinNoiseLowLimit public float perlinNoiseHighLimit EDIT 1 I tried simplifing my problem, because I'm more interested in the concept, but here are more details. I have a class named HexSettings, which contains the hex prefab (HexTile) named tile, its HexType, and the perlin noise bundaries. System.Serializable public class HexSettings public HexTile tile public HexMetrics.HexType hexType public float perlinNoiseLowLimit public float perlinNoiseHighLimit Here is the HexType enum contained inside HexMetrics public class HexMetrics Hex metrics data for placement in grid data public enum HexType GRASS, FOREST, WATER, SNOW, DESERT, LAKE What I would like is to have some soprt of dictionnary that contains the correct prefab according to the selected HexType. As you can see in the image below, I can set my HexType to my terrain types, but I also have to set the HexTile object manually, where it could be set automatically according to the HexType value set. That is what I'm looking for. I tried adding it in a dictionnary (something like Dictionnary lt Hextype, HexTile gt ), looking for prefabs in my folder prefab with Resources.LoadAll lt HexTile gt ("prefab") , no success, prefabs couldn't be loaded in HexSettings. |
0 | Unity animator controller animations don't work I'm having problems animating a character pack I purchased from unity asset store. I've placed the character in an environment and created an animator controller. After I drag the animation that to the animator tab, there aren't any motions. Even if I place triggers or booleans in my script as parameters in the animator it doesn't work. It worked with other characters but the animations were somehow embedded in the 3d models. How is this supposed to work? |
0 | Move enemy left in sin wave motion over time I'm trying to create a top down shooting game where the enemy moves in sinusoidal motion over time. For the first 10 seconds the enemy needs to move only left and after that it needs to move left in sin wave motion. This is the code I'm using. public float enemySpeed float frequency 5.0f float magnitude 1.8f void FixedUpdate() if(Time.time lt 10.0f) transform.Translate((enemySpeed Vector2.left) Time.deltaTime) if(Time.time gt 10.0f) transform.Translate(enemySpeed 1.0f Time.deltaTime, 1.0f Mathf.Sin(Time.time frequency) magnitude Time.deltaTime, 0) What's happening is that for the first 10 seconds the enemy just moves left but after that all the enemies in the screen start moving in sin wave motion. What I want to achieve is that if the enemy has already spawned before the 10th second, it should move left without sin motion. Right now if the enemy is in the middle of the screen and the time is over 10 seconds, even this enemy starts moving in sin motion. |
0 | Moving my character camera makes environnement jerky I'm learning to make a Tilebased game with Unity and for that I use the Zelda alttp assets. I just have Tiles, a Camera and a moving Character with a rigidbody2D and a CircleCollider. When the Camera follows the Character, the scene feels Jerky. Info The Camera uses the 2D Pixel Perfect package. The Character is moving via Rigidbody2D.MovePosition() in the FixedUpdate Method code void Update() float yInput float xInput region yMovement if (Input.GetKey(keyMoveTop)) if (Input.GetKey(keyMoveBot)) yInput 0f else yInput 1f else if (Input.GetKey(keyMoveBot)) yInput 1f else yInput 0f endregion region xMovement if (Input.GetKey(keyMoveLeft)) if (Input.GetKey(keyMoveRight)) xInput 0f else xInput 1f else if (Input.GetKey(keyMoveRight)) xInput 1f else xInput 0f endregion Walking isWalking Input.GetKey(keyMoveWalk) moveDirection Vector2.ClampMagnitude(transform.right xInput transform.up yInput, 1f) private void FixedUpdate() rb.MovePosition( rb.position moveDirection (isWalking ? walkSpeed runSpeed) Time.fixedDeltaTime) You can see the problem here https youtu.be MA2zZPME5X4 Edit Added all my movement code |
0 | Rect transform stretch of a child object is set to 0 after instantiation I have the following hierarchy of my prefab PopupParent Popup ScreenDim They all have Rect Transform set to Stretch. Anchor mins are set to 0 and Anchor maxes to 1. Left, top, right and bottom are set to 0. When I pull this prefab to a Canvas manually, all works as expected. When I instantiate the prefab the problem I am encountering is, that the PopupParent is stretched as expected, to the full screen, but all its children are not. PopupParent looks like this Children Popup and ScreenDim look like this The instantiation I am doing using the Spawn Prefab Node in the Event editor provided by the ORK Framework. I am Mounting the PopupParent to my UICanvas. It could be, that the issue is caused by some Framework settings, but it might very well be related to how Unity works in general. I am not sure and can't find a way to figure it out. SOLUTION I got ORK support to reply and solve the issue for me http forum.orkframework.com discussion 6465 spawning a prefab with a stretch property latest TL DR Regular mounting and UI mounting works slightly different. |
0 | "ArgumentNullException Value cannot be null" for AudioSource.PlayOneShot I am working on a game and I am trying to add a sound effect. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody playerbody private Animator playerAnim private bool grounded public bool gameover public float jumpforce public float gravmod public ParticleSystem explosion public ParticleSystem dirt public AudioClip jumpSound public AudioClip crashSound private AudioSource playerAudio Start is called before the first frame update void Start() playerbody GetComponent lt Rigidbody gt () playerAnim GetComponent lt Animator gt () playerAudio GetComponent lt AudioSource gt () Physics.gravity gravmod Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.Space) amp amp grounded amp amp gameover false) playerAudio.PlayOneShot(jumpSound, 1.0f) playerbody.AddForce(Vector3.up jumpforce, ForceMode.Impulse) playerAnim.SetTrigger( quot Jump trig quot ) grounded false dirt.Stop() private void OnCollisionEnter(Collision collision) if (collision.gameObject.CompareTag( quot Ground quot )) grounded true dirt.Play() if (collision.gameObject.CompareTag( quot Obstacle quot )) playerAudio.PlayOneShot(crashSound, 1.0f) gameover true playerAnim.SetBool( quot Death b quot , true) playerAnim.SetInteger( quot DeathType int quot , 1) explosion.Play() dirt.Stop() At playerAudio.PlayOneShot, it just won't play and the rest of that part of the code stops working. It returns ArgumentNullException Value cannot be null even though jumpSound and crashSound are both clearly defined. What is wrong? |
0 | Mask not applying to gameobjects in UI layer I have a bunch of item slots in my scroll view. The item slots contain 3d objects, but they are all set to use the UI layer. My problem is that they are not being masked the same as the 2D elements are. See this example Notice how the 3D items in the scroll view are overflowing, but the 3D item slot panels are not. Like I said, I put everything in the UI layer. I'm not sure how to fix this. Is there a simple fix for this? |
0 | Unity How to make grass details look good from top down I have an issue with the terrain details. Since it only draws a single plane per texture, it looks quite crappy with a angled top down camera, for example for an RTS camera. Is there some way around this, I know one solution people use is to angle the grass towards the camera a bit, but that isnt possible with the terrain details painter. The issue is circled in red If there is no solution to this, are there some techniques I can use to make some interesting looking grass for an RTS camera? |
0 | Instantiate creates a clone in wrong position I have this prefab with this transform And then using this code to create a clone (the prefab is assigned to a public property of a script, which I assign using the editor, which is the e.Weapon) Instantiate(e.Weapon, new Vector3(0f, 0f, 0f), Quaternion.identity, rightHand.transform) I am parenting it to my character's right hand. But whenever the clone gets created, it has different position than the one I have in my code. It appears like this Any idea why this is happening? |
0 | just download first assetbundle In the Start of my scenes I call the method that downloads the assetBundles for that scene. The problem is that it only downloads the first assetBundle from the list, the second does not download it. My code is Note The Debug that shows the url shows the correct url both times, first http mihost.com assetbundles asset1 and then http mihost.com assetbundles asset2. However, in the Debug that shows the assets 'added' in both cases it shows the name only of those in asset1 public virtual IEnumerator LoadBundleFromServer() var AssetPathOnServer "http mihost.com assetbundles " var assetBundleNames new List lt string gt () assetBundleNames.Add("asset1") assetBundleNames.Add("asset2") for (int i 0 i lt assetBundleNames.Count i ) var currentAssetBundleName assetBundleNames i var url AssetPathOnServer currentAssetBundleName Debug.Log("url " url) var request UnityWebRequestAssetBundle.GetAssetBundle(url) yield return request.SendWebRequest() if (!request.isHttpError amp amp !request.isNetworkError) var asseBundle DownloadHandlerAssetBundle.GetContent(request,) Debug.Log("count assets " AssetNames.Count) for (int j 0 j lt AssetNames.Count j ) string assetName AssetNames j AssetBundleRequest asset asseBundle.LoadAssetAsync lt AudioClip gt (assetName) yield return asset AudioClip myClip asset.asset as AudioClip if (!assetDictionary.ContainsKey(assetName)) assetDictionary.Add(assetName, myClip) Debug.Log("added " assetName) asseBundle.Unload(false) else TODO aqui hay que mostrar un error Debug.LogErrorFormat("error request 0 , 1 ", url, request.error) public abstract List lt string gt AssetNames get |
0 | Why Unity3d takes so long time to "rebuild" when I change build platform? I would like to know what happens "behind the scenes" when I change my unity game target platform . If I switch from Android to iOS or Pc or etc, Unity rebuild something and takes a lot of hours to complete. What is the reason ? Thanks |
0 | How to move 3D Object With Touch Dragging Finger By the screen In android Unity Game My Code is As Followed using System.Collections using System.Collections.Generic using UnityEngine public class Sphere MonoBehaviour SerializeField private Touch touch private float speedModifier Start is called before the first frame update void Start() speedModifier 0.01f Update is called once per frame void Update() if (Input.touchCount gt 0) touch Input.GetTouch(0) if (touch.phase TouchPhase.Moved) transform.position new Vector3( transform.position.x touch.deltaPosition.x speedModifier, transform.position.y, transform.position.z touch.deltaPosition.y speedModifier) I tried with this code but object is not even responding |
0 | Testing Live Ads Before Publishing Admob I am testing ads with the test device method and test ads are showing perfectly but when I try to load live ads they won't load. I have implemented the OnAdFailedToLoad which tells me that ads are not loading, this only happens when I try to load live ad but in the test ad everything works fine. Does this happens all the time? we can't see live ads without publishing the game first? or there are no ads available at the moment if so when do the get available or they even get available for new users. How can I make sure that I will get live ads after publishing the on Google Play Store. I don't know I am just confuse about this thing, I am using Unity 3D and building for Android. I have searched on internet but everybody says that ads might not available at the moment I am just curious why are ads not available its been two days and I haven't seen any ad when are the ads going to be available. Thanks for reading this. |
0 | What does 'vertex splitting' mean? In the documentation of MeshUtility.SetPerTriangleUV2 it is said the following Will insert per triangle uv2 in mesh and handle vertex splitting etc. What do they mean by 'vertex splitting' ? |
0 | Detect Collisions While Dragging 3D Game Object Hello i am making a game in which i have to drag a sphere on x axis and z axis on a plane with my mouse and i have created walls from cubes so that my sphere not go anywhere else in the game but while dragging my sphere is not detecting collisions with the wall i also added rigidbody but nothing is working ths is my code thanks using UnityEngine using System.Collections public class Ball MonoBehaviour Rigidbody r private void Start() r GetComponent lt Rigidbody gt () void OnMouseDrag() float distance to screen Camera.main.WorldToScreenPoint(gameObject.transform.position).z Vector3 pos move Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance to screen)) transform.position new Vector3(pos move.x, transform.position.y, pos move.z) |
0 | Unity runs custom AssetPostProcessor every time on save I've written a AssetPostProcessor script that make some changes to prefabs and materials on import in some specific folders. I'm using this method to do that private static void OnPostprocessAllAssets(string importedAssets, string deletedAssets, string movedAssets, string movedFromPath) if the importedAsset is a prefab GameObject obj (GameObject)AssetDatabase.LoadAssetAtPath(objName, typeof(GameObject)) if (obj) if (AssetDatabase.GetAssetPath(obj).Contains("Assets Tiled2Unity Prefabs")) Here's some code that changes the asset For some reason, every time I save this AssetPostProcessor is run which is something I don't want because this is lost time for something that isn't needed. What can I do to stop this? |
0 | Dynamic model scaling Imagine a (3D) game like Railroad Tycoon 3. Player selects a rail track, clicks LMB and drags the mouse to the end position. During this drag, the rail track model scales and adopts to the landscape, so user sees the resulting track in dynamic. The question how this can be done? A brief idea links sketches will be enough. I just don't know how to start (I'm novice game developer). If it is matter, I use Unity as a game engine. Thanks in advance. |
0 | Create an atlas texture in photoshop to use in unity To create a button in NGUI looks like we need to create something called Atlas that is a material that contains a lot of little images called Sprites. I created a set of 40 sprites (for 20 buttons needed in game, normal state and clicked state) in photoshop in a 2048x2048 image file. When i tried to use NGUI atlas maker i realized that atlas maker requires each sprite in a separate file and wants to merge them in the atlas itself! Well, i already have them in one file, should i slice all these buttons and save them in 40 other separate files and let the atlas maker merge them again for me? (Sounds very stupid!) Isn't there any way to give the merged 2048x2048 file to atlas maker (or any other equivalent plugin software) and then tell the software "Hey! I have 40 sprites in this image, let me tell you where they are! The first one is in (3,3) with size of (150px, 150px), The second one is..."? UPDATE I found a part of solution, unity could identify my 40 sprites in texture using sprite editor tool, but NGUI cannot still find them. I created a material using "Unlit Transparent Colored" shader and referencing the atlas to it, then i created a new empty game object, added UI Atlas component to it and referenced the material in it, but it says there are no sprites. If i make a prefab out of this game object then NGUI can use it as an atlas and my problem will be solved |
0 | How do I run a headless Unity server in a Windows Docker (without GPU)? I am trying to run a headless Unity server on a Windows Docker. On Linux, there is Xvfb, but I don't know how I could get similar results on Windows. How would I do that? |
0 | Coroutine wrong Behavior when scene is loaded. Ok so I have this coroutine IEnumerator ShowCharTraits() while(!hasPlayerChosen) yield return null traitPanel.SetActive(true) hasPlayerChosen false traitPanel.SetActive(false) Debug.Log("Got called! job done") It's being called like this from the awake method in my GameManager players GameObject.FindGameObjectsWithTag("Player") foreach (GameObject g in players) ui Controller.StartShowCharTraits() g.GetComponent lt PlayerToken gt ().isTurn false StartShowCharTraits() is a simple method that does this public void StartShowCharTraits() StartCoroutine("ShowCharTraits") Now, I have checked the tags, no null reference exception, actually no errors or warnings are being thrown. If i load the scene in the editor and then play it everything works fine. traitPanel.SetActive(true) get called and my panel shows up. However when I load my scene from another scene using SceneManager.LoadScene(1) the above mentioned line is never reached. Any ideas why this is happening ? |
0 | In Unity, how do I make text annotations appear when I mouse over GameObjects in playmode? How do I make text appear when I mouse over GameObjects in game? What is the Unity jargon for this? I'm assuming it's 'annotations'. |
0 | How to get error line when debugging APK from Logcat I made android game by Unity and built APK. When I got error from this game, I can see the error message 07 06 00 35 38.905 I Unity(31609) (Filename . Runtime Export Debug.bindings.h Line 43) 07 06 00 35 38.906 E Unity(31609) NullReferenceException Object reference not set to an instance of an object 07 06 00 35 38.906 E Unity(31609) at GameManager.OnRealTimeMessageReceived (Boolean isReliable, System.String senderId, System.Byte data) 0x00000 in lt filename unknown gt 0 07 06 00 35 38.906 E Unity(31609) at GooglePlayGames.Native.NativeRealtimeMultiplayerClient OnGameThreadForwardingListener lt RealTimeMessageReceived gt c AnonStorey4. lt gt m 0 () 0x00000 in lt filename unknown gt 0 07 06 00 35 38.906 E Unity(31609) at GooglePlayGames.OurUtils.PlayGamesHelperObject.Update () 0x00000 in lt filename unknown gt 0 07 06 00 35 38.906 E Unity(31609) 07 06 00 35 38.906 E Unity(31609) (Filename Line 1) However file name and error line is wrong, so I can't check where exactly error came from. I checked my logic almost 2 hours also the object references too, but there is no logic to access undefined object code. It could be, but I can't see where it is. I must run this app because it uses Google Play Games Service, so it requires completed built APK without developlemt option checked. Using Application.RegisterLogCallback not much help, it has exactly same result. How do I get exact error line in this case? |
0 | Assigning a colour to imorted obj. files that are being used as default material I am having a problem with assigning a colour to the different meshes that I have on one object. The technique that I have used is the first approach on this site. Is it possible to export a simulation (animation) from Blender to Unity? So what I would like to do is the following. I have about 107 meshes that are different frames from my shape key animation of my blender model. What I would like to have is that the first mesh will be bright green and up to the 40th mesh the colour turns to be white greyish... the best would be if I could assign every mesh by hand a colour, however they are all default materials. And if I assign the object a colour, the whole "animation" is going to be in that colour |
0 | Detect clusters of tokens on an x y grid Ok, so I have a two dimensional grid working on integer x and y coordinates. Each of this coordinates can have one and only one token on it. The tokens have the capability of check and return an adjacent token given a direction in which to search (they'll return null in case nothing is there) I now need an algorithm to check the grid for clusters of 3 or more adjacent tokens and add each cluster to a dedicated variable (meaning than, instead of just stopping after return one cluster, it needs to check for all clusters on the board) I've been thinking for a while but came out with nothing, any help? |
0 | Concept design pattern for industry simulation required I am making a mobile game simulating industry. A brief high level description is below. A hub could be thought of as a base city, within which there are rooms buildings which determine what is produced and consumed. Rooms buildings need people to work them. People have their own produced and consumed resources that need to come from rooms buildings. The buildings like machines in a production line have paths of commodity flow defined. How to implement people with their own needs like thirst, sleep and illness while coordinating the buildings is causing me trouble. I know many games have this same premise but can t turn up enough info on their workings to help me. The real challenge is that I do not want to run the game where time passes relatively slowly and each person can move around and make decisions constantly. I want to be able to change the speed of the game, likely from running a day every 30 seconds to a month every two minutes. So was focusing more on when changes to the system were occurring. The number of hubs is likely to reach 80 each with 20 rooms and say 30 people to give an idea of scale. Do you have any example games or coding approaches that could help light my way? Each concept I think through falls over. Your help is very much appreciated and thanks for reading! If I have not included enough details please let me know, it is my first post so unsure how far to go into it. |
0 | How to detect RayHit on part of model and not entire model I'm building a low poly role playing Hack and Slash game. When I click it renders a sprite amp character moves to that location(with RayCast). But in this case. I don't want the click to occur on side of the bridge. Clicks should only occur in green coloured part amp not in the red part. How should I fix this problem? |
0 | Models keep turning white Unity 5.3.5p1 I'm using Unit 5.3.5p1 but for some reason my models randomly turn white after I build an exe to run outside the editor. The textures work perfectly fine within the editor, but as soon as I build and run outside they sometimes show with appropriate colour, but many times do not and end up blank white. Does anyone know what might be causing this in general? I've downloaded the latest unity shaders and replaced all current shaders. Currently I'm using the Standard shader only, and it is 100 unmodified. |
0 | How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction? Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead. It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre existing momentum will carry it wildly off course, and not straight toward PointB. It could turn exactly 180 around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions. It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course correcting so that it is now moving toward PointB. I'm trying to figure out how to calculate that quot specific direction quot that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed. Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc. Can anyone help me out? |
0 | Top Down Octree Generation of Procedural Terrain I'm trying to implement a voxel based terrain generation system in Unity3d (C ). I have successfully implemented a uniform 3d grid system, and have extracted the isosurface out using Marching Cubes and Surface Nets algorithms. I quickly bumped up against the inherent issues in representing all space with a 3d grid. Much of this space was either above or below the surface, and I turned to space partitioning with octrees, as it didn't seem too difficult. One of the great things about octrees is that octree nodes that that don't have edges intersected by the surface don't need to be split again. I researched, and found a couple resources to construct my code. One is Volume GFX, and another is the original Dual Contouring paper by Ju et al. My edge checking is done by the Marching Cube's checking from Paul Bourke's code. If the "cubeindex" is either 0 or 255, then no edge is intersected, and the octree node does not need to be split. My Octree generation code works for something like a quarter sphere, where the surface features are extremely normal As seen in the picture, only octree nodes containing the surface are subdivided. Working great. Now, however, when we move to something more complex, like Unity3d's PerlinNoise function GASP! What's that hole doing in the mesh at the lower right corner? Upon closer inspection, we see the octree didn't subdivide properly (red lines highlighting the offending node's dimensions) This turns out to be the same issue Jules Bloomenthal highlights in her paper on polygonization, page 10, Figure 10. Traditional methods at generating top down octrees ("Adaptive Subdivision"), are sensitive to fine surface features relative to the size of the octree node. The gist X X lt Node X X X's tested values, all outside of the surface! lt surface The surface breaks the surface, but comes back down before it goes over a vertex. Because we calculate edge intersections by looking at the signs at the two vertices, this does not flag the edge as crossed. Is there any method to determine if these anomalies exist? Preferably, the solution would work for more than just the Unity3d noise function, but for any 3d noise function (for cliffs overhangs floating islands, etc). UPDATE Thanks to Jason's awesome answer, I was able to answer my own questions I asked (in the comments under his answer). The issue I had was that I didn't understand how I could create a bounding function for trigonometric functions (sine,cosine,etc) due to their periodic nature. For these guys, the periodicity is the key to bounds functions. We know that sin cos reach their extrema values at a set interval, specifically every 2. So, if the interval we are checking contains any multiple (cos) or half multiple (sin) than 1 1 is the certain extrema. If it doesnt contain a multiple (i.e. the interval 0.1,0.2 ), then the range is simply the values of the function evaluated at its endpoints. UPDATE 2 If the above doesn't make sense, check Jason's answer to my comments. |
0 | Change alpha value of the Standard Shader I want to edit the Standard shader provided by Unity in order to change the alpha value of a fragment (pixel) according to given parameters I pass to the shader. For now, thanks to this link, I have been able to Retrieve the standard shader, Retrieve a custom Core.cginc I included in the DEFERRED pass of the custom shader, Create a custom Editor script to handle the Shader and my custom parameters, Selecte Fade as the rendering mode of the shader to handle transparency, using the custom editor script, Create a custom file replacing UnityStandardInput.cginc and changed the references in the Core.cginc file. But now, I can't seem to figure where to change the alpha value of the fragment. I've tried a ton of possibilities in the Core.cginc file. Changing the color and the map of the Albedo works, but I can't find where the final alpha value is set. I've browsed the files in the CGIncludes folder in the builtin shaders of Unity. UnityStandardCore.cginc Already tried many possibilities (including the returned value of Alpha declared in UnityStandardInput.cginc CustomInput.cginc Alpha function, no effect Since the files are huge, I don't feel it will be useful to copy paste them here. Thanks for your help in advance. |
0 | Colliders stop working when they move I'm trying to make a game where you play basketball as a catapult. Obviously an idea like this leans heavily on the unity physics engine. The cup of the catapult has a bucket on it to keep the ball from falling out. When you hit space, the arm of the catapult spins, which should throw the ball out of the bucket of the catapult. Instead, the ball passes through the cup of the catapult(when it isn't spinning, it acts normally and rolls around the bucket) and then it doesn't fall whatsoever, eve though has gravity is enabled. Here are my physics settings The ball The cup(and also a cup with flipped normals) The Rim of the bucket Here's my ball throwing code public class BallThrower MonoBehaviour private Vector3 axis Start is called before the first frame update void Start() axis transform.position Update is called once per frame void Update() if (Input.GetKey(KeyCode.Space)) if (transform.rotation.z gt 95.4) transform.Rotate(0f, 0f, 5f, Space.Self) What's missing here? Should I make the cup a rigidbody? Let me know if you need more info, Thanks! |
0 | Creating a list of buttons dynamically in code I have a list of contacts. I need to create a scrollable list of buttons that are created dynamically so I can add each contact name as the button text. How would I do this all in code? My biggest concern is making sure the sizes stay consistent. I haven't had to do that in code before. EDIT And here is the code to add the buttons to this for (int i 0 i lt count i ) if (i gt 0) crt.sizeDelta new Vector2(crt.sizeDelta.x, crt.sizeDelta.y initHeight) GameObject contactButton Instantiate(Resources.Load("Contact Button")) as GameObject contactButton.transform.parent contactsList.transform contactButton.GetComponentInChildren lt Text gt ().text names i |
0 | No shadow on custom model I have custom low poly model ,the thing is it is not receiving shadows. Unity's default plane do receive the shadow but not my low poly plane. Here is image that demonstrate more, |
0 | Filling of a multidimensional array with string I'm trying to fill a dropdown with a lis,t if some input is correct. now when trying to create the list from a text file (to save the program) i should split the line on a comma so i have 3 settings for one asset For ex asset1,colour,used,broken. the list should show the asset if the item is broken (0 is not broken, 1 is broken). public string ,,, UsedAssetList string lines System.IO.File.ReadAllLines( "" Application.persistentDataPath " assetlist.txt") cmbAssetNumber.ClearOptions() for (int i 0 i lt lines.GetLength(0) i ) UsedAssetList lines i .Split(',') if (UsedAssetList i,0,0,1 "1") list new Dropdown.OptionData(UsedAssetList i,0,0,0 ) cmbAssetNumber.GetComponent lt Dropdown gt ().options.Add(list) The lines i .Split(',')gives me the error Error CS0029 Cannot implicitly convert type 'string ' to 'string , , , ' I think everything is on point, except the filling of my list. any idea on how i can get this right? EDIT I was thinking the list should look like this "asset1","Gold","1","0" , "asset2","Green","0","1" , ... EDIT While the text file looks like asset1,Gold,1,0 asset2,Green,0,1 ... |
0 | Smooth Lighting Falloff So, I'm having some issues with lighting in my Unity game. I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow". The reflected and refracted light ends up having two issues the light abruptly ends at the edge of floor tiles, and depending on the position, the light sometimes goes from it's blue color to a reddish color. I have a short (11 second) video here http www.labyrintheer.com wp content uploads 2016 11 Nov 17 2016 21 07 57.mp4 so that you can see what I'm talking about. I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue. Still images for anyone hesitant to click the video link Hard falloff Reddish color Using a single point light inside the cube, instead You can see it on the wall in the upper right and the floor at the top a bit. The upload seems to have lowered the quality a bit, but you can still see it. The single light makes it a little bit better, but there's still complete falloff. |
0 | What are the steps to instantiate a button in Unity? Given a Canvas test canvas containing a Button test button and an empty GameObject that manages instantiation and scripts and the like called test manager, what are the steps to instantiate this button through code as opposed to having it already there? I've tried making the button a prefab and instantiating it as I would any other object but that didn't work. I tried making the canvas a prefab and then trying the button but nothing. I've searched around for quite some time and there's mention of RectTransform and SetParent but steps or specific details would clear up my confusion |
0 | Raycast Masks not working Unity3D I'm having a problem with filters masks when raycasting. I've created a LayerMask and then in the inspector selected the layer I want to ignore when Raycasting. however then I print out the name of the object hit by the raycast I am still getting hits on objects on the layer masked out, as well as on other layers. public LayerMask rayMask RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast (ray, out hit,rayMask)) Debug.Log (hit.collider.name) I have paused the Game and checked that the object I'm getting a hit on is indeed on the layer in the mask. |
0 | How To Rotate A Vector around A Pivot Point In Unity, I'm trying to figure out how to rotate an object around a pivot point. I found a snippet of code over on the regular stack overflow, but it wasn't working even close to correctly. I have edited it a bit and now its starting to work a little better, but its still pretty off from what I need. It rotates around the object, but about half way through it jumps to another position. The one half actually rotates with the pivot point, albeit a little bit offset from where it should be, and if you keep rotating it the offset becomes greater and greater. Then the other half is just completely off, still not as bad as the original code though. Sorry I'm having trouble explaining, here is a GIF to make it easier. public Vector3 RotTesta(Vector3 point, Vector3 pivot, Quaternion pointRotation, Quaternion pivotRotation) To rotate an object around an arbitrary point, translate first (the arbitrary offset) then rotate as opposed to rotate scale translate Vector3 offset point pivot Vector3 rotationOffset pivotRotation.eulerAngles pointRotation.eulerAngles offset Quaternion.Euler(rotationOffset) offset return offset pivot calculate rotated point This just handles its position, after you call this you would just do transform.rotation pivotRotation. If someone could please help me out with this I would be very grateful. |
0 | How to Change position rotation of a parent while keeping X and Z Rotation Sooo this question is a problem , a evolution by another solution of this problem here How can I change the parents rotation so the childs rotation is looking at a specific direction Basically We have a "Eye" (HTC Vive). We have a "Parent" which is the Parent of "Eye". We can not change the position or rotation of the Eye in code. We can only change the position and rotation of the Parent. 1.We want to modify the Parent Position so that Eye to goes to a certain "Target 1" position. 2.We want to modify the Parent Y Rotation so that the Eye looks at a certain "Target 2" position. 3.While doing this we dont want to modify the Parent X or Z , because this would lead to a Rotated game experience. The Parent Position changes so the Eye gets to "Target 1" position. The Parent Position changes so Y Rotation should look at Target 2 position The Parent X Z Rotation should not modify the Eye X Z |
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" Zoom out to correctly "frame" all my points (i don't know how to calculate ) Use Unity LookAt(myAvaragePoint) I think i've to use some trigonometryc function to calculate the Y Camera position (to zoom in, zoom out), but i don't know which! Thanks |
0 | Discrete line inside a 3D matrix First of all a little premise I'm following this tutorial on YouTube for procedural 2d cave generation in unity using cellular automata and I'm extending it in order to make caves in all three dimensions. With this approach, caves are based on a 3d matrix where if a cell value is 1 it is a wall and if 0 it is an empty space. The "rooms" created, after being logically connected, need to be "physically" connected by making a path of zeros in the 3d matrix and the tutorial explains how to do this in 2d. Can you, please, suggest me the approach on how to draw a discrete line (of zeros in this case), in a 3d matrix, that goes from point A to point B? I'll attach a screen of a map example where rooms are drawn with cubes and red lines are the logical connections. |
0 | Unity Rigidbody2d jittering movement in the y axis As said, rigidbody moves fine, even smoothly in the x axis. Problem comes in on the y axis. Whenever the character goes up or down, it noticeably shakes. Additional Info Unity 5.6 Using linear interpolation Mass is 5 Linear Drag is 20 Gravity is 0 Angular Drag is 0 Locked rotation on the z axis Dynamic Rigidbody No parent Object, not even a child using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour Rigidbody2D rbody Animator anim public float speed 0 SpriteRenderer sr Vector2 movementVector void Start () rbody GetComponent lt Rigidbody2D gt () anim GetComponent lt Animator gt () sr GetComponent lt SpriteRenderer gt () void Update() sr.sortingOrder ((int)Camera.main.WorldToScreenPoint (sr.bounds.min).y) 1 movementVector new Vector2 ((Input.GetAxisRaw("Horizontal")) 3, Input.GetAxisRaw("Vertical")) if (movementVector ! Vector2.zero) anim.SetBool ("isWalking", true) anim.SetFloat ("inputX", movementVector.x) anim.SetFloat ("inputY", movementVector.y) else anim.SetBool ("isWalking", false) void FixedUpdate() rbody.AddForce (movementVector speed) I also noticed that changing the mass and linear drag affected the movement speed on the y axis but not on the x axis, and movement on the y axis is noticeably faster than on the x axis, which is why I multiplied the horizontal input by 3. |
0 | Random Sobol 3D Cell in Unity There is a blueprint in UE4 for making Sobol random 3D cell. It places random objects inside cell structure. How to make this in Unity? For example, if I make a sphere prefab I would need to generate Sobol distribution in some volume. EDIT Seyed Morteza Kamali have made a script |
0 | Overriding CoRoutine doesn't execute base code I want to have a CoRoutine declared as virtual in parent class and then overridden in child classes. protected override IEnumerator f(Vector3 to) ... yield return base.f(to) ... What happens (or doesn't happen) is that the base code doesn't get executed. Debuggin it I step into the base.f(to) and the cursor just stand on function name. If I press step next control returns to the child. I really have no clue how to handle this situation. Any clue? |
0 | Starting Couroutine in newly activated gameObject I'm working on a UI system that animates an element's properties using coroutines. Every element that should be animated has a component called AnimatedUIElement which provides the function Enter(). The function Enter() is basically starting coroutines depending on the chosen animation settings, but only after calling Enable(), which sets the gameObject active with gameObject.SetActive(true) , updates its component references and makes the element interactable. AnimatedUIElement also defines an Exit() function acting similar, but disabling the element after the animation. public class AnimatedUIElement MonoBehaviour private CanvasGroup canvasGroup ... public void Enter() ... TriggerEntry() private void TriggerEntry() PlayChildrenEntry() Calls Enter() on all animated Children Enable() StartCoroutine(SomeAnimation(...)) private void Enable() gameObject.SetActive(true) Init() canvasGroup.interactable true canvasGroup.blocksRaycasts true private void Init() canvasGroup GetComponent lt CanvasGroup gt () ... private IEnumerator SomeAnimation(...) ... public void Exit() Similar to Enter, but disabling the element Now I want to open the options panel by clicking a button in the game's UI. The panel is inactive (unticked) in the beginning, while the AnimatedUIElement component is enabled. UI Hierarchy Options Button calls Enter() on Options Panel. The desired setup in the Button Component calling OptionsPanel.Enter() and MainPanel.Exit() But clicking the button throws the following exception Coroutine couldn't be started because the the game object 'Main Menu Button' is inactive! UnityEngine.MonoBehaviour StartCoroutine(IEnumerator) AnimatedUIElement AnimatePosition(Vector2, Vector2, Single, AnimationCurve) (at Assets Animated UI Elements AnimatedUIElement.cs 265) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 93) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) AnimatedUIElement PlayChildrenEntry(Transform) (at Assets Animated UI Elements AnimatedUIElement.cs 219) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 79) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) UnityEngine.EventSystems.EventSystem Update() In this stack trace you can see that the Options Panel did not start coroutines as no animation was defined in its component, but called Enter() on its children, which are animated. Using debug logs I found out that, while Init() is called immediately after Enter(), Awake() is called after the coroutines (which happen later in the program flow) throw errors. This makes it seem like the object is not available instantly after calling setActive(true). Is there an explanation and possibly a fix for this behavior? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.