Why it isn't possible to get a progress in SceneManager.LoadSceneAsync between 0.0 and 0.9? I am trying to understand why does SceneManager.LoadSceneAsync progress always jumps from 0.0 to 0.9, no matter how big a scene can be. To try trigger smoother progress of the scene being loaded, I've tried the following Generate a large scene from an EditorWindow, containing tens of thousands of objects referencing thousands of assets. Loading this scene didn't produce the intended behavior, rather, it ended up being exactly the same (jumps from 0.0 to 0.9) but with a huge lag at the end since there are many objects. According this behavior, I am now considering that the supposed asynchronicity in SceneManager.LoadSceneAsync is just about the loading of the scene file itself, not processing its content for being usable by Unity. Is this correct? An example on how to load a large scene and report its progress would be appreciated )


Render object transparent with camera instead changing object render mode I have a pretty large area where I want to show the floor with 60 transparency using a so called Opacity camera (an idea). I know I can set mesh rendering mode to transparent and then decrease the alpha value. My question is that, is there any way available to apply mesh transparent rendering setting to my camera instead of the object.


Loading images using their bytes in Unity If you import an image into the Unity inspector, the image will be encoded in Unity's own format. Usually the resulting image is much bigger than the original (from 100kb to 1MB). Of course, you can do stuff like compress and change the texture max size to reduce the image's size, but at the end it will almost always be bigger. I noticed that you can create a Texture2D if you got the necessary bytes. As an experiment, I took my 100kb image and imported it to Unity as a .bytes file. Then I read the bytes and created my Texture2D Texture2D texture new Texture2D(100, 100) texture.LoadImage(myTextAsset.bytes) Sprite sprite Sprite.Create(texture, new Rect(0,0,350, 288)) And it works. And it is smaller (100kb). So my question is what's the difference between Unity's builtin way of handling images and my way of loading them using their bytes? Because I'm saving tons of memory with this method. I imagine that it is a bit slower. But if that's the only difference, I can live with that.


How can I add two Vector3 directions together? I have a direction to my target object, which is in a Vector3 format. I want cast a number of rays, as offsets from this initial direction. X is the object. D is the direction the player needs to travel in. A amp C are other directions that I want to cast rays towards to check for impacts. A D C x I was trying to add an offset, such as Vector3.Right to the Direction and then normalise the result, however this only works if everything is oriented towards World Space. So how can I convert and add a direction (Vector3.right) as an offset to an existing direction? I'm fairly sure I just have World Space and Local Space directions mixed up but can't see an easy way to convert between this with Vector3?


How to execute code every x seconds in unity? So I have a flashlight battery script I created and I need to know how do you make the battery variable go down every few seconds(whatever time you set.) I tried InvokeRepeating but it was an absolute disaster (The battery variable just went down really fast and ignored my script). Anyways this is the code I have void Update () if (light false) battery 0 if (light true) battery This is what I want to have every few seconds if (battery 0) myLight.enabled false light false battery InvokeRepeating("invoke", 1, 0.01F) void invoke() light false myLight.enabled false


How to show specific item in question on trigger entry? (Unity c ) So I have multiple, random objects on a plane, and when my player walks into them, I want them to be 'picked up'. The player can only hold one object at a time, and needs to return the item to the base before he can pick up another. Using the OnTriggerEntry function in a collider script, a set of commands are called when the player touches the object. Within the function, the 'itempickup' function from the player script is called using 'col.transform.SendMessage()'. How do I tell the itempickup function which specific object was 'picked up' in the trigger script? That is, is there a variable of some kind that acts as an ID for game objects? Thanks )


How to rewind time on just the main character? I have a 2D sidescrolling game and I want the character to be able to rewind time on him if he messes up. I don't want anything else to change, just the main character's position. Any idea how I can do this?


Blender Unity Import Animation Failing by Overlapping Mesh Objects I'm new to both Unity and Blender. I created this penguin 3d model, rigged it up and animated it in Blender and all looked good. When I imported it into Unity, I noticed that this idle animation did not appear to be working correctly. As the body moves, the body mesh overlaps the belly mesh and covers a portion of it. This is not the case when viewing the animation from blender 2.9. The belly uses a shrinkwrap modifier with the body as a target. Is this a problem with Unity import, or how I modeled this penguin in Blender? Can anyone see what I have done wrong here? Any help is much appreciated!


How can I change a materials properties in my Unity c code? Hello everyone I want to change my materials tiling offset in code, but the only way I found to access it other than drag dropping to a public field in inspector is to check by name. But I then noticed the name is suffixed with ' (Instance)' . So it seems a little odd to me having to access it this way, is there another way that I don't know about? foreach(Material m in GetComponent lt MeshRenderer gt ().materials) if (m.name "card front (Instance)") m.mainTextureOffset new Vector2(value 1 13f, (int)suit 1 5f)


How to cast colored shadows I have a glassy object and when light passes through it I want it to cast colored light behind it, instead of the shadow. I could just use another light object to cast that colored light, but is it possible to do this using shaders?


How to create a boxcollider, which surrounds the gameobject and all of his children? I have a Car, who needs a Box Collider. If the car would be 1 single mesh, i would only need to call boxCol gameObject.AddComponent lt BoxCollider gt () and it would create a boxCollider, which fits perfectly my car, based on my car's mesh. Now I have a car which exists of many different parts in the hierarchy. (for example Body of the car is the parent of the 4 doors. Every door is 1 seperate gameobject, and has a doorknob child etc. ) now i need a script which changes the boxCollider so, that it has the box surrounding the whole car. i found http answers.unity3d.com questions 22019 auto sizing primitive collider based on child mesh.html but it just doesnt get me the right collider. Edit I just tried again and the Boxcollider stays the same. using UnityEngine using UnityEditor using System.Collections public class ColliderToFit MonoBehaviour MenuItem("My Tools Collider Fit to Children") static void FitToChildren() foreach (GameObject rootGameObject in Selection.gameObjects) if (!(rootGameObject.GetComponent lt Collider gt () is BoxCollider)) continue bool hasBounds false Bounds bounds new Bounds(Vector3.zero, Vector3.zero) for (int i 0 i lt rootGameObject.transform.childCount i) Renderer childRenderer rootGameObject.transform.GetChild(i).GetComponent lt Renderer gt () if (childRenderer ! null) if (hasBounds) bounds.Encapsulate(childRenderer.bounds) else bounds childRenderer.bounds hasBounds true BoxCollider collider (BoxCollider)rootGameObject.GetComponent lt Collider gt () collider.center bounds.center rootGameObject.transform.position collider.size bounds.size


Determine Mesh Vertex Index Given Another Mesh Index Please bare with me as I explain what I am trying to accomplish P Each 'X' below represents a mesh vertex For my Unity3d GameObject (G1) the mesh vertices are stored in a C List object in the following order. Note the mesh index 'A'. This is a value I know in this case A 16 (mesh index 16). I have another GameObject (G2) whose shape is the same (a simple rectangle) but the mesh vertices are ordered differently. Note the mesh index 'B'. This is a value I dont know and I want to find this value (mesh index) in this case B 17 (mesh index 17). As you can see the mesh arrangement is pretty much the same except rotated 90 degrees. If I know the 'mesh vertex index' of A how can I find the 'mesh vertex index' of B? Whats an algorithm that can calculate the mesh index of B? My attempt is not working at all uint A 16 uint nCols 6 uint nRows 4 Technically both B and A sit on Row 3, Column 5 so if I can find A's row and column maybe I am there? uint aCol 16 nCols nup not right uint aRow (16 nCols) 1 gives 3 Once I've calculated aCol and aRow its easy uint B (aRow nRows) aCol ie, (3 4) 5 17


Why is my sine based scale animation not changing? I followed the code at this YouTube channel https www.youtube.com watch?v OR0e 1UBEOU amp t 4178s, and did some modification on the code so that the scale of the bird will change during projectile using the absolute sine function under the if statement. I'm using the scale (16 20) sin(distance) for my x and y component. However, when I launch the game, the scale stays as 0 along the path. Why is my scale staying as a constant zero? using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour Vector3 OldPosition Vector3 DistanceDifference float TotalDistance 0 Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 void start() OldPosition transform.position private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1) DistanceDifference transform.position OldPosition TotalDistance DistanceDifference.magnitude OldPosition transform.position transform.localScale new Vector3((16 20) Mathf.Abs(Mathf.Sin(TotalDistance 5)), (16 20) Math.Abs(Mathf.Sin(TotalDistance 5)) , Mathf.Sin(TotalDistance 5)) if (transform.position.y gt 15.00 transform.position.y lt 15.00 transform.position.x gt 18 transform.position.x lt 18) string currentSceneName SceneManager.GetActiveScene().name SceneManager.LoadScene(currentSceneName) void OnMouseDown() GetComponent lt SpriteRenderer gt ().color Color.red private void OnMouseUp() GetComponent lt SpriteRenderer gt ().color Color.white Vector2 directionToInitialPosition initialPosition transform.position GetComponent lt Rigidbody2D gt ().AddForce(directionToInitialPosition launchPower) GetComponent lt Rigidbody2D gt ().gravityScale 1 birdWasLaunched true private void OnMouseDrag() Vector3 newPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position new Vector3(newPosition.x, newPosition.y)


How do you reference one game object from another? I am trying to reference a game object that was created in the editor and added to the scene (not created dynamically). How can I reference this object in a script added to another gameobject? For example I have a Mesh called QuantumCold B (in the editor), and I try to get its position in a script to be added to First Person Player, but instead I get Unknown identifier ('QuantumCold B'). Here is my script function Update () transform.RotateAround(QuantumCold B.position, Vector2,20 Time.deltaTime) Also is position the right way to get the Vector position on QuantumCold B?


Transactions on lists of coins of different values For learning purposes, I am developing the first steps of an idle game with exponentially higher income numbers. Usual int, long, etc. can't store big enough numbers for that. I looked through many threads which I found on google and using a list (or an array) which is separated in e.g. bronze coins, silver coins, gold coins, etc. seems to be the cleanest version. In my first approaches I created this list namespace Coins public class script coinHandler MonoBehaviour public List lt Coin gt coinList new List lt Coin gt () list based on the quot Coin quot class new Coin() Name quot bronze quot , new Coin() Name quot silver quot , new Coin() Name quot gold quot , new Coin() Name quot diamond quot , public class Coin public string Name get set public int Amount get set public int Multiplier get set I want each coin type to go up to 999999. This means 1 silver 1000000 bronze, 1 gold 1000000 silver. I can't get my head around a way to do maths with this list. Example Player has 3000 GOLD, 320000 SILVER, 524321 BRONZE Player wants to buy something for 20 GOLD, 120000 SILVER, 300000 BRONZE Just subtracting 20 from GOLD, 120000 from SILVER, and 300000 from BRONZE won't always work. For example when a Player has no BRONZE but some SILVER you can't subtract 300000 BRONZE without converting SILVER to BRONZE first. Q What would be an efficient function to subtract the price from the total amount? What about multiplying and dividing? Accuracy is not important. When spending a few GOLD, nobody will care about 10000 BRONZE.


Only 1 TextMeshProUGUI being affected by coroutine I have a prefab m wordContainer which is empty other than having a TextMeshProUGUI as a child (I did this so that I could position this container freely not being bugged by an animation played by the TMPUGUI object). At the start of the program I start a coroutine (SpawnWordPopups) which splits the words in a sentence, making a copy of m wordContainer and assigning that word to the text property of its TMPUGUI, spawning such m wordContainer in a random location within the screen, and then starting a coroutine (FadeText) that fades in the text of every TMPUGUI. The problem is that only one of the TMPUGUI has its text faded, even though the FadeText coroutine is called seemingly correctly. All words are shown as expected, only thing missing is the fading effect on all but the first word that fades. If I called FadeText like this if (i gt 0) yield return FadeText(true, tmpText, 2) then only the second word will be faded. SerializeField private GameObject m wordContainer void Start() yield return StartCoroutine(SpawnWordPopups( quot test foo bar quot )) private IEnumerator SpawnWordPopups(string l line) string words l line.Split(' ') List lt Vector3 gt wordPositions new List lt Vector3 gt () for (int i 0 i lt words.Length i) Vector3 spawnLocation new Vector3(Random.Range(m wordScreenDistanceOffset, Screen.width m wordScreenDistanceOffset), Random.Range(m wordScreenDistanceOffset, Screen.height m wordScreenDistanceOffset), 0) if (IsWordOverlapping(wordPositions, spawnLocation)) i continue wordPositions.Add(spawnLocation) GameObject wordContainer Instantiate(m wordContainer, transform.parent) wordContainer.transform.position spawnLocation TextMeshProUGUI tmpText wordContainer.GetComponentInChildren lt TextMeshProUGUI gt () tmpText.text words i yield return FadeText(true, tmpText, 2) private IEnumerator FadeText(bool l fadeIn, TextMeshProUGUI l textBox, float l time) float time Time.time float until Time.time l time int alphaFrom l fadeIn ? 0 1 int alphaGoal l fadeIn ? 1 0 Color textColor l textBox.color textColor.a l fadeIn ? 0 1 l textBox.color textColor while (time lt until) textColor l textBox.color textColor.a Mathf.Lerp(alphaFrom, alphaGoal, Time.time l time) l textBox.color textColor time Time.deltaTime yield return null textColor.a l fadeIn ? 1 0 l textBox.color textColor Could anyone shed some light into this issue I'm having? Why are not all the words being faded?


Adding some new velocity to player in FixedUpdate. Should I use FixedDeltaTime or nothing? I am trying to learn how to move objects in Unity without using the built in features like AddForce etc. Some tutorials on Unity website (and other places) is where I have got most of my 'knowledge' so far from. This script for moving players (in topdown Space SHMUP) has been working fine for me and includes acceleration and artificial drag (basically 'smooth' movement, or like being on ice). I'm sure this code is overly long, bloated, inefficient and in most cases downright wrong, but it is written for me to understand it, rather than simply using Unity Prefabs and AssetPackages i download from Store. QUESTION Do I need the Time.fixedDeltaTime mutlipiers when calculating my 'delta v' values here. And also what about on the drag part at the bottom. As usual all help and comments are greatly appreciated. Thanks! public class Player Movement SpaceShooter TopDown MonoBehaviour public Vector2 maxVelocity public float drag public float moveForce private Rect moveBounds private Rigidbody2D rb private void Start() rb GetComponent lt Rigidbody2D gt () moveBounds Game Manager.instance.ScreenBounds private void FixedUpdate() float input h Input.GetAxis("Horizontal") float input v Input.GetAxis("Vertical") Vector2 delta v Vector2.zero delta v.x input h moveForce Time.fixedDeltaTime delta v.x Mathf.Clamp(delta v.x, maxVelocity.x, maxVelocity.x) delta v.y input v moveForce Time.fixedDeltaTime delta v.y Mathf.Clamp(delta v.y, maxVelocity.y, maxVelocity.y) Vector2 pos rb.position Vector2 vel rb.velocity if (pos.x lt moveBounds.xMin) pos.x moveBounds.xMin vel.x 0f if (pos.x gt moveBounds.xMax) pos.x moveBounds.xMax vel.x 0f if (pos.y lt moveBounds.yMin) pos.y moveBounds.yMin vel.y 0f if (pos.y gt moveBounds.yMax) pos.y moveBounds.yMax vel.y 0f rb.position pos rb.velocity vel delta v rb.velocity rb.velocity (1 Time.fixedDeltaTime drag) It appears to me that if FixedUpdate was somehow slowed down, the velocity would get changed slower, the same with the enemy movement but I don't know how that would effect the gameplay and if how the slowing down would occur


Selective Image Effects with Stencils I am trying to create an image effect where only a part of the image has the effect applied to. One way I can think of to do this is to define the portion of the image using the stencil buffer. Stencil Mask Shader Stencil Ref 1 Comp always Pass replace Image Effect Shader Stencil Ref 1 Comp equal Pass keep OnRenderImage Function void OnRenderImage(RenderTexture source, RenderTexture destination) saturationPassMat CheckShaderAndCreateMaterial(saturationShader, saturationPassMat) saturationPassTex RenderTexture.GetTemporary(source.width, source.height, 24) Graphics.SetRenderTarget(saturationPassTex.colorBuffer, source.depthBuffer) Desaturate(source, saturationPassTex, saturation) Graphics.Blit(saturationPassTex, destination) Applying the stencil portion of the image effect shader to any other object produces a desirable stencil effect (aka it works). The Problem By the time OnRenderImage is called, it seems that the stencil buffer has already been cleared. Changing Ref to 0 in the Image Effect shader will apply the effect to the entire screen. Any other value will result in a black screen. This can only mean that the stencil buffer has been cleared to 0. Is there a way to prevent the stencil buffer from clearing? Or is this the right method to use the stencil buffer with image effects? Or perhaps there are other solutions that are still efficient, without the use of Stencils?


How to use an overlapping shader so that it uses layers sort from sprite renderer and its transparent Im using the shader from question , but once I put it in the game, and my character gets close to it, it will be hidden by the shadow of the tree, which is transparent. Any way to make the shader transparent and or maybe use the sprite renderer sort layer system I have been trying to use stencil configurable shader with no luck Thank you for your help Not sure what combination of these should work The character is using a normal sprite renderer.


Unity 4.6 sprite image automatically splits to single sprites when clicking I'm viewing Unity tutorial. As in this tutorial, I see when author clicks to sprite image, they will automatically divide to each frame as below But in my Unity, I just can view this So. My question is How can my sprite image automatically divides to each sprite. Thanks )


Make HD trailer for Unity game I am making a HD trailer for my Unity game. How do I record awesome HD shots of my game inside the Unity editor?


Reused Avatar moves mesh I have a humanoid avatar and it's animation controller. I also have two different human meshes, they're quite similar. When I use the generic avatar and it's controller in the animator the meshes shot out into the sky and perform their animation correctly. The animations run normal they just move in weird directions and don't stay in their original locations. How to fix it so the mesh doesn't move far away and retain original position?


Best practice for 4x game management in Unity? I'm trying my hand at creating a turn based 4x game in Unity, with a galaxy map and 2D hexagon grid maps for each individual planet. The planet grid hexes would be gameobjects, with the overall grid being around 30x40 in size. The number of planets would be under 50. What would be the best way to set this up? I'm looking for a solid approach regarding performance here, but one that also caters to easier design programming would be a plus. Some approaches I've come up with Load all of the grids for the individual planets at the start into a single scene, with each being under a "planet gameobject", and then set those gameobjects to inactive. The galaxy map would be its own scene that is loaded additively when needed clicking on a planet to view it would set its associated gameobject to active and then unload the galaxy map scene. Instantiate the gameobjects for planets as they're called up the grid data for the planet is dynamically loaded as part of this. The planet gameobject is destroyed when no longer needed. Galaxy map would function the same as approach 1. Individual scenes for each planet, loaded unloaded additively when needed. A separate, single scene would be used for loading procedurally generated planets. Seems to have serious challenges for managing units resources across planets scenes. Approach 1 seems to be the most straightforward, as the core of the game would be managed in a single scene, but I am concerned about performance. I'm setting up some test projects to stress test the approaches, but it'd be great to get feedback from someone with more experience. Any help is appreciated!


How do I get an object to rotate in world space via RigidBody.AddTorque? I'm getting really discouraged because I can't seem to figure how how to rotate my object via Rigidbody.AddTorque like it is on a figurative global turn table rather than a local turn table. Another way of describing it is that I want to c calculate a torque vector that will rotate the object's yaw and keep it upright regardless of its pitch without rolling it around. This is a problem for me because I want my player to remain upright without ending upside down because they were pitched and decided to turn. Someone else had posted about the same problem on a different forum but he didn't receive much in the line of help, however he did provide this really helpful image describing the problem Notice how the left object is tilted and then rotating with respect to its own local coordinates but the one on the right is rotating with respect to the global coordinates instead of rolling around like the one on the left. How can I achieve this? Is there something obvious I am overlooking or forgetting? Am I explaining it right? EDIT In the following image the top half illustrates what I want while the bottom half is showing what is actually happening. What I want is to be able to tilt the player's pitch and have them be able to rotate almost like a turret. I was able to accomplish this for demonstration purposes by first rotating the player and then pitching. Instead what I am getting is if the player tilts their pitch and then turns they start to bank, or in other words they start to roll. My code looks something like this rigidBody.AddTorque(Vector3.up horizontal RotateImpulse Time.fixedDeltaTime, ForceMode.Impulse) rigidBody.AddTorque(Vector3.right vertical RotateImpulse Time.fixedDeltaTime, ForceMode.Impulse) I sincerely appreciate you all offering to help me with this.


Firing a particle effect toward the tapped target I am editing this game, where i have to destroy this pyramid when user will tap, i want to show particle effect moving towards Pyramid Like this but sometime it is not moving towards pyramid like this but moving straight Like this Script for RayCast and Particle Effect Instantiation using System.Collections using System.Collections.Generic using UnityEngine public class General MonoBehaviour public static GameObject currentPyramid RaycastHit Hit public GameObject LineStart public GameObject ParticleEffect void Awake() void Start() void Update () Debug.Log (currentPyramid) if (Input.GetMouseButtonDown (0)) RaycastHit hitInfo new RaycastHit () bool Hit Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo) if (Hit) currentPyramid hitInfo.transform.gameObject if (currentPyramid ! null) Instantiate (ParticleEffect, LineStart.transform.position, LineStart.transform.rotation) code for Pyramids using System.Collections using System.Collections.Generic using UnityEngine public class PyramidScript MonoBehaviour void Update () if (PlayerPrefs.GetString ("Pyramid") gameObject.name) General.currentPyramid this.gameObject


How to make a gui button follow a path after a touch? I would like a button in my gui menu to follow a specific path if we selected it, I am wondering how I could do it if we touch the button, then it can only move on the specific path, it is an arc such as this path Would you know how to achieve this? I am using Unity, but I think the theory should be the same for other software language ? Thanks for your help EDIT here is the code for the bezier curve in unity Where should I put the script? using UnityEngine using System.Collections public class DrawBezierHandle extends Editor public Transform startT public Transform endT function Start() startT GameObject.Find("start").GetComponent("Transform") as Transform endT GameObject.Find("end").GetComponent("Transform") as Transform function OnSceneGUI() var width float HandleUtility.GetHandleSize(Vector3.zero) 0.1 Handles.DrawBezier(startT.position, endT.position, startT.position 5 Vector.up, endT.position 5 Vector.up, Color.red, null, width)


Interpolate object collision stuck in Unity I am working on a very basic test in 2D. The problem I am having is that, when my sprite collides with the ground, it is checking the event too frequently. The sprite stays in limbo, as it doesn't have a chance to leave the ground. By the time it does, the check tells it to turn around, resulting it quickly going up and down. I uploaded an example clip to YouTube. When contact is made, the sprite needs to change it's Y axis direction. How do I fix this? Please see my code, below void Update () hitWall Physics2D.OverlapCircle(wallCheckUp.position, wallCheckRadius, whatIsWall) if (hitWall) moveUp !moveUp if (moveUp) transform.localScale new Vector3( 1f, 1f, 1f) GetComponent lt Rigidbody2D gt ().velocity new Vector2(speed, GetComponent lt Rigidbody2D gt ().velocity.x) else transform.localScale new Vector3(1f, 1f, 1f) GetComponent lt Rigidbody2D gt ().velocity new Vector2( speed, GetComponent lt Rigidbody2D gt ().velocity.x) Here is my object


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


Can I use Google Ads on a game published on non Google platforms? I just made a game with unity personal. And I want to publish release it on sites like Getjar, Aptoide, Slideme etc. instead of Play Store. So I want to know if I can still get revenue from Google ads or if I have to publish it on the play store to get revenue from ads.


What is the standard practice for animating motion move character or not move character? I've downloaded a bunch of (free) 3d warriors with animations. I've noticed for about 25 of them, the 'run' animation physically moves the character forward in the z direction. For the other 75 , the animation just loops with the characters feet moving etc., but does so in place, without changing the character's physical location. I could fix this by 1.) Manually updating the transform in code for this 75 , to physically move the character 2.) Alter the animation by re recording it, with a positive z value at the end (when I did this it caused the character to shift really far away the rest of the units, probably something to do with local space vs world space I haven't figured out yet). But before I go too far down this rabbit hole, I wonder if there is any kind of standard? In the general case, are 'run' 'walk' animations supposed to move the character themselves, or is it up to the coder to manually update the transform while the legs move and arms swing in place? Is one approach objectively better than the other, or maybe it depends on the use case? If so, what are the drawbacks of each? I know nothing about animation, so I don't want to break convention (if there is one).


How can I pool objects with differing properties? My game requires a 2D GameObject to be spawned every second until they fill the whole screen and the game ends (around 60 objects total). On Android I see some performance spikes whenever a GameObject is spawned, so I'd like to use object pooling to help alleviate this. However, some of my objects have random properties like a second sprite, different tag, particle effect, and so on, so I don't think it's possible to save them for object pooling. Is there any way for me to pool objects that have variable properties?


Having trouble defining a FindMyTag I'm not a coder, im an artist, so this stuff doesn't make a ton of sense to me. I know enough to know I don't know enough, and i'm old enough to know my brain doesn't 'get' code... that said for context of what level of help I need ) ... I'm trying to get an AI path based on an object tag. When I instantiate the object this script is on, it should look for 'mytag' on another object in the scene, and set that as 'target' public class pickAItarget VersionedMonoBehaviour lt summary gt The object that the AI should move to lt summary gt private Transform target public string mytag IAstarAI ai void Start() Debug.Log(GameObject.FindWithTag("mytag")) GetComponent lt pickAItarget gt ().target GameObject.FindWithTag("mytag").transform The script compiles fine and im able to put in the tag I want to find in the inspector but when the object instantiates I get UnityEngine.GameObject.FindWithTag (System.String tag) (at C buildslave unity build Runtime Export Scripting GameObject.bindings.cs 195) Pathfinding.pickAItarget.Start () (at Assets Scripts pickAItarget.cs 26) I feel like I HAVE defined mytag, but obviously I don't understand something.


Find out triangles that are not occluded from a camera view? For a project i need to find out triangles that are directly seen by the camera user. Triangles that are occluded by other triangles should be ignored. There may be 200 thousand triangles in a model, so raycasting on a CPU is no possibility due to performance. Is there something build in to unity or opengl that can do this? If not how would you approach this problem? Many 3d editing software use techniques, e. g. to select or slice only triangles that are visible.


Is this bad design to have a static class which plays sound effects? I am trying to make a audio manager. I want this audio manager to setup itself and be accessible from everywhere. So I made a static class that creates the audio sources when you need them. Is this bad design? using System.Collections using System.Collections.Generic using UnityEngine using NodeEditorFramework.Utilities public static class AudioManager private static bool musicIsSetup private static AudioSource musicSource private static bool sfxIsSetup private static AudioSource sfxSource public static void ManualSetup() SetupSFXSystem() SetupMusicSystem() public static void PlaySFX(AudioClip clip) if (!sfxIsSetup) SetupSFXSystem() sfxSource.PlayOneShot(clip) public static void PlayMusic(AudioClip clip) if (!musicIsSetup) SetupMusicSystem() musicSource.clip clip if (!musicSource.isPlaying) musicSource.Play() private static void SetupMusicSystem() musicIsSetup true GameObject MusicHandler new GameObject("MusicHandler") musicSource MusicHandler.AddComponent lt AudioSource gt () private static void SetupSFXSystem() sfxIsSetup true GameObject SFXHandler new GameObject("SFXHandler") sfxSource SFXHandler.AddComponent lt AudioSource gt ()


How can I make a look around effect of the player some kind of cutscene? I want that at some point in the game the player will be looking over the view out of the window. So I added a new Camera and positioned the camera close to the window. Then using a small script I'm turning the Camera on. But after turning the camera on I wan to make that the camera will rotate around the window area so it will give a natural feeling that the player is looking over the view outside. And the script that is attached to another GameObject that activating the Camera using System.Collections using System.Collections.Generic using UnityEngine public class ItemAction MonoBehaviour public Camera viewCamera private void Update() public void ViewCamera() viewCamera.enabled true The part I'm using is the ViewCamera method. But I messed it up. But the idea is after turning on the Camera to make it feel like looking around the view outside. How can I make the camera move first to one direction and then mirrored to the other direction ? using System.Collections using System.Collections.Generic using UnityEngine public class ItemAction MonoBehaviour public Camera viewCamera public float Speed public void ViewCamera() viewCamera.enabled true StartCoroutine(animate()) IEnumerator animate() while (transform.localEulerAngles.y gt 45) transform.Rotate(0, Time.deltaTime Speed, 0) yield return null and then possibly the same but mirrored to look in the other direction while (transform.localEulerAngles.y lt 45) transform.Rotate(0, Time.deltaTime Speed, 0) yield return null The way it is now it's just keep rotating to the same direction nonstop.


Animator, gameObject position not being kept I have idle amp popout animations. Idle simple scaling up and down 2d object and popout get the gameobject's position to the right and leave it there. I'm using animator for this purpose. I have a trigger Popout, which when triggered the animator goes from playing the Idle animation to the popout animation. Then another transition from the popout anim back to the idle anim. The problem is that when it gets back to the idle anim, the position gets back to the first one(i.e. as if the popout anim hasn't been played). My goal is, after playing the popout, the gameObject to stay at the last position from the popOut anim and to continue to be scaled up and down(the idle anim). My goal is, the gameObject to keep its last position set from the popout anim(which is to the right of its initial one) and to continue playing the idle anim from there instead of going back to its initial position. Why does the animator reverses the gameobejct's position to its initial one, after the popout anim has been played? In this video you can see the problem and what exaclty I'm doing.


How can I launch the Unity Editor and open a specific project from C code? I created a very simple console application namespace ConsoleApplication4 class Program static void Main(string args) The project I want to open var arg """ projectPath C Users Administrator Downloads New Unity Project""" Start Unity and open the project Process.Start( "C Program Files Unity Editor Unity.exe", arg) But only the Unity Editor is launched the specified project is not opened. What do I need to modify to launch the project?


most efficient way to create a grid system in unity I'm creating a little tower defence game to get myself acquainted with unity. At first I was going to emulate a grid system by capturing touches mouse clicks and rounding the coordinates to the nearest whole numbers. This is very low cost and works well for placing things, however I'm a bit of an AI geek and I've decided to make a more tangible grid so that the agents can run searches on it for pathfinding. For this I'll need a grid of nodes and for those nodes to have a bit of information attached. Would it be a much better idea to do this entirely in code? Or could I get away with placing actual cubes in a big grid on the map? This would certainly be easy as then I could ray cast against them but I've tried this and rendering that many cubes slows down the game a lot! I suppose my question is is it unnecessarily expensive to have a load of cubes set up like this, but not rendered? Or should the cost of having a load of cube shaped collision volumes be only marginally more expensive than emulating this in code? (if at all...) Also as a side question should I be able to render say, 200 cubes and have a smooth game? Am I missing some instancing options? I presumed things would be automatically instanced.


What to use if you want a looping list? No, I'm not talking about foreach. I have the following list public List lt float gt angles new List lt float gt (new float 0, 90, 180, 270 ) This list can vary depending on the object I use, having only 0 and 90 or all except 270 for example. What I want to do is have a rotClockwise and rotCounterClockwise function that grabs the value before or after a given value. Here's some pseudo code function float rotClockwise(angle) return angles.grabNextAngle(angle) function float rotCounterClockwise(angle) return angles.grabPrevAngle(angle) So calling rotClockwise(90) would return 180, rotCounterClockwise(90) would return 0, rotClockwise(270) would return 0, etc. How can I accomplish this? Is there a list type that allows me to loop back to the beginning when I reached the end?


Show 3d object on device live camera in Unity3d for iOS Possible Duplicate How to add render able Texture in Unity 3d for iOS How render a 3d or 2d(.jpg or .png )object at device live camera in Unity3d, and this 3d object shouldn't stuck with camera. It has to show at specific point, like we can set any object in game scene at particular location.


Array Out Of Range Exception I have been working on my this aspect of my project since last night and have finally got this code to work exactly as I want it to. However if the first target is removed before the second one, I get an out of range exception. I would like to know if there is a better way to fix my problem. void LateUpdate() if (targets.Count 0) return Move() Zoom() void Move() GetBoundsData() Vector3 newPosition new Vector3(centerPoint.x offset.x, transform.position.y, centerPoint.z offset.z) transform.position Vector3.SmoothDamp(transform.position, newPosition, ref velocity, smoothTime) SerializeField Bounds bounds SerializeField Vector3 centerPoint public Vector3 maxBoundsPoints void GetBoundsData() if (targets 0 null) targets.RemoveAt(0) if (targets.Count 1) centerPoint targets 0 .position SetUpBounds() centerPoint bounds.center maxBoundsPoints bounds.max void SetUpBounds() bounds new Bounds(targets 0 .position, Vector3.zero) for (int i 0 i lt targets.Count i ) if (targets i null) targets.RemoveAt(i) bounds.Encapsulate(targets i .position)


Improving Position Sync Bandwidth Usage in a Multiplayer Game This is the class i use to sync position between clients in a multiplayer top down 2D shooter game System.Serializable public class MovementUpdateClass public int MessageTime get set public Vector2Serializer PosXY new Vector2Serializer() public Vector2Serializer VelXY new Vector2Serializer() public float RotZ get set public MovementUpdateClass(int messageTime, Vector2 posXY, Vector2 velXY, float rotZ) MessageTime messageTime PosXY.V2 posXY VelXY.V2 velXY RotZ rotZ Any advices about how to improve amp optimize it so it spends less bandwidth for both sender and receivers? Thanks.


uNet Client cant see server spawned objects I'm facing a problem where when I connect with the host, all the towers spawn. After I connect with a client only to find out there are no towers visible and I can walk through them when looking at the host screen. My tower spawn script ( GameManager.cs ) public int numberOfDestroyedTopTowers 0 public int numberOfDestroyedMidTowers 0 public int numberOfDestroyedBotTowers 0 public GameObject topTowerSpawns public GameObject midTowerSpawns public GameObject botTowerSpawns public GameObject towerPrefab void Start() CmdSpawnTowers() Command void CmdSpawnTowers() for (int i 0 i lt midTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position midTowerSpawns i .transform.position currTower.name "Tower MID " i NetworkServer.Spawn(currTower) for (int i 0 i lt topTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position topTowerSpawns i .transform.position currTower.name "Tower TOP " i NetworkServer.Spawn(currTower) for (int i 0 i lt botTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position botTowerSpawns i .transform.position currTower.name "Tower BOT " i NetworkServer.Spawn(currTower) The script is derived from NetworkBehaviour and it does have a Network Identity on it (Server Only checked). Also on my towerPrefab I also have a network identity with server only checked. I have added my tower prefab under the network manager "Registered Spawnable Prefabs".


Pivot not updating programmatically I have a canvas. It has an empty game object as a child. That object has a RectTransform component. The RectTransform pivot value is set to 0.4, 0.5 (x, y). In some code I wanted to update the pivot value using the following Debug.Log(((RectTransform)transform).pivot) logs (0.4, 0.5) ((RectTransform)transform).pivot.Set(0.3f, 0.8f) Debug.Log(((RectTransform)transform).pivot) logs (0.4, 0.5) I don't know why the set command is not working. The tooltip for Set is "Set x and y components of an existing Vector2"


FPS Hands Weapon Animation I want to create multiplayer first person shooter . Now I want to create animation where the soldier is walking with rifle . I have separated hands from the body of the model and I have dropped hands and rifle in the camera , but when I move the camera hands don t move with camera but the rifle does . Hands are controlled by the bone . How can I make the walk animation camera movement together?


Unity3D Lightmap bleeding in standalone build I'm running into an issue about some lightmap glitches made of black seams lines occuring only in the standalone build of our game, and it does only affect certain scenes. below is attached a screenshot of both editor and .exe build of the same scene. I'm also attaching below the current Lighting settings for that current scene, but before, our second UV Channel is not generated inside Unity3D but authored in 3DSMAX Now, even if the generated lightmaps are 4096, their texture inspector shows a max size of 2048 and no compression (tried a build with a max size of 4k with no change), i also discovered that Mip Maps are enabled by default (might be the problem ?). Above all, my build settings are Windows standalone x86, although the game is VR Only wouldn't be better to make it x86 64 only and would it solve this issue ? Current Unity Version and infos Unity 5.6.0f3 Oculus Utilities 1.14 Build settings for windows Auto graphics API Static Dynamic Batching GPU Skinning VR supported (Oculus OpenVR) MultiPass Stereo Rendering Optimize Mesh Data enabled. Mesh import infos Mesh compression off Read Write enabled Optimize Mesh Enabled Normals Import i would also state that we had a previous gearVR build (with 2048 resolution lightmaps) and this issue was never encountered Thank you.


Get internal and external IP addresses in Unity 2018.2.0? Unity 2018.2.0 makes the Network class obsolete. I have used "Network.player.ipAddress" in my code to get the local LAN IP address. internalIP Network.player.ipAddress externalIP new WebClient().DownloadString("http icanhazip.com") What code should replace this? What would be best practice for getting internal and external IP addresses for manual LAN and internet direct connections between server and client? Internal external IP addresses are needed so players can load the game, then tell their friends what their IP is to direct connect.


Can't open scripts in Unity 2019.2.11.f1 version I'm using Visual Studio 2017, Unity Hub to 2.1.3 and just created a project using Unity's 2019.2.11.f1 version. Once trying to open a script in Unity, it doesn't open and then I'm forced to use Task Manager to End Unity's task because can't even close it normally due to not being able to interact with the screen. No errors or warnings, VS doesn't open, can't interact with Unity anymore. This doesn't block me from working, it just isn't as convenient as before.


Why do I not see the back of a model in the model I have created a die in blender, that uses two materials. One material is transparent and the second is opaque. When I look throught the die, I expect to see the opaque parts blocking the view, but I do not see them at all. As you can see in the image above, the 6 dots on the back of the die are not shown, it just looks like it is empty. What can I do to fix this?


Sticking to a moving platform My character is not sticking on the platform when jumping on it, but I don't know why. I checked, and I have rigidbodys and colliders. The problem appeared when I moved the game to another hard drive. Here is mycode void OnCollisionEnter2D(Collision2D other) if (other.transform.tag "MovingPlatform") transform.parent other.transform void OnCollisionExit2D(Collision2D other) if (other.transform.tag "MovingPlatform") transform.parent null Why doesn't my character stick to the platform?


How do I flatten terrain under a game object? I've got a script that makes a terrain object and paints it with textures, but I'm having an issue. When I attempt to place game objects (such as the simple water object that unity provides), I use a Raycast to determine the correct height to place the game object, but that just ensures that it is correctly placed at that particular point. How would I go about flattening the terrain under the game object so that it doesn't go into the terrain or hang out into thin air in the case of hills?


Why is this MeshRenderer null? The following line fails in my class MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () This is the entire class. All works except the mentioned line. using System.Collections using System.Collections.Generic using UnityEngine public class SphereMaker MonoBehaviour private GameObject Sphere void Start() Sphere GameObject.CreatePrimitive(PrimitiveType.Sphere) Sphere.AddComponent lt MeshFilter gt () MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () Material nMat new Material(Shader.Find("Universal Render Pipeline Lit")) I'm using the URP if (nMat null) Debug.LogError("no mat!! n") nMat.color Color.red nRenderer.material nMat float fSize 0.4f Sphere.transform.localScale new Vector3(fSize, fSize, fSize) Sphere.transform.position new Vector3(0, 0, 0) Does anybody see what I'm doing wrong? Thank you!


.blend scenes are not showing texture in Unity I am new to Unity and Blender. I am getting a problem when importing .blend files into Unity in Unity scenes the textures created in Blender are not showing. But there are no problems with color. How can I fix this problem?


Aim prediction along a parabola How to make a Tower Defence Mortar aim accurately I am building a very basic tower defence game in Unity3D where one tower is your standard long range mortar artillery. I want the projectile it fires to follow a parabola curve to make its movement seem like a mortar. This movement is not dependant on any physics (as I can make a projectile follow a curve but I could implement the Unity3D physics if the method used would benefit from it. My question is What technique should I use to ensure the projectile hits the locked unit whilst taking into account that the unit is moving along a possibly non linear path (defined with my A implementation.) I have not implemented any code as of yet as I wanted to consult the masses for any wisdom you can provide! My initial idea was to fix the time the projectile would take along its parabola curve (regardless of distance) and try and track the position the unit would be at after this time delay. Is this along the right lines or are there alternative methods to consider when aiming a projectile that follows a curved path instead of a linear one? Thank you for your time.


Why it's not removing the right doors from the list? GameObject doorsLeft GameObject.FindGameObjectsWithTag(c doorLeft) GameObject doorsRight GameObject.FindGameObjectsWithTag(c doorRight) List lt GameObject gt allDoors doorsLeft.Union(doorsRight).ToList() for(int i 0 i lt allDoors.Count i ) if(allDoors i .transform.parent.name ! "Wall Door Long 01" amp amp allDoors i .transform.parent.name ! "Wall Door Long 02") allDoors.RemoveAt(i) foreach(GameObject door in allDoors) Debug.Log("Door Parent " door.transform.parent) If it's not "Wall Door Long 01" and not "Wall Door Long 01" then remove the item from the list. After that when I'm doing a loop on the allDoors again and debug log the parents I see that some of the parents are not "Wall Door Long 01" and not "Wall Door Long 02" but after removing they all should be only "Wall Door Long 01" or "Wall Door Long 02" Maybe the comparison is wrong ?


Pinball flippers Joints or not? When making pinball flippers in Unity C , what would be the pros and cons of using a simple mesh transform where the mesh is properly centered around the wanted pivot, so its rigidbody could be torque force rotated vs creating the flipper with a joint? Thanks!


How can I tune material values with the slider in the Unity inspector more finely? I'm adjusting a material's texture tiling and offset values in the editor but its increments are too large and it's jumping over the value I need. Is there a way to slow it down or adjust the amount it increments by (without using a custom script)?


How can I record gameplay footage as a video within Unity? I am building a traffic simulator in Unity. I need to record my game as a video, so that I can use the video for machine learning purposes. I used fraps for the same but didn't find it worked for me since it's not within Unity. How can I make a video recording of the gameplay?


How to force keep the aspect ratio and specific resolution without stretching the output screen view? I'm using Screen.SetResolution() But when I run in Android device, it shows the output image is stretched to fill up the full screen which I don't want. I want it to keep the aspect ratio properly. Example 01 This is coincidentally match and ok because my device screen aspect is 16 9. But here is the incorrect one (stretched) Example 02 This is 640 x 480 in resolution but it should remain in aspect ratio of 4 3. How could I keep it's aspect ratio and make it black at the extra space outside or customize it using my own image to cover the extra space ? in Android. Note I'm not talking about the canvas but entire output view.


Spot Light color fade in Unity 3d I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight. void Update() if(Time.time() 120 0) transform.light.color new Color(Random.Range(0,255),0,0,1) I know I am missing something big here. Help is appreciated. Thanks in advance.


Unity Mirror Shader double image in HTC Vive Steam VR I'm implementing a mirror in Unity for SteamVR HTC Vive. I'm using the mirror reflection shader for Unity. It looks fine, overall, but the left eye and right eye don't align unfortunately, so it's creating double image. How do I resolve it?


Generating lakes and rivers on 2D grid I recently posted a question about how to technically represent a generated terrain similar to the game kingdoms and castles. I got some great advice and decided to create a 1x1 cube at each coordinate since I will have very small maps, for now 50x50. I wrote some code to generate terrain, this is super basic atm and simply instantiates either grass or water tiles depending on the noise value at the coordinate public static class Noise public static float , GenerateNoiseMap(int mapWidth, int mapHeight, float scale) float , noiseMap new float mapWidth, mapHeight if (scale lt 0) scale .0001f for (int y 0 y lt mapHeight y ) for (int x 0 x lt mapWidth x ) float sampleX x scale float sampleY y scale float perlinValue Mathf.PerlinNoise(sampleX, sampleY) noiseMap x, y perlinValue return noiseMap public class MapGenerator MonoBehaviour public int mapWidth public int mapHeight public float noiseScale Space public GameObject grassTile, waterTile public void GenerateMap() float , noiseMap Noise.GenerateNoiseMap(mapWidth, mapHeight, noiseScale) for (int x 0 x lt mapWidth x ) for (int y 0 y lt mapHeight y ) if (noiseMap x,y gt .3) Instantiate(grassTile, new Vector3(x, 0, y), Quaternion.identity) else Instantiate(waterTile, new Vector3(x, 1, y), Quaternion.identity) It generate something like this Now this obviously does not look like a realistic landscape. My question is, how do I decide which values should represent water, and which should represent grass, in order to get a landscape that makes sense? What I would like my landmass to look like something that has lakes and maybe rivers, instead of these random puddles you see in the image above, more something like this EDIT Setting a higher scale value lead to this


Unity Unable to rearrange "Sorting Layer" for 2D game Since yesterday I got a bit into game development with Unity (i've never done game development before), and I am currently making a small 2D game. I am attempting to rearrange the various layers in the "Sorting Layers" list. According to Unity's own official tutorial, you can simply drag amp drop the layers around to rearrange them. However, when I click on one of the layers, I can not drag it anywhere. Can someone help me out?


Why are transform values in inspector different from animation tab? I m trying to make animation in timeline. But transform values in animation tab and inspector are different from each other. It causes problem when try to rotate player. It doesn t rotate the way I want.


PlayerPrefs.SetInt Stops code below from running This is the code... void storeStarData() Code to store star data in PlayerPrefs... Debug.Log("Writing to PlayerPrefs") PlayerPrefs.SetInt("totStars", NumOfStars) int i 0 Debug.Log("test") while (i lt NumOfStars) PlayerPrefs.SetString("starID" i, StarIDID (i) ) PlayerPrefs.SetString("starName" i, StarName (i) ) PlayerPrefs.SetString("starHIP" i, StarIDHIP (i) ) PlayerPrefs.SetString("starHD" i, StarIDHD (i) ) PlayerPrefs.SetString("starHR" i, StarIDHR (i) ) PlayerPrefs.SetString("starGL" i, StarIDGL (i) ) PlayerPrefs.SetString("starBF" i, StarIDBF (i) ) PlayerPrefs.SetString("starRA" i, StarRA (i) ) PlayerPrefs.SetString("starDec" i, StarDec (i) ) PlayerPrefs.SetString("starMag" i, StarMag (i) ) PlayerPrefs.SetString("starCI" i, StarCI (i) ) Debug.Log("star " i " complete") i PlayerPrefs.Save() i 0 int ok 0 while (i lt NumOfStars) if (PlayerPrefs.GetString("starID" i) ! null) ok i Debug.Log(ok) And this is the Debug.Log output that I am getting... As you can see, the program gets up to the First Debug Log Debug.Log("Writing to PlayerPrefs") But then stops before the Debug.Log("test") . After removing PlayerPrefs.SetInt("totStars", NumOfStars) The program gets to the Debug.Log("test") . So it is the PlayerPrefs.SetInt causing the issue. How do I fix this?


Snap to Grid building palcement So I have created plane in which my buildings are going to be placed on and I was wondering how to add grids to it and make my building snap to it, just like in clash of clans. Thanks!


Smoothness texture map in unity I shall submit a 3d asset to the Unity asset store. Their submission guidelines say,"... must include at least an albedo,normal,metallic (or specular) and smoothness texture map." My query is how do I get the smoothness map and where do I put it ? There is just one slot by the smoothness slider where I put the metallic map. Is it really necessary to put a smoothness texture map if I already have a metallic map attached to the material? It's my first attempt to submit an asset to the asset store.


World Canvas InputField cursor precision control from RenderTexture output in Overlay UI How do you have a world canvas input field cursor be controllable from the input being mapped from a UI overlay with its raw image supplied from render texture from a render camera? Described another way World Canvas Input Field gt Render Camera creates renderTexture for gt Screen Overlay UI Raw Texture gt Main Camera How do you have the cursor position be mapped from the Screen Overlay UI Raw Texture?


How can I make an instantiation random? I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far public GameObject anyItem void Start() Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity) Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity) How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?


How to place grass on custom terrain mesh I made a custom terrain mesh and textured it, now I want to place grass on it, but I don't know how. I only find info about grass with the unity terrain. I am not even sure what exactly to look for. What is the best easiest way to place grass on a terrain? I'd like to do it in the shader if possible, but I guess I will need additional geometry if I want it to "stick out"? (Random example picture http www.beamng.com attachments stuff png.16516 ) I'd appreciate a general outline on how to tackle this problem and maybe some links for further reading. Thanks.


Unity SkinnedMeshRender is there a way to cache mesh and restore later? In unity, I'm writing a script that deforms a mesh associated with a SkinnedMeshRenderer pretty significantly. However, at some point, I'd like to reset it back to particular states. I'd like the ability to both reset to its original position, and an intermediate position. Right now, I've tried baking the mesh Mesh originalMesh new Mesh() skinnedMeshRenderer.BakeMesh(originalMesh) But when I then try to restore it skinnedMeshRenderer.sharedMesh originalMesh It doesn't seem to behave as I would have expected. I've also tried Mesh originalMesh skinnedMeshRenderer.sharedMesh deform sharedMesh skinnedMeshRenderer originalMesh but this does nothing since it seems to be just storing a reference. Am I missing something obvious here? Just to add detail, I want to take a snapshot of all the verticies, weights, blendshapes, etc. And then restore everything back to the snapshot at a later moment in time. I can reset the blendshapes fine, but the mesh seems to be messed up.


Serialize classes in unity c Is there some best practices to serialize objects to file on mobile devices in Unity using C . I've tried to search it myself, but found only this link. However, it looks like here they are trying to cache AssetBundles. I'm new to Unity, but I have some experience in iOS (swift) development. Here we have opportunity to cache some objects(variables) in local storage, to avoid overusing network. So I wanted to create some static class (for example Storage), which caches variables to file permanently and return them by some key.


Trying to make pitch black night some meshes still dimly lit I have a directional light as a "sun". At night, I need a pitch black scene, but a mesh I'm using as terrain somehow stays faintly lit when the light intensity is 0. At night The direction light "sun" is rotated so it's beneath my world. The sun light is set to black, intensity to 0 I tried setting fog and ambient light color in RenderSettings to black I tried setting ambient intensity to 0 Notice how the background is lighter than the character. Something is causing that light to remain. However, if I enter playmode with the light object inactive, the coloring works fine.


Start timer when button pressed (what is wrong with my code?) I want a timer to start when my rocket takes off and stop when it lands. Stopping works fine (using a collider and state switching) but I can't get the timer to start when I press the boost button. Currently the timer text is displayed at the moment I pressed the button but clearly has been counting from the moment the scene started, not the moment the button is pressed. Any help will be greatly appreciated. If there is a better way to start the timer rather than when I press the boost button then I am open to ideas! Here is the all relevant code (I think). It appears as though it should be working to me, but it isn't. Timer public Text timerText private float startTime private bool started false private bool finished false void Start () startTime Time.time get time since scene started void Update () if (currentState State.Alive) ProcessBoostInput() ProcessRotationInput() ProcessFiringInput() if (started) RunTimer() private void ProcessBoostInput() if (Input.GetKey(KeyCode.A) (CrossPlatformInputManager.GetButton("Fire1"))) BoostShip() PlayBoostSound() if (started ! true) started true private void RunTimer() if (finished) return else if (started) float timeSinceTimerStart Time.time startTime string minutes ((int)timeSinceTimerStart 60).ToString() string seconds (timeSinceTimerStart 60).ToString("f3") timerText.text minutes " " seconds private void StopTimer() finished true timerText.color Color.green


Why do I see " lt " and " gt " in Unity C code? I copied Unity code from a website and now it contains stuff like amp amp lt T amp amp gt which my IDE flags as an error. It looks like the intended text has been corrupted somehow. What is this supposed to be, and how can I correct it? public class Tree amp lt T amp gt public T Data get set public IEnumerable amp lt Tree amp lt T amp gt amp gt Childs get set public bool Opened get set public Tree() Childs Enumerable.Empty amp lt Tree amp lt T amp gt amp gt () Opened true


Instantly snap into specific directions? In my 2d setup, I want the player to constantly move in a specific direction at a set speed. It's similar to "Snake" in that you can only move in four directions and you can't stop your movement. Right now, the way I do this is by having a char variable "direction", which can either be u, d, l, r (take a guess what those stand for). Based on those letters, I use GetComponent().MovePosition and increase decrease the position on the x or y axis. Is there a better way to do this? I would prefer if I could just enter the degree (0, 90, 180, 270) to make the player move in the right direction. I tried AddForce but I couldn't get it to work. Side note it's important for me that I can set the direction without player input, as there are some objects that force the player into a different direction. Edit As the tag would suggest, I'm looking for a Unity specific answer, as I'm not sure which function would best suit my needs.


Plugins for creating and styling custom Editor Windows like C C Form Designer or Web Inspector ? Unity3d allows to construct window with custom UI. Just need to use EditorGUI EditorGUILayout classes and their static methods. Example of custom window The problem is that all the components have to be added manually via script. Then need to save, switch to Editor, wait for little compile things, and then we can see the result. In web development people use Web Inspector (for example, we can press F12 in chrome, Tab Elements Styles). We can add all needed properties to element and can see the result in real time. EDIT. another example (better than previous) we know C winFormApp, C MFC e.t.c, which has form designer. We can choose any elements and set their properties It would be nice to have similar plugins for Unity So. Does Unity3d have similar tools, utilities, plugins? Utilities to inspect code and editing styles (position, margin, padding, background, width, height, color e.t.c.)?


Can't drag image onto scene First time trying Unity and I'm having trouble with importing assets. border horizontal.png is fine, but I can't drag border vertical.png onto my scene. It also doesn't have an arrow next to it in the asset menu. What is going on here?


Scale a sprite as it moves down a triangle I have a sprite that is inside a triangular like shape. How to make the sprite decrease in size as it moves down the shape? https ibb.co gjc6oS


Movement nudge instead of constant I am making a small game where the player is constantly moving upwards, and I am having slight problems with the movement to the sides. The script located under works quite perfectly in itself, but my problem is that I want the balloon player to nudge in a direction, rather than go at a constant speed. Kinda like a small punch to the side of the balloon. How could I easily implement this? GetMouseButton or GetMouseButtonDown? Thanks in advance. ) void Update () transform.Translate(Vector3.up Time.deltaTime, Space.World) if(Input.GetMouseButton(0)) transform.Translate(Vector3.left Time.deltaTime, Space.World) if(Input.GetMouseButton(1)) transform.Translate(Vector3.right Time.deltaTime, Space.World)


Best practice for toggling between ragdoll and CharacterController One feature of the game I'm working on is that if a character is hit with a certain amount of force, it will temporarily ragdoll, then get up off the ground after a small period of time. This character is moved by a CharacterController (CC) component. At the moment, I have the model as a child of an object with a CC component and movement script. My issue is that when the ragdoll is activated animator is disabled, the model moves independently of the CC if it ragdolls with some arbitrary force in any direction, the CC does not move with it (as you'd expect). This would be fine if the ragdoll wasn't meant to be re enabled, but it is. At this stage, the model teleports moves to where the CC is, and it looks very weird. I have tried a few different methods to synchronize the two Decoupling the CC and model. Both objects are children of a shared parent, and I added them both to an PhysicsIgnoreLayer (for now eventually if I go with this I'll probably add all the ragdoll colliders to an array and ignore them individually). When the ragdoll state is enabled in the parent, the CC is disabled and the object is teleported to the root bone every frame. When the CC is enabled, the model is teleported to the CC object every frame. See here. The issue here is that setting the position means extra Update() calls and it lags behind the controller a little. Also, because the model isn't a child of the controller, it doesn't inherit the velocity of the controller, so it needs to be manually applied. Changing the parented GameObject at runtime. Depending on the state of the character, the CC model will be parented to each other if the CC is active, the model is set as its child and vice versa using SetParent. I couldn't get this one working (the local position variable was a little confusing to me, but no configuration I tried worked for me). Conjoined CC and model. I placed the CC on the same object as the model. This isn't really ideal for me because I want greater control over the rotation and presentation of the model. I couldn't get this one working either I don't know how I could set the position of the CC without moving the whole thing. Is there a more effective way of doing this? If so, what? I feel like I am greatly overcomplicating this. Any help would be great. In an ideal situation, I could have the model as a child of the controller (or behave that way) and move the CC when it is inactive without affecting the model position.


Find centre of rotation from two locations Ultimately I need to get c from the image and have a, b and that it takes 90 degrees to get a to d. My solution to this was to rotate a around to get to d by the rotation. Then use the Y value from a and X from d to get c. So far I an having trouble getting the rotation of a to d to work properly, what am I doing wrong in the rotation? Vector3 d (Quaternion.Euler(0f, 0f, rotation) (a b)) b


UI Button Click Animation We have animation states for Normal, Highlighted, Pressed and Disabled. How to set animation when a button is clicked?(after button released not pressed)? Thanks in advance


Move parent according to child axis in Unity? Can I ask my parent to move according to the child axis? This means if I turn right, then right again, the parent has to be at 180 from its original position, and not only at 90 (because "Right" would mean "stay on the right axis from the parent axis", and what I want is "move the parent according to the child axis"). The parent has a script to move, and the child has the script to rotate, so I would need to use the new rotation from the child, and not the rotation from the parent. My attempt so far is this one in "MoveBody()", oldTr transform.position works without a bug, but it is using the parent axis. With oldTr this objW , there is a bug, the parent goes somewhere in the scene and move its "z" axis in an odd way this obj GameObject.Find("this obj").transform the child to rotate this objW this obj.TransformDirection(this obj.forward) world ... MoveBody( new Vector3( 3.0f, 0, 0 ) ) ... private void MoveBody( Vector3 vec ) Debug.Log("transform.position " transform.position " this objW " this objW) same value here Vector3(0,0,1) oldTr this objW transform.position newTr this objW transform.position newTr vec transform.position Vector3.MoveTowards(oldTr, newTr, sideSpeed Time.deltaTime) Is it possible to do it this way? Or should I translate each axis by hand? Thanks


Multiple cameras using a single skybox with same perspective I am using the enviro package for weather and to have a moving sun in the background. I'm building an installation with 3 screens and I want to have the sun track across the screens. However what I end up with is 3 separate skyboxes and 3 suns, one on each screen. Is there a way I can have the cameras share a single skybox?


How do I add a Rigid body and a box collider component to a Texture2D? I am making a snake game. I'm basing it on a basic tutorial game, which does no collision detection, wall checking or different levels. All snake head, piece, food, even the background is made of Texture2D. I want the head of the snake to detects 2D collisions with them, but Rect.contains isn't working. I'd prefer to detect collisions by onTriggerEnter() for which I need to add BoxCollider to my snakeHead.


Isn't OnGUI and Event cyclical? Here's what I don't understand about Events the documentation says that Events correspond to user input (key presses, mouse actions), or are UnityGUI layout or rendering events. For each event OnGUI is called in the scripts so OnGUI is potentially called multiple times per frame. Event.current corresponds to "current" event inside OnGUI call. the documentation pertaining to onGUI states that it hasone call per event That doesn't make sense to me, because I know I can call Events within OnGUI. I have an OnGUI function that draws a grid using x and y nested for loops, then checks using Event.current.mousePosition if your mouse is hovering over a grid block. What I don't get is how OnGUI is ever called, if OnGUI is only called when an event occurs, but I have the event inside OnGUI so how can you ever check if the event is being called inside a script that is only called after the event is called? I know that probably sounds confusing I'm just puzzled by the seemingly cyclical nature of ongui.


UI Button Not Working On Animation I have hit a problem with my player, I have been following a tutorial on building a platformer. I have put in the UI buttons and linked then to the functions with a script like this public GameObject player link to player script Player playerVariable Start is called before the first frame update void Start() playerVariable player.GetComponent lt Player gt () public void MobileMoveLeft() playerVariable.MobileMoveLeft() public void MobileMoveRight() playerVariable.MobileMoveRight() public void MobileStop() playerVariable.MobileStop() public void MobileFireGun() playerVariable.MobileFireGun() public void MobileJump() playerVariable.MobileJump() When I press the up arrow on the keyboard the player jumps and the animation jump is played, but when I press the UI jump button the player still jumps however the jump animation is NOT played. public void Jump() if (SantaOnGround) SantaOnGround true rb.AddForce(new Vector2(0, JumpForce)) Animation.SetInteger("state", 2)


How can the player open this door and have its collision physics stay in sync? I just finished modeling a scene in Blender like this Now I'm animating and creating interactions between the player and the objects inside the house. When I reached the doors, I started having doubts. Originally, I created the doors animations using Blend Shapes to easly control the transition between the open close states and to allow the door being half opened or closed. (That's because my interaction system allows to interact partially with object, like for example the door system at Amnesia The Dark descent outlast) The trouble is, that the collider of the doors doesn't update when the Blendshapes values changes. How can the player open this door and have its collision physics stay in sync


Errors when baking lights in unity3d So, i'm developing a game in unity and avoided baking lightmaps untill now ( i just assembled my new workstation setup wich is capable of baking the lightmaps and not the computer ). And now i have opened my project, imported it nicely and all, went to the lightning tab and clicked generate lightning ( naturallly i had auto bake disabled). And everytime i do that i get a billion errors, and they do not stop popping up even after i force stop amp cancel, i have to clear baking data in order to do anything ( of course unity is laggy as hell when it's spitting out these errors ). I even tried just a simple scene with just a plane on it. It's the same. I checked and it works fine on another empty project, wich lead me to the conclusion that some texture in my assets folder is causing the error even though it's not on the scene at all. In this case i'm kina doomed, i have absolutely 0 idea wich texture could this be ( i have quite a lot of them) and why would it even cause problems. Any way to check that? Or maybe does somebody know another possible reason for this problem? I tried to do research but found literally nothing. No thread about the issue, nothing. Not even the same errors. Thanks in advance. PS i have baked amp realtime GI disabled


Making my characters modular I'm making a school based sandbox adventure game in Unity. I need a lot of NPCs with different apperances. I dreaded this since I don't have fun doing art and it is usually the reason I end up becoming burnt out of projects. My solution for this was to segregate parts of the characters by color. The skin being green, hair being blue, shirt being red and trousers leg wear being yellow. Then, I would use a shader to change these colors to something else. The result is this sprite sheet and the ability to easily change the apperance of my NPCs to make them look different from eachother but there's still an issue. A lot of the characters have the same hair style etc. Not to mention when I make a new hair style for a female, I have to then draw that style 3 4 more times for the different combinations of clothes. The solution for this that would work ideally would be a modular apporach. I would only need to draw the sprite once and just swap out different clothing combinations. I have attempted this before but the main issue that kept on coming up was the different sprites not lining up, especially when changing the different sprites. The art style is pixel art so they have to line up perfectly to look nice. How should I go about doing this to ensure I can fit every sprite together perfectly, no matter the combinations I choose?


Massive CPU Usage by WaitForTargetFPS in the Profiler So I was checking the Standard Assets Example Projects of Unity, and they all have high FPS numbers in the Profiler. I started a little project myself, just a simple sprite with movement via rigidbody and a plane as a floor, and suddenly this I searched for what exactly does WaitForTargetFPS represents, but apparently there is not a general consensus about what can cause such high CPU usage. So why exactly such a little and simple project have this performance (in contrast with the more complex Unity Example Projects)?


How to load unload chunks data where view port is currently focused on? I have a 2D tile based engine with infinite procedural chunk generation. But I can't invent an algorithm, that will fill only chunk tiles on view port (and destroy old). Pls help ViewPort size can changing on the fly (2 100) I can't load all chunks completely, because I need to analyze the tiles in the visibility zone class Map public List lt Chunk gt get set public int viewPortWidth 2 ... 100 public int viewPortHeight viewPortWidth public Vector2Int playerPosition get set class Chunk Tile Tiles get set public int chunkWidth 16 public int chunkHeight chunkWidth public Chunk(int leftX, int bottomY) for (int y 0 y lt chunkHeight y ) for (int x 0 x lt chunkWidth x ) randomNumberGenerator.InitState(x leftX, y bottomY) chunk x, y randomNumberGenerator.Range(100) Tiles.Add chunk x, y


Exporting unity features to your game I wonder if it is possible to export Unity features to my game. For example if I want user to be able to modify scale or rotation of object, do I have to scritp it myself or can i somehow export it ? Same question about some simple texturing, adding lights, etc.


Unity Collider2D Know the collider type ob the object collider with the other object I have my GameObject which represents a soldier in my game. It has the following colliders 1st BoxCollider2D in child named "sword". Is Trigger checked. Tag Sword. This collider is enable when player attacks and disabled otherwise. 2nd BoxCollider2D in parent GameObject. Is Trigger unchecked, since it's the body. Always enabled. When the sword (1st) collider collides with the the body (2nd) collider, damage happens. Until now everything works fine. Here is the OnTriggerEnter2D function I have void OnTriggerEnter2D(Collider2D collision) if (collision is BoxCollider2D) Debug.Log( " this.name collided with collision.name ") if (collision null collision.tag Constants.TAG WEAPONS collision.tag Constants.TAG SIGHT) return if (collision.GetComponent lt LivingObjects gt ().AreEnemies(this)) Debug.Log( " this.name attacked with collision.name ") Attack(collision.GetComponent lt LivingObjects gt ()) else return Now I want my unit to search for enemies within a said range. I added a new collider 3rd CircleCollider2D in child named "sight". Is Trigger checked. Tag Sight. Always enabled. Now, when the sight (3rd) collider collides with the body collider, damage is trigger into the unit colliding with the sight collider. That is because I block damage one way around with the condition if (collision is BoxCollider2D) but not the other collision happening at the same moment. If i can discrimate collision from CircleCollider2D into BoxCollider2D, I can remove the attack function. However, I cannot see how to do it. My question is how do I know what Collider2D type is my object colliding with the other ? I'm open to other suggestion if this is impossible.


Why is it that I m still able to call a coroutine from another script, even though I marked it as private? I have this private coroutine in my WinDialogue script private IEnumerator ActivateStars(int count) for (int i 0 i lt count i ) stars i .SetActive(true) yield return new WaitForSeconds(.3f) And somehow I m still able to call it from my UIManager script winDialogue.GetComponent lt WinDialogue gt ().StartCoroutine("ActivateStars", starCount) How can that be if I marked it as private?


How to check if gun may shoot again (because animation has stopped playing)? When the user presses the fire button, I set a trigger animator.SetTrigger( quot HG Shoot quot ) This trigger causes a quot pistol shoot quot animation to be played. The gun should only be able to shoot again as soon as the shoot animation has finished. I could check at each Update() if that certain animation is still being played like this bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) amp amp anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime lt 1.0f) return true else return false But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation. Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun. This would make everything even more complicated. How can I solve this problem?


Variable Variables in unity using JavaScript? I'm working on a custom built save system for a project a friend an myself are working on. Currently all variables that are saved to file, are stored as static variables in a global variables script file. The current save system involves running through each variable individually and saving it a line on a document, completely hard coded and very annoying to expand upon with new variables and elements in the game. I've decided to look into serialization of the global variables file, however static variables are not serializable. My solution is to use a getter and setter function, that is called instead of the direct GV.whatevervariable, that we currently use. Ive been looking for something that allows me to store a variables name inside of another variable and then call it. for example, say the variable in the GV script is A , the function would look like static function getter(vget) return GV 'vget' var A string "testcode" where the call code would look like var stuff string GV.Getter("A") the problem with this though is that I keep getting "system.type does not support slicing" I currently cannot think of any other way to do this, and would really prefer not to hard code a getter and setter for each variable.


Shader and Texture Scrolling depending on Direction I am trying to scroll a texture using its uv in Unity but I don't get the result I need. The aim is to have two components, the speed and the direction. I would like to define the direction in normalized values and the speed should influence the velocity of the scrolling according to the direction. If I change the speed at runtime, I don't want to have some hiccups but maybe this should not be handled but the GPU. How can I do that in a better way, maybe using matrix ? Here is an example but the result is not as good as expected. uv.xy uv.xy frac( Time.y float2( Direction.x, Direction.y))


How to animate alpha channel of sprite color using Animator in code in Unity3D? I tried Animator AnimationClipPlayable, but failed. Sprite disappears completely after 1 second, without animation happening. If I set "1" instead of "0" for final point, then nothing happens. Code AnimationClip clip new AnimationClip() AnimationClipPlayable playable AnimationClipPlayable.Create(clip) gameObject.AddComponent lt Animator gt () AnimationCurve alpha AnimationCurve.Linear(0, 255, 1, 0) clip.SetCurve("", typeof(SpriteRenderer), "m Color.a", alpha) gameObject.GetComponent lt Animator gt ().Play(playable)


In Cricket games, how is the ball synced with batsman's shot animation? How does the ball hit right at the center of the bat? How does this work? I've been trying to figure this out for quite some time now. In Cricket games, when the bowler bowls, and batsman takes a shot, how does the ball sync with batsman's shot animation? For example, let's say the batsman hits a straight drive, how does the ball hit the bat perfectly? Can anyone help me out with this? I'm also curious about how in football games, the player animations sync with the football. How does the player's foot correctly hit the ball? Thanks in advance.


Smooth Lighting Falloff So, I'm having some issues with lighting in my Unity game. I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow". The reflected and refracted light ends up having two issues the light abruptly ends at the edge of floor tiles, and depending on the position, the light sometimes goes from it's blue color to a reddish color. I have a short (11 second) video here http www.labyrintheer.com wp content uploads 2016 11 Nov 17 2016 21 07 57.mp4 so that you can see what I'm talking about. I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue. Still images for anyone hesitant to click the video link Hard falloff Reddish color Using a single point light inside the cube, instead You can see it on the wall in the upper right and the floor at the top a bit. The upload seems to have lowered the quality a bit, but you can still see it. The single light makes it a little bit better, but there's still complete falloff.


How to determine the amount of idel time left in main thread for Unity before next frame? Hi I'm trying to improve a thread tool and would like to make a function which use the idle time before the next frame. So how can I determine the time left?


Prevent Unity click go trough Canvas I'm currently facing this problem If I click on a Button on my Canvas, the currently selected Unit moves towards the location under the Button. Is is there any option to solve this? I'm using the A Project for this. Sadly, I can not provide a lot of things I've done so far as I absolutely have no clue how to solve this problem. If I disable the Button Option "Raycast Target" ist still moves to this position but holds a bit earlier. Also, adding this as check didn't work if (!EventSystem.current.IsPointerOverGameObject() ) I also checked if the Raycast hit's the layer of the GUI My Movement code so far public override void MouseClick(GameObject hitObject, Vector3 hitPoint, Player controller) base.MouseClick(hitObject, hitPoint, controller) if (hasAuthority amp amp player amp amp player.human amp amp currentlySelected) if (hitObject.name "Ground" amp amp hitObject.name ! "UI" amp amp hitPoint ! ResourceManager.InvalidPosition) float x hitPoint.x float y hitPoint.y player.SelectedObject.transform.position.y float z hitPoint.z destination new Vector3(x, y, z) Debug.Log("Start Move") StartMove(destination)


Unity, Which side of Collider2D was hit by raycast? I've got a player firing out 2d raycasts. If one of them hits a boxcollider2d I would like to know if it hit the top side, bottom side, left side, or right side. How would I go about doing this? I've tried using Bounds but that didn't work out very well.


Player movement vs world movement in infinite runner game? Well I'm developing a Temple Run or Subway Surfer style infinite runner game. Which is more good? Moving the player and make the Main Camera follow, or keep the player in one position and move the generated worlds? And the generated paths or worlds will have many animations in it. So which choice ouuld be good and why?


Two Points Rotating Around Circle? Currently I am working on a 2D game just like duet game, it is my first game (Unity 2D). When I press left key both points rotate fine. But when I press right, the points are not rotated. So my problem is why do both points rotated only in one direction Code public class TouchControll MonoBehaviour float movespeed 3 float angle 45 void Update() if (Input.GetKey(KeyCode.LeftArrow)) when i m press leftarrow both point should be rotate fine transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Horizontal") angle movespeed) Debug.Log("moveleft") if (Input.GetKey(KeyCode.RightArrow)) problem is here when i m press right arrow key both point are not rotated transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Vertical") angle movespeed) Debug.Log("moveright") Output create a empty gameobject first circle second circle


Pressing the jump button also makes my character fire their weapon In my game I want my player jump without firing their weapon, but when I press the button it jumps and also fires too in same moment. In this Update method, I used Input.GetButton so my player will fire continuously while holding the button. void Start () isJumped true Update is called once per frame void Update() if (!transform.GetChild (0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (Input.GetButton ("Fire1") amp amp Time.time gt firespeed amp amp isJumped true) nextFire myTime firespeed newProjectile Instantiate (projectile, transform.position, transform.rotation) as GameObject nextFire nextFire myTime myTime 0.0F EnergyCharging () void JumpButton() if(!transform.GetChild(0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (grounded) grounded true myRigidBody.AddForce (new Vector2 (0, jumpPower), ForceMode2D.Impulse) if(myRigidBody.velocity.y gt jumpPower) myRigidBody.velocity new Vector2 (0, jumpPower) animator.SetBool ("isGrounded", grounded)


How to keep AI goalkeeper inside their bounds I'm making a soccer themed top down 2D endless game, but I have a problem with the goalkeeper AI. My game looks like this As you can see, the goalKeeper is moving out of bounds. I have tried to clamp them with transform.Translate(Mathf.Clamp(target.transform.position.x, 1,1),0,0) ...but I think this for clamping the speed, not the area boundaries. What should I do instead? What I want is to have two kinds of goalkeeper Active Goalkeeper (Call them GKA) This goalkeeper should chase the player, but only within the bounds of the goal area. Stationary Goalkeeper (Call them just GK) This goalkeeper should just stand in the middle of the goal, like in the first animation. But before the player reaches them I want this goal keeper to move forward slightly, to pretend it's defending the goal. Here is my goalkeeper script if (gameObject.CompareTag( quot GK quot )) anim.SetBool( quot GKRun quot , false) gkballInRange Physics2D.OverlapCircle(transform.position, gkballRange, playerMask) float distancePlayer Vector2.Distance(target.position, transform.position) if (gkballInRange) transform.Translate(0, .3f Time.deltaTime, 0) if (distancePlayer lt gkballRange) if (theBall.isOver) anim.SetBool( quot GkC quot , true) anim.SetBool( quot GKRun quot , false) transform.Translate(0, 0, 0) else Animation anim.SetBool( quot GKRun quot , true) transform.Translate(target.transform.position.x speed Time.deltaTime, 0, 0) and this one is GKA script if (gameObject.CompareTag( quot GKA quot )) Animation gkballInRange Physics2D.OverlapCircle(transform.position, gkballRange, playerMask) float distancePlayer Vector2.Distance(target.position, transform.position) if (gkballInRange) transform.Translate((target.position.x Time.deltaTime), 0, 0) if (distancePlayer lt gkballRange) if (theBall.isOver) anim.SetBool( quot GkC quot , true) anim.SetBool( quot GKRun quot , false) transform.Translate(0, 0, 0) else anim.SetBool( quot GKRun quot , true) transform.Translate(0, speed Time.deltaTime, 0)


Collision detection not working on some parts of mesh Racing game with a single mesh to act as a collider for all the track sides. Recently revised the mesh and now it is behaving strangely. The player correctly collides (bounces off) some parts, on other parts it is hit and miss whether the collider works and on others the player acts like there is no collider present at all. I have checked that all the meshes normals are facing the correct direction and that there are no gaps in the mesh. I have set the collisions on the player rigid body to be continuous. Can anyone suggest what might be happening? I was previously using the exact same technique but re created the collider mesh to clean it up and upon importing from Blender into Unity the collider behaviour is now all over the place. This picture shows part of the collider where the player just passes straight through the walls. Car collider in Unity Track mesh collider in Unity


Working with retina graphics on Unity 2D I begun trying Unity for iOS 2D development. I am curious about how to work with retina devices. The first thing I did was create a 1136x640 solid rectangle sprite and throw it into my scene, then run the game on my iPhone 5. My expectation was that this image would perfectly fill the screen that is, the retina would "kick in". Alas, this was not the case my sprite was much smaller than the iPhone's screen. Then I saw the main camera game object, and played around with the size property. By default is was like 5, but I determined that the number I needed for my sprite was somewhere around 3.2. This works and looks fine in my phone. But I am unsure if this is how I am suppose to do things what is the correct way of supporting retina images? I feel like guessing the size property of the main camera is a bit hackish. Actually, how do I know if Unity is indeed using retina?


Unity Syncing Downloading overwriting files to a local folder accessed by the game when offline? I currently have a game application (PC Standalone only) made in Unity which features a multitude of buttons which all link to external webpages which open up in the user's browser window. Recently my client expressed an interest in having an offline version, where all the online content is available locally offline, as their users regularly go offsite to areas without an internet connection and the buttons are then useless. I have done a new version which has all the webpages, PDFs and videos saved off as local files and placed in a folder within the build folder, the buttons now use the following script to read the files from there instead public class URLOpener OFFLINE MonoBehaviour public void relativeURL(string url) Application.OpenURL(url) This works perfectly on a basic level. However my client has expressed an interest in being able to update the offline content without having to make a new build each time or manually go and update the folder content. So basically what I need is to be able to store all the offline files somewhere online, which can be overwritten as and when is needed. Then I need some way of syncing the game with this online location (when the user is online), to pull down the latest files into the offline folder and overwrite the files in there, so the latest offline files are included when they go offsite to an area without internet. Is this possible at all? I am more than happy to pay for a plugin or service that would provide this sort of feature. I already have a plugin for translated languages which essentially does this (https www.assetstore.unity3d.com en ! content 14884) changes to the online spreadsheet containing all the text is pulled down when the game syncs. But this is obviously a bit different to downloading actual files and placing them in a specific folder. Any help or advice would be appreciated. Many thanks in advance


Unity3d calling a web service in unity editor works, but not in standalone. Why? I have this line of code SDE3D webService new SDE3D() int result webService.UserLogin(txtLoginUsername.text, hashString) My UserLogin function looks like this System.Web.Services.Protocols.SoapDocumentMethodAttribute("http www.something.com UserLogin", RequestNamespace "http www.something.com ", ResponseNamespace "http www.something.com ", Use System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle System.Web.Services.Protocols.SoapParameterStyle.Wrapped) public int UserLogin(string username, string password) object results this.Invoke("UserLogin", new object username, password ) return ((int)(results 0 )) In the Unity Editor it works well. At runtime, in my Unity game build, it doesn't work and doesn't return any error message! What is the issue? Thanks