Calculating price increases in a virtual economy I'm trying to design a method to have price increase depending on the number of items bought from shops in my game. I'm fairly new to coding and I am struggling to figure out how to program the increase in price when buying multiple items. Currently the price increase is a percentage increase based on the quantity of items in store, however if I buy 5 items, all 5 items will be charged the same. How can I get it so each item is charged at a different price? I also need a reasonable inflation system, right now my code just determines a price increase based on the percentage of items remaining, but it's very simple and easy to exploit. It looks like this 30 2 28 1 (28 30) 0.07 0.93 1 0.07 1.07 10 1.07 10.7 Rounded up Price 11 I'd like to make this more complex also.


CrossPlatformInput Prefabs Button handler to move? I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would... And my code for moving my character is as follows private void Update() isGrounded Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer) float move CrossPlatformInputManager.GetAxis("Horizontal") moveSpeed playerRB.velocity new Vector2(move, playerRB.velocity.y)


How can I turn off the sound from another scene? I attached music file to my first scene and thanks to following javascipt code, sound continues without stopping in other scenes. public static var object SingletonMusic null function Awake() if( object null ) object this DontDestroyOnLoad(this) else if( this ! object ) Destroy( gameObject ) My problem is that I want to turn off the sound from the button in the another scene (setting scene) so that I added a new button to my setting scene and attached the following javascript code to the button that I have created. Javascript code var objects AudioSource SingletonMusic.object.GetComponent(AudioSource) if( objects.isPlaying ) objects.Pause() else objects.Play() However, it gives following errors If I start the game from Setting scene I get this error If I start the game from first scene and then, go to Setting scene I get this error


Why does the Unity manual add "Quaternion.identity" to an instantiated object? In Unity's documentation you can find an example usage of Instantiate https docs.unity3d.com ScriptReference Object.Instantiate.html using UnityEngine public class InstantiateExample MonoBehaviour public GameObject prefab void Start() for (int i 0 i lt 10 i ) Instantiate(prefab, new Vector3(i 2.0f, 0, 0), Quaternion.identity) Why do they add the "Quaternion.identity" instead of leaving it blank? Wouldn't the engine instantiate the object with the original object's rotation anyway?


How to create a tube 2D in unity I want to create a 2D tube in unity which I can cut, suture and drag it, My idea is to use a small image in form of fragments but how i can do it like the picture bellow EDIT What I did until now Firstly I tried to use Linerenderer but it didn't work for me because i couldn't cut it so tried to create a tube of cubes I used an empty object as parent whit childs of cubes as you can see on the picture bellow with this way it was easy to apply the cut script so I just remove the fixed joint between the cubes where i click and for the appearance of the tube I started by creating it as a direct line and I turned on the game then by dragging the tube i get the form bellow and i copy the position of each cube and set it on the instantiation of the childs GameObject intestines top GameObject.Find("intestine top") setPositions() on this method I instantiate an array of vector3 contains all the position i get fragments new GameObject fragmentNum Vector3 position Vector3.zero for (int i 0 i lt fragmentNum i ) fragments i Instantiate(fragmentPrefab, positionArray i , Quaternion.Euler(new Vector3(0.413f, 259.96f, 536.531f))) fragments i .transform.SetParent(transform) var joint fragments i .GetComponent lt FixedJoint gt () joint.connectedBody parent.GetComponent lt Rigidbody gt () parent fragments i the result of what i did NOTE other problem of my solution is sometimes all the gameobjects disperss due to collision I think That's happen after a while of dragging the tube I didn't find what exactly the problem but when I change the direction of the collider to the X axis its solve the problem by 85 and for the drag script i use AddForce and velocity rigid.AddForce((dest rigid.position) 200f) rigid.velocity 0.8f


How can I change a shader alpha color in script? How can I get access to the Main Color and change the alpha color ? How do I know what is the variable of the main color in the shader code ? If it's Main Color in the Inspector then this is the parameter I should get in the script "Main Color" ?


changing color of sprite not every frame So I have been trying making this game, which changes color of sprites in it. It should only happen when OnMouseDown(). but it is executing every frame and cannot go out of the couroutine. I want the color change to be slower. Please mark the colors should still change. Please Help, public class control MonoBehaviour public bool startstop false SpriteRenderer m SpriteRenderer private void Update() StartCoroutine("Changecolor", 3f) IEnumerator Changecolor() yield return new WaitForSeconds(3) if(startstop true) int random Random.Range(1, 4) if (random 1) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.blue else if(random 2) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.red else if(random 3) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.green else m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.yellow private void OnMouseDown() startstop !startstop


How to get smoother transition between the surface normals rotation of player in Unity I kinda have a problem that my player is snapping onto the other surface while I wanna move a ramp up. I want to have it rotate smooth to the normals of the ramp. How can I change the code below to a smoother rotation function of the player? Code void NormalsOfGround() RAYCASTS THE NORMALS ON THE GROUND THAT THE PLAYER MOVES ALONG SURFACE Debug.DrawRay(rayCastNormal.transform.position, transform.up, Color.blue, 2.5f) Ray ray new Ray (transform.position, transform.up) RaycastHit hit if(Physics.Raycast(ray, out hit, 2.5f, GroundLayer) true) transform.rotation Quaternion.FromToRotation (transform.up, hit.normal) transform.rotation


NULL REFERENCE EXCEPTION Object reference not set to an instance of an object So I have 3 scripts first for my player movementscript second for my speed powerup speedscript third for my obstacle box script i I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error Here are those scripts public class box MonoBehaviour SerializeField GameObject effect public int damage 1 SerializeField float Speed 10f SerializeField GameObject audioexplosion void Update() transform.Translate(Vector2.left Speed Time.deltaTime) void OnTriggerEnter2D(Collider2D col) if(col.CompareTag("Player")) Instantiate(audioexplosion, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) movment tmp col.GetComponent lt movment gt () tmp.health damage Destroy(gameObject) public void added(float spd) Speed spd And here is my speed script. public class speedscript MonoBehaviour SerializeField GameObject effect SerializeField GameObject speedaudio SerializeField public float speed public float add v 5 private float timeindue SerializeField public box io void Start() io GetComponent lt box gt () Debug.Log(io) void Update() transform.Translate(Vector2.left speed Time.deltaTime) void OnTriggerEnter2D(Collider2D sp) if (sp.CompareTag("Player")) Instantiate(speedaudio, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) box io GetComponent lt box gt () Debug.Log(io) io.added(add v) Destroy(gameObject)


Unity Hide GameObject that is behind UI I have the following example How can I prevent the part of the sprite that is highlighted in red and is behind the UI from being displayed on the camera, but having the background image still showing?


Circular draggable UI element in Unity canvas I am trying to implement my own runtime color picker that's easy to use for touch interfaces. I want the hue slider to be a ring, along these lines, except the whole ring texture would rotate when dragged. I have scavenged enough code to get a raw image object rotating when dragged in a UI canvas in the manner I'm looking for private float baseAngle private Vector2 pos public void OnBeginDrag(PointerEventData eventData) pos transform.position pos eventData.pressPosition pos baseAngle Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle Mathf.Atan2(transform.right.y, transform.right.x) Mathf.Rad2Deg public void OnDrag(PointerEventData eventData) pos transform.position pos eventData.position pos float ang Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle transform.rotation Quaternion.AngleAxis(ang, Vector3.forward) Since it doesn't use colliders, how can I limit the draggable region to a circle within the square bounds of the texture? Even better, also limit it to a ring rather than a whole circle. Will I have to implement my own check based on some pure math or is there a built in way? thanks!


Respawn not working properly upon scene reload. Why is this? So I made a respawn function and what is supposed to happen is the script it supposed to load a saved checkpoint. However I need to reset the scene (and again this worked just fine last night which was odd...). Essentially the checkpoint waits for a player and then when the player enters the current checkpoint is written to a .txt file. Upon reload or death the scene is restarted, the .txt file is read and grabs the checkpoint. Everything works fine without Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. but I need that in order to "refresh" the scene. CheckPoint Code using UnityEngine using System.Collections public class Checkpoint MonoBehaviour public LevelManager levelManager Empty level manager. Use this for initialization void Start() levelManager FindObjectOfType lt LevelManager gt () Unnneeded void OnTriggerEnter(Collider coll) if (coll.tag "Player") levelManager.currentCheckPoint gameObject lt DISABLE WHEN ES2 is fixed!!! Debug.Log("Activated Checkpoint " transform.position) ES2.Save(gameObject.name, "myFile.txt?tag checkpoint") Saves checkpoint to file. LevelManger Code using UnityEngine using System.Collections using UnityEngine.SceneManagement public class LevelManager MonoBehaviour Tooltip("Note this will also serve as the spawnpoint for the player!") public GameObject currentCheckPoint private GameObject player private int PHP public int RespawnHP Amount of health to give player upon respawn. void Awake () Use this for initialization void Start () player GameObject.FindGameObjectWithTag("Player") Update is called once per frame void Update () PHP GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth if (PHP lt 0) Debug.Log("Player HP has been depleted. Respawning.") RespawnPlayer() if (Input.GetKeyDown("r")) Debug.Log("Restarting level!") RespawnPlayer() public void RespawnPlayer() Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. currentCheckPoint GameObject.Find(ES2.Load lt string gt ("myFile.txt?tag checkpoint")) Load saved checkpoint. Debug.Log("Player Respawning...") player.transform.position currentCheckPoint.transform.position GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth RespawnHP void RestartLevel() ToDo Restart level, and reload last check point. public static void SaveLevel() Saves the current level to file. ES2.Save(SceneManager.GetActiveScene().name, "myFile.txt?tag levelName") Saves level to file. ES2.Save("none", "myFile.txt?tag checkpoint") Overwrite checkpoint? Does anyone have a clue what is wrong? Like I said earlier the problem seems to arise on scene reloading. Response to comment(s) What behaviour are you observing at the moment? Jack Currently what happens is the player enters a checkpoint, the checkpoint is saved to a file, and upon respawn the checkpoint is loaded. After this I get spawned to the checkpoint that was saved but then immediately the level reloads itself and the player is not respawnd at the checkpoint. Here is a video to better demonstrate the issue (it will take a minute or two to finish up processing here as I've just pasted the link).


Creating paralax background in Unity3D I am trying to create some parallax background in Unity in 2D mode by tweaking offset of the background material and using tiling. I used this tutorial https www.youtube.com watch?v nGw UBJQPDY as a reference, but my material doesn't tile like one in the tutorial. Any tips for creating infinite background with tiling and tweaking offset? What am I doing wrong?


What can cause shadow slicing while moving camera? Can't explain better than with video https youtu.be 4nIMIL6w 0M The effect I'm trying to achive is a simple fog of war. See, I have a point light casting shadows on a plane. The plane has a shader which takes light attenuation and either draws a black pixel if there is no light, or discards a pixel to draw background if the light touches that pixel. After hours spent on this, I came up with a thought that I cannot do anything more. A problem as I see it Light successefully casts a shadow of shadow casters on a plane, however, with camera at a distance from the shadow, the shadow it self gets splitted and sliced, like it would've been, if some of the shadow casters' faces are suddenly removed from their meshes. What I have tried Changing Z coordinate of a light. Changing Z height of obstacles (shadow casters). Changing vertices on the obstacles so that every face would have its own vertices so no faces could share a vertex. Changing shadow quality in the settings. Changing camera rendering mode, all four of them. Changing point light to a spot light with wide cone radius. Using nice and simple standart unity's shader for a shadow receiver (a plane) Standart Diffuse. Switching between hard and soft shadow types. Changing light's shadow's resolution, shadow strength and biases Trying out the compiled EXE on another machine. Changing light's baking type, rage and intensity. You name it. None of those had any improvementes on an issue. I would like to hear authoritive replies (best option would be from the developers) as well as any information you guys think I can try out (so I can do that).


Stop Animated Tile from looping Unity2D C I am using the animated Tile script and starting the animation when I need it, by replacing a static tile with an animated one. Currently on collision with the player, however, I need the animation to run to its end and then stop when it finishes. My current code is trying to find if the current sprite on the position is the same as the last one of the animation and if that is true it should just replace it with a static tile. However, that happens instantly after the animation has been triggered. Check if the animation is finished if (playingAnimation) if (tilemap.GetSprite(lastPPosition) destructableLast.sprite) if animation ended Debug.LogWarning("Destructable Animation finished Returning to end sprite") tilemap.SetTile(lastPPosition, destructableLast) playingAnimation false Code for setting the animated tile private void AnimatedTile Destroyable(TileBase type, Collision2D collision, Vector3Int pPos) if (type destructable0) tilemap.SetTile(pPos, destructable1Animation) lastPPosition pPos playingAnimation true I did find this in the Animated Tile script public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData) tileData.transform Matrix4x4.identity tileData.color Color.white if (m AnimatedSprites ! null amp amp m AnimatedSprites.Length gt 0) tileData.sprite m AnimatedSprites m AnimatedSprites.Length 1 tileData.colliderType m TileColliderType Which confuses me, because from what I see, the sprite that is used as the animated tile sprite is the last one from the animation. Shouldn't the sprite change constantly when the animation plays, and is there a way to stop the animation once it has finished?


How should I organize 2D sprites? I'm using a Unity Tilemap in my 2D game, and I have several hundred 32x32 sprites. Most of the examples I've seen using sprites have a few consolidated sprite sheets that contain all of the game's sprites. For instance, I'd have a few 1024x1024 sprite sheets that contain all of my game's sprites. Those examples all say that the reason to do it this way is that performance is improved when sprites are packed together like that. The problem with these large consolidated sprite sheets is that it's difficult to find the sprites that I want when I'm making a tile pallet or animated scripted sprite. For example, I have two 1024x1024 sprite sheets called "House Interior 1" and "House Interior 2" that contain all my walls, floors, furniture, doors, windows, and miscellaneous interior objects. Now I want to create one Unity tile pallet that has only tiles for western style houses and one tile pallet that has only tiles for eastern style houses. Each tile pallet is going to require some, but not all, sprites from both of my sprite sheets (House Interior 1 and House Interior 2). Additionally, I want to create some animated tiles. Each animated tile will use a few sprites from somewhere in the middle of one of the large sprite sheets. My problem is that each sprite sheet image has so many child sprites that it becomes very tedious and time consuming to visually scan through each huge sprite sheet to find the tiles I want, and then drag each of them individually onto my tile pallet. Making animated tiles results in the same problem because when I assign each animation frame, I have to find the correct sprite from a huge list of sprites that are named House Interior 1, House Interior 2, House Interior 3, and so on. I'd like to have smaller sprite sheets that only contain one specific type of sprite, rather than huge sprite sheets of often unrelated sprites. For example, I'd like to have one sprite sheet that has only masonry walls, one that has only brick walls, one that has only the animation frames of a fireplace, and so on. That way it'll be easier to build up Unity tile pallets by dragging several sprite sheets into the tile pallet in the Inspector, and it'll be easier to find my animated tiles because I can easily find the sprites named Fireplace 1, Fireplace 2, and Fireplace 3. So my questions are How big of a performance hit will I experience if I don't pack my tiles together into a few big spritesheets? Is it even worth taking this into account considering modern devices are so powerful compared to what is necessary to do sprite based graphics? Is this a case of balancing the pros and cons of both methods, or is it generally strongly recommended that I large consolidated sprite sheets?


How to show NGUI menu in the upper of a Game Scene? I am new to Game Development. I made a menu with NGUI plugin. I have a background image in the behind of this menu. Now, I want to place my Game Scene in place of the background image. I have tried in several ways. But, Failed. Any suggestions will be highly appreciated. Thanks


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


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.


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


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.


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


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.


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?


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?


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


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?


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.


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.


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?


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..


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?


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.....


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.


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


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...


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.


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)


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!


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?


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()


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.


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?


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.


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.


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.


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?


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.


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)


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!


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


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.


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...


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...


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)


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 !!!!


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?


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


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).


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.


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?


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?


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?


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


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)


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.


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.


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.


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 ?


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.


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.


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


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


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.


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.


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.


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?!


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!


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.


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.


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)


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)


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?


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!


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?


Getting the rightmost point of gameobject How do i determin the point on a gameobject that is most to the right (highest x value).


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


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?


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?


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)


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?


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?


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?