_id
int64
0
49
text
stringlengths
71
4.19k
0
Problem with Blender model imported to Unity (Lighting problems) I made a simple box in blender and imported it to unity. Now I'm facing with this weird lighting problem I've been messing around with normals, duplicated vertex, lots of things, even lightning properties but still I'm not getting any results at all. Why does this happen and how can I solve it? Source blend file https drive.google.com open?id 1Ze1JBRFBvhnnY w36U2KDe7Q2zcfXsmf
0
Prototype experience Unity3D vs UDK Has anyone yet prototyped a game in both Unity3D and UDK? If so, which features made prototyping the game easier or more difficult in each toolkit? Was one prototype demonstrably better than the other (given the same starting assets)? I'm looking for specific answers with regard to using the toolkit features, not a comparison of available features. E.g. Destructable terrain is easier in toolkit X for reasons Y and Z. I can code, so the limitations of the inbuilt scripting languages are not a problem.
0
Conservation of energy of a bouncy ball in Unity3d My problem is that in the project I have a ball with a physicMaterial where Dynamic Friction and Static Friction both are 0 Bounciness 1 Friction Combine is set to Multiply Bounce Combine is set to Maximum This ball has a rigid body attached in which mass 1 drag and angular drag both are 0 useGravity true There are some cubes which create a boundary for the ball to bounce inside. The ball bounces in a closed boundary. The problem is overtime its top velocity keeps on increasing and after sometime it gets out of the boundary. I want the velocity of this ball to NOT exceed a provided maxVelocity. Here i am sharing my project through google drive bounceProblem.unitypackage
0
Unity3D behaves differently in scene and game view We are having AI being able to shoot. Everything works fine when having them play in Scene view, but when going into Game view the position they are shooting from is different. Does anyone know what could cause this? That the Unity "Scene view" behaves other than "Game view"? Hope there's anyone there to help us out, thanks in advance.
0
Preventing a Child object (eg. some weapon) from going inside other objects in the scene? I have Cube with a sword like object as its child object. But when the cube moves in the scene the sword goes into the other objects in the scene. The sword have a BoxCollider attached to it but the scene contains objects that are stationary and don't have a Rigidbody attached as I don't want them to be controlled by physics, same for the sword. If I attach Rigidbody to it then it will be displaced from its main position on collision. I tried to render only the Cube including the sword with one camera having higher depth value then the main camera in the scene. If my game was in first person then this works fine but In 3rd person when object get behind other objects in the scene we can still see the object. How can I prevent the sword from going into other object without being controlled by physics? Image
0
How to disable gravity for a RigidBody moving on a slope? I created a script that handles movement for my player (moving around, going down and up slopes). However, since I'm using a RigidBody not a CharacterController when I go up slope and stop on the middle of it the gravity pulls me backward, which is fine, but the problem is when I move forward, the gravity force pulls me backward when I'm trying to go forward. This problem wouldn't have appeared if my character wasn't a sphere but my character is a sphere so it always roll down when gravity is applied to it. What I want is to somehow stop the gravity for a second or reset it to zero when I move my character, and when I'm going up a slope so it won't hold me back. I tried if(grounded) rb.velocity Vector3.zero but I don't think it's the right approach.
0
How to stop counting point when player dies (Destroy) In my game, I'd like to stop counting points when the player's y is 4. When the pink and red balls fall off the Plane the player gets points. But it seems a bit strange to be able to collect points after the player dies. This is the code for the player if (transform.position.y lt 4) Destroy(gameObject) gameManager.GameOver() And in the GameManager.cs I have this public bool isGameActive public void UpdateScore(int scoreToAdd) score scoreToAdd scoreText.text "POENG " score public void GameOver() isGameActive false restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) And this is the code for adding points when the enemies fall over the edge if (transform.position.y lt 4) Destroy(gameObject) gameManager.UpdateScore(pointValue) How can I make the game stop counting points when the player dies?
0
Unity3d Rigidbodies overlap even at low speeds I have an issue that I can't solve. There are many questions relating to similar issues and they come down to "change some settings" and "object is travelling too fast". My problem doesn't seem to equate to either of these. I am running through the basic tutorial for the Breakout Game and have added some of my own tweaks to the code, my issue is that even at low speed my ball overlaps with the bricks, rather than bouncing off them. I have read various related questions but nothing seems to fix this for me. Things I've done Set Project Settings Physics2d Maximum penetration For Overlap 0.0001 Set Ball RigidBody Collision detection to "Continuous Dynamic" . Set Brick RigidBody Collision Detection to "Continuous" Forced a speed limit on the ball of 25 15. Which I think is not fast at all, as most the given solutions are talking about situations arising when the offending object is travelling at much higher speeds. Bricks are standard rigidbody cubes and ball is a standard rigidbody sphere. According to this answer I have also set the rigidbody interpolation to "interpolation" for both ball and bricks. But this seems processor expensive and doesn't solve the issue. As well as set the Project Settings Physics Solver Iteration Count to 25. This does seem to have helped somewhat (ball no longer gets "stuck" inside brick wireframes, but still overlaps). Below are some screenshots of my issue and my code. The only aspect that I can't fully account for is that I've added an acceleration function so when ball is launched it accelerates over a course of several seconds to it's max speed. It's start speed is 8 (although the force applied is actually 1000 when launched, ignore that figure), and the max speed is set to 25 15. I don't know enough to say if this is somehow "breaking" rigidbody overlap detection but it seems pretty silly if so. See line 63 below Ball Source Code using UnityEngine using System.Collections public class Ball MonoBehaviour public float initialVelocity 500f public float accelerationSpeed 5f public float MaximumSpeed 15f private Rigidbody rb private bool ballInPlay false void Awake () rb gameObject.GetComponent lt Rigidbody gt () void Update () if (Input.GetButtonDown("Fire1") amp amp ballInPlay false) transform.parent null rb.isKinematic false rb.AddForce(new Vector3(initialVelocity,initialVelocity,0)) ballInPlay true void FixedUpdate () Gradually increase ball speed if (ballInPlay true amp amp rb.velocity.magnitude lt MaximumSpeed) speedUp() Debug.Log("Ball Speed is " rb.velocity.magnitude) Clamp to maximum speed if (ballInPlay true amp amp rb.velocity.magnitude gt MaximumSpeed) rb.velocity rb.velocity.normalized MaximumSpeed rb.velocity.magnitude void speedUp() This is line 63 rb.AddForce(rb.velocity.normalized accelerationSpeed,ForceMode.Acceleration) Why are the rigidbodies not detecting and preventing overlap?
0
How to reset scene (stage1) when selecting it from Level stagemain menu Good day I have a problem when the player finish stage 1 the screen look like this Then going back to selecting level When I try to play the stage 1 again. I want to reset the stage 1 so i can play it again. I only use Scene.LoadScene("stage1") in main menu to go to stage1 and Scene.LoadScene("mainmenu") to back to main menu
0
What makes a shader function with a LineRenderer? A LineRenderer has both Material and Color properties. But many shaders do not work, ie the line will not respect the Color property, or the line will show black (regardless of the materials having its own color). For example the Standard, Diffuse, Mobile Diffuse shaders all show black. Unlit Color ignores the LineRenderer color and uses only the Material Color property. Particles Additive works great, but Particles Standard Surface does not. What part of the shader code is important to make a LineRenderer display using its own Color property? When it does work, how should shader code decide how to merge between the two colors?
0
Looking for the best way to store game data that is meant to be user editable at runtime I have a broad question, hopefully I'll synthesize it well. I've been looking for the best way to store the standard data of my project. So far, I've found 4 possible answers to my problem Binary files, Json files, XML files and local DB(using SQLite). While the first 2 seems to be common sense for store data, I would still need some opinions about it, instead of create a bunch of content and code in vain. The chosen option must generate files that can be editable at runtime. Already used some XML files for basic saving and watched tutorials on Json and Binary files but I'm still uncertain about what road to take. I believe DB's are a different animal, but maybe it would worth for my case. To contextualize, my project is a sports game, so I must start to generate and store virtual players and teams. After that I need to link those virtual players at their respective teams. It happens that I would like to enable human players to edit those generated virtual players and teams attributes at runtime through some kind of editor. Furthermore, I want to enable human players to create their own virtual players and teams, so the chosen method must have scalability, so it's expected to have hundreds of teams and thousands of virtual players at some point. My target platform is PC, so file sizes and general performance isn't so critical as it could be on mobile for example. Anyway, hopefully my doubts are clear enough. It would be cool if someone have something to say, I would like to know the best choice for my case. PS Already take a look at these 2 questions How to choose how to store data? Would it be better to use XML JSON Text or a database to store game content? But most of it's answers have some years now and I still have doubts on this matter.
0
I have a game based on combining 2 ingredients to create a product. What is the best way to code this? (Unity) So to go a bit more in depth, in my game, you can combine a variety of ingredients to make a product. For example, you could combine water and dirt to make mud. What I am currently doing to achieve this is by listing each combination possibility that a particular ingredient has. The one thing i managed to do to make it a little more efficient is that I managed to remove duplicates (So for example, if i have coded ingredientA IngredientB Cheese, there isn't another entry for IngredientB Ingredient A Cheese). The problem I have with my method is that it is very annoying adding new ingredients. If i do so, I have to go back to every previous ingredient i have coded, and add it's interaction with the ingredient(s) i want to add. The amount of ingredients I have means this is becoming increasingly time consuming. Is there a better way to do this? This is a Unity game, coded in C . Let me know if you need any further info.
0
How to build a hidden 3D snapping grid effect? Looking to build a 3D grid similar to the image below taken from Google Blocks. Seems like it consists of these main components A set of spheres that can go transparent. A stencil that follows the controller's location. When stencil overlaps with spheres, they show up, otherwise, alpha fades to zero. Any advise on how to approach building this?
0
How to flatten the collider for a tilemap? I am relatively new to game development, and am working on a simple 2D platformer. I have created a tilemap and painted some tiles for the character to walk on.. but he is getting stuck. Yes, I know this is a common question and I did find some answers (including this one Player gets stuck on edges between TilemapCollider2D tiles), but none seem relevant for me. The thing is my tiles are not flat.. they have pointy edges due to grass.. see the image below As you can see, the edge is not flat. I have overcome the problem of getting stuck by changing the quot Edge Radius quot to what you see in the above screenshot and that works, but the character now looks like he is floating slightly above the ground. Is there any way I can just tell Unity to ignore the jagged grass and make the collider flat and move the edge of it down a bit? That way it would fix the issue and also have the added bonus of looking like some of the grass is behind him and some in front..
0
How do I include XML files in an Android build? I have a few XML files I want to include in a build of my game, and I want to have access to those XML files in Android. How to I store and load those XML files?
0
Changing contents of level depending on which character was selected I'm trying to create a character selection menu in Unity, where each character has their own version of the level that follows. There are about 10 characters. Each character has a different location where they spawn in the level, and each enemy has a different spawn position as well, depending on which character was selected. What I have been doing is to create separate levels (scene files) for each character. Then in the character selection menu, I load the level depending on the level selected by the user. This seems to be a lot of code and data repetition, as the scene is the same in all levels it's just that the spawn positions and enemies are different. Is there any way have only one level scene, and get the spawn position and enemy spawns based on the character? This is the code I have so far in GameManager.cs public GameObject enemy public Transform enemySpawnPoint public GameObject player public Transform playerSpawnPoint public static GameManager instance private void Awake() if (instance null) instance this void Start() StartCoroutine("SpawnEnemies") SpawnPlayer() IEnumerator SpawnEnemies() while (true) yield return new WaitForSeconds(1.0f) SpawnEnemy() public void SpawnEnemy() Vector3 enemySpawnPos enemySpawnPoint.position Instantiate(enemy, enemySpawnPos, Quaternion.identity) public void SpawnPlayer() Vector3 playerSpawnPos playerSpawnPoint.position Instantiate(player, playerSpawnPos, Quaternion.identity) ...and the character selection script public void Level1() SceneManager.LoadScene(1) public void Level2() SceneManager.LoadScene(2) ... public void Level10() SceneManager.LoadScene(10) Now the issue is, if I want to make any changes in one scene, like the skybox or background color, I will have to open all the other level scenes and make the changes. Another thing is that if I want to add new levels, I will have to do the same thing, which seems like a lot of repetition. Is there some way to set the enemy prefab, enemy spawn positions, player prefab and player spawn position once the character has been selected? For example, if the user clicks on level1, all the preceding variables are set automatically and so on.....
0
ScreenToWorldPoint problems in otherwise awesome Unity demo I am using this neat Unity demo I found on Stack Overflow, which demonstrates texture masking via RenderTexture Can you erase a texture in real time in Unity But the mapping from mouse position to world space is wrong. This is the script that does the mapping using UnityEngine using System.Collections public class MaskCamera MonoBehaviour public Material EraserMaterial private bool firstFrame private Vector2? newHolePosition private void CutHole(Vector2 imageSize, Vector2 imageLocalPosition) Rect textureRect new Rect(0.0f, 0.0f, 1.0f, 1.0f) Rect positionRect new Rect( (imageLocalPosition.x 0.5f EraserMaterial.mainTexture.width) imageSize.x, (imageLocalPosition.y 0.5f EraserMaterial.mainTexture.height) imageSize.y, EraserMaterial.mainTexture.width imageSize.x, EraserMaterial.mainTexture.height imageSize.y ) GL.PushMatrix() GL.LoadOrtho() for (int i 0 i lt EraserMaterial.passCount i ) EraserMaterial.SetPass(i) GL.Begin(GL.QUADS) GL.Color(Color.white) GL.TexCoord2(textureRect.xMin, textureRect.yMax) GL.Vertex3(positionRect.xMin, positionRect.yMax, 0.0f) GL.TexCoord2(textureRect.xMax, textureRect.yMax) GL.Vertex3(positionRect.xMax, positionRect.yMax, 0.0f) GL.TexCoord2(textureRect.xMax, textureRect.yMin) GL.Vertex3(positionRect.xMax, positionRect.yMin, 0.0f) GL.TexCoord2(textureRect.xMin, textureRect.yMin) GL.Vertex3(positionRect.xMin, positionRect.yMin, 0.0f) GL.End() GL.PopMatrix() public void Start() firstFrame true public void Update() newHolePosition null if (Input.GetMouseButton(0)) Vector2 v camera.ScreenToWorldPoint(Input.mousePosition) Rect worldRect new Rect( 8.0f, 6.0f, 16.0f, 12.0f) if (worldRect.Contains(v)) newHolePosition new Vector2(1600 (v.x worldRect.xMin) worldRect.width, 1200 (v.y worldRect.yMin) worldRect.height) public void OnPostRender() if (firstFrame) firstFrame false GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)) if (newHolePosition ! null) CutHole(new Vector2(1600.0f, 1200.0f), newHolePosition.Value) I fixed line 49 and 50 like so Vector2 v GetComponent lt Camera gt ().ScreenToWorldPoint(Input.mousePosition) Rect worldRect new Rect(0.0f, 0.0f, 16.0f, 12.0f) So the script compiles and the worldRect is in the right place now. Through debugging I found that the world coordinates returned on line 49 are off. I also tried setting the z value of mousePosition to 10, even though the cameras are orthographic, like so Vector3 mousePos Input.mousePosition mousePos.z 10 Vector2 v GetComponent lt Camera gt ().ScreenToWorldPoint(mousePos) The mapping from the mouse to worldspace is still wrong though. Mouse coordinates within a small rectangle near the center are mapping to the full width and height of the image in world space.
0
Get closest Child to cursor I'm currently rewoking my RTS cover system. This should highlight the closest coverspots from my mouse cursor and sent the units to these locations. everything works, but I can't get the closest sport, it always selects the sames ones, regardless to the mouse position. These cover spots are child objects of the obstacle, that has this script attached. This is my not working implementation of the idea void Update() var dist Mathf.Abs(transform.position.z Camera.main.transform.position.z) var v3Pos new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist) v3Pos Camera.main.ScreenToWorldPoint(v3Pos) mousePos v3Pos ... public void getPointDistances() foreach (CoverPosition pos in coverPositions) if (!pos.occupied) pos.distanceToCursor Vector3.Distance(pos.transform.position, mousePos) Array.Sort(coverPositions, delegate (CoverPosition x, CoverPosition y) return y.distanceToCursor.CompareTo(x.distanceToCursor) ) Later, I simply Iterate over the sorted array and make it visisible. I'm woking on this for hours, but i cannot find, a solution why it always displays the same cover spots. I hope, someone can find my (possibly stupid) error. Edit I also tried this, but tata returned always the same values, regardless of my mouse positioning Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) mousePos hit.transform.position
0
Import Unity Package Into Specific Folder Everytime i do import custom unity package file, I alwasy get Messy Folder and files in root of Asset Folder. Any Idea how to solve this ? Many Thanks in advance...
0
Keeping a Character Controller grounded? I've got a character that makes use of isGrounded() to determine whether I can jump, whether my air jump is reset, and the amount of friction to be applied. I've run into a common problem, isGrounded() is fluctuating every frame returning true and false randomly resulting in jagged movement. The standard suggestion is to constantly apply gravity. Unfortunately, aside from any other more nuanced issues that this could result in, this only works for me if I apply so much gravity that I am no longer able to climb up slopes. I need a way to keep the character grounded without applying large amounts of gravity every frame.
0
Rotating game object without using localEulerAngles I'm building a player controller. While aiming, the player can rotate the chest bone. This looks as if the character aims in different directions. The chest bone should only be allowed to rotate within a certain range. If this range is exceeded (either to the left or to the right), the chest bone should stay at its current rotation, and the player should be rotated instead. I'm having problems applying the desired rotation to the parent game object instead. I'm trying to work with the localEulerAngles in order to applying an additional Y rotation to the gameobject, but the Y rotation value tells me for example "359.9" while I expected to work with a value of 0. private void pHandle LateUpdate Aim() Quaternion oldNeckRotation Neck.transform.rotation Fade old input before capturing new, so we don't dull the freshest data. float yawBlend Mathf.Pow(1.0f Aim yawInputFalloff, referenceFramerate Time.deltaTime) A Lerp toward zero is just the same as a multiplication by the blend factor. Chest yawRate yawBlend Accelerate by mouse movement over the past frame. (May need adjustment for display resolution). Chest yawRate Input.GetAxis("Mouse X") float yawDelta Chest yawSpeed Chest yawRate Time.deltaTime float offCenterYaw Chest currentYaw Chest yawCenter float fDesiredChestYaw Chest currentYaw yawDelta float fHeroRotation 0f if (fDesiredChestYaw gt Chest rotateRange) the allowed chest rotate range would be exceeded. Instead, move the gameobject the parent. fHeroRotation (fDesiredChestYaw Chest rotateRange) fHeroRotation this.transform.localEulerAngles.y this.transform.Rotate(0, fHeroRotation, 0) return else if (fDesiredChestYaw lt Chest rotateRange) fHeroRotation (Chest rotateRange fDesiredChestYaw) fHeroRotation this.transform.localEulerAngles.y this.transform.Rotate(0, fHeroRotation, 0) return else If we're moving away from the center, slow down as we approach the edge. if (yawDelta offCenterYaw gt 0) float extremityYaw offCenterYaw Aim yawMaxRange yawDelta 1.0f extremityYaw extremityYaw fHeroRotation yawDelta Ensure we never overshoot the allowed range. Chest currentYaw Mathf.Clamp(Chest currentYaw yawDelta, Chest yawCenter Aim yawMaxRange, Chest yawCenter Aim yawMaxRange) Vector3 nNewChestRotation new Vector3(Chest.localEulerAngles.x, Chest currentYaw, Chest.localEulerAngles.z) Chest.localRotation Quaternion.Euler(nNewChestRotation) Quaternion newNeckRotation Neck.transform.rotation the neck should not rotate with the chest. So I first counter rotate it against the new chest rotation, then rotate it a little towards the chest rotation Neck.transform.rotation Quaternion.Lerp(oldNeckRotation, newNeckRotation, neckFollowChest)
0
Unity Quaternion Rotate Unrotate Error I'm trying to un rotate a quaternion, aligning it with the axis, and then rotate it back to where it was originally. But with every iteration it seems to lose precision and just after 20 iterations the rotation disappears. Here is an example, which is a simplification of my code Quaternion rotation Quaternion.Euler (0f, 90f, 0f) Debug.Log ("Before " rotation.ToString ("F7") " Euler " rotation.eulerAngles.ToString()) int iterations 1 for (int i 0 i lt iterations i ) var currentRotation rotation rotation Quaternion.Inverse (currentRotation) rotation rotation currentRotation rotation Debug.Log ("After " rotation.ToString ("F7") " Euler " rotation.eulerAngles.ToString()) With 1 iteration the output is Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7071067, 0.0000000, 0.7071067) Euler (0.0, 90.0, 0.0) With 5 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7071019, 0.0000000, 0.7071019) Euler (0.0, 90.0, 0.0) With 10 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7059279, 0.0000000, 0.7059279) Euler (0.0, 90.0, 0.0) With 15 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.4714038, 0.0000000, 0.4714038) Euler (0.0, 90.0, 0.0) And finally with 19 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.0000000, 0.0000000, 0.0000000) Euler (0.0, 0.0, 0.0) At the 19th iteration the euler angles becomes zero, and at previous iterations altough the euler angles are still correct, if I rotate a vector with the quaternion its magnitude is changed. I hope you can help me and sorry for my bad english!
0
How to create scene template? I'm creating a game with Unity 3D, where has many levels, and I want create a button in all levels, to back to level menu. Is possible can I create a "scene template" where I can only change one time, and all level scenes inherit template changes?
0
Cannot implicitly convert type 'T' to 'UnityEngine.Vector3' I'm trying to use C generics on a method in order to send a Vector3 (position) as a parameter. I can print the value correctly but can't store it on a local variable. I also can't access its x, y or z attributes separately. I'm implementing a state machine. My intention is to use generics for allowing sending different parameters to the different states. The value will be sent to an "Enter" method which will be called once on each state every time that state is set to active or current. So for example the player will be on the DefaultState something happens change state to HeroTeleportingState while sending it it's new position This is my Enter method on the HeroTeleportingState class void IState.Enter lt T gt (T newPosition) The following line prints the correct value Debug.Log("move this hero to " newPosition) The following lines don't work pos newPosition pos.x newPosition.x The method call is just something like currentlyRunningState.Enter(Vector3.one) pos newPosition gives me the following error on Visual studio (I'm paraphrasing cause my visual studio is in spanish) Cannot implicitly convert type 'T' to 'UnityEngine.Vector3' And pos.x newPosition.x gives me something like 'T' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type 'T' could be found EDIT IState interface public interface IState void Enter lt T gt (T value) void Execute() void Exit()
0
Instantiate and launch prefab that's overlapping player? I m very new to Unity and C . I m trying to create my first game and I have now invested about 15 hours trying to find solutions to this issue...I m stumped! My player sprite (blue square) needs to launch a prefab sprite (red circle) of similar size appearing to originate from itself. Here is a GIF of what I have so far...I don t want the blue cube to collide and go flying. After clicking and dragging on Player (drag to aim) via OnMouseDrag to set the target vector, I m trying to Instantiate a prefab sprite (Dynamic RigidBody2D, CircleCollider2D) using the Player sprite s position (a Dynamic RigidBody2D, BoxCollider2D) and have it APPEAR to be originating from inside the Player object. Launch is triggered via function called in OnMouseUp. Both objects should immediately come under control of Physics to collide with the environment which will include other moving RigidBody2D objects later. Targeting should allow 360 degrees to include straight into an obstacle allowing rebound effect. Here is some excerpts of my code using System.Collections using UnityEngine public class Teleportation Grenade MonoBehaviour This script is attached to Player and requires projectile prefab. tested with thrust set between 100 and 200. public float thrust public Transform prefab public LineRenderer playerShotLine private Vector2 playerToMouse private Vector2 targetVector ... void OnMouseDrag() Vector3 mouseWorldPoint Camera.main.ScreenToWorldPoint (Input.mousePosition) Vector2 playerToMouse mouseWorldPoint transform.position mouseWorldPoint.z 0f playerShotLine.SetPosition (0, transform.position) playerShotLine.SetPosition (1, mouseWorldPoint) playerShotLine.sortingOrder 3 opposite direction of line renderer targetVector playerToMouse void OnMouseUp() SpawnPrefab () void SpawnPrefab() Instantiate(prefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity) prefab.GetComponent lt Rigidbody2D gt ().AddForce (targetVector thrust, ForceMode2D.Impulse) This is only one of many, many iterations. It's the gist of it though. I appreciate any insight from the community.
0
Unity animations not playing where they are suppose to be Hello to all those Unity Developers out there, I am having a big issue with my game, what I am trying to do is to make a cutscene but when I change camera it just goes in a completely different spot. There are no scripting errors and the only thing that I have on the camera (Blender model) is an animator component that plays the animation when the DCT (Drone, Camera, Thing) flies into the room. Should I try to not equip the camera with the DCT model or should I remove the animator component?
0
Unity get component throwing NullReferenceException only in standalone build I'm having a very frustrating issue with GetComponent(). private void Show() var transition GetComponent lt TransitionAnimation gt () Debug.Log( "Transition transition ") transition?.FadeIn() In the editor, this works just fine. transition is not null and FadeIn() is called. In the standalone build, GetComponent() returns null, throws a NullReferenceException, and execution stops before it can even print transition to the console. This is the output from the log file. Uploading Crash Report NullReferenceException at (wrapper managed to native) UnityEngine.Component.get gameObject(UnityEngine.Component) at UnityEngine.Component.GetComponentInChildren (System.Type t, System.Boolean includeInactive) 0x00001 in lt e314adc5a7494b5f8760be75461a94d4 gt 0 at UnityEngine.Component.GetComponentInChildren T (System.Boolean includeInactive) 0x00001 in lt e314adc5a7494b5f8760be75461a94d4 gt 0 at Winglett.RR.UI.Gradient.Show () 0x00001 in Users redacted Documents repos radical relocation Assets Core Scripts UI Gradient.cs 63 at (wrapper delegate invoke) lt Module gt .invoke void() at Winglett.RR.Gameplay.GameState.SetPause () 0x00001 in Users redacted Documents repos radical relocation Assets Core Scripts Gameplay GameState.cs 46 at Winglett.RR.Gameplay.GameState.SetPause STATIC () 0x00000 in Users redacted Documents repos radical relocation Assets Core Scripts Gameplay GameState.cs 70 at Winglett.RR.UI.Wrapper.SetGameStatePause () 0x00000 in Users redacted Documents repos radical relocation Assets Core Playground ui Wrapper.cs 27 at UnityEngine.Events.InvokableCall.Invoke () 0x00011 in lt e314adc5a7494b5f8760be75461a94d4 gt 0 at UnityEngine.Events.UnityEvent.Invoke () 0x00023 in lt e314adc5a7494b5f8760be75461a94d4 gt 0 at Winglett.RR.Utils.ESCButton.Update () 0x00026 in Users redacted Documents repos radical relocation Assets Core Scripts Utilities Other ESCButton.cs 21 I wondered if the issue might be because the gameobject is disabled. So I tried GetComponentInChildren lt TransitionAnimation gt (true) where true is an overload for inactive gameobjects. This didn't change anything.
0
How to align angular velocity wit target rotation in 3D? I'm making a space crew sim (controlling a ship) and have recently posted a question about how to calculate ETA between two rotations. I how now a new question more well defined. Background I have Qtarget and Qcurrent(the ships rotation) and can find Qdelta using Qdelta Qcurrent 1 Qtarget. And I have the angular velocity in rotation speed around the world axis from the Unity. I want to control the ship only using delta angular velocity around ships axis. I want to get the angular velocity aligned with Qdelta so i can just use that angular velocities e.g. x part and the angel to solve for if I should accelerate or decelerate and just decelerate along the y and z axis. After that I want to rotate that data back to ship rotation. I have this test code using UnityEngine using System.Collections public class RoationTest MonoBehaviour public Vector3 startAngularVelocity new Vector3() public Vector3 targetRoation new Vector3() public Vector3 maxShipDeltaAngularVelocity new Vector3() Use this for initialization void Start () rigidbody.angularVelocity startAngularVelocity Mathf.Deg2Rad rigidbody.WakeUp() Update is called once per frame void Update () Vector3 currentAngularVelocity rigidbody.angularVelocity Mathf.Rad2Deg This seams to work Quaternion deltaRoationQuat Quaternion.Inverse(rigidbody.rotation) Quaternion.Euler(targetRoation) This seams to work float deltaAngel Quaternion.Angle(rigidbody.rotation,Quaternion.Euler(targetRoation)) This seams to work Vector3 xAxis new Vector3(1,0,0) Vector3 deltaRotationAxis deltaRoationQuat.eulerAngles Vector3 deltaRotationAxisClampedToShortestDist ClampEulerAngelsToClosest(deltaRotationAxis) Quaternion AlignQuat Quaternion.FromToRotation(deltaRotationAxisClampedToShortestDist, xAxis) Vector3 angularVelocityAligend AlignQuat currentAngularVelocity This should be Quaternion.Inverse(AlignQuat) currentAngularVelocity But that does not work as I think I should but this do. Vector3 maxDeltaAngularVelocityGlobalRotaion rigidbody.rotation maxShipDeltaAngularVelocity Transform max delta angular velocity from ship rotation to global space. The same as maxShipDeltaAngularVelocity Quaternion.Inverse(rigidbody.rotation) but Unity do not suport that. Vector3 maxAlignedDeltaAngularVelocity AlignQuat maxShipDeltaAngularVelocity private Vector3 ClampEulerAngelsToClosest(Vector3 rotation) if(rotation.x gt 180) rotation.x rotation.x 360 if(rotation.y gt 180) rotation.y rotation.y 360 if(rotation.z gt 180) rotation.z rotation.z 360 return rotation Questions Why do this Vector3 angularVelocityAligend AlignQuat currentAngularVelocity align y axis with x axis? It should be Vector3 angularVelocityAligend Quaternion.Inverse(AlignQuat) currentAngularVelocity in my understanding. Also how can Vector3 maxDeltaAngularVelocityGlobalRotaion rigidbody.rotation maxShipDeltaAngularVelocity be right? General thoughts Is this clear enough or am I taking the wrong approach? I general words I want to find the optimal solution in every frame on how to reach target rotation only using delta angular velocity limited by a max value (the ships engines effect) and also receive and ETA. I understand this is an approximation I state above since i assumes no rotation perpendicular to Qdelta but this solution will do for a start.
0
How can I check if component is enabled? using System.Collections using System.Collections.Generic using UnityEngine public class CameraInformation MonoBehaviour public string currentCameraState Start is called before the first frame update void Start() var components new List lt Component gt () foreach (var component in GetComponents lt Component gt ()) if (component ! this) var fullName component.GetType().FullName if (fullName.StartsWith( quot Cinemachine quot )) currentCameraState component. Update is called once per frame void Update() private void OnEnable() private void OnDisable() At this line I want to assign the string the component status if it's enabled true or false.
0
Generate random number in Unity without class ambiguity I have a problem in Unity (C ) where I would like to create a random number. I wanted to use System.Random (reference using System) but Unity complains that it's ambiguous to their own UnityEngine.Random. I can not specify the reference (using System.Random) as random is not a namespace. How do I specify that I want to use the system random and not the Unity one?
0
Referencing Tilemap inside Grid Prefab I have a prefab of a grid which contains 3 different tilemaps Main, Foreground, amp Background I want to reference the tilemaps inside a script of the prefab but can't figure out how to do that... I just need to edit the tiles in the tilemaps located inside the prefab.
0
Replacing keycode by UI Buttons doesn't work I have tried everything but it still doesn't work. I am not talking about implementing functions wich has stuff inside when you click the UI Button. I want literally replace this Input.GetKeyDown(KeyCode.E). That is inside an if statement and replace with the UI Button object. How can i do this? I have tried with GetButton, GetButtonDown, trying to give a name and with Input.touchCount 0 I am developing a game like Resident Evil old style and when you enter a triggerStay and push the button, a text is showing up. The Script using System.Collections using System.Collections.Generic using UnityEngine.UI using UnityEngine.EventSystems using UnityEngine public class readingNote MonoBehaviour public AudioSource audio public AudioClip collectSound public bool playerNextToKey false bool hasCollided false public GameObject pic public GameObject text public GameObject notePad public Button yourButton void Start() pic.SetActive(false) text.SetActive (false) Button btn yourButton.GetComponent lt Button gt () btn.onClick.AddListener(TaskOnClick) void TaskOnClick() THIS IS SHOWING ALL TEXT IN THE SCENE AND NOT ONE BY ONE WHEN PRESSING text.SetActive (true) pic.SetActive(true) void OnTriggerStay ( Collider other) if(other.gameObject.tag "Player") if(Input.GetKeyDown(KeyCode.E)) if(Input.touchCount gt 0) text.SetActive (true) pic.SetActive(true) AudioSource.PlayClipAtPoint(collectSound, transform.position) void OnTriggerExit ( Collider other ) if (other.gameObject.tag "Player") enter false print("close") playerNextToKey false hasCollided false pic.SetActive(false) text.SetActive (false)
0
Rotate an object with 'Quaternion.Slerp' in world space I'm currently working on a multiplayer skydiving Unity game in which i rotate the players like this transform.rotation Quaternion.Slerp(transform.rotation, desiredRotation, delta) Now this rotates the player relative to it's own rotation. I know rotation in world space is done by multiplying the quaternion of the desired positon with the quaternion of the current position like this localRotation transform.rotation desiredRotation worldRotation desiredRotation transform.rotation But how do i slerp to that position in world space? Thank you all in advance and have a great day!
0
My trigger does not detect my player My trigger does not detect my player. My Trigger.cs file using UnityEngine public class Trigger MonoBehaviour public Camera camera1 public Camera camera2 public GameObject panel void OnTriggerEnter(Collider other) camera1.enabled false camera2.enabled true panel.SetActive(true) Debug.Log ( quot Entered quot ) void OnTriggerExit(Collider other) camera2.enabled false camera1.enabled true panel.SetActive(false) private void Update() if(Input.GetKeyDown(KeyCode.DownArrow) Input.GetKeyDown(KeyCode.S)) panel.SetActive(false) Where I can start troubleshooting te issue? Object on which the trigger script is sitting on. The solution I created two colliders, and assigned one as a collider, the other (bigger) is a trigger. I also had problems with the small triggers in the scene. The triggers were to small to be detected by my main player, althought they detected my quot sphere quot player object
0
How to move player out of multiple penetrating colliders? The player in my game can teleport like Noctis from ffxv.The player shots a weapon projectile and then teleports to the projectile. I'm using raycast to calculate the weapon position after thrown. However, I need to check if the weapon is stuck in an unteleportable position after being thrown. It is possible to have multiple penetrating colliders. Ex spear gets sandwiched between two walls that is narrow enough for the weapon to pass through but not tall enough for the player to stand. I want to somehow check for a nearby valid position for after teleporting in that situation. I also want the teleport to fail if the weapon is horizontally in the middle of the "pipe". I could do a bunch of overlapBox checks within a radius distance from the teleport point but that doesn't seem efficient. I want to give the player some leeway when aiming a teleport. Also, the teleport is not immediate. The player can wait some time before teleporting to the weapon. So it is possible for a moving platform to block a raycast from the player. In which case I still want the raycast to succeed. I'm using unity and a custom raycast based 2d character controller for normal movement.
0
Position GUI Text in 2D game I am working on a 2D game, and my camera is a orthographic with a size of 320. I want to display some text, but not with OnGUI(). Rather, with a GUI Text game object. I couldn't help but notice that positioning my GUI Text object is a real pain apparently, the onscreen coordinates where the text appears range from 0 to 1. That is, 0.5 is the center of the screen. If I wanted to put my label at exactly (100,50) regardless of the screen size, I would have to calculate something like (100f Screen.width, 50f Screen.height) Is there a way to tell the GUI Text to appear at the actual transform position as it appears on the scene editor? Currently, if you move the GUI Text game object's transform slightly to the right, the rendered text will be displaced a LOT to the right instead...
0
Get MouseUp event outside of Sceneview scene window? So I have an editor script that uses a dragging operation which works quite nicely. Except, if you release the button while OUTSIDE the Scene Window, the event doesn't register. How do I detect mouseup outside of the scene window? private static void OnScene(SceneView sceneview) Event e Event.current if (e.type EventType.MouseDrag) do some drag stuff e.Use() if (e.type EventType.MouseUp amp amp e.button 1) is the Right Mouse button released? I suspect somehow it's due to my Event e being inside the OnScene making the mouse actions only existing in the context of the Scene Window perhaps? I have no idea, very new to Editor scripting...
0
C invoke stops unity I'm making a game where in needs to randomly generate objects on a plane, so I setup a code to spawn Food, but whenever I run the code Unity uses up all my computers memory and 40 cpu. I have a fairly good computer and have no issue with anything else in the project. The code has worked when I called it in FixedUpdate but as soon as I try and call it in an invoke it just breaks everything. I have only started working with unity for less than 24 hours so I don't really know what could be wrong, since I didn't get any errors or warnings. using System.Collections using UnityEngine public class SpawnFood MonoBehaviour public Rigidbody Food public float x public float y public float z public Vector3 pos public float spawnTime void FixedUpdate() Start Invoke("FoodSpawn", spawnTime) goto Start void FoodSpawn() x (UnityEngine.Random.Range( 110f, 110f)) z (UnityEngine.Random.Range(0.50f, 0.51f)) y (UnityEngine.Random.Range( 50f, 51f)) Vector3 pos new Vector3(x, z, y) Instantiate(Food, pos, Quaternion.identity)
0
Why occlusion culling isn't working? I've bought a 3d model from a 3d marketplace. It is a big interior scene. I've imported the single FBX into Unity, added some collider, changed materials (6 7 materials) etc. There are hundreds of child object mesh Despite what my camera is looking, i noticed Unity is rendering 3 400K tris. Why Occlusion Culling isn't working ? Maybe importing a single huge Fbx isn't the right practice ? Thanks This image is my player looking at a black wall... 360K tris rendered !!!!
0
Unity WebGL Build Why it shows only Empty Folder? i'm trying to built my game, made in Unity 2018.3, and i'm trying to built it in WebGL, but the problem is this built was succeeded, but the Folder is still Empty, and here is the problem occured This was never happened to me before. anybody know how to fix it?
0
How to find or compute or look for overall max RPM by simply checking for rotation? I find it hard to determine the wheel RPM since I'm only making a simple 2D game of rotating object via Z axis. I wanna try this solution but I got no change since I'm trying to find the RPM from a game object that has a rigid body 2D and a circle collider. I decided to think of something more simple but alternate solution. I'm a bit good at math but not much. Took around to calculate but no luck yet. I want to know possibilities of checking its rotation from transform properties, figuring out yet about 6 degrees per second equivalent to 1 RPM as said from the link. I used the method transform.Rotate() for rotation speed. Also, when the rotation value reaches beyond 360, clockwise or counter clockwise, sometimes it goes back either 0 or a negative value and I have to maintain total degree so that I can compute for the overall RPM. Please help me. Re direct from my original question http answers.unity3d.com questions 1123755 how to find or compute or look for overallmax rpm.html
0
Unity3D Android Move your character to a specific x position I want to move my character (which is a cube for now) to a specific x location (on top of a flying floor ground thingy) but I've been having some troubles with it. I've been using this script var jumpSpeed float 3.5 var distToGround float function Start() get the distance to ground distToGround collider.bounds.extents.y function IsGrounded() boolean return Physics.Raycast(transform.position, Vector3.up, distToGround 0.1) function Update () Move the object to the right relative to the camera 1 unit second. transform.Translate(Vector3.forward Time.deltaTime) if (Input.anyKeyDown amp amp IsGrounded()) rigidbody.velocity.x jumpSpeed And this is the result (which is not what I want) https www.youtube.com watch?v Fj8B6eI4dbE Does anyone have any idea how to do this? I'm using UnityScript (Javascript).
0
How to store a Transform , grid in an ArrayList? I am new to Unity game dev and trying to expand my knowledge of data structs. I'm building a match 3 game, and I currently have a multi dimensional ArrayList holding transform coordinates on a grid of x width and y height. I have game objects tied to these coordinates in world space, with the grid syncing the data back in game space. I am attempting to push these coordinates into the nested list (familyList) to be deleted pending 3 or more units being added to familyArrayList (seen below). Here's the abridged code private static Transform , grid new Transform width, height public static ArrayList familyArrayList new ArrayList() Go through game grid line by line and add game objects from game space into family ArrayList for (int y height 1 y gt 0 y ) for (int x 0 x lt width x ) if (grid x, y ! null) Add grid x, y to familyArrayList familyArrayList.Add(grid x, y ) Debug.Log(familyArrayList 0 ) Output Green Unit(Clone) (UnityEngine.Transform) How can I get familyArrayList to properly story the grid coordinates and not the game object the grid coordinates are referencing? i.e. familyArrayList 0 '3,4' Should I instead use a nested list? At a later point in the code, I want to clear the game object from the board in world space as well as set the grid x,y to null Loop through all family array and destroy game objects foreach (var x in familyArrayList) Destroy(familyArrayList(x).gameObject) Loop through all family array and set their values to null in grid as well foreach (var x in familyArrayList) familyArrayList(x) null But I get errors like "Argument 1 cannot convert from 'object' to 'int'" and "Non invocable member 'Piece.familyArrayList' cannot be used like a method" which I can imagine are explained by my above problem of not storing the grid coordinates properly and instead storing the referenced game object. I'm truly stumped on this problem and thank anybody in advance who can point me in the right direction to solving this.
0
When creating an FPS style game, how should the iron sights be setup? I am working on creating an FPS style game for learning purposes. I previously was using self created animations for aiming down the iron sights of a gun. The animation would play when you zoom to iron sights and it would hold it there as long as you have the mouse held down. However, talking to a high rated designer, he told me usually it is done with a second camera that sits perfectly aligned with the guns iron sights. I would imagine you would still have to have an animation that then transitions you into that iron sight camera though. Now my animation works fine but I feel I may run into a problem later down the road if I am approaching it the wrong way from the start. Can someone verify the right way to do this and explain why it is?
0
Hide move the Particle Effect panel on the Scene view window The problem for example is if I want to drag the particle system object to the bottom right corner of my view, then it goes behind the Particle Effect panel. Is there any way to do hide or move this panel in editor mode and or in runtime mode?
0
Why does physics not behave consistently in Unity? I'm making a game in which AI players throw a ball. In the screenshot, you can see the arena which is separated by a net in the middle. Each side of the arena has 6 players belonging to one of 2 teams. Right now, one of the players on the right side has the ball (the top right player). He is going to throw the ball to the left side. According to my code, the ball should always land on the same place, because the player always applies the same force to the ball. However, I have noticed that the ball doesn't always land in the same place. I have marked where I've seen the ball land with several red circles. Interestingly, on my main PC, the ball almost always lands on the right most circle. It rarely lands on the other circles, although that does happen. On 3 other PCs I've tested this game on, however, the ball most often lands on the legs of the top left player, sometimes on his head or behind him, but never on the right most circle (in front of him). My game relies heavily on physics. The AI is supposed to calculate how to throw the ball to get it to land on a very specific location, as well as guess where it'll land depending on the ball's position and movements. If the physics don't behave consistently on all machines all the time, how is the AI supposed to calculate all of this accurately? Here is the code in charge of throwing private IEnumerator Serve() var ball GameObject.Find("Ball").GetComponent lt BallController gt () if (ball.ServingPlayer ! this) yield break yield return new WaitForSeconds(3) Vector3 shootDirection transform.forward.normalized var q Quaternion.AngleAxis( 45, transform.right) ball.RigidBody.AddForce(q shootDirection 20f, ForceMode.VelocityChange) As you can see, the ball is always thrown "forward" (facing the net) at a 45 upward angle, using a normalized vector and a constant speed (20f). Before each throw, the position of the players is reset to the exact same location (and rotation) they are seen on the screenshot. player.transform.localEulerAngles new Vector3(0, playerRotation, 0) player.transform.position startingposition posOffset In this case, playerRotation is either 90f or 90f depending on which side the player is on, startingposition is their "horizontal" position (relative to the net), and posOffset is their "vertical" position. The ball has its velocity and angular velocity reset, but not its rotation (since it's a sphere, its rotation shouldn't influence anything). Its position is also set to a fixed location relative to whichever player has to serve the ball. rb.velocity Vector3.zero rb.angularVelocity Vector3.zero transform.position ServingPlayer.ServingPosition Here, rb is the ball's RigidBody. Finally, I am not influencing the ball's movement in any way. I simply apply a force to it when serving, which happens only once. 3 seconds after the ball lands, the match is reset and everything repeats. The flow is basically like this (pseudocode) Start() ResetCourt() StartCoroutine(Players 0 .Serve()) event BallLanded() wait for 3 seconds repeat starting with ResetCourt() I really need the ball's trajectory to be reproducible every single time on every possible machine. Obviously I'm doing something wrong here, but what?
0
Combining mesh on the fly without using gameObject I procedurally generate chunks and use the marching cube algorithm to create meshes in 3D. At first, I just created a gameObject for each cube (of course, I knew it was not optimized, but I wanted to see if the algorithm worked). For now I stock all gamesObject in child of "blocks" but it would be much more optimized to directly merge the meshes between them and only create a single gameObject. However, i did not find any way to directly merge the meshes between them. So my question is is there a way to directly merge meshes between them without having to use gameObject? (don't worry about texturing) Here's the code public static GameObject GenerateChunk(int ,, map, int chunkSize, Vector3 chunkPosition) GameObject blocks new GameObject("BlockList") GameObject newMesh int cubeVertices new int 8 create each mesh in a gameObject as child of "blocks" for (int x 0 x lt chunkSize x ) for (int z 0 z lt chunkSize z ) for (int y 0 y lt chunkSize y ) define the vertices (cubeVertices) Vector3 cubePosition new Vector3(chunkPosition.x x, chunkPosition.y y, chunkPosition.z z) newMesh GenerateCube(cubePosition, cubeVertices) if (newMesh ! null) newMesh.transform.parent blocks.transform combine every children of "blocks" and delete them MeshFilter filters blocks.GetComponentsInChildren lt MeshFilter gt () List lt CombineInstance gt combine new List lt CombineInstance gt () for (int i 0 i lt filters.Length i ) if (filters i .sharedMesh null) continue for (int j 0 j lt filters i .sharedMesh.subMeshCount j ) CombineInstance ci new CombineInstance mesh filters i .sharedMesh, subMeshIndex j, transform filters i .transform.localToWorldMatrix combine.Add(ci) Destroy(filters i .gameObject) create the chunk and set the final mesh with the CombineMeshes function GameObject chunk new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer)) chunk.GetComponent lt MeshFilter gt ().mesh.CombineMeshes(combine.ToArray(), true, true) Destroy(blocks) return chunk
0
How do I make function on user clicked on close button Ads reward? So I'm here want to make function when the user closed the Ads before video ads end, the function is stopping or revert, in this case, I'm using ienumerator methods, but I don't know how to add the handler on Ads, because I already using HandleRewardClosed method not like I want but because its same with user watch the vid till end not closed the videos before ended . public void loadRewardVideo() rewardedAd.LoadAd(new AdRequest.Builder().Build(), rewarded Ad ID) rewardedAd.OnAdLoaded HandleRewardedAdLoaded rewardedAd.OnAdClosed HandleRewardedAdClosed rewardedAd.OnAdOpening HandleRewardedAdOpening rewardedAd.OnAdFailedToLoad HandleRewardedAdFailedToLoad rewardedAd.OnAdRewarded HandleUserEarnedReward rewardedAd.OnAdLeavingApplication HandleOnRewardAdleavingApp rewarded video events public event EventHandler lt EventArgs gt OnAdLoaded public event EventHandler lt AdFailedToLoadEventArgs gt OnAdFailedToLoad public event EventHandler lt EventArgs gt OnAdOpening public event EventHandler lt EventArgs gt OnAdStarted public event EventHandler lt EventArgs gt OnAdClosed public event EventHandler lt Reward gt OnAdRewarded public event EventHandler lt EventArgs gt OnAdLeavingApplication public event EventHandler lt EventArgs gt OnAdCompleted Rewared events public void HandleRewardedAdLoaded(object sender, EventArgs args) Debug.Log( quot Video Loaded quot ) public void HandleRewardedAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) Debug.Log( quot Video not loaded quot ) public void HandleRewardedAdOpening(object sender, EventArgs args) Debug.Log( quot Video Loading quot ) public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args) Debug.Log( quot Video Loading failed quot ) public void HandleRewardedAdClosed(object sender, EventArgs args) Debug.Log( quot Video Loading failed quot ) StartCoroutine(ClosedAds()) IEnumerator ClosedAds() GameManager.instance.isGameOver true yield return new WaitForSeconds(.05f) GameManager.instance.isStarted false Time.timeScale 0 FirebaseRemoteConfig.instance.DisplayAds() GameManager.instance.ShowingGameOverPanel() GameManager.instance.pauseBtn.SetActive(false)
0
Why are my colliders offset on my isometric map? I'm building an isometric environment in Unity and having some trouble with my colliders aligning with what shows in the scene editor to the reality in gameplay. There is nothing in the collider component to indicate that it should have any offset, or that there is anything at play other than the default settings. This goes for all types of 2D colliders I should add. I did try a 3D collider just out of curiosity, and nothing happens at all. This has been my experience with multiple objects, not only the one I've highlighted in the picture below. I'm using the Adventure Creator add on if that makes any difference.
0
Ways to improve endless racing traffic I am looking for ways to improve my traffic AI for endless racing game. Currently, I have hard coded situations where randomly cars will be spawned ahead of user bike depending on position of player. The thing most bothering me is how to provide user challenging situations where he will feel fun to play. Good example of such AI can be found here, https www.youtube.com watch?v CJozc6PA9lI What are the ways you guys would go on implementing Traffic AI for endless racing? What's your suggestion on same.
0
How can I reference for a two cameras on prefab through script? I have this script for controlling the cameras using System.Collections using System.Collections.Generic using UnityEngine public class CamerasViewSwitch MonoBehaviour public List lt Camera gt cameras new List lt Camera gt () public string currentViewMode Start is called before the first frame update void Start() if (cameras 0 .enabled) currentViewMode quot Third Person quot else currentViewMode quot First View quot Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.V)) cameras 0 .enabled !cameras 0 .enabled cameras 1 .enabled !cameras 1 .enabled if (cameras 0 .enabled) currentViewMode quot Third Person quot else currentViewMode quot First View quot In the Assets, I have a prefab with two children's cameras that I want to use in this script. In this screenshot to show what I mean, I dragged the prefab name Platform to the hierarchy to show where the cameras are. The script is on the object name Cameras Switch. How do I get these two cameras from the prefab and using them in the script? I'm using the Platform prefab with this script but the problem is when I'm starting the game the CamerasViewSwitch script is missing the two cameras I'm not to get find them.
0
NavMesh going in the ground I'm trying to do a navmesh. Everything seems to work fine exept that my character in almost completely under the ground. The ground is a plane with a mesh collider. I have baked it and checked my heigth mesh. My character has a rigidbody and a collider. What could be the problem ?
0
Unity Giving following error NullReferenceException Object reference not set to an instance of an object im going to probably look really stupid and i will be no means admit this is my code however i cant seems to get it to work so i was wondering you you might be able to? I'm getting the following error when trying to break a block with the left click button in unity "NullReferenceException Object reference not set to an instance of an object Player.Update () (at Assets Scripts Player.cs 67)" the code that is causing the error is below if (Input.GetMouseButtonDown(0)) Vector3 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) RaycastHit2D hit Physics2D.Raycast(mousePos, Vector2.zero) if (hit.collider.gameObject ! null) Destroy(hit.collider.gameObject) else Debug.Log("hit nothing") i've searched around for other ways to do this and after many itterations i cant seem to get it working still so i have come to the forms. Sorry line 67 is Camera.main.ScreenToWorldPoint(Input.mousePosition) i know it looks simular to other questions however i have looked at the link that was attached to this being a duplicate and i cant see anything in there that will help me so i am still stuck with the same issue.
0
Unity OnCollision() not working Seem to have exhausted google looking for an answer to a VERY bullet simple code that should work. void onCollisionEnter(Collision col) print ("hit " col.gameObject.name) Destroy (gameObject) Bullet object has the above script, SphereCollider (radius a lot bigger than object), RigidBody, not a trigger, not kinematic, is travelling slow. All checked during runtime. When it hits a wall (Box collider), it just bounces off but no collisionEnter code is ran. Debug console bubble is on.
0
Sprite won't change with direction I am making a top down Pacman game. I have two sprites one for facing up and one for facing left. When I press W, the sprite showing is still the one for when Pacman is moving left, but I want to see the up sprite instead. using System.Collections using System.Collections.Generic using UnityEngine public class pacman MonoBehaviour public int speed Vector2 dest public Transform points Start is called before the first frame update void Start() dest transform.position speed 25 Update is called once per frame void FixedUpdate() Vector2 p Vector2.MoveTowards(transform.position, dest, speed) GetComponent lt Rigidbody2D gt ().MovePosition(p) Check for Input if not moving if (Input.GetKey("w")) transform.position Vector3.MoveTowards(transform.position, points 0 .position, speed Time.deltaTime) gameObject.GetComponent lt SpriteRenderer gt ().sprite GameObject.Find("up").GetComponent lt SpriteRenderer gt ().sprite if (Input.GetKey("d")) transform.position Vector3.MoveTowards(transform.position, points 2 .position, speed Time.deltaTime) if (Input.GetKey("s")) transform.position Vector3.MoveTowards(transform.position, points 1 .position, speed Time.deltaTime) if (Input.GetKey("a")) transform.position Vector3.MoveTowards(transform.position, points 3 .position, speed Time.deltaTime) gameObject.GetComponent lt SpriteRenderer gt ().sprite GameObject.Find("left").GetComponent lt SpriteRenderer gt ().sprite
0
Unity build issue GooglePlayGamesManifest and GameServicesManifest I have added leaderboard to my unity game for which I have used the google play services plugin. But when I try to build, this is the error I get Execution failed for task 'processReleaseManifest'. gt Manifest merger failed Attribute meta data com.google.android.gms.games.APP ID value value ( 728999946156) from unityLibrary GameServicesManifest.plugin AndroidManifest.xml 10 13 42 is also present at unityLibrary GooglePlayGamesManifest.plugin AndroidManifest.xml 20 13 46 value ( u003728999946156). Suggestion add 'tools replace quot android value quot ' to lt meta data gt element at AndroidManifest.xml 8 9 10 45 to override. Here's what's in the first manifest file lt ?xml version quot 1.0 quot encoding quot utf 8 quot ? gt lt ! This file was automatically generated by the Google Play Games plugin for Unity Do not edit. gt lt manifest xmlns android quot http schemas.android.com apk res android quot package quot com.google.example.games.mainlibproj quot android versionCode quot 1 quot android versionName quot 1.0 quot gt lt uses sdk android minSdkVersion quot 14 quot gt lt application gt lt ! The space in these forces it to be interpreted as a string vs. int gt lt meta data android name quot com.google.android.gms.games.APP ID quot android value quot u003728999946156 quot gt lt ! Keep track of which plugin is being used gt lt meta data android name quot com.google.android.gms.games.unityVersion quot android value quot u0020.20.20 quot gt lt activity android name quot com.google.games.bridge.NativeBridgeActivity quot android theme quot android style Theme.Translucent.NoTitleBar.Fullscreen quot gt lt application gt and the second file lt ?xml version quot 1.0 quot encoding quot utf 8 quot ? gt lt manifest xmlns android quot http schemas.android.com apk res android quot package quot com.google.example.games.mainlibproj quot gt lt application gt lt meta data android name quot com.google.android.gms.games.APP ID quot android value quot 728999946156 quot gt lt activity android name quot com.google.games.bridge.NativeBridgeActivity quot android theme quot android style Theme.Translucent.NoTitleBar.Fullscreen quot gt lt application gt lt manifest gt
0
How can I create color fonts to be used in Unity? I've been searching, downloaded a couple programs that lets you convert images into fonts, but none let you obtain the color. They all switch them to black and white. While searching the internet, I found a few colored fonts. Yet, almost all games have their own fonts that are colorful. How do they do it? Did they just opt to program the font with coded position and sizes? I'd just like to make my own true type or open type font (ttf or otf) from some images I created. And the images aren't even that colorful, just fill and stroke color.
0
Unity Animate Sprite Shape Sprite? Is it possible to animate a sprite shape? I don't see the Sprite Shape Profile in the animator properties, so I was just wondering if there's another way to do that. To clarify Our game is 2D animated by hand, and one level has conveyor belts that span the level. We can animate it normally, but that will end up taking more video memory than if we were able to animate the conveyors as tiled sprite shapes. It may not end up being worth the effort to save the memory, but I figured it was worth a shot. Because the sprites span the level, they end up taking up lots of space in a sprite atlas.
0
Unity Main manifest has but library uses minSdkVersion '17' I got this error message when trying to build and run for Android. Error Temp StagingArea AndroidManifest main.xml 22, Users MNurdin Documents unity TangoMotion Temp StagingArea android libraries google unity wrapper AndroidManifest.xml 3 Main manifest has but library uses minSdkVersion '17' UnityEditor.BuildPlayerWindow BuildPlayerAndRun() Where I can set android minSdkVersion inside Unity? I'm using Unity5 right now. Please advice.
0
Servers do not remove spawned prefab after disconnection I built a multiplayer game with the Unity UNET. For doing this I bought a VPS server. Everything works fine. But sometimes when players want to quit the game, the servers do not destroy him from the scene!!! amp the other players still can see him in the scene till the servers being restarted and ran again!! For quitting the game I wrote this code NetworkManagers.singleton.client.Disconnect() Destroy(NetworkManagers.singleton.gameObject) For more explanation, this is my ConnectionConfig for server amp client MinUpdateTimeout 15 ConnectTimeout 1200 DisconnectTimeout 2000 PingTimeout 500 NetworkDropThreshold 50 OverflowDropThreshold 50 AckDelay 32 AcksType 1 MaxSentMessageQueueSize 150 Why this happening?! Did I miss something?! amp how can I avoid that?!
0
Loading a heavy scene behind some loading screen in unity Is there a way to load a heavy built scene behind a loading screen in unity to not make the game look like stuck loading the scene rather show the player some loading bar that would help the player think some background process is happening. any sites or vidoes that describe about this would be a great help! Thanks!
0
Unity Rigidbody sitting on top of another Rigidbody does not move with the Rigidbody its sitting on I have a mesh with a rigid body that moves back and forth like a platform. Other rigidbodies fall onto the upper surface of this cube. The problem I have is that when the platform rigid body moves the other rigid bodies stay in the position they landed in, they do not move with the cube. Everything else physics wise works. I have tried adding a physicsmaterial to both the platform and the rigidbodies falling onto the platform but this made no difference. I do no want to tether them to each other because I want them to fall off when they are pushed by other objects. The platform is moved back and forth using the RigidBody.MovePosition function.
0
Multiple Input.GetKeyDown happens in low frame rate There is a code that needs to be invoke each time user pressed specific button in my game. So I used Input.GetKeyDown to achieve that, but some reason, that code invokes multiple times even I keep pressing the button. After some tests, I figured out this happens a lot when the game has low frame late. In a very laggy moment, GetKeyDown returns true very many times. void Update() if(Input.GetKeyDown(KeyCode.RightArrow)) print("Pressed") I saw a similar issue in here but couldn't find any related information. https forum.unity.com threads problems with input at low framerates.16828 My game is a very input sensitive game, so my code when the user each time pressed a specific button always invoke when they pressed. I checked my keyboard is something wrong, but there was no problem with my keyboard. Why does this happen? According to the Unity doc, it said Returns true during the frame the user starts pressing down the key identified by name If I used wrong way, then how do I check each time user pressed a button? Using Unity 2019.1.0f2.
0
Playing an animation all the way through with one quick keypress with Mechanim Unity I have an if statement inside of the Update function that is only called if three other conditions are met. The problem is that right now the function sets a boolean to true which causes the animation to play inside of unity Mechanim. This boolean is only true when I hold down the button, but I would like it to play the whole animation or keep this boolean true for a certain amount of time, thanks and here is my Code. Running and jumping animation if (Input.GetKey (KeyCode.W) amp amp (Input.GetKey (KeyCode.Space)) amp amp otherAnimation false) anim.SetBool ("isRunningAndJumping", true) else anim.SetBool ("isRunningAndJumping", false)
0
How should I load change activate scenes? Scenes are confusing the hell out of me and I'm pretty sure they should be simple to understand. When the game loads, only the current scene has a buildIndex ! 1. In order give it a 'real' build index I need to load it by path or name (because there's no build index). The scenes are ten game scenes, one title scene and one persistent scene (which has the player and the status bar with the score etc.). Should I load a scene every time I change scene and then load additive afterwards or should I be using Set Active Scene? All the scenes are ticked in the Build Settings. I'm looking at the index with this private void Start() var sceneName "Persistent" var sceneBeforeLoading SceneManager.GetSceneByName(sceneName) Debug.Log( "Scene sceneBeforeLoading.name , BI sceneBeforeLoading.buildIndex ") SceneManager.LoadScene(sceneName) var sceneAfterLoading SceneManager.GetSceneByName(sceneName) Debug.Log( "Scene sceneAfterLoading.name , BI sceneBeforeLoading.buildIndex ") Which outputs Scene , BI 1 UnityEngine.Debug Log(Object) Title Start() (at Assets Scripts Title.cs 10) Scene Persistent, BI 1 UnityEngine.Debug Log(Object) Title Start() (at Assets Scripts Title.cs 13)
0
Does marking a GameObject as static actually improve performance? I'm currently working on a small game that will include somewhat large levels. Each level will have a somewhat large amount of GameObjects lying around as props. I was told by a friend of mine that marking the GameObjects that the map is comprised of as static will improve performance. However, I am aware that this can greatly increase the amount of space the built game takes up on the disk. Does the performance boost gained from marking GameObjects as static outweigh the cost of increased build size? Is there even a performance increase at all?
0
Would it be possible to randomize LOD distance in unity like in BOTW grass I was studying the BOTW grass shader and noticed how the grass appears uniform at a distance but complex up close. From watching gameplay it appears the LOD is randomized to make the transition between the two types of grass smooth. I can't find any way to do something like this in unity and am wondering if anybody has advice, or can guess as to how they did it. Thanks!
0
Android build has white image over game In unity when I am playing my game it displays fine, but when I build and run it to my nexus 5 there is this white something I don't even know over my game. Any suggestions for fixes?
0
Getting the rightmost point of gameobject How do i determin the point on a gameobject that is most to the right (highest x value).
0
How to place an instance of Editor Window in screen center? I want to create an instance of Editor Window by using CreateInstance or GetWindow. And I want to place it in center of the screen (or center of Unity). I didn't find any methods in Unity Engine that could help me. Do they exist? How can I do it within the script? Note I mean how can I find out what is the user's screen resolution? Which method can give me that? P.S. Screen.width Screen.height is not what I need. Because it refers to the Game View's window, not Unity.exe Editor's size and not monitor Screen
0
How to approach a coloring app? I want to make a coloring app in unity. I don't need flood filling. THe player will select a color and click the shape to fill that color. The app will have designs as shown below Here the problem is, design has to be empty with black outline. One way would be to create textures using the jpg of each shape. However, there are thousands of shapes and each can be colored in about 7 colors. So, i will have to create 7 textures for each shape.Is there any way to create model with black outline so that only inner color can be changed?
0
Incorrect placement of diacritics in Arabic fonts I put AdobeNaskh font on my texts and use Arabic text support for unity and use show Tashkeel function then the text appears so what is the solution of this problem?
0
How can I continue to rotate a 2D UI Object using OnPointerEnter when object is on its side? (OnPointerExit is triggered) I have been wracking my brain on this for days. I'm trying to create a nice looking hand of cards, when the card is hovered over, it bobs up and down and rotates. This is triggered by OnPointerEnter, however, whenever it turns on its side and out of the mouses path OnPointerExit triggers, I've tried MANY things, including a bool that triggers the hover effect OnPointerEnter but it is just toggled off when it's turned on its side. Is it possible to use the collider on my card with OnPointerEnter? Because that would probably solve my problem but haven't found anything on this. Since the card is on UI, I have some placeholder code in there in order the have the inspected card render on top and return to its place. void Update() if (inspect) transform.localScale cardUpscale posOffset transform.position transform.Rotate(new Vector3(0f, Time.deltaTime degreesPerSecond, 0f), Space.World) Float up down with a Sin() tempPos posOffset tempPos.y Mathf.Sin(Time.fixedTime Mathf.PI frequency) amplitude transform.position tempPos public void OnPointerEnter(PointerEventData eventData) zoomPlaceholder new GameObject() zoomPlaceholder.name "zoomPlaceholder" zoomPlaceholder.transform.SetParent(this.transform.parent) binds the placeholder to the hand zoomPlaceholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex()) LayoutElement cardProxy1 zoomPlaceholder.AddComponent lt LayoutElement gt () cardProxy1.preferredHeight this.GetComponent lt LayoutElement gt ().preferredHeight cardProxy1.preferredWidth this.GetComponent lt LayoutElement gt ().preferredWidth cardProxy1.flexibleHeight 0 cardProxy1.flexibleWidth 0 zoomPosition transform.parent transform.SetParent(transform.parent.parent) inspect true public void OnPointerExit(PointerEventData eventData) inspect false this.transform.SetParent(zoomPosition) this.transform.SetSiblingIndex(zoomPlaceholder.transform.GetSiblingIndex()) transform.localScale cardNormalScale Destroy(zoomPlaceholder)
0
Unity editor PropertyDrawer custom button I has a PropertyDrawer, everything goes fine, except one feature I can't figure out how to add button and I use checkbox instead using UnityEngine using UnityEditor using System.Collections CustomPropertyDrawer (typeof (InteractiveObject)) class InteractiveObjectPropertyDrawer PropertyDrawer public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) EditorGUI.BeginProperty (position, label, property) position EditorGUI.PrefixLabel (position, GUIUtility.GetControlID (FocusType.Passive), label) var indent EditorGUI.indentLevel EditorGUI.indentLevel 0 Rect colorRect new Rect (position.x, position.y, 40, position.height) Rect unitRect new Rect (position.x 50, position.y, 90, position.height) Rect nameRect new Rect (position.x 150, position.y, position.width 150, position.height) EditorGUI.BeginChangeCheck() EditorGUI.PropertyField (colorRect, property.FindPropertyRelative ("show"), GUIContent.none) if (EditorGUI.EndChangeCheck() ) RenderSettings.skybox.SetColor(" highlight", property.FindPropertyRelative ("id").colorValue) EditorGUI.PropertyField (unitRect, property.FindPropertyRelative ("name"), GUIContent.none) EditorGUI.PropertyField (nameRect, property.FindPropertyRelative ("name"), GUIContent.none) EditorGUI.indentLevel indent EditorGUI.EndProperty () How I can add button there?
0
Execute native ios code in unity I want to execute native iOS code in unity. For this I have added two files in plugins ios. ViewController.h ViewController.m Code for each file represented as under. ViewController.h interface ViewController (void)sampleMethod end ViewController.m import "ViewController.h" implementation ViewController (void)sampleMethod NSLog( "Sample Method Execute") end For C file I have added following code DllImport(" Internal") private static extern void sampleMethod() and call to above method sampleMethod() When I am export project for iOS, xCode give me following error that I can't able to understand. I can't able to understand how to solve this problem? Please give some suggestion here. EDIT I have added extern keyword in my .m file after reading some suggestion. import "ViewController.h" implementation ViewController extern "C" (void)sampleMethod NSLog( "Sample Method Execute") end But in xCode now I am getting Expected Identifier or '(' at the line of extern keyword line. So what to do next?
0
How to calculate the stopping distance of a wheel collider? I have an 'AI' bus in my game that needs to pull over occasionally at a bus stop. What I want to do is change the acceleration and brake force based on the stopping distance of the bus. I don't want to simply use the distance between the bus stop and the bus because each time the bus pulls over, it could be traveling at a different speed. Right now it uses the distance between the bus stop and the bus. It doesn't really work well though because if a bus is traveling faster, it will take a longer distance to stop and will likely go past the bus stop. Same thing if it were going slower. How do I calculate the stopping distance my bus will take to come to a complete stop?
0
How to give a Jerk Effect when the player is moving left of right float amttomove Input.GetAxis("Horizontal") playerspeed Time.deltaTime transform.Translate (Vector3.right amttomove) Currently, I have above script in Update function to move the object to left or right.But this movement is way smoother.To give it more realistic feel, I want it to have a slight jerk when it stops moving to left or right and not just stop right there and then. What exactly needs to be done to have that effect?
0
Mathf.Hermite not available in Mathf I see here that Hermite should be function in the class Mathf. However, when I try to use it, the compiler tells me that Mathf doesn't contain a definition for Hermite. This is an example float fNewDistance Mathf.Hermite( initialDistance, GoalDistance, fTime) What am I doing wrong here? Thank you!
0
How to draw a line in 3d space? I have a top down billiard game. And on click tap the ball moves in the clicked direction like in the image below Now, I want a line to be drawn in the direction where the mouse is hovers or the finger is swiped, here is my update code void Update () this should make the line, why not working? Vector3 forward transform.forward Debug.DrawRay(transform.position, forward) Debug.DrawLine(transform.position, transform.position forward 10000) if (Input.GetMouseButtonDown (0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit, 100.0f)) Vector3 startPos transform.position Vector3 clickPos new Vector3(hit.point.x, hit.point.y, transform.position.z) Vector3 direction Direction (clickPos startPos) direction rb.velocity new Vector3(direction.x 5, direction.y 5, 0) I tried DrawLine, Drawray, any ideas?
0
what happens when you set transform.position in Unity? Unity has both transform.positionandtransform.localPosition. When I do transform.position.x 3f does unity automatically update transform.localposition? and vice versa? Why can I not see this when I go to the definition of transform.position in VS?
0
I found out how to rotate both Sphere and Cube (1) like a Turret facing a target but why is it so hard? I just added 3 objects to my scene to a new project. To be sure where the problem is I created a new project. Then added to the scene 2 Cubes and 1 Sphere 1 empty GameObject. Cube is the target. Sphere and Cube (1) are the Turret and both are childs of the empty GameObject. The script is attached to the empty GameObject. The logic say if I will rotate the empty GameObject both Sphere and Cube (1) will rotate at the same time. But I found that if I'm not setting both Sphere and Cube (1) same direction before running the game they will never face to the target only the Sphere. I had to figure out where is the Sphere facing direction before running the game and change the Cube (1) to face the same direction of the Sphere on the Z Blue axis. I can't figure out yet and understand why is it so hard to rotate two objects at the same time to be facing the same direction (target). Now it's working once the sphere and the cube (1) are facing same direction before running the game. It didn't work if I made them childs or parents or changed the Cube (1) position to 0,0,0 nothing. They were both rotating but never faced the target only the Sphere faced the target. So now each time I want to rotate two objects at the same time to face another gameobject like a turret, or cannon or anything that is built of two parts I need first to make them facing same direction ? I guess I did something wrong but not sure what. The script using System.Collections using System.Collections.Generic using UnityEngine public class Rotateturret MonoBehaviour public float speed 3.0f public GameObject m target null Vector3 m lastKnownPosition Vector3.zero Quaternion m lookAtRotation private void Start() Update is called once per frame void Update() if (m target) if (m lastKnownPosition ! m target.transform.position) m lastKnownPosition m target.transform.position m lookAtRotation Quaternion.LookRotation(m lastKnownPosition transform.position) if (transform.rotation ! m lookAtRotation) transform.rotation Quaternion.RotateTowards(transform.rotation, m lookAtRotation, speed Time.deltaTime) bool SetTarget(GameObject target) if (!target) return false m target target return true Here is a link for a short video clip I recorded showing what I mean Video clip of the problem
0
Reuse and Interact With Multi Layer Tile Maps I'm new to game development and try to make a game where buildings are created in tile maps. My problem is that I need to interact with these buildings and I want to reuse the buildings I created. Now I would like to export these two layers to a single sprite or prefab to create multiple buildings and to make them clickable. Is there a way to achieve this or do I have the wrong approach? EDIT My current setup looks like this Two tile maps One tile map contains the wall of the building. Another tile map contains decoration like door or window. My problem is, that I am not able to export these tile maps as one prefab to reproduce it or to attach scrips. I am looking for a way to combine these two layers into one resource ( The building with all its decorations, doors, windows), so that I can place them anywhere I want and make them clickable as a game object.
0
Keep state in Unity editor without hitting serialization In my game I have a MonoBehaviour WorldView that, when created at editor time, initializes a large dictionary. Later from a Editor WorldViewEditor I call WorldView.SetBlock() that tries to access this dictionary, but finds it empty. If I understand correctly this is because my editor doesn't access the same WorldView instance, but rather a copy it received through serializing and de serializing my original instance. Pushing this dictionary through the serializing process is a performance nightmare and not supported by Unity out of the box. This dictionary should never be shown in any editor, is private to the instance and initialization will be called every time the scene is loaded. This sounds like a perfect case for keeping it somewhere outside the serialization process. I could try to leverage ISerializationCallbackReceiver but this still requires me to pull the entire dictionary through some serialization process. I'm looking into keeping everything state related in a separate library outside of unity, but this has it own downsides. Is there a way to put this dictionary in a place where its state is kept?
0
Bring GameObject in front of GUI Texture I have a GUI Texture that dims the screen, however I want certain game objects to not be dimmed. I tried putting them in front of the GUI Texture, but it doesn't work. How can I do this?
0
Player appears in front of objects even if it's in the background I have a player in Z 0 and a fence object that I want it to be in from of the player so I set it to Z 1, it's a 2D game but in the 3D view I can see that the fence is actually in front of the player but in the 2D view the player is displayed in front. Here are a couple of screenshots. 3D view, fence in front of player 2D view, player in front of fence Any idea how to fix this?
0
Nestling into contact with a group of physics objects without exerting forces on them I'm making a pool game, and would like the circle (imaginary) to be in contact with the table and balls, and to fit perfectly as a ball would. Now I thought I would use Rigidbody and lerp the position of the circle to the raycast hit, and its collider it would force it into a fitting position. The problem I encountered is that since it has a collider, it also pushes the balls, which I do not want. So my question is, how do I make an object act like it's touching amp blocked by other GameObjects with Colliders and Rigidbodies, without pushing them?
0
How can I manipulate a layer with click and drag functionality? This works well on clicking layers but not click and dragging layers. public class FishClicker MonoBehaviour public LayerMask whatIsFish public float clickRadius 0.1f void Update() if (Input.GetMouseButtonDown(0)) var mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) var hit Physics2D.OverlapCircle(mousePos, clickRadius, whatIsFish) if (hit ! null) var fish hit.GetComponentInParent lt Fish gt () if (fish ! null) fish.DoClickThing() for DoClickThing() this works public void ControlFishClick() screenPos myCam.WorldToScreenPoint(transform.position) Vector3 v3 Input.mousePosition screenPos angleOffset (Mathf.Atan2(transform.right.y, transform.right.x) Mathf.Atan2(v3.y, v3.x)) Mathf.Rad2Deg for DoDragThing() i want this to work public void ControlFishDrag() stopMovement true rigid2D.velocity new Vector2(0, 0) Vector3 v3 Input.mousePosition screenPos float angle Mathf.Atan2(v3.y, v3.x) Mathf.Rad2Deg transform.eulerAngles new Vector3(0, 0, angle angleOffset) print(stopMovement) for DoReleaseClick() i want this public void ControlFishUp() stopMovement false SnapToPosition()
0
Show 3D elements on 2D background I'll make a navigation menu in my game and had the good idee to this the enemies to start games or go to the gun store. The problem is when I look in game mode, the enemy named ZomBear in hierarchy and gun are away. The ZomBear and the gun are 3D elements that I will show on a canvas named StartScreen in hierarchy. How Can I do that? (Click on image to see full size) Notes by the hierarchy Everything that begin whit Btn are button elements. StartScreen, PlayButtons and LevelButtons is a panel Gun and ZomBear are 3D elements form the Prefab folder. Here you have also a screen from aside
0
Can't go above max speed with RigidBody2D.AddForce() I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top down 2D game (constrained to the x y plane). I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed" going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ) private void WASDMovement() Vector3 translationVector Vector3.zero if (Input.GetKey(KeyCode.W)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.A)) translationVector new Vector3( 1.0f, 0.0f, 0.0f) if (Input.GetKey(KeyCode.S)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.D)) translationVector new Vector3(1.0f, 0.0f, 0.0f) translationVector.Normalize() rigidbody2D.AddForce(translationVector MovementSpeed) Here's a video demonstrating my problem to make it easier to see what I'm doing wrong http youtu.be 9kwKvfDOYoo
0
How do I create a circular progress bar in Unity3D 5? I am new to programming and Unity3D. I want to show a circular progress bar starting invisible and growing in 3 seconds to a circular line when reloading is done. How can I do that?
0
How to set default pose of model from Blender? (Exported as FBX) I have a model that has lots of animation clips(actions). Before export as FBX, I set the pose to named "default" pose and exported as FBX like this. But in Unity, it's changed to first animation clip in animation list in Blender! I try to fix it, but there is nothing I can do. I can't change the order of animations in Blender and Unity either. This wasn't first time, I had same issues before but I just ignored because it's fine in game play, but I really want to fix it this time. What I want is set "default" pose in edit mode in Unity(not play mode). How do I set "default" pose as default, not first animation clip in the list? Using Blender 2.78, and Unity 2017.3.0f3.
0
Programmatically creating sprite animations in Unity Some background I have a set of animated gifs which I've converted to spritesheets, which are then imported into Unity as multiple sprites. The end result is that each spritesheet in the Unity editor contains a list of sprites named xxxxxxx yyy zzz for example 1313000 000 000 to 1313000 000 014, followed by 1313000 001 000 to 1313000 001 008, followed by 1313001 000 000 to 1313001 000 031, and so on. Now, I would like to make simple sprite animations out of this spritesheet. In the example above, 1313000.anim should contain all sprites beginning with 1313000 played in numerical order, 1313001.anim should contain all sprites beginning with 1313001, etc. etc. This isn't hard to do by hand highlight desired range of sprites, drag and drop but we're talking about a lot of animations. Creating an editor script which lets me right click a spritesheet and generate a series of .anim files seemed the best solution, but I'm turning up conflicting info on the subject. Getting a sprite array from the spritesheet is simple enough, but programmatically creating an animation is something very few people seem to have discussed. Essentially, is it possible and practical to create and populate sprite animations from an editor script?
0
VS code doesn't recognise new Unity Files Vs code was working fine for some time, and suddenly it stopped supporting new unity c classes Also, there is no regenerate project files option in unity I tried restarting unity and vscode, but no success.... Also, assemblyCSharp doesn't add new files to it....
0
Visual Studio not updating files made in Unity In the past Visual Studio simply updated solution based on files added in Unity but now all of them have to be added manually and they are as miscellaneous when they are added. How can I fix it?
0
Touch control pan 3D map I'm working on recreating the board game quot Hex quot as a mobile game. I'm working on implementing zoom and pan features using two fingers. I feel like I managed to get the zoom to work, but the pan moves more than I want it to and I feel like it is because I'm missing something and must be somewhere in the conversion to World Space coordinates. if I could get some help it would be greatly appreciated. For reference, oldMidpoint is initialized to 0 earlier on. Touch touchA Input.GetTouch(0) Touch touchB Input.GetTouch(1) Vector3 midpoint (touchA.position touchB.position) 2 if(midpoint ! oldMidpoint) if(oldMidpoint Vector3.zero) oldMidpoint midpoint Vector3 moveDistance oldMidpoint midpoint moveDistance.y 0 Camera.main.transform.Translate(moveDistance, Space.World) oldMidpoint midpoint
0
In Unity, how do I create a drag and drop object? I have a 2d scene. I want the player to be able to pick up an object, move it around the scene and drop it somewhere. I can't find any way to do this, and all of the resources for Unity are really daunting and I can't find anything relevant to what I'm doing. I've tried adding the drag rigidbody script to both my camera and the sprite I want to drag, to no effect. Where can I find relevant documentation for stuff like this? Basic things like how to implement a script or what objects I need to attach these scripts to the stuff on the unity website is a little too advanced.
0
How to place same canvas on multiple cameras in Unity? I know how to do It on one, but I don't know how to do it using multiple cameras, 3 of them are important, i want to show the whole UI except for the minimap. I need to change the camera angle on some spots, while keeping the same canvas for displaying the number of coins XP and the current level.
0
How to playlay multiple Particle Systems when colliding with multiple obstacles using object pooling? I have two types of particle, one for each player Player 1 (Red Particle) Player 2 (Blue Particle) When player 1 collides with an obstacle then I want to play the red particle system, and when player 2 collides with an obstacle then I want to play the blue particle system. Code TouchControll.cs public GameObject PlayersPartical void OnTriggerEnter2D(Collider2D other) here my player collided with obstacle foreach (Transform child in transform) if (child.tag "point") GameObject partical Instantiate(twopartical Random.Range(0,1) , transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() GameObject partical Instantiate(PlayersPartical, transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() ObjectPooler.Instance.SpawnFromPool("redandbluepartical", transform.position, Quaternion.identity) ObjectPooler.cs public static ObjectPooler Instance public void Awake() Instance this System.Serializable public class Pool public string tag public GameObject prefab1 public GameObject prefab2 public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt pooldictionary which gameobject you should be pool void Start () pooldictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) add a pool in list Queue lt GameObject gt objectpool new Queue lt GameObject gt () for(int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab1) GameObject obj1 Instantiate(pool.prefab2) obj.SetActive(false) obj1.SetActive(false) objectpool.Enqueue(obj) pooldictionary.Add(pool.tag, objectpool) public GameObject SpawnFromPool(string tag,Vector3 position,Quaternion rotation) two tag red and blue partical if(!pooldictionary.ContainsKey(tag)) Debug.Log("doesnot exist" tag) return null GameObject objecttospawn pooldictionary tag .Dequeue() here how to call my trigger objecttospawn.SetActive(true) objecttospawn.transform.position position pos objecttospawn.transform.rotation rotation rotation pooldictionary tag .Enqueue(objecttospawn) return objecttospawn Image1 Image2 How do I call these particles?
0
I can add event animation but I can't add keyframe? I am trying to add animation to my UI panel but the problem is I can't add a keyframe to my animation (the button is grayed out). But I can add event animation (the button is not grayed out). Here is the video of what's happening. Anyone know how I can resolve my problem?
0
Is there anyway to disable the script "gameplay" from running once you start the simulation? Was following the tutorial in this video https oxmond.com how to make multiple copies of a gameobject on how to duplicate object. I want to modify my code I learned from this tutorial https www.youtube.com watch?v OR0e 1UBEOU amp t 4178s so that the bird will increase its size proportion to the distance travel and when scale gt certain value, it break into 2 identical bird object that possess the same properties as the first one. I already did the part size increase in proportion to the distance travel. Now I create an empty game object and attach the script quot explode quot together with prefab of the bird object to it but how to write the proper code to carry out the function if the main bird object is destroyed then it run the code quot explode quot to duplicate bird? using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour Vector3 OldPosition Vector3 DistanceDifference float TotalDistance 0 Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 void start() OldPosition transform.position private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1) DistanceDifference transform.position OldPosition TotalDistance DistanceDifference.magnitude OldPosition transform.position transform.localScale new Vector3(0.2f Mathf.Abs((TotalDistance 0.2f)), 0.2f Mathf.Abs(TotalDistance 0.2f) , TotalDistance 0.5f) if (transform.position.y gt 20.00 transform.position.y lt 20.00 transform.position.x gt 23 transform.position.x lt 23) string currentSceneName SceneManager.GetActiveScene().name SceneManager.LoadScene(currentSceneName) void OnMouseDown() GetComponent lt SpriteRenderer gt ().color Color.red private void OnMouseUp() GetComponent lt SpriteRenderer gt ().color Color.white Vector2 directionToInitialPosition initialPosition transform.position GetComponent lt Rigidbody2D gt ().AddForce(directionToInitialPosition launchPower) GetComponent lt Rigidbody2D gt ().gravityScale 1 birdWasLaunched true private void OnMouseDrag() Vector3 newPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position new Vector3(newPosition.x, newPosition.y) This the 2nd script to duplicate the bird but i'm not sure what the correct codes I have to put in if the 1st game object destroy, then it duplicate 2 bird? using System.Collections using System.Collections.Generic using UnityEngine public class Explode MonoBehaviour public GameObject Bird Update is called once per frame void Update() (if Destroy(Bird)) GameObject BirdClone Instantiate(Bird)