_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | delaying enemy attacks I have an enemy attack script that when a raycast hits the player it deals damage to the player, however the enemy attacks at multiple times per second and I wish for the enemy to have to wait 1 second after it attacks the player before it can attack again. The script is here, the main focal point is the void update(). Any help is appreciated, let me know if I've missed out any needed details. ) public class DamagePlayer MonoBehaviour int attackDamage 10 SerializeField float agroRange SerializeField Transform castPoint Rigidbody2D rb2d bool isFacingLeft Start is called before the first frame update void Start() rb2d GetComponent lt Rigidbody2D gt () bool CanSeePlayer(float distance) bool val false float castDist distance if (isFacingLeft true) castDist distance Vector2 endPos castPoint.position Vector3.right castDist RaycastHit2D hit Physics2D.Linecast(castPoint.position, endPos, 1 lt lt LayerMask.NameToLayer( quot Action quot )) if (hit.collider ! null) if (hit.collider.gameObject.CompareTag( quot Player quot )) val true else val false Debug.DrawLine(castPoint.position, endPos, Color.red) else Debug.DrawLine(castPoint.position, endPos, Color.green) return val Update is called once per frame void Update() if (CanSeePlayer(agroRange)) PlayerHealth.currentHealth attackDamage Debug.Log( quot can see player quot ) else |
0 | Melee Range trigger collider does not detect object with Player tag In my 2D game, I have a Player which has a BoxCollider2D with isTrigger false a dynamic Rigidbody2D a Player script ...tagged as quot Player quot and in the quot Player quot Layer. Also I have an Enemy in the scene which has a BoxCollider2D with isTrigger true an EnemyMelee script ... tagged as quot Enemy quot and in the quot Enemy quot Layer. The Enemy has its own collider because when to handle taking damage or changing colors when shot by the Player's bullets. The Enemy has an empty child game object following it where it goes, called MeleeRange and it has a BoxCollider2D with isTrigger true a kinematic Rigidbody2D an EnemyMeleeAttack script ...tagged as quot MeleeRange quot and in the quot MeleeRange quot Layer. What I want is When Player is inside of the MeleeRange area, the EnemyMeleeAttack script will detect this and call the Coroutine from the EnemyMelee script. I want my Enemy to trigger its quot attackMove quot animation and attack my Player every 1.5 seconds. It has an exit time to the idle animation, and because the Player is still in the MeleeRange collision area, the attack will start again and return to idle again. The problem is MeleeRange simply cannot see the Player tag in the area. I put Debug.Log if it detects the player but nothing happened. EnemyMeleeAttack script public class EnemyMeleeAttack MonoBehaviour public EnemyMelee enemyMeleeScript void OnTriggerEnter2D(Collider2D coll) if(coll.tag quot Player quot ) Debug.Log( quot MeleeRange Collision Reached! quot ) enemyMeleeScript.anim.SetBool( quot isRunningBool quot , false) enemyMeleeScript.StartCoroutine(enemyMelee.attackStance()) EnemyMelee script public class EnemyMelee Enemy region Variables public bool inRange endregion region Attack public float attackTime public float timeBetweenAttacks endregion region Movement with AI public bool isRunningBool public AIPath aipathScript public EnemyMeleeAttack emeleeattackScript endregion public override void Start() base.Start() anim gameObject.GetComponent lt Animator gt () aipathScript gameObject.GetComponent lt AIPath gt () aipathScript.OnTargetReached() private void FixedUpdate() Code for if Enemy dies, disable all functions attached to Enemy. if (health lt 0) GetComponent lt AIPath gt ().enabled false StopCoroutine(attackStance()) DamageColorUpdate() Reference from A Pathfinding for following player and running animations when following occurs. if (aipathScript.reachedEndOfPath false) anim.SetBool( quot isRunningBool quot , true) inRange false else anim.SetBool( quot isRunningBool quot , false) inRange true StartCoroutine(attackStance()) public IEnumerator attackStance() if (Time.time gt attackTime) anim.SetBool( quot isRunningBool quot , false) player.GetComponent lt Player gt ().TakeDamage(damage) attackTime Time.time timeBetweenAttacks anim.SetTrigger( quot attackMove quot ) yield return null |
0 | How to find 1 3 and 2 3 of the distance between two given points? I know how to find the middle of two given points var midpoint (pointA pointB) 2 where pointA and pointB are Vector2 I thought that var thirdBtnPoints (pointA pointB) 3 var twoThirdBtnPoints 2 (pointA pointB) 3 should give me 1 3 and 2 3 between the two points but it doesn't. I guess this might be more of a math question though, but how can I find 1 3 and 2 3 of the distance between two given points? |
0 | AssetBundles for sprites, or download the images from my server? I need to host several sprites in my server, and then have Unity download and use them. I have tested two methods AssetBundles If I pack my sprites into an AssetBundle, the bundle is about 4MB. It works fine. Download the images If I download the image bytes from my server, you can use those bytes to create a Sprite. Curiously, this is much, much smaller than an AssetBundle (just like 1.5MB). Both methods work. It seems pretty obvious that the second one offers an advantage due to reduced memory size. My questions are Why is the second method so much smaller? Is there any reason I'd rather use AssetBundles? |
0 | Adjust postion only in X axis I have two game objects named A and B, just as follows I want to move object B to this virtual line without any rotation so that the destination is B' . What I have are transformation of object A and B. I'm brand new to Unity3D and its APIs, so I don't know how should I get this done. |
0 | Animation shown as playing in the animator, but it doesn't show in game (Unity 2D C ) I have an Animator on this gameObject. The Animator hits one state when some parameters are true, it can transition to this state from any state. The parameters are fine because i can see in the animator that the state is getting hit when i want it to. The blue progress bar is showing, but the animation doesn't play on the screen in the game, it just shows the state before it. I have tried changing exit time, apply root motion, update mode, static batching. Nothing works Help pls internet gods As requested here are some images, first this is my animator and the transition that is set up (I have also tried this with the same transition but from flies buzzing directly and the same behaviour happens) Also here is what the animation state looks like and the preview of it, showing that it works in scene (just not in game) And here's how it behaves in game, as you can see the blue bar is progressing (and this is going into the state at the correct time, after dealing 2 damage to the fly, isDead gets set to true). However the only animation that plays is the fly buzzing one. Here's my code using System.Collections using System.Collections.Generic using UnityEngine public class FlyCombatAndFollow MonoBehaviour Space Header("References ") public Animator animator public GameObject fly Space Header("Character attributes ") public int maxHealth 2 int currentHealth Start is called before the first frame update void Start() currentHealth maxHealth public void TakeDamage(int damage) currentHealth damage Play hurt animation animator.SetTrigger("IsHit") animator.SetInteger("Hit", damage) if (currentHealth lt 0) StartCoroutine(Die()) public IEnumerator Die() Debug.Log("Fly died") play death animation animator.SetBool("IsDead", true) yield return new WaitForSeconds(1.0f) Disable fly Destroy(fly) |
0 | OnCollisionEnter only triggering if colliding object starts inside collider Despite the absurdly high number of "OnCollisionEnter not working" threads around the internet, no one else seems to have had this specific problem. To start off with, I have a spherical "shield" object around my ship, which has a shader designed to give off impact effects when hit by an object. To trigger the shader impact effect, you need to give it the position from which do the effect. So, the easiest way to do this is to give the shield a Collider and, whenever OnCollisionEnter is called, it sends the contact.point details to the shader. That's not the difficult part. The part that isn't working is that OnCollisionEnter is not being called when the laser bolt fired at the shield actually collides with the shield. Both the shield and the laser bolt have Sphere colliders, both are not triggers. Only the shield has a rigidbody, which is not kinematic. void OnCollisionEnter (Collision collision) Debug.Log (Time.time) if (collision.transform.tag "Impact") Debug.Log ("go") Does the shader stuff That script is attached to the shield object. Not only is "go" never being logged, but neither is the Time, so OnCollisionEnter is not being called. The odd thing about this scenario is that, OnCollisionEnter will be called by objects that begin inside the shield's collider so if I start the laser bolt inside the shield, then the function gets called as usual. But when I start the laser outside the shield and Translate it into the shield, nothing happens. For the life of me, I can not work out what's going wrong with it. |
0 | RenderPipleinManager.DORenderLoop Internal() Taking Unusual Amount In profiler I am developing for WebGL and for optimization purposes I have converted to URP. After converting the tri count has dramatically improved but the problem is my FPS is not improving. I tried to profile and found that RenderPipleinManager.DORenderLoop Internal() is taking 13 . Is this normal? An initial search brought that it was a bug and fixed in a later unity version. But even after converting to the latest lts 2019.4.20, i am getting the same issue. |
0 | How do you allow joints in a character to fall freely based on gravity? I am building a game in Unity in which a character falls down on death. Is it possible to make the joints fall and bend based on gravity? That is to leave the joints fully dependent on gravity and colliders and not any skeletal animation. |
0 | How do I add a "pointer" to my UI menu? I'm sure there has to be a simple answer to this, but frankly I cannot find anything about it anywhere on the internet, so I'm asking here. How do I add a pointer like this hand to the side of the currently selected UI button in my game? I tried using Unity's built in UI system to do this, using the "sprite swap" feature that changes sprites based on whether or not the button is currently selected. I made an image for my "Play" button, and then an image for when the play button was selected that included a pointer as part of the image, but the image would either resize when the button was selected, or the image was moved to the right to accommodate Unity's centering mechanic on the UI. Perhaps this wasn't so wrong, and I'm just not using the UI system correctly. Does a feature like this have to be hard coded into the UI design? |
0 | Unity Script and game not syncing after player respawn I have a health system for my player that looks like this public int fallBoundary 10 public int Health public int numOfHearts public Image hearts public Sprite fullHeart public Sprite emptyHeart void Update() if(Health gt numOfHearts) Health script works, why does heart display not? Health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt Health) hearts i .sprite fullHeart else hearts i .sprite emptyHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false Unfortunately, after respawn, the hearts do not sync anymore. My debugging showed, that the elements of hearts still did their job, resetted and got replaced correctly. However, in my game, nothing changes after the respawn (should reset to full health and change if player gets damaged). For the respawn, I am loading my prefab, which I also checked (everything is there). To avoid confusion my hearts never reset to 0, but stay at 1. Player Prefab that loads during respawn Hearts after respawn |
0 | timeScale 0 doesnt stop all prefabs in unity As expected timeScale 0 can be used for stopping the game or pausing but when i make timeScale equal to 0 some prefabs still move and they can shoot bullets but addforce doesnt effect to bullets and they stop there. I know i can fix the problem on handling code of my prefabs but they are a lot. is there a good way to do the trick in my game? thank you for helping |
0 | How to apply Image effect only on specific part of objects? I need a way to censore part of characters' bodies like Cyberpunk 2077.this is mean I want to apply Image effect only to specific parts of bodies that you can see in the below Image |
0 | Unity "Find" can only be called from the main thread, but moving variables to the Start() function causes other errors pragma strict var collided false var thrust float var pizza GameObject.Find("pizza small").GetComponent. lt Rigidbody2D gt () function Start() hand pizza collision detection function OnCollisionStay2D(coll Collision2D) if (coll.gameObject.tag "Pizza") collided true Debug.Log("Hand Pizza") function Update() Input if (Input.GetKey(KeyCode.W)) Debug.Log("Up") transform.position.y 0.2 if (collided true) Adding force to the pizza pizza.velocity Vector3(0,15,0) else if (Input.GetKey(KeyCode.A) Input.GetKey("left")) Debug.Log("Left") transform.position.x 0.1 else if (Input.GetKey(KeyCode.D) Input.GetKey("right")) Debug.Log("Right") transform.position.x 0.1 else if (Input.GetKey(KeyCode.S) Input.GetKey("down")) Debug.Log("Down") transform.position.y 0.1 else if (transform.position.y gt 3.5) transform.position.y 0.25 else collided false Moving the 3 initial variable declarations into Start() removes the "Find can only be called from the main thread" error, but then they cannot be used in the Update() function due to variable scope. If I declare them initially and then set their values inside of the start function, new errors arise. var pizza function Start() pizza GameObject.Find("pizza small").GetComponent. lt Rigidbody2D gt () If I do that, then when I use pizza.velocity Vector3(0,15,0) It states that velocity is not a member of "object". I have no idea how to fix this, as the program works with no changes to my initial code, but does still give the error. This could be causing problems, as the rigidbody2D of the "pizza small" is pulled toward any non preexisting colliders that I add. |
0 | How can I reset the mouse axes when respawning a player? I am making a simple parkour game in which the camera will follow the mouse based on the mouse input axis the sensitivity. This works great, but when I want to reset my character to the start I cant figure out how to reset the mouse axis to zero, thus preventing me from resetting the camera rotation. I have tried Input.ResetInputAxes() , but that seems to only reset the buttons. using System.Collections using System using System.Collections.Generic using UnityEngine public class Movement MonoBehaviour public CharacterController characterController public Transform Player, camera public Camera cam public float XSensitivity, YSensitivity public bool grounded, jumping public float forwardSpeed, horizontalSpeed, jumpPower, gravity, sprintModifier HideInInspector public float sideSpeed, lastPlayerPosX, lastPlayerPosZ, jumpSpeed, verticalRotation, horizontalRotation private float isSprinting 1 void Update() This is where I get the axes float mouseX Input.GetAxis( quot Mouse X quot ), mouseY Input.GetAxis( quot Mouse Y quot ) This is how I rotate the player and camera verticalRotation mouseY YSensitivity Player.transform.localRotation Quaternion.Euler(0, horizontalRotation, 0) horizontalRotation mouseX XSensitivity cam.transform.localRotation Quaternion.Euler(verticalRotation, horizontalRotation, 0) if (Input.GetMouseButtonDown(0)) Cursor.lockState CursorLockMode.Locked float horizontal Input.GetAxis( quot Horizontal quot ), forward Input.GetAxis( quot Vertical quot ) grounded characterController.isGrounded if (grounded) if (Input.GetKey( quot left shift quot )) isSprinting sprintModifier if (Input.GetKey( quot left shift quot ) false) isSprinting 1f jumping false jumpSpeed 0 sideSpeed .75f else jumpSpeed (gravity 25) Time.deltaTime if (Input.GetKey( quot space quot )) sideSpeed .25f if (Input.GetAxisRaw( quot Jump quot ) ! 0 amp amp !jumping) jumping true jumpSpeed jumpPower lastPlayerPosX Player.transform.position.x lastPlayerPosZ Player.transform.position.z Vector3 motion new Vector3(horizontal horizontalSpeed sideSpeed, jumpSpeed, forward forwardSpeed isSprinting) characterController.Move((Player.transform.rotation motion) Time.deltaTime) void OnTriggerEnter(Collider col) if (col.gameObject.name quot deathbarrier quot ) Resets player to starting position Player.transform.position new Vector3(20.5f, 2, 22.5f) Is supposed to reset all inputs (including mouse) Input.ResetInputAxes() Sets camera rotation to 0, but only for one frame before the stored mouse axes change it camera.transform.rotation Quaternion.Euler(0, 0, 0) Thanks for any tips! |
0 | Vertex Snapping on a mesh with an armature I've made a selection of modular walls for a game i'm working on and some of the pieces have moving parts, like doors and flaps, but the moving pieces with an armature attached don't use vertex snapping like all of the other pieces and it leaves ugly gaps in the walls. I've tried everything I can think of to get them lined up, the closest I can get is lining them up by eye and this leaves small gaps when in game and isn't perfect. Does anyone know of a way to get vertex snapping to work with meshes that have an armature attatched? I've attached a picture to try and explain |
0 | Asset workflow for Blender models? As a coder, I don't have much experience in asset creation workflow. I'm trying to figure out the best way to work effectively with Unity Blender combo. I don't export to FBX, I prefer to work directly with Blender files, with no intermediate export step. I have parts of the map that I place in the scene walls, decorations, whole rooms, etc I keep them in one Blender file. I have models of collectibles, like treasures, keys and the like I keep them in another Blender file. I have models of characters, which I keep in another one. It has worked OK so far, however I feel like it's not the best way to work. While it makes sense in Blender, it gets messy in Unity. What is an effective way of working with this combo? Or with asset import in a larger project, in general? Should I export to FBX instead of using Blender files directly? I'd like to understand now how and why to adapt the workflow than have everyone involved being slowed down later. |
0 | When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why? |
0 | Coloring a Voronoi Graph Intro I want to convert a Voronoi Graph made with this awesome library by jceipek on GitHub into something I can work on. So far so good, this user provides with a demo to start with and shows how to generate the VG. Question How do I convert the VG (made by edges and that dot in the middle) into something that I can work with? Such as, after you generate some noise and apply to it (height), you colour the polygons based on it. Thoughts Something comes to my mind about instantiating meshes and tiles based on the edges and the position of the dot as a start, but it won't work if I can't "detect" the polygon. Expected result Image from this blog about Voronoi Mapping link What I have It is drawn with Gizmos (for visual debugging in Unity) I want to know how to color my polygons as in the expected image above. So I thought about doing a mesh or individual tile (and color it based on height afterwards but that is sauce for another question if needed) Edit of my progress To further explain this question I provide the next image. The image shows that I could use that position data somehow and turn that random polygon shape into a "tile" that will have a colour (mesh?) and possible data in it (script). I hope this helps otherwise let me know in the comments. |
0 | How to Implement a Timer for my Prefab for Roll a Ball Game (C in Unity) I am trying to create a public float timer that senses when the particular prefab has not been there for a certain amount of time. Then, it will replace that particular object. The goal is to randomly spawn 10 of these cubes across the game board. Then when the player picks one up, it disappears. Then after say, 2 seconds, a new cube should be placed on the board. Right now the Player already moves around the board just fine, and can pick up the cubes. When the player picks up a Cube, a new cube is automatically placed on the board with no delay. This script will be attached to the cube prefab directly. Apologies for the appearance of the code in advance. using UnityEngine using System.Collections public class RandomPlacement MonoBehaviour public GameObject prefab private GameObject prefabClone public int count private GameObject getCount public float timer 2 Instantiate the Prefab somewhere between 10, 10 on the x, and z planes, with a height of 0.5 in y. void Update () getCount GameObject.FindGameObjectsWithTag("PickUp") count getCount.Length if (count lt 10) timer Time.deltaTime if (timer lt 0f) Vector3 position new Vector3(Random.Range( 9.0f, 9.0f), 1.0f, Random.Range( 10.0f, 9.0f)) prefabClone Instantiate(prefab, position, Quaternion.identity) as GameObject timer 2 The code for the collision between the pick up and ball is given by void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag("PickUp")) other.gameObject.SetActive(false) The "Cube" prefabs are all given the tag "PickUp" This script is attached to the "Player" |
0 | How do I keep a rigidbody from making unnecessary collisions on smooth surfaces in Unity3d? I have been having trouble with a custom character controller I am making. The root of the problem lies with collisions. I am trying to make movement code, but I have a problem with ground movement. Pay attention to this gif. It might be hard to notice due to the low frame rate, but the collider registers collisions with objects (in red) that do not point out of the ground. They share the same y position as the ground. I've printed the normals of the collisions, and there are a lot of normals that are perpendicular to the normal of the ground (which is causing the rigidbody to get stuck). The problem lies with collisions in unity. If I were to print the y position of the bottom of my collider, it would be just a tad lower than the y position of the ground. The collider actually rests below the ground by an almost negligible amount (which is why it doesn't always collide with these objects). Here is what I have tried I created a function that runs at the beginning of every FixedUpdate() that uses current collisions to change the y position of the rigidbody. It only runs on collisions that would ground the player (meaning that they are below the collider). The problem with this approach is that the same issue can occur with walls, meaning that the collider can get stuck on walls. I cannot create another function that would do the same for walls for various reasons. Here is what would fix the issue I need help figuring out how I can make collisions more discrete in unity. Colliders rest slightly below objects when ontop of them. They can also "sink" just a little into walls. In other words, colliders can rest into other colliders, and I need this to stop. Any help is appreciated. Thank you. |
0 | Stuttering movement when approaching boundary I'm trying to limit my movement in the y axis by checking if the position will be within the boundaries after the Translate. If it is, only then do I translate the Player. public class Player MonoBehaviour private float speed 5.0f private float bottomY 4.37f void Start () transform.position new Vector3(0, 4, 0) void Update () Movement() void Movement () vertical movement Vector3 yTranslateVector Vector3.up Input.GetAxis("Vertical") speed Time.deltaTime float newYPos (transform.position yTranslateVector).y if (newYPos gt bottomY amp amp newYPos lt 0) transform.Translate(yTranslateVector) horizontal movement Vector3 xTranslateVector Vector3.right Input.GetAxis("Horizontal") speed Time.deltaTime transform.Translate(xTranslateVector) However, when I do this, the Player kind of pauses when approaching the boundary and then stutters forward towards the absolute limit upon releasing the key. I tried putting the Movement function in the Update and FixedUpdate method, but neither made any difference. Can anyone give me any insight into this? |
0 | How do I convert distance covered from meters to kilometers, in Unity? I am developing a game in Unity where I have to find a distance in kilometers, to find a passenger's fare based on the covered distance. This is what I have tried private Vector3 previousPosition public float cumulatedDistance void Awake() initialize to the current position previousPosition transform.position Update is called once per frame void Update () cumulatedDistance (transform.position previousPosition).magnitude previousPosition transform.position How can I determine the distance covered, and convert it to kilometers? |
0 | Variable value in inspector is not updating automatically? Something weird is happening when I change a variable value in script and hit play the var value doesn't update I have to reset the script in inspector. Is this normal? Aren't the values suppose to update when we hit play? The Simple Code I used to test this var a int 0 function Start () print(a) |
0 | VertexColor shader is not working correctly in built application I want to change the vertex colors of my mesh. The light sources must not affect the objects with this shader, its lighting must be determined only by its vertices colors, so I turned the Lighting Off. I use this simple shader Shader "VertexColored Simple" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Pass ColorMaterial AmbientAndDiffuse Lighting Off SetTexture MainTex Combine texture primary Fallback "VertexLit" And this script using UnityEngine using System.Collections public class BehaviourScript MonoBehaviour void Start() Color exclrs new Color 11 new Color32(25, 25, 25, 255), new Color32(50, 50, 50, 255), new Color32(75, 75, 75, 255), new Color32(150, 150, 150, 255), new Color32(200, 200, 200, 255), new Color32(255, 255, 255, 255), new Color32(200, 200, 200, 255), new Color32(150, 150, 150, 255), new Color32(75, 75, 75, 75), new Color32(50, 50, 50, 255), new Color32(25, 25, 25, 255), Mesh mesh GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 normals mesh.normals Color colors mesh.colors for(int i 0 i lt vertices.Length i ) for(int j 0 j lt 11 j , i ) colors i exclrs j i mesh.colors colors When the game is launched, in editor I can see this This is EXACTLY what I wanted to achieve! But in built for PC(x86) version I see this Why the results from the editor and from the built .exe differs? What should I do to see my effect in built version? Maybe I need to use an another shader? |
0 | Trouble GamePad input on iOS but works perfect on Android I am having trouble getting input from on iOS devices (iPhone 6 Plus and iPad). Here is my code, if (Input.GetKey (KeyCode.JoystickButton14)) A chr show "A" if (Input.GetKey (KeyCode.JoystickButton13)) B chr show "B" ........................................... if (Input.GetKey (KeyCode.JoystickButton11)) Select chr show "SELECT" And in OnGUI() GUI.Label (new Rect(0,0,100,100), "Pressed Button " chr show, guiStyle) Code works perfect on Android device. I also have tried following if (Input.GetButton ("JSButton")) JSButton chr show "JS Button 14" Please Help Me! |
0 | Custom Camera View Fustrum in Unity Is it possible in Unity to make some sort of bounding box (with a running application) within the current viewpoint of the actual screen? Let me explain I'm working on a project which uses a projection for visual output, the screen I am projecting on is smaller than the actual projectors resolution. This means that the unused spaces around the actual working application, are black and visually hidden. Made an image for exra explanation As i'm new to Unity and still learning, I'm not sure if this is even possible because of the use of camera's and environment. I happen to know that it's possible in three.js. But if anyone could point me in the right direction or explain that it's impossible would be much appreciated because I'm not sure where to look anymore! |
0 | How can I get Unity to do letterbox pillarbox to maintain aspect ratio? I'd like my game to have the same aspect ratio at all cost, including keeping all UI elements fixed in the same place. I'm totally ok with losing screen space in the interest of fixing the aspect ratio. |
0 | Controlling Instantiation I have an problem where I instantiate a GameObject and it keeps on instantiating a million times over, even though I put the line of code under the start function. I am trying to have the player collide with the coin(then a point is added to your score) , then the coin deletes itself and then re instantiates at a random coordinate, but I cant get past the initial instantiation. using System.Collections using System.Collections.Generic using UnityEngine public class Coin MonoBehaviour public GameObject coins Vector2 randomPosition public UIScript UIScript Use this for initialization void Start () UIScript GameObject.FindWithTag("UI").GetComponent lt UIScript gt () randomPosition new Vector2(Random.Range( 8f, 8), Random.Range( 4f, 4f)) Instantiate(coins, randomPosition, Quaternion.identity) Update is called once per frame void Update () private void OnTriggerEnter2D(Collider2D coinCollision) switch(coinCollision.tag) case "Player" collisionWithPlayer() break private void collisionWithPlayer() UIScript.highScore UIScript.highScore 1 Object.Destroy(coins) |
0 | How to handle day and night in a 2D sprite game Do I need to draw, for example, a tree how it looks in the day (normal colors) and how it looks at night (colors aligned according to the moonlight)? Or does Unity have a function for that? |
0 | Draw a sphere with a custom material from script How can I spawn or draw a sphere with a custom material with a script? So far I've tried using Gizmos.DrawSphere, but I can't find a way to control the material used to draw it. I would like to draw it with a material with some specularity, around 0.5. |
0 | 2DRaycast is shooting slightly in wrong directions I wanted just a simple 2DRaycast, which points from my character to my mousePointer. So I found the following code in the Internet, most people seem to use it like that. So I tried it, but it isn't working for me like it is supposed to do, check the screenshot below. The direction is kinda weird, so I tried some variants of the variables and tried with Normalize, which didn't solve the problem. Vector2 test new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y) Vector3 test1 (Camera.main.ScreenToWorldPoint (Input.mousePosition)) test.Normalize () RaycastHit2D hit Physics2D.Raycast (transform.position, test) Debug.DrawRay (transform.position, test, Color.red) I tested both variables, test and test1, same things happen, even with Normalize and without it. The following Screenshot shows, what happens (The red thing is the mouse pointer). Edit Solution Vector2 test new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y) Vector3 test1 (Camera.main.ScreenToWorldPoint (Input.mousePosition)) test.Normalize () RaycastHit2D hit Physics2D.Raycast (transform.position, test1 transform.position) Debug.DrawRay (transform.position, test1 transform.position, Color.red) I use now the second variable, because we need the Vector3 here, because we substract with Transform.position which is a Vector3. |
0 | How to debug fatal signal 11 code 2 in UnityMain? i have searched for the fatal signal caused by Render or GxDriver, FlashMuller in unity forum says it's google play the error 08 03 14 59 47.503 32020 32092 ? A libc Fatal signal 11 (SIGSEGV), code 2, fault addr 0xcbe8dffc in tid 32092 (UnityMain), pid 32020 (com.tuo3.alive) 08 03 14 59 47.533 32121 32121 ? A DEBUG Build fingerprint 'OnePlus OnePlus5T OnePlus5T 8.1.0 OPM1.171019.011 1807181208 user release keys' Revision '0' ABI 'arm' pid 32020, tid 32092, name UnityMain gt gt gt com.tuo3.alive lt lt lt 08 03 14 59 47.544 32121 32121 ? A DEBUG backtrace 00 pc 000575d0 system lib libc.so (je arena tcache fill small 71) 01 pc 00077919 system lib libc.so (je tcache alloc small hard 16) 02 pc 00058fc7 system lib libc.so (je arena palloc 1650) 03 pc 00069bd1 system lib libc.so (imemalign 1164) 04 pc 0006d373 system lib libc.so (je memalign 26) 05 pc 001d6f18 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (UnityDefaultAllocator lt LowLevelAllocator gt Allocate(unsigned int, int) 24) 06 pc 001da888 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (MemoryManager Allocate(unsigned int, unsigned int, MemLabelId const amp , AllocateOptions, char const , int) 852) 07 pc 001da254 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (malloc internal(unsigned int, unsigned int, MemLabelId const amp , AllocateOptions, char const , int) 128) 08 pc 00193bc8 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (core StringStorageDefault lt char gt assign(char const , unsigned int) 180) 09 pc 00a350bc data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so ( gnu cxx hashtable lt std pair lt core basic string lt char, core StringStorageDefault lt char gt gt const, ZipCentralDirectory PathDescriptor gt , core basic string lt char, core StringStorageDefault lt char gt gt , gnu cxx hash lt core basic string lt char, core StringStorageDefault lt char gt gt gt , std Select1st lt gnu cxx hash gt , std equal to lt core basic string lt char, core StringStorageDefault lt char gt gt gt , std allocator, lt ZipCentralDirectory 10 pc 00a34adc data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so ( ZZN19ZipCentralDirectory20readCentralDirectoryEvEN3 08 invokeERK15FileSystemEntryR12FileAccessorPKcRKN3zip4CDFDEPv 508) 11 pc 00a38160 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (zip CentralDirectory Enumerate(bool ( )(FileSystemEntry const amp , FileAccessor amp , char const , zip CDFD const amp , void ), void ) 804) 12 pc 00a348d0 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (ZipCentralDirectory readCentralDirectory() 20) 13 pc 00a26630 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (apkAddCentralDirectory 84) 14 pc 00a19074 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (Mount(char const ) 84) 15 pc 00a090dc data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (UnityInitApplication() 216) 16 pc 00a0a660 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (UnityPlayerLoop() 264) 17 pc 00a0cc68 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (nativeRender( JNIEnv , jobject ) 228) 18 pc 000114cb data app com.tuo3.alive VZWALBY70nH dSDIQa rKA oat arm base.odex (offset 0x10000) More discussion 2 |
0 | How to animate material alpha property via script? I am creating Animator OverrideController via script based on current controller assigned to animator component. I have created animation curve for position and it works. When i try to animate transparency (material color alpha) it does not work (it does not make any effect, however in Animation Dopesheet there is yellow line "Object name Material.Color.a (Missing!)"). Did I fail to properly access this property or is it the consequence that creating animation via script works only for legacy animations with Animation component? using System.Collections using System.Collections.Generic using UnityEngine public class AnimationScript MonoBehaviour void Start() AnimationClip clip new AnimationClip() AnimationCurve curve AnimationCurve.EaseInOut(0.0f, transform.position.x, 1.0f, transform.position.x) clip.SetCurve("", typeof(Transform), "localPosition.x", curve) curve AnimationCurve.Linear(0.0f, 1.0f, 1.0f, 0.0f) clip.SetCurve("", typeof(Material), " Color.a", curve) Animator anim GetComponent lt Animator gt () AnimatorOverrideController animatorOverrideController new AnimatorOverrideController(anim.runtimeAnimatorController) "loop" is the name of clip not name of state animatorOverrideController "loop" clip anim.runtimeAnimatorController animatorOverrideController However analogous code for legacy Animation component works void Start() Animation anim GetComponent lt Animation gt () AnimationCurve curve create a new AnimationClip AnimationClip clip new AnimationClip() clip.legacy true update the clip to a change color curve AnimationCurve.Linear(0.0f, 1.0f, 2.0f, 0.0f) clip.SetCurve("", typeof(Material), " Color.a", curve) now animate the GameObject anim.AddClip(clip, clip.name) anim.Play(clip.name) What am I missing and why is first script not working? |
0 | Implementing my own UI sprite class in Unity using shaders where and how to position the sprites For learning purposes, I am trying to implement my own UI classes in Unity "from scratch", in the GPU using shaders. I mean, I am trying to use simple 2D sprites either positioned via shaders or created within the geometry shaders. These sprites should be, of course, displayed above all else. I know how to create or translate the sprites within the shader. However, I am struggling with a couple of conceptual issues 1) where exactly, relative to the camera (or to the near frustum plane), should the UI sprites be positioned? I man, thinking of the Z axis as being the camera.forward, what is the correct default distance to display the sprites at (assuming that at that location, the sprite texture would be the closes to its correct 100 zoom scale). 2) for the correct positioning rotation, would it just be the case of, every frame, calculating in the shader such correct world position of the sprite in relation to the camera near frustum plane, and then making the sprite rotate towards the camera? Or is there a better way of doing that, i.e. disregarding world position at all and going directly for the screen position of the sprites within the shaders, since the final step of shaders is to paint the pixels in screen space? Thanks for your suggestions! |
0 | How can I restart an animation? The first time the player clicks a button, my animation plays properly. The problem is that when the player presses the button a second time, the animation does not play. Here is the code I'm using to control my animation public Animator anim public Animator animsfirst public Animator animssecond public Animator animsthird public Animator reanimsfirst public Animator reanimssecond public Animator reanimsthird public Animator closeinstruct public void instructionpanel() (instruction panel open animation) anim.enabled true when button click instruction panel open animsfirst.enabled true animssecond.enabled true animsthird.enabled true public void closeinstructionpanel() (instruction panel close animation) Debug.Log("animationrun") when button click instruction panel close reanimsfirst.Play("freverse") reanimssecond.Play("srevese") reanimsthird.Play("lreverse") closeinstruct.Play("clreverse") Here is the animator controller setup for the animsfirst object And for the reanimsfirst object How can I resolve this issue? |
0 | How do you deal with transparent fonts that you want to be white? I'm a bit of a total amateur, but I thought I would learn how to make a simple game during quarantine. However, I stumbled into a problem with fonts. I'm thinking about using the free font quot Pixelmania quot to show a score at the top of the screen. But the font is transparent! How do I make the inner part of the font white? Do I have to manually edit the font file myself? Or is there an easier way? |
0 | Is it possible to capture screenshots in headless (no graphics) mode in unity? I am trying to capture screenshots while running unity simulation in headless mode (no graphics), if anybody tried to do the same and it worked, please share how could you make it work. |
0 | Get object position on texture I'm rendering a 3D object to texture (2048x1600) and show this texture on a panel (1600x285) using a RawImage (2048x1600) component as child. This texture is rendered successfully on screen. This 3d object contains several mountpoints as empty objects. Now I want to show several sprites to visualize those mountpoints on the texture (panel) at their corresponding screen position (must not pixel perfect). I tried several camera transforms, but could not get the correct position values var main camera.WorldToScreenPoint(slot.mountpoint.position) Debug.Log("Maincam screenpos " main.ToString()) RectTransform rect this.GetComponentInParent lt RectTransform gt () Debug.Log("Rect size delta " rect.sizeDelta.ToString()) Vector2 viewPos camera.WorldToViewportPoint(slot.mountpoint.position) Debug.Log("Viewport pos " viewPos.ToString()) Vector2 localPos new Vector2(viewPos.x rect.sizeDelta.x, viewPos.y rect.sizeDelta.y) Debug.Log("Viewport pos local " localPos.ToString()) How I could realize this? |
0 | My character can jump even when its not grounded Here is the code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovementscript MonoBehaviour vars public CharacterController controller public float speed 12f Vector3 velocity public float gravity 9.81f public Transform groundCheck public float groundDistanace 0.4f public LayerMask groundMask public float jumpHeight 3f bool isGrounded Update is called once per frame void Update() isGrounded Physics.CheckSphere(groundCheck.position, groundDistanace, groundMask) if(isGrounded amp amp velocity.y lt 0) velocity.y 2f float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z controller.Move(move speed Time.deltaTime) if(Input.GetButtonDown( quot Jump quot ) amp amp isGrounded) velocity.y Mathf.Sqrt(jumpHeight 2f gravity) velocity.y gravity Time.deltaTime controller.Move(velocity Time.deltaTime) character controller and etc |
0 | How to instantiate an object to a randomised Vector2 So I'm trying to make a little game where squares randomly spawn around a set area and you have to tap them. The game is 2D. I'm having trouble using my randomly generated x and y floats to instantiate a cube in the game. Here is my code pragma strict public var play false public var xpos float public var ypos float public var cube GameObject function Start () function Update () function Game () xpos Random.Range( 10f,10f) ypos Random.Range( 4.45f,4.45f) Instantiate(cube, new Vector2(xpos, ypos)) And here's the error! Assets gameController.js(18,20) BCE0023 No appropriate version of 'UnityEngine.Object.Instantiate' for the argument list '(UnityEngine.Rigidbody, UnityEngine.Vector2)' was found. Any help would be appreciated. Thanks! Alex |
0 | ScriptableObject's custom objects begin reset to default? I'm using ScriptableObjects as a way to serialize objects that I work with in an editor script. I save them as assets using AssetDatabase.CreateAsset and get them resetted It is saving correctly native c class objects like strings, primitives and arrays of primitives. The problem is that my ScriptableObject also contains objects of custom classes and structs of my code. These custom objects are being set to default() (ie. value types being set to 0 and reference types to null) every time the code is recompiled and when the editor is restarted (while the primitive variables still have the right saved value). Even with blittable structs the problem persists. Is that expected? Edit with some code to contextualize StructLayout(LayoutKind.Sequential, Pack 1) public struct MeshHeader public int numBones public int numVerts public class MyClass public string s1 get set public string s2 get set public class MySO ScriptableObject public int myInt OK public int myArr OK These 2 variables will have their value reset after any recompilation of the code public MeshHeader meshHeader This will become 0 0 public MyClass myClass This will become null public static void SaveMySO(MeshHeader h, MyClass c) var mySO ScriptableObject.CreateInstance lt MySO gt () mySO.myInt 10 mySO.myArr new int 2 9, 8 mySO.meshHeader h mySO.myClass c AssetDatabase.CreateAsset(mySO, quot Assets foo.asset quot ) public static MySO LoadMySO() return AssetDatabase.LoadAssetAtPath lt MySO gt ( quot Assets foo.asset quot ) When I call MySO.SaveMySO it will save the ScriptableObject. However if I run MySO.LoadMySO after any code recompilation between these two calls, it will have both meshHeader and myClass values set to default, which will be 0 and null respectively while still holding the right values for myInt and myArr. |
0 | Texture doesn't scale and repeat I wrote the script for automatic repetition of texture background. To save it I typed Cmd S. I dragged and dropped the script to Background in Hierarchy. When hit play button the texture doesn't scale and doesn't repeat itself. What is it that I am doing wrong? using System.Collections public class TiledBackground MonoBehaviour public int textureSize 32 void start() var newWidth Mathf.Ceil (Screen.width (textureSize PixelPerfectCamera.scale)) var newHeight Mathf.Ceil (Screen.height (textureSize PixelPerfectCamera.scale)) transform.localScale new Vector3(newWidth textureSize, newHeight textureSize, 1) GetComponent lt Renderer gt ().material.mainTextureScale new Vector3(newWidth, newHeight, 1) Expected Results Results that I'm getting are same as before. Script doesn't seem to work |
0 | Strange Light Angles in Unity I'm quite sure that I'm missing something very simple here, but I'm a complete Unity noob and I absolutely can't figure out what I'm seeing. I'm trying to light a sphere from both sides, perpendicular to the camera angle, to create an effect where each side of the sphere is illuminated but there's a strip of darkness down the center. Instead, I'm getting really weird angles from the two lights. My setup (I've quintuple checked all numbers)... A single sphere (textured like Mars) at position (0, 0, 0). An orthographic camera pointed at it from position (0, 0, 20) and rotation (0, 0, 0). Two Point lights at ( 5, 0, 0) and (5, 0, 0), with the same intensity and all other light settings. By my understanding, that should position each light equidistant from the sphere, exactly on either side from the camera's POV. Sort of like a capital " T " configuration. In theory their shine on the sphere should be mirrored on each side, complimentary angles toward the sphere from exactly horizontal. Instead, I'm getting this Left Light... Right Light... So, instead of being horizontal and mirrored, it appears as though the Right Light is significantly closer to the camera than the Left Light along the Z axis, and they both seem to be somewhat below the vertical center of the sphere (despite all elements having a Y value of zero). Even weirder, viewing it in the Scene panel from above, there's a spiral pattern of darkness when both lights are on, rather than a single dark band between them... Can someone help me out here? Does Unity handle perspective in a way I'm not getting, or have I messed up my arrangement of elements? And aside from eyeballing it, what positions should I use to create the effect I'm going for? |
0 | How can I distribute the source code of my project without the imported assets? I have a Unity project that uses some assets that I downloaded for free in the Unity asset store. I would like to make my project open source and distribute its source code in GitHub. But, I do not want to put the assets I downloaded in my GitHub, since they are not mine. Also, these assets take a lot of space in my repository. Can I arrange my project in such a way that any user who downloads it will be automatically sent to the Unity asset store to download the required assets? I found that it works well with TextMesh Pro I can remove the TextMesh Pro folder from my Assets folder, and then when I open the project in Unity, it prompts me to re import TextMesh Pro, and when the import is done, the game works well. Is it possible to achieve a similar effect with other assets? |
0 | Box collider pushes me out of it's area slowly, I can pass through it if moving quickly I am new to Unity. I Setup a character in unity2D with a rigidbody. I had the scale off my sprites set to 100 pixels per unit. At this scale, my rigidbody character stood on top of platforms and could not pass through walls containing box colliders. I decided, that to make things easier, I would change all sprites to 1 pixel per unit. After doing so, I scaled everything (variables, sizes, etc.) by 100. I confirmed that the box colliders on both the caharcters, floor, and walls, are all in the same places, relatively. The box colliders on the floors still work, but the wall box colliders behave differently. When I walk into a wall, the wall slowly pushes me in a direction (depending on whether or not my character has walked through half the wall or not). The wall should be stopping my motion completely. The code is very simple, but this is what I use to move if (Input.GetKey (KeyCode.D)) transform.Translate (Vector2.right moveOffset Time.deltaTime) transform.localScale new Vector3(1,1,1) anim.SetBool("moving",true) Do note that the moveOffset variable, was scaled by 100 after the change. Thanks in advanced! |
0 | Unity 2D Object following target instead of moving towards it I'm making a 2D game with Unity that's based on avoiding evading enemies. The problem i'm facing right now is i can't get the enemies to move towards the target player, but instead they follow it. So they never actually "attack" because they only follow it around and don't even come close to it. Also if the target player stops moving, they stop moving. I'm wondering if it could be something in my scene, since i've asked this question on multiple forum threads in the unity forums section and everyone seems to answer with the same lines of code. Extra information My enemy has a box collider on it with no rigidbody 2D. My player has a box collider on it with a rigidbody 2D. Kind regards. using UnityEngine using System.Collections public class BeeBehaviour MonoBehaviour public Transform target public float moveSpeed 3 void Start () target GameObject.Find("MainObject").transform void Update () Chase() void Chase () Vector3 targetDirection target.position transform.position transform.position targetDirection moveSpeed Time.deltaTime |
0 | How to orbit an object at certain speed in Unity? I want to move an object around a circle. So I have this code below static public int theta 0 void Update() Vector3 position this.transform.position position.x 0 50 Mathf.Cos (theta) Time.deltaTime position.y 0 50 Mathf.Sin (theta) Time.deltaTime this.transform.position position theta 1 The object orbits, but it orbits so fast!!! I want the object to rotate like 1 orbit per second only. How to do that? ANSWER TO THIS PROBLEM, THANKS! static public int theta 0 void Update() Vector3 position this.transform.position position.x 0 50 Mathf.Cos (theta) Time.deltaTime position.y 0 50 Mathf.Sin (theta) Time.deltaTime this.transform.position position theta 1 Time.deltaTime |
0 | Handmade Terrain vs. Terrain Engine in Unity? I'm planning a game right now, to be made in Unity, and I'm trying to decide how I'll approach the basic level construction. Essentially, my game takes place on an island in an infinite ocean, very similar to Wuhu Island My question concerns all the stuff heightmaps can't handle. To use Wuhu Island as an example, note the lighthouse cliff, and the nearby similarly jutting out cliff. The volcano itself is also empty, and there are some tunnels through it on the other side. I was thinking I would just model the entire island myself in Cinema 4D, but as I read more about the terrain system, it seems Unity has special optimized rendering systems in place for terrain objects. Would I be shooting myself in the foot performance wise if I just built my island entirely by hand? This will be for mobile, so the little stuff might well count. Am I even approaching this question correctly if not, how would you best go about creating (something very close to) Wuhu Island as a level in Unity? Is there any reason for me to not do it as one mesh? I have effectively zero experience with 3D game dev only rendered 3D video stills for other applications, so this is a learning process. |
0 | SocketException No connection could be made because the target machine actively refused it I am working on connecting a client to a server using socket connection. I have a button, when I click on the button, it's giving the below exception in Unity. "SocketException No connection could be made because the target machine actively refused it.". What will be the issue? Can anyboady help me out? Below is the code I have written for connecting to the server internal Boolean socketReady false NetworkStream theStream StreamWriter writer StreamReader reader try connect new TcpClient (host, port) theStream connect.GetStream () writer new StreamWriter (theStream) reader new StreamReader (theStream) return true socketReady true catch(ObjectDisposedException) return false |
0 | Locomotion system with irregular IK Im having some trouble with locomtions (Unity3D asset) IK feet placement. I wouldn't call it "very bad", but it definitely isn't as smooth as the Locomotion System Examples. The strangest behavior (that is probably linked to the problem) are the rendered foot markers that "guess" where the characters next step will be. In the demo, they are smooth and stable. However, in my project, they keep flickering, as if Locomotion changed its "guess" every frame, and sometimes, the automatic defined step is too close to the previous step, or sometimes, too distant, creating a very irregular pattern. The configuration is (apparently)Identical to the human example in the demo, so I guessing the problem is my model and or animation. Problem is, I can't figure out was it is S Has anyone experienced the same problem? I uploaded a video of the bug to help interpreting the issue (excuse the HORRIBLE quality, I was in a hurry). |
0 | Draw a perfect circle in UI This is the problem I have. I have created a shader that draws circle. But depending on the distance from the camera thickness changes. Is it possible to keep thickness constant? |
0 | Performance overhead on Non POT Texture in POT Atlas Using atlas, we can reduce memory and draw call. And the atlas is usally POT(Power of Two) Texture. And I know non POT texture have a lot of GPU and memory performance overhead. (link) I have many rendering objects and they have also their non POT textures. And I packed the images into one 1024 1024 POT atlas and applied them to the objects. (each textures is non pot, and the atlas is pot texture) In this case, Can I avoid non pot texture overhead? Are they treated as non pot texture or not internally? |
0 | Why can't I use the operator ' ' with Vector3s? I am trying to get a rectangle to move between two positions which I refer to as positionA and positionB. Both are of type Vector3. The rectangle moves just fine. However, when it reaches positionB it does not move in the opposite direction, like it should. I went back into the code to take a look. I came to the conclusion that as the object moved, the if statements in the code missed the frame in which the rects position was equal to positionB. I decided to modify the code to reverse direction if the rects position is greater than or equal to positionB. My code is not too long, so I will display it below using UnityEngine using System.Collections public class Rectangle MonoBehaviour private Vector3 positionA new Vector3( 0.97f, 4.28f) Start position private Vector3 positionB new Vector3(11.87f, 4.28f) End position private Transform rect tfm private bool atPosA false, atPosB false public Vector2 speed new Vector2(1f, 0f) private void Start() rect tfm gameObject.GetComponent lt Transform gt () rect tfm.position positionA atPosA true private void Update() NOTE Infinite loops can cause Unity to crash Move() private void Move() if ( atPosA) rect tfm.Translate(speed Time.deltaTime) if ( rect tfm.position positionB) atPosA false atPosB true if ( atPosB) rect tfm.Translate( speed Time.deltaTime) if ( rect tfm.position positionA) atPosA true atPosB false When I changed it, however, it warned me of the following error message Operator cannot be applied to operands of type Vector3 and Vector3. This confuses me for two reasons first, both values are of the same data type. Second, using the comparison operator( ) on the two values works without error. Why can't I use the operator gt with Vector3s? |
0 | What does the "DXGI Flip Model Swapchain" setting in Unity do exactly? I'm preparing a Standalone Unity game for Windows and Mac. There is a checkbox in Player Settings called "Use DXGI Flip Model Swapchain for D3D11", which seems disabled by default. Needless to say, I don't understand this setting at all. The Unity documentation has this Flip model ensures the best performance. Disable this to fallback to Windows 7 style BltBlt model. This setting affects only D3D11 graphics API on Windows 8.1 or greater. Note that even if the flip model is enabled, the BltBlt model will be used in exclusive fullscreen mode to reduce input latency. It doesn't exactly tell me what this is (I literally don't know what most of that means) but it almost seems like there is no reason not to have it enabled. Can someone explain the pros and cons of this setting? Under what scenarios would I want to enable disable it? Since disabling it fallbacks to the Windows 7 style, it almost gives the impression that enabling this might make the game less compatible on Windows 7? |
0 | How many directional lights in Unity In Unity, how many directional lights can be active at once? 1, 2, 4, or 8? I thought 2, but I have searched and cannot confirm. |
0 | Added tiles not loading in run time So I have a game object MapGenerator and 2 attached scripts MapGenerator.cs and Lexicon.cs. I need to be able to access a couple variables in Lexicon.cs from MapGenerator.cs, so I imported it with void Awake() GameObject gameObject new GameObject( quot Lexicon quot ) lexicon gameObject.AddComponent lt Lexicon gt () Now, this allows me to pull variables from Lexicon, and I am able to do that successfully for the most part. However, the public fields that are being set from Unity (tiles sprites) are not being pulled in. They just show up as null. Example scenario public class Lexicon MonoBehaviour public Tile thiccTile public Tile thiccTile2 public Tile thiccTile3 private string fact quot Yummy porchop quot private string favoritefact private Tile favoritetile public Lexicon() favoritetile thiccTile2 this guy is public and set in unity under components. favoritefact fact public Tile Favoritetile get return favoritetile set favoritetile value public string Favoritefact get return favoritefact set favoritefact value Start() UnityEngine.Debug.Log(lexicon.Favoritefact) quot Yummy porchop quot UnityEngine.Debug.Log(lexicon.Favoritetile) null My first thought was it was because I never explicitly call Lexicon(). However, since favoritefact works, im guessing the gameobject stuff is enough? Anyway, how can I fix this? EDIT This is where I set the values (Different variable names but you get the idea) |
0 | How to add tiles randomly? I made a set of 10 different "ocean" tiles, all interchangeable with one another, and I'd like to randomly attach these 10 different tiles together in different combinations over a large rectangular area what would be the best way to do so? I've thought of just adding each sprite into a script and then calling a for foreach loop to add it into my world but that seems extremely expensive since I'd be adding over 1000 sprites. I don't want to reduce the number of sprites I have to add, I'm just seeing if there's a typical way people do this sort of thing. |
0 | UNITY passing metalic map from Blender to Unity automatically? I have .blend file contains very basic material shader structure (no fancy nodes), just add some textures (diffuse, normal, roughness, metallic etc) . When i imported the .blend file as prefab in unity (and copy all necessary texture map to unity asset folder ) , the blender shader can pass albedo and normal maps (automatically) without problem. But it never be able to carry metallic map (or any other maps) Right now i have to rebuild the metallic map within unity manually. I'm just curious if unity can only recognize albedo and normal map from blender shader ? How about the other map ? How about metallic or smoothness roughness etc ? |
0 | Gun clipping through arm during third person animation I have been setting up a Blend Tree for motion animation in Unity. I'm using Root Motion for now. I parented the gun to the root of the player and then I use OnAnimatorIK to lock the two hands in position. The overall looks and feel is great by my standards. The only thing I am disappointed about is the butt of the gun clips through the character's upper arm when running. Is there a way to crop this in the game? I'd like to avoid going into a 3d Editor and making it two separate meshes which I could then I guess somehow disable. I'm hoping there is a better way to handle this situation. Also I wonder if the gun being parented to the Root player object is wise. I had tried parenting to the 'right hand' bone but this made the gun point upwards about 45 and looked silly. |
0 | I cant Instantiate a particle system for the duration of a subroutine I have a sub routine that lowers the timescale to 0.3 for 2 seconds. while in those two seconds i would like to spawn a trail of particles that follow the player. I can get the particles working if I attach them to the player in the editor but I'm having trouble spawning them at the start of the time slow down. The slow down subroutine works fine its just the particles that i cant spawn. Thanks, any help is appreciated. public GameObject particles public Transform playerParticles Start is called before the first frame update void Start() slowDownActivateNoise GetComponent lt AudioSource gt () void Update() if (hasCollided) if (!activated) StartCoroutine("SlowDownActive") public IEnumerator SlowDownActive() Debug.Log("subroutine Start") activated true Instantiate(particles, playerParticles.position, playerParticles.rotation) Time.timeScale 0.3f GetComponent lt Collider gt ().enabled false yield return new WaitForSeconds(2) GetComponent lt Collider gt ().enabled true Time.timeScale 1.0f hasCollided false activated false Debug.Log("subroutine end") |
0 | Controlling loop frequency in a Coroutine I want this coroutine to execute continuously and change the colors. But right now it just waits 1 second at the start and then loops the Coroutine very fast. So my question is how can I loop the Coroutine every 2 seconds. public class control MonoBehaviour public bool gravity false public bool m isRunning false public SpriteRenderer m spriteRenderer private Rigidbody2D rb private void Update() if (gravity) rb.gravityScale 1 StartCoroutine("Changecolor", 3f) private void Start() m spriteRenderer this.GetComponent lt SpriteRenderer gt () rb GetComponent lt Rigidbody2D gt () private IEnumerator Changecolor() lt this coroutine yield return new WaitForSeconds(1) int random Random.Range(1, 4) if (random 1) m spriteRenderer.color Color.blue else if (random 2) m spriteRenderer.color Color.red else if (random 3) m spriteRenderer.color Color.green else m spriteRenderer.color Color.yellow this.StartCoroutine("Changecolor", 3f) private void OnMouseDown() gravity true |
0 | How to store an array of prefabs together with configuration parameters I have attached the following script to a number of weapon prefabs public class WeaponScript MonoBehaviour public enum Direction Right, Straight, Left public Direction weaponDir void Start () prepareDirection (weaponDir) void prepareDirection(Direction dir) if (dir Direction.Straight) transform.localEulerAngles new Vector3 (0, 0, 0) else if(dir Direction.Left) transform.localEulerAngles new Vector3 (0, 0, 30) else if(dir Direction.Right) transform.localEulerAngles new Vector3 (0, 0, 30) I also added the following script to an empty game object SetupWeapon public class SetupWeaponsScript MonoBehaviour public GameObject weaponPrefabs public GameObject weapons void Start () weapons new GameObject weaponPrefabs.Length for (int i 0 i lt weaponPrefabs.Length i ) weapons i Instantiate(weaponPrefabs i ) as GameObject When I select my SetupWeapon object, I am able to populate the weaponPrefabs array with the weapon prefabs I want to use, but I can't directly alter their parameters in that same inspector view. I want to be able to override the direction of each weapon prefab in the list, rather than use the value that's stored on the prefab itself. How can I create the weaponsSetupScript in such a way that I can set the direction enum for each weapon entry at the same time that I set select the prefab in the editor? I believe it might have something to do with inheritance, just not too sure how to go about it though. |
0 | Leaderboard not working in Unity I'm trying to create a leaderboard for my game. I have the game created and added the leaderbaord using cloudonce. I have also created the app on google play console and linked the app to the game services. I have followed the following tutorial to create the leaderboard Leaderboard tutorial I have followed the exact same instruction as given in the tutorial. Once the game is over, the leaderboard button is activated. I have attached LeaderboardsButton script(this script comes with the CloudOnce package) to the leaderboard button. Here is the code in the game over panel for getting the score void OnEnable() DisplayGameOverScore() void DisplayGameOverScore() gameOverScore.text ((int)gameManager.playerScore).ToString() gameOverHighScore.text PlayerPrefs.GetInt( quot HighScore quot , 0).ToString() CloudOnceServices.instance.SubmitScoretoLeaderboard(PlayerPrefs.GetInt( quot HighScore quot , 0)) This is the CloudOnceServices script as per the tutorial public static CloudOnceServices instance private void Awake() TestSingleton() private void TestSingleton() if (instance ! null) Destroy(gameObject) return instance this DontDestroyOnLoad(gameObject) public void SubmitScoretoLeaderboard(int score) Leaderboards.HighScore.SubmitScore(score) I have attahced this script to an empty game object along with the InitializeCloudOnce script(this is provided with the CloudOnce package). I have also created an alpha test on googleplay. Once I open the link and start the game, the google play services console open and when I hit the leaderboard button, google play services console loads but after that nothing happens. It just goes back to the game. I read that other people ran into similar issues and the advise given was to check if the SHA1 certificate fingerprint is the same in app signing under release management and the credentials in GoogleApis. They both match. I'm not sure what the issue is? |
0 | I can t get a teleport to work c these are the pics of the inspect panel on the parts of the 3D pacman that you asked for. (I just added these photos because I couldn t while i was away and because even though the advice given so far was amazing, it didn t resolve my problem, so please help if you can) I ve been trying to make a teleport for a while and it works only part of the time. the collisions work because i put a debug.log in it but the teleporting part doesn t work. there are no errors in the collision, it just doesn t teleport the pieces of pacman. here is the script (it's not the most improved but i was trying to make it work) public GameObject pacman public GameObject Camera public GameObject pointLight public GameObject body public Vector3 pacmantele public Vector3 cameratele public Vector3 pointlighttele public Vector3 bodytele void OnTriggerEnter(Collider other) Debug.Log("works") pacman.transform.position pacmantele Camera.transform.position cameratele pointLight.transform.position pointlighttele body.transform.position bodytele here is a photo of the inspection panel on the non working teleporter |
0 | Mouse look rotation not rotating object axis in Unity So, I made a simple First Person Camera script for my game, and the way it's supposed to work is the camera is rotated by localEulerAngles to rotate the camera around, and then just the Y axis rotation is also applied to the character, so that he moves in the direction of the camera. This isn't how its working now. I've narrowed down the two most likely problems in the scripts, and this first one is from the camera controller player.transform.localEulerAngles new Vector3(0, rotationX, 0) cam.transform.localEulerAngles new Vector3( rotationY, rotationX, 0) Note the camera works just fine, and rotates perfectly in all directions. Secondly, the player movement controller, which might not be actually be moving locally? I can't tell. transform.Translate (new Vector3(0, 0, Input.GetAxis("Vertical") walkSpeed)) transform.Translate (new Vector3(Input.GetAxis("Horizontal") strafeSpeed, 0, 0)) There you go. Right now, even though the camera moves just fine with the mouse, and, incidentally, the whole script used to work, the player moves forward on the global Z axis with W and backwards with S, all the while acting like a shooter on rails. Thank you! |
0 | How do I get the player to collide with another object to use as a boundary? I'm trying to make a simple game where you move a sphere from left right and try to avoid falling cubes. If a cube touches the player (sphere), the player dies. I'm trying to set up boundaries using a cylinder with a collider, but every time I hit the collider boundary, the player disappears like they would if they hit a cube. Here is my player script using System.Collections using System.Collections.Generic using UnityEngine public class Move MonoBehaviour public float moveSpeed 1 Start is called before the first frame update void Start() Update is called once per frame void Update() transform.position new Vector3(Input.GetAxis("Horizontal") moveSpeed, 0, 0) void OnCollisionEnter(Collision collision) if (collision.gameObject.tag "Cube") Destroy(collision.gameObject) Destroy(gameObject) |
0 | How do I apply domain warping to my marching cubes voxel terrain in Unity? So, in GPU Gems 3 there is a cool warped terrain that I seek to replicate. Currently, I'm generating the terrain fine, but I want to add that warp effect. Do this before using 'ws' to sample the nine octaves! float3 warp noiseVol2.Sample( TrilinearRepeat, ws 0.004 ).xyz ws warp 8 Im wondering how to replicate the above code in C . What does the above code do? What type of variable is noiseVol2.Sample(x,y).xyz? I want to warp my own terrain, currently I have a system that creates octaves of perlin noise with certain frequencies and amplitudes. It looks something like this var perlin0 new Perlin3(0,baseFreq 4.03f, 0.25f) var perlin1 new Perlin3(1, baseFreq 1.96f, 0.50f) var perlin2 new Perlin3(2, baseFreq 1.01f, 1.00f) var perlin3 new Perlin3(3, baseFreq 0.49f, 2.00f) var perlin4 new Perlin3(4, baseFreq 0.24f, 4.00f) return new Density(ws gt start with plane float density plane.Evaluate(ws) add perlin noise to get density values at each ws co ord. 3 octaves currently (3 perlin noise ) density perlin0.Evaluate(ws) density perlin1.Evaluate(ws) density perlin2.Evaluate(ws) density perlin3.Evaluate(ws) density perlin4.Evaluate(ws) return density ) I've tried replicating it like so var q new Vector3(perlin0.Evaluate(new Vector3(0,0,0)), perlin0.Evaluate(new Vector3(5.2f, 1.3f, 1.3f))) var q1 new Vector3(perlin1.Evaluate(new Vector3(0, 0, 0)), perlin1.Evaluate(new Vector3(5.2f, 1.3f, 1.3f))) var q2 new Vector3(perlin2.Evaluate(new Vector3(0, 0, 0)), perlin2.Evaluate(new Vector3(5.2f, 1.3f, 1.3f))) density perlin0.Evaluate(p 4.0f q) density perlin1.Evaluate(p 4.0f q1) density perlin2.Evaluate(p 4.0f q2) I've read the article that igo Qu lez created, and implemented it like above. Am I doing something wrong? It looks the same without that, just using density perlin0.Evaluate(p) density perlin1.Evaluate(p) density perlin2.Evaluate(p) I want to know what I'm doing wrong, what I misunderstood and how to implement it correctly. This is all based off this lumpn's proceedural generation on github (I would link it, but I can't) Thanks. I would also want to know if there are any examples (I learn best from codebases) with this implementation using shaders. (Maybe it will run faster because it uses the GPU instead of the CPU?) This is still unanswered on how to do it on the CPU (and I'm still confused on how to do it on the GPU, do you have to do some vertex stuff? how do you pass in a noise texture through the shader?) |
0 | How to find position of the edge of an object? I have two planes and I want to put both planes one after another so that I can form a road. I set them from the editor and that was very easy but I wanted to do this from code. So in the code void Start() secondRoad.position firstRoad.position But this just set the second plane in the center of the first plane, kind of overlapping. But I want the second plane to be placed next to the first plane where it ends right the edge of the first plane. How will I do this? |
0 | How do I refer to a native library with Unity 5 on Android? I have a library called mylibandroid.a. This is given to me by another developer. I also have the iOS version of this lib, and have been able to access it from Unity. It is supposedly built for android. I have included it in my Plugins folder in my Unity 5 project, but I renamed it mylibandroid.so as droid libs use this naming convention. I can see the library included in the .apk file, so Unity seems to know it should go in there. My code looks like this public class AlmoTest MonoBehaviour if UNITY ANDROID DllImport("mylibandroid.so") private static extern void FreeGlobals() public void TestFreeGlobalsButtonPress() Debug.Log("Pressed") FreeGlobals() endif When my function is called, I get this error E Unity ( 4188) Unable to find mylibandroid.so I Unity ( 4188) Pressed I Unity ( 4188) I Unity ( 4188) (Filename . artifacts generated common runtime UnityEngineDebug.gen.cpp Line 56) I Unity ( 4188) I Unity ( 4188) DllNotFoundException mylibandroid.so I Unity ( 4188) at (wrapper managed to native) AlmoTest TestFreeGlobalsButtonPress () I Unity ( 4188) at AlmoTest.TestFreeGlobalsButtonPress () 0x00000 in lt filename unknown gt 0 |
0 | Unity Messages in Compound Colliders Lets say I have a 2D character with two colliders a circle collider that represents the feet, and a box collider that represents the body. Lets say that the character is currently standing on the ground, i.e. only the feet collider is in contact with the ground collider. According to the Unity manual, I will receive an OnCollisionEnter2D message. That message contains a Collision2D object that contains an otherCollider field of type Collider2D. I don't see anything in that object that would tell me which of the two colliders the body or the feet initiated the message. So my question is this how do you figure out which collider in a compound collider initiated a collision trigger message? |
0 | Unwanted rotations with transform.RotateAround I didn't tough i would have issues with this, but unfortunatly I did. I have a Character (which is more a pile of cube) with a body, a empty GameObject for each leg attached to the body with a join and 2 cubes for leg too. The body and the two empty gameobject are child of a Empty gamebject. The 2 cube that represent leg are both child of one of the empty gameObject. What I want to achieve is to rotate the leg around the position of its empty parent by doing this if(Input.GetKey("l")) l leg.transform.RotateAround(l leg.transform.parent.transform.position, new Vector3(1,0,0), 75 Time.deltaTime) unfortunatly, I only want it to rotate on x, but all of the axis are changing, which lead to unwanted rotation. Now, I know rotations aren't independant like translations, but I don't know how to fix this. If possible, i'd prefer to rotate locked joint via script but I have now idea how, I haven't seen anything about it when I looked up 2 |
0 | Background music not stopping while game is set to paused I am implementing pause game functionality in a Unity3D game using the following script public class PauseGame MonoBehaviour lt summary gt class to pause the game using Time.timeScale and implement the related behaviours associated the game lt summary gt region Fields Boolean variable that informs script if game should be paused or not, false by default. private bool isPaused false endregion region MonoBehaviour Messages At Start, void Start() Whenever 'ESC' key is pressed, toggle 'isPaused' boolean and call SetPause() to pause resume game void Update() if (Input.GetKeyDown(KeyCode.Escape)) isPaused !isPaused SetPause() endregion region Methods A function to pause resume the game public void SetPause() Debug.Log("SetPause") Invert 'isPaused' boolean and convert it into a float variable, being true 1 and false 0f. float timeScale !isPaused ? 1f 0f Set the Time Scale as 1(game runs normally) or 0(game pauses) Time.timeScale timeScale endregion All the game elements pause as expected using the above, except the background music. I can pause the background music by additionally referencing the AudioSource and disabling it while timescale is set to 0. However, I was wondering whether it was a bug. Kindly suggest. |
0 | How to create custom inspector to display generic Stack class I have a member that I would like to expose Serializable private sealed class InputGameObjectStack Stack lt GameObject gt public InputGameObjectStack() base( InputGameObjectStackSize) Inside the MonoBehaviour, I have SerializeField private InputGameObjectStack inputGameObjectStack Inside the editor script, I'm able to fetch the property from the MonoBehaviour object (as SerializedProperty), but there is nothing usable that allows me to traverse through the elements. Is there any way of showing the constents of the stack in the inspector as immutable (no functionality to push pop)? |
0 | Instantiating Prefabs at run time I'm trying to move my project to Addressables and upload assets, prefabs and screens to an archive on the server. I'm a new in Unity and this a bit challenging for me. I've prepared all prefabs for addressable usage and now I'm trying load them. All my prefabs have loads throw GameObject.Instantiate For example public class PlatformObject LocationObject other properties and methods public PlatformObject Clone() var clone ((Runner.PlatformObject)GameObject.Instantiate(this)) clone.Id this.Id clone.NextPlatforms this.NextPlatforms clone.IsStartPlatform this.IsStartPlatform clone.Level this.Level clone.Type this.Type clone.MinimumDistance this.MinimumDistance clone.AllowDispose false clone.Size this.Size return clone I've tried change this code for usage Addressables. public async Task lt PlatformObject gt Clone() var handle Addressables.LoadAssetAsync lt GameObject gt (this.name) var clone (await handle.Task).GetComponent lt PlatformObject gt () clone.Id this.Id clone.NextPlatforms this.NextPlatforms clone.IsStartPlatform this.IsStartPlatform clone.Level this.Level clone.Type this.Type clone.MinimumDistance this.MinimumDistance clone.AllowDispose false clone.Size this.Size return clone I've got a cloned object successfully, but object doesn't appears on the scene. Looks like object not initialized properly, bcouz I've got a lot of warnings like that Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject 'Mid Town 07'). UnityEngine.Transform set parent(Transform) I've googled and have found a few solution related with parent location. Made changed but it didn't help. I'm still getting those warnings. |
0 | Unity3d Do I need to destroy gameobject AND script? From proper leak protection do I need to delete both of these or will getting rid of one take care of both? Currently I am destroying the script AND the gameobject private void OnDestroy() Destroy(this.gameObject) Destroy(this) |
0 | Why does the player grab the object outside the trigger zone? I want the player to be able to grab an object (in this case the knife) when he is in the object's trigger zone. He can get the knife but there is a problem if I press grab button outside of the trigger zone, then he can get the knife immediately after entering the zone. I want Unity to get the input only when the player is in the trigger, otherwise it should not be working. Here's the grab script using System.Collections using System.Collections.Generic using UnityEngine public class Grab MonoBehaviour public GameObject player private bool grabbed public GameObject knifePosition private bool isInTrigger void Update() if (Input.GetButtonDown( quot Grab quot )) grabbed true else grabbed false if (grabbed amp amp isInTrigger) gameObject.transform.position knifePosition.transform.position private void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject player amp amp grabbed) gameObject.transform.SetParent(player.transform) isInTrigger true Debug.Log( quot Picked up quot ) |
0 | ClientDisconnected due to error Timeout UnityEngine.Networking.NetworkIdentity UNetStaticUpdate() Why am I getting this error. I think it has problem with port so I change port number and still getting same error. yesterday it was working fine but when I start today it giving me error like this. ClientDisconnected due to error Timeout UnityEngine.Networking.NetworkIdentity UNetStaticUpdate() I refer this question but, there is not any answer presence for this error. |
0 | Moving panel between two positions smoothly? I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script public GameObject gunsWindow private Vector3 a, b public bool open use inspector void Start() a gunsWindow.transform.position b new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z) void Update() if(open) gunsWindow.transform.position Vector3.MoveTowards(a, b, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(a, b, Time.deltaTime) panel shaking else gunsWindow.transform.position Vector3.MoveTowards(b, a, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(b, a, Time.deltaTime) shaking |
0 | Using State Pattern with Unity I am new to Game Development and Unity. I have written a component for Jumping and Running, CharacterJumpAbility.cs and CharacterRunAbility.cs. I would like the Character to be able to Jump only if the Character is not moving. I came across a State Pattern but I can't understand how to apply it. For example if I want to Jump, first I must check if the Character is Running, but I have to do this in the CharacterJumpAbility.cs or in the CharacterController.cs (the component who handles inputs)? If I define a state for example public enum CharacterState Run, Jump For example if the player is pressing the space bar, I have to set the Jump state, the code that sets state CharacterState.Jump should be written in the CharacterJumpAbility.cs or in the component that handles inputs? And if I want to set a new state for example Jump, while I am running, this is clearly not possible, how to handle situations like these? |
0 | Texturing different block types on an optimized voxel mesh I have a cubic world (like Minecraft) where I'm generating chunks. In those chunks, only visible vertices and faces are generated. Currently, it means that if I have a 2x2x1 chunk, it will generate 8 triangles for the top part (2 for each block). I'm trying to generate only two following this greedy meshing method If I combine adjacent faces together, I'd still like to be able to draw transitions in materials between adjacent blocks, something like this As you can see it has 3 different tiles grass, dirt grass transition, and dirt. Currently, my shader looks like this Shader quot MultiTexture Diffuse Worldspace quot Properties Color ( quot Main Color quot , Color) (1,1,1,1) TexAbove ( quot Above texture quot , 2D) quot surface quot TexSide ( quot Side texture quot , 2D) quot surface quot TexBelow ( quot Below texture quot , 2D) quot surface quot TexTopSide ( quot Top side texture quot , 2D) quot surface quot Scale ( quot Texture Scale quot , Float) 1.0 SubShader Tags quot RenderType quot quot Opaque quot CGPROGRAM pragma surface surf Lambert struct Input float3 worldNormal float3 worldPos sampler2D TexAbove sampler2D TexSide sampler2D TexBelow sampler2D TexTopSide float4 Color float Scale void surf (Input IN, inout SurfaceOutput o) float2 UV fixed4 c if(abs(IN.worldNormal.y gt 0.5)) UV IN.worldPos.xz c tex2D( TexAbove, UV Scale) else if(abs(IN.worldNormal.x) gt 0.5) UV IN.worldPos.yz c tex2D( TexSide, UV Scale) else if(abs(IN.worldNormal.z) gt 0.5) UV IN.worldPos.xy c tex2D( TexSide, UV Scale) else UV IN.worldPos.xz c tex2D( TexBelow, UV Scale) o.Albedo c.rgb Color ENDCG How would I modify this shader to work with faces that have been merged together? Or would I have to keep separate faces per block and handle them individually? |
0 | Projector does only affect model I'm working on a simple selection of a RTS unit. Therefore I used a projector to display a circle on the ground around the unit. But it happened, that the circle is only displayed on the head of the unit placeholder, not on the ground. At first I thought it has something to do with the terrain, but as I added a Plane there was'nt a change. I followed the steps from this tutorial http hyunkell.com blog rts style unit selection in unity 5 (skipped the drag box part) Here's a screenshot from the scene I'm wondering how I can solve this. I'll provide every information you'll need. |
0 | Issue with multiplayer interpolation In a fast paced multiplayer game I'm working on, there is an issue with the interpolation algorithm. This interpolation is for a moving object not controlled by the local computer. The server sends packets with the object's position at a fixed rate. (red markers) The interpolation algorithm is attempting (and failing) to create a smooth path between the red markers. The results of this interpolation are shown by green and black markers. Green is the local position at the exact time a packet is received, and black is the local position at every frame. Green Local position when a packet is received (edited for clarity) Red Position received from packet (goal) Blue Line from local position to goal when packet is received Black Local position every frame On a network with a realistic amount of lag and packet loss, this is the result The local position (green amp black lines) seems to oscillate around the goals (red lines) instead of moving between them smoothly. This is how it looks on a perfect network with the object moving right to left. (0 ping, 0 packet loss, etc.) The code works like this Every x ms, receive a packet with a Vector3 position Set the goal to that position Set the positionAtLastPacket to the current local position Every frame, lerp from positionAtLastPacket to goal, attempting to reach the goal approximately when the next packet should arrive. If the next packet takes longer than expected, interpolation continues past the goal and becomes extrapolation. I believe what is happening is the extrapolation overshoots a bit to far. Over several packets, this issue compounds, causing the oscillation. local transform position when the last packet arrived. Will lerp from here to the goal private Vector3 positionAtLastPacket location received from last packet private Vector3 goal time since the last packet arrived private float currentTime estimated time to reach goal (also the expected time of the next packet) private float timeToReachGoal private void PacketReceived(Vector3 position, float timeBetweenPackets) positionAtLastPacket transform.position goal position timeToReachGoal timeBetweenPackets currentTime 0 Debug.DrawRay(transform.position, Vector3.up, Color.cyan, 5) current local position Debug.DrawLine(transform.position, goal, Color.blue, 5) path to goal Debug.DrawRay(goal, Vector3.up, Color.red, 5) received goal position private void FrameUpdate() currentTime Time.deltaTime float delta currentTime timeToReachGoal transform.position FreeLerp(positionAtLastPacket, goal, currentTime timeToReachGoal) current local position Debug.DrawRay(transform.position, Vector3.up 0.5f, Color.black, 5) lt summary gt Lerp without being locked to 0 1 lt summary gt Vector3 FreeLerp(Vector3 from, Vector3 to, float t) return from (to from) t Any idea about what's going on? |
0 | Calculating the weight of an object irrespective of the triangle or vertices count in Unity I have a meat piece which I want to weigh. Now there can be anything like fish, cheese, or other items that we can cut and measure. I want the weight to be determined by myself instead of determining from getting the surface of the item as it varies with different tris count. Currently, I am calculating the weight from the following code. public static float CalculateSurfaceArea(Mesh mesh) var triangles mesh.triangles var vertices mesh.vertices double sum 0.0 for (int i 0 i lt triangles.Length i 3) Vector3 corner vertices triangles i Vector3 a vertices triangles i 1 corner Vector3 b vertices triangles i 2 corner sum Vector3.Cross(a, b).magnitude weightMultiplier is a constant value for getting a reasonable weight value. return (float)(sum 2.0) weightMultiplier So if there's a meat piece like bellow and I want it to be a weight of let's say 3kg(6.6lb) then when I cut it into half it should give me values respectively (1.5kg). So I want the weighing factor to be in my control so that if in the future we have really detailed high poly items the weight shouldn't get affected by that. |
0 | How can I support many point light sources in a dynamically generated level in Unity? I'm currently working with a dungeon game which is similar to Dungeon Keeper by Mythic Entertainment. I'm using Unity and developing this game for Ipad 2 and above. Player can modify his dungeon, and I'd written a dungeon generator which creates it. In this case, I can't use lightmaps, because the dungeon has been created dynamically and player can tweak it. I also devised a way to combine separate game objects in a single mesh, so imagine that the entire dungeon (except special objects such as pillars, statues and mobs) is the single mesh. There's many point light sources (10 15 and above) on the stage, but Unity don't allow to use more than 8 light sources per object. So, if all dungeon cells are separated objects, I can use the diffuse or even vertex lit lighting, but if the entire dungeon is a single mesh, there's the hardware limit appears. Ways to solve this problem I'd divised Use separated geometry (tried) bad, because it harms berformance because there's many many many drawcalls (16 17 fps on Ipad 4). Use deffered shading (tried) bad, because it harms performance even more than separated geometry. Use a custom shader (haven't tried) I don't know how. Don't unite all cells in the single mesh but unite groups of cells to reduce the number of separated objects (haven't tried) Use the light manager (haven't tried) I don't know how. ??? How can I deal with it? |
0 | How can I get sensor data on iPhone onto a Windows PC? For use as a steering wheel I am making a Unity game. I want to be able to allow the phone to be used as a steering wheel, as input into the PC game. Technically, How can I achieve this? Can this be done through bluetooth? Thanks |
0 | How can I distribute the source code of my project without the imported assets? I have a Unity project that uses some assets that I downloaded for free in the Unity asset store. I would like to make my project open source and distribute its source code in GitHub. But, I do not want to put the assets I downloaded in my GitHub, since they are not mine. Also, these assets take a lot of space in my repository. Can I arrange my project in such a way that any user who downloads it will be automatically sent to the Unity asset store to download the required assets? I found that it works well with TextMesh Pro I can remove the TextMesh Pro folder from my Assets folder, and then when I open the project in Unity, it prompts me to re import TextMesh Pro, and when the import is done, the game works well. Is it possible to achieve a similar effect with other assets? |
0 | Using DLL's for a cross platform Unity Game Just a quick theoretical question so I don't hit a landmine further down development. In my current project, I have quite a lot of dll's that I made myself for use in Unity. If I were to develop for Android, would these dll's still function or is there another library format that Unity prefers to use? Basically, I'm looking for a rundown of all the ways you have to import libraries into Unity for use on a specific platform. For example, 1.) .dll files. Can you use them on other platforms? 2.) If not, how would I have to recompile code to allow me to access it the same way I currently do on a different plaform? |
0 | Why are there weird texture artifacts in baked light which don't appear with realtime light? This is the comparison of the same scene, realtime light vs baked light. What's am I wrong ? EDIT In particular, also texture are low quality (see image 2). Why ? |
0 | Procedural Islands Voronoi Pattern I'm trying to keep this as simple as possible, as I've found out the last few days this is a very difficult topic. I'd like to generate multiple flat islands, formed by a voronoi diagram. I've followed a long and (for me) difficult tutorial of building a procedural hexagonal grid just to find out it looks to artificial. I'd like to create a plane with faces divided in a voronoi diagram, and extrude multiple groups upwards to create islands. With that I'd like to achieve something similar as this http applemagazine.com wp content uploads 2015 10 image2.jpg Please help to get me started in the right direction, since my approach might be wrong in itself. EDIT I've found this https github.com jceipek Unity delaunay. Which draws lines in a voronoi diagram. Now I'm guessing the next step is to convert this to a mesh. Then I'd have to highlight random faces to be extruded to create the islands. Maybe this could be done with perlin noise, which I've just learned about. Extruding might not be the best way. Maybe deleting the faces that won't be land, and creating fall of edges (Like Wardy said). I'm doing my best to figure this out on my own, but any help is greatly appreciated. |
0 | Get all supported resolutions for a monitor I've been receiving complaints from users that my game doesn't support the 16 10 aspect ratio. Currently I list everything in Screen.resolutions in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor. I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc. I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example. |
0 | Where to put rigidbody on a car model ? I have a GameObject car like this MyCar Body with mesh collider Wheel Left with wheel collider Wheel Right with wheel collider ... and so on Where I have to put rigidbody ? Thanks |
0 | A Pathfinding lose target after spawning from script? I have been using A Path finding to enable object tracking. It works fine if I have both objects on the scene at the same time. However, if I were to use a script to spawn the seeking object instead, it will only track the first path to the object and not repath again. I am using the default AI Follow script and a prefab variable as the object to be tracked (which is an empty child game object to a moving character). Code import Pathfinding var tankTurret Transform var tankBody Transform var tankCompass Transform var turnSpeed float 10.0 var targetPosition Vector3 var seeker Seeker var controller CharacterController var path Path var speed float 100 var nextWaypointDistance float 3.0 private var currentWaypoint int 0 function Start() targetPosition GameObject.FindWithTag("GTO").transform.position GetNewPath() function GetNewPath() Debug.Log("GETTING NEW PATH!") seeker.StartPath(transform.position,targetPosition,OnPathComplete) function OnPathComplete(newPath Path) if(!GetNewPath.error) path newPath currentWaypoint 0 function FixedUpdate() if(path null) return Debug.Log("NO PATH!?") if(currentWaypoint gt path.vectorPath.Length) return var dir Vector3 (path.vectorPath currentWaypoint transform.position).normalized controller.SimpleMove(dir) tankCompass.LookAt(path.vectorPath currentWaypoint ) tankBody.rotation Quaternion.Lerp(tankBody.rotation, tankCompass.rotation, Time.deltaTime turnSpeed) if(Vector3.Distance (transform.position,path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint Any help will be greatly appreciated. |
0 | Check if vertex is visible in shader Im trying to figure out when a vertex is visible from the main camera. I have this function bool in frustum(float4x4 M, float4 p) float4 Pclip mul(M, float4(p.x, p.y, p.z, 1.0)) return abs(Pclip.x) lt Pclip.w amp amp abs(Pclip.y) lt Pclip.w amp amp 0 lt Pclip.z amp amp Pclip.z lt Pclip.w I call it in the vertex shader, and it works fine. The problem is when I have multiple cameras, and I only want to know if it is within the frustum on one of the cameras. If the vertex is not visible from my target camera, I want all other cameras to render it (if it is visible) a particular way (for example red). I am a little rusty on matrix transformations and the graphics pipeline, but maybe instead of passing UNITY MVP MATRIX into the in frustum function, I need to pass in the MVP matrix of the target camera? Or maybe just the View of the target camera needs to be replaced in. |
0 | How can I rotate a Transform over a specified time in a single line of code? How can I rotate a Transform over a specified time in a single line of code? I have had a lot of trouble with this in the past. I wrote a script which rotates a Transform by a specified rotation over n seconds, or rotates a Transform towards a Vector3 over n seconds, in a one liner. I hope it helps others in the future. See below. |
0 | 3D Studio Max biped restrictions? I have a stock biped character in 3D studio max which has a jump animation. The problem I have with the jump animation is that there is actual y offset happening inside it which makes it awkward to play while the character is jumping since it's not only jumping in the game world but the jump animation is adding its own height offset. I'm tryuing to remove the jump animations height offset, so far I've found the root node and deleted all its key frames which has helped a bit. The problem I'm having now is that the character still has some height offset and if I try to lower it it has a fake 'ground' that isn't at 0 and the limbs sort of bend on the imaginary floor, si there a way to remove this restriction just for the jump animation? Here's what I mean http i.imgur.com qoWIR.png Any idea for a fix? I'm using Unity 3D if that opens any other possibilities... |
0 | Unity 2D map and walkable collisions I have a 2d player who can only walk on black area. There is a red collider so player can't walk past it. Player has capsule collider. The problem is player can't walk toward the edge with his feets becasue of the it's collider. But player would probably want to walk toward the edge. Here is a sketch I've made. Is there a way to tweak this ? |
0 | How can I attract repel the mouse cursor from particular UI controls? This question came from some of my students. I wanted to share it here so others can find amp improve on the solutions we've found so far. In particular, my answer below doesn't behave as well as I'd like in windowed editor mode UI buttons no longer respond to hovering the cursor. I welcome alternative answers that solve this more completely. We're making a visual novel game using the Fungus asset for Unity. We want to add a twist where some dialogue options are easier or harder to press, because they attract or repulse your mouse cursor. Unfortunately, we haven't been able to identify a cross platform way to manipulate the mouse's position, nor a way to create a "Fake" mouse cursor image that can still interact with Fungus's UI buttons. How can we pull this off? |
0 | Target Lower API Level than Package or Plug In Requirements I am working on a project that I want to use local mobile notifications for Android using Unity as game engine. I want to reach as much as users I can, so I want to target API level 16 for the lowest Android API level. As expected, when targeting Android API level 16 for a build, build fails with that error Execution failed for task ' processReleaseManifest'. Manifest merger failed uses sdk minSdkVersion 16 cannot be smaller than version 19 declared in library androidnotifications release C Users Tumay Varel.gradle caches transforms 2 files 2.1 71d39d4badfde5815e850866bcf079c9 AndroidManifest.xml as the library might be using APIs not available in 16 Suggestion use a compatible library with a minSdk of at most 16, or increase this project's minSdk version to at least 19, or use tools overrideLibrary "com.unity.androidnotifications" to force usage (may lead to runtime failures) In documentation , it is explicitly saying that the package supports Android 4.4 (API 19) and higher API levels. I can handle this problem by targeting lowest API level 19, however I want to ask Is there a way to use this package or any other package or any plug in for required and higher API levels while not using for lower API levels than requirement at the same project? |
0 | Unity won't Instantiate() outside of Start(), even though code is the same I am trying to add a gameobject to my game using a socket connection. I have a SocketHandler class, which simply connects to my NodeJS socket server, which can also call a method on another class, which will add a new gameobject to the game. Here is how it basically works void Start () GameObject car Instantiate(CarGameObject) car.transform.parent this.transform car.GetComponent lt TestCar gt ().text.text "Volkswagen" This works fine and it adds the gameobject to the game upon starting. However, if I do something like this in my SocketHandler, it doesn't work var addCar new AddCar() socketio.On("addCar", (data) gt string str data.ToString() Car data2 JsonConvert.DeserializeObject lt Car gt (str) addCar.AddNewCar(data2) ) and then inside my AddCar class, I have the AddNewCar() method public void AddNewCar(Car input) GameObject car Instantiate(CarGameObject) car.transform.parent this.transform car.GetComponent lt TestCar gt ().text.text input.name it does not work. If I do a Debug.Log(input.name) inside the AddNewCar() method, it does log the name the server sends. It should do the exact same thing, but the AddNewCar() doesn't get added to the game. It simply does nothing. What could be wrong? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.