Can I force a manually created texture to not be divided with low quality? I have a texture that I have created that looks something like this . This is a very low texture map, but it helps me in a shader that I'm making that distinguishes between land and ocean, the ocean tiles do different things than the land. To try and figure out what was going on, I used the shader to turn the ocean, as defined by the mask, black. Note that this image doesn't match the ocean texture example from above, but it's the best I had... The ocean is a binary color, either it is ocean or isn't, and is set appropriately. But what I'm actually seeing is that if the 2x2 tile area has mixed land ocean, the value is averaged. What I've noticed is that the pixels were combining together, a 2x2 pixel area was averaged. After tracing through this for some time, I discovered that the issue was a quality setting that reduced the resolution of certain images. There are some images that I don't mind lowering the resolution of, but images such as this one I absolutely don't want to lower the resolution. Is there a setting that I can add to a runtime generated texture to tell it not to reduce it's resolution if requested to by the quality settings? EDIT Code fragments to produce the results above. It's kind of hard to pull just the fragments that produce this code and not produce an overwhelming bit, but hopefully this will do. Code to generate textures Color32 windMask new Color32 world.width world.height for (int x 0 x lt world.width x ) for (int y 0 y lt world.height y ) windMask x world.width y world.Tiles(x, y).baseType Tile.BaseType.Ocean?new Color32(255,255,255,255) new Color32(0,0,0,255) sharedMaterial.SetTexture(" WindMask", TextureUtilities.TextureFromColors(world.width, world.height, windMask, FilterMode.Point)) public static Texture2D TextureFromColors(int width, int height, Color colors, FilterMode filterMode FilterMode.Trilinear) Texture2D texture new Texture2D(width, height) texture.SetPixels(colors) texture.filterMode filterMode texture.Apply() return texture The Shader code o.Albedo 1 tex2D( WindMask, IN.uv MainTex).r The "Fastest" quality settings that show the issue The "Fantastic" quality, which correctly isolates the ocean. Image of the correctly isolated ocean The issue is the "Texture Quality", which you will note for the fastest setting is half resolution. I would really like to keep the ability to use lower resolution in the game, but have a few textures that do not use the lower resolution if the quality settings change.


Optimal way to select a random item from a list based on its chance to appear in Unity I am creating a random object spawning script in Unity with c , and am wondering what the ideal way to do this task would be. So I have a list of 31 objects or so, of my special class type. Each one has an arbitrary number assigned as it's weight. This number is divided by the sum of all their weights and multiplied by 100 to make their percent chance for appearing. It's at this stage where I'm stumped. How should I go about selecting them with a random number between 0 and 100? My first idea was to give each one a range and if the random number falls within it, I select that one, but that method does not sound like it would be the most elegant and would involve like 31 IF statements. What is the standard way to do this sort of random selection?


Changing animation speed at runtime Is there a way in Unity to change the animation speed of an animation managed by an animator controller (Mecanim)? I'd like to do that at runtime so that I can speedup and slow down an animation based on conditions in code.


Why do I have render problems happening frequently in my Unity scene? I am making vertical endless runner. My platforms are moving down, and the camera and players are remaining in the same location, resulting in the effect of player movement. The obstacles are generated and move in same direction as platforms. The problem is obstacles rendered by the camera is not right. I mean that the obstacles are in camera's FOV but are still visible after some time when they reach the player to close.


Colliders slightly intersecting each other any solution? Consider this simple scene In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider. And the problem if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall. This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist. Is there a workaround? How can the box smoothly move across the floor without colliding with the seam? Notes This does occur with capsule colliders but rare and is not very noticeable. A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks. This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity position of the transform.


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.


Accessing a char array from another class I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this First class public class GenerateBoard MonoBehaviour public static char , gameBoard new char 15,15 void Start() gameBoard 0, 0 'W' Second class public class SetLetter MonoBehaviour Text letter public int x public int y Start is called before the first frame update void Start() letter GetComponent lt Text gt () letter.text GenerateBoard.gameBoard x,y "" Update is called once per frame void Update() Debug.Log("glitch " GenerateBoard.gameBoard 0, 0 ) I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'.


Can both High poly model go with a low poly scene? I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.


Destroy physics triggered GameObject in Unity ExecuteInEditMode To destroy GameObjects I'm using this code try DestroyImmediate(g) catch (Exception e) Destroy(g) It is giving me error, something like this Full code using System using System.Collections.Generic using UnityEngine ExecuteInEditMode public class Road MonoBehaviour public List lt Vector3 gt points new List lt Vector3 gt () public List lt GameObject gt gameObjects new List lt GameObject gt () void Start() void OnValidate() foreach(GameObject g in gameObjects) try DestroyImmediate(g) catch (Exception e) Destroy(g) gameObjects.Clear() foreach (Vector3 point in points) GameObject tem GameObject.CreatePrimitive(PrimitiveType.Cube) tem.transform.position point tem.transform.localScale new Vector3(0.1f, 0.1f, 0.1f) tem.transform.parent gameObject.transform gameObjects.Add(tem)


Unity Mathf.Lerp() didn't work as expected? I want to rotate an object 360 degrees so this is what I did xRotation Mathf.Lerp(0, 360, Time.fixedDeltaTime lerpTime) and then I used Quaternion.Lerp() to rotate the Object so targetRotation Quaternion.Euler(initialRotation.x xRotation, initialRotation.y, initialRotation.z) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime lerpTime) But it didn't work as expected, the xRotation didn't go from 0 to 360, it just changed from 0 to 9 (instantly), and that's it, it never changed. This is my full code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class QuaternionExpirement MonoBehaviour SerializeField Range(5, 10) float lerpTime Vector3 initialRotation bool mousePress, readyToRotate float xRotation private void Awake() initialRotation Vector3.zero mousePress false readyToRotate false xRotation 0 private void Update() mousePress Input.GetMouseButtonDown(0) private void FixedUpdate() if (mousePress) initialRotation transform.eulerAngles readyToRotate true if (readyToRotate) xRotation Mathf.Lerp(0, 360, Time.fixedDeltaTime lerpTime) Quaternion targetRotation Quaternion.Euler(initialRotation.x xRotation, initialRotation.y, initialRotation.z) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime lerpTime) if (xRotation gt 360) readyToRotate false


How to drag my dragging object in 'game' unity? I have made a dragging sphere which drags, problem is how can I drag it using keyboard keys , I dont want to build it again on iphone simulator after experimenting with my code. for dragging it is not accepting mouse or any keyboard keys. Is it possible ?


How do I prevent floating and jittering when on the ground and using spherical gravity? TL DR My ship floats and jitters when it lands on a sphere. To elaborate on the title I'm experimenting with a 3D space game. I have created a sphere, which in turn has a larger sphere overlapping it, within which, gravity will take place. However, once my player's ship (currently using an arrowhead) lands on the planet, it doesn't actually make contact with the surface of the sphere, and then the ship begins to rotate erratically and jitter. Code below. private void OnTriggerStay(Collider other) if (other.CompareTag("SoI")) inSoI true This trigger checks to see if the ship is in the larger overlapping sphere. I have another identical block for OnTriggerExit which sets inSoI to false. I also have a OnCollisionEnter which sets another variable, landed to true, and a OnCollisionExit which sets it to false. private void FixedUpdate() if (inSoI amp amp !landed) gravityVector (planet.transform.position transform.position) rb.AddForce(gravityVector.normalized planetrb.mass rb.mass gravityVector.sqrMagnitude) Simply, if in the larger sphere, then accelerate towards the planet. I tried disabling gravity if in contact with the sphere. It removed a lot of the jitter, however it still floats, and it still rotates side to side. The sphere by the way, is the standard Unity sphere, scaled 10000x in every axis. I don't need code (though it would help), any solution is fine, even if it means abandoning the project.


Should I ask my artist to make Sprites in full resolution or can I scale them up? I'm started with Unity development and my artist asked me what size she should make the sprites for the game. They are all pixel art and she didn't know if she should make them on Photoshop on a small resolution, do them already on the iOS resolution 1920x1080 or even if she should use a vector program and then rasterize them. How is this normally done?


How to not freeze the main thread in Unity? I have a level generation algorithm that is computationally heavy. As such, calling it always results in the game screen freezing. How can I place the function on a second thread while the game still continues to render a loading screen to indicate the game is not frozen?


pathFinding performance in Unity3d I am making Sniper game in unity 3d. In this game zombies will come randomly towards the sniper and sniper have to kill them. I am using RAIN(indie) for path finding. It works best when zombies are few . As I increase the Zombies( that is 10) the performance decrease a lot. The fbs drops to 25. I want to know is there any technique or steps so I can improve fps Any other technique algorithm that I can use for pathfinding weith good fps. PS I already remove Sensor component from AI. FPS of game without AI is 61


Effect only on one object (two cameras) I have a problem. I want a Grayscale effect to be applied ONLY to the chair on the stage. The chair has a layer CurrentItem. And I have two cameras Camera All renders everything except layer CurrentItem (I set this exception in CullingMask) Camera CurrentItem Finally I need to apply not just one effect, but a few.


Animator Panel in Unity Where is "Entry"? I am following a tutorial on Unity, and I saw a screenshot like the following When I reproduced the steps of the tutorial, I realized that the green quot Entry quot box was not present on my screen. I have been thinking why this could be and the only reasons that I could think of are The tutorial skipped a step I have something misconfigured In the latest version of Unity that box has been erased or replaced Which one is it? Did I forget a 4th option? PS If it is option 3, could someone explain me what was this feature for, and what has it been replaced with? UPDATE I am using Unity 4.6.2f1


What is grid in Unity and how can I implement it? I'm a beginner. I need to place a grid on my map in Unity and would like to access it to place a simple object on mouse click. How can I achieve this ? I am unable to understand the grid functionality, should I have to write code for a 2D array or is there something in Unity that I can access, and what is basically the grid like something when I click my background image ?


Optimal solution to render sprites with transparent edges in Unity Since I'm currently developing a 2D game for mobiles, overdraw and drawcall count is my first priority in the design of the application I've thought initially to split each sprite in two parts one where each pixel is fully opaque (to render with cutout shaders in front to back order) and the other part with semi transparent edges (which will be ordered back to front) Since I need to support ES2.0 devices, I can't use texture arrays and I need to fit as many sprites as possible in a single 2048x2048 texture atlas to reduce drawcalls and ensure mobile compatibility, but as you can see from this picture Splitting sprites in opaque and non opaque parts will certainly double the space occupied in the atlas, thus decreasing by half the potential amount of consecutive sprites I can draw in a single drawcall This way, I'm paying drawcalls to reduce overdraw. By rendering the entire sprite with transparent shaders I'd pay overdraw to reduce drawcalls. Am I missing something? Is there a better approach?


Why is Unity ignoring my camera on Android? I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app. Here's what it should look like Here's what it ends up looking like My game is forced in portrait, and I want to keep it that way. I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera I think it is just using the canvas. I tried many different things, including changing the scaling and setting the anchors. None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor. Why is Unity ignoring my camera on Android?


How to make a 2D sprite slowly vanish as it crosses a line as if disappearing behind a wall? ...Except there is no wall. Only one of its edges. Here is what I mean. Notice how the lines "sink" into the center square. I've been trying to do something very similar, in Unity. My approach is to detect when the lines come into contact with the center square (hexagon, in my case), and first initiate an animation that decreases the width of the lines, precisely timed via math to last exactly as long as needed. But there's a problem. The animation doesn't play. I've spent the last few hours debugging it, to no avail, and now have finally given up, because the problem is too complex to post here. Too many variables. Are there any better methods of achieving this? My own, even if it had worked, wouldn't have been perfect, because the width would've decreased on both sides (of the line running in the middle of the thick squares or hexagons that are to disappear), giving it a strange, swallowing effect, but I'd be satisfied, since it's just a practice project. So, I'm giving up on this approach. What are easier ways to do this? (Preferably in Unity, but I'll take anything.) Hasty edit Keep in mind that my "lines" are not sprites but line renderers, but I'm looking for ways to work on either.


Lighting doesn't work properly in WebGL build only at one place So I have a 2d game where a player walks around the level (top view) with a flashlight in front of him. Everything works fine in the editor, however whenever I build it for WebGL and test it in my browser, one room only one, has a problem with lighting, and as I walk in different parts of the room lighting changes in a weird way, and the floor is blinking in the first half of the room, as well as the flashlight is barely visible (if at all). Here's how it looks in the editor and is supposed to look like And here's a few screenshots from the web build P.S. Everything works fine in a standalone build. Also there seems to be no problem when I disable the 4 lights (the whole room works fine), these are the lights (the ones that look like from a window)


How to modify a property after animating it in Unity3D? I animate localPosition. The animation works well, but after, I can't change a value of localPosition in editor or code. I want to change a value after the animation completes, not at the same time. I use Animator with AnimationClipPlayable. I create Animator in editor and the rest in code (AnimationClip, AnimationClipPlayable, AnimationCurve). The animation animates a property from one position to another. It finishes, I don't do anything to stop the animation. Let me know, if you need a code example or video presentation.


Unity Pink Texture On WebGL I'm trying to follow a youtube tutorial for my new game(images puzzle) and by using it's implementation on github to upload it later on facebook. When I run the game inside unity editor its work without any problem, but when I export the game to exe or WebGL I get pink images background instead of the image am using. Youtube tutorial link here. GitHub repository link here. The game works Fine inside unity But shows pink images on web browsers and exe games Why the images are showing pink background?


Explaining Unity Sprite Default Shader I would like to know why we would use alpha blending in that shader for just rendering a sprite, which is just a texture ? What is tint color ? Why we multiply the alpha value by the color here ? fixed4 c tex2D( MainTex, IN.texcoord) IN.color why ? c.rgb c.a why ? Shader "Sprites Default" Properties PerRendererData MainTex ("Sprite Texture", 2D) "white" Color ("Tint", Color) (1,1,1,1) MaterialToggle PixelSnap ("Pixel snap", Float) 0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" "PreviewType" "Plane" "CanUseSpriteAtlas" "True" Cull Off Lighting Off ZWrite Off Fog Mode Off Blend One OneMinusSrcAlpha Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma multi compile DUMMY PIXELSNAP ON include "UnityCG.cginc" struct appdata t float4 vertex POSITION float4 color COLOR float2 texcoord TEXCOORD0 struct v2f float4 vertex SV POSITION fixed4 color COLOR half2 texcoord TEXCOORD0 fixed4 Color v2f vert(appdata t IN) v2f OUT OUT.vertex mul(UNITY MATRIX MVP, IN.vertex) OUT.texcoord IN.texcoord OUT.color IN.color Color ifdef PIXELSNAP ON OUT.vertex UnityPixelSnap (OUT.vertex) endif return OUT sampler2D MainTex fixed4 frag(v2f IN) SV Target fixed4 c tex2D( MainTex, IN.texcoord) IN.color c.rgb c.a return c ENDCG


Physics.CheckSphere() appears not to work in Unity My scene is simple, I have a single GameObject with the following script attached usings ... public class GalaxyManager MonoBehaviour public int numberOfStars 300 public int maximumRadius 100 public float minDistBetweenStars 2f void Start() for (int i 0 i lt numberOfStars i ) float distance UnityEngine.Random.Range(0, maximumRadius) float angle UnityEngine.Random.Range(0, 2 Mathf.PI) Vector3 cartPosition new Vector3(distance Mathf.Cos(angle), 0, distance Mathf.Sin(angle)) if (!Physics.CheckSphere(cartPosition, minDistBetweenStars)) GameObject star GameObject.CreatePrimitive(PrimitiveType.Sphere) star.transform.position cartPosition else i Update is called once per frame void Update() What this is supposed to do is generate 300 quot stars quot within the maximumRadius of 100 that are separated by at least minDistBetweenStars. I haven't been able to figure out what's actually happening sometimes the check finds a collider and sometimes it doesn't. It's almost as if the CheckSphere() check is happening before the stars get placed via the star.transform.position cartPosition. I'm very new to Unity and appreciate the help. Anyone have any idea what's going on? edit Some more information, I've tried the script in both 2020.1.12f1 and 2019.4.14f1 to no avail. I'm also aware that this will lead to an infinite loop if it can't find a placement.


Retrieve the original prefab from a game object How would one proceed to retrieve the original prefab used for instantiating an object? In the editor these two functions work Debug.Log(PrefabUtility.GetPrefabParent(gameObject)) Debug.Log(PrefabUtility.GetPrefabObject(gameObject)) But I need something that works in the release version. I have objects that can be transported between scenes ands I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated. ie Game designers create new prefabs. Game designers create objects from prefabs and place them in scenes (50 to 150 scenes). Game is played and objects are moved across scenes. Game is saved and infos about objects which have moved are saved in the save streams (files or network). This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field). Maybe there is a better way to achieve proper save games without having to access to the original prefab name. But currently we keep the saves segmented on a per level basis (easier and safer to save load to files and transfer the save games to from servers)


Unity 2D map and walkable collisions I have a 2d player who can only walk on black area. There is a red collider so player can't walk past it. Player has capsule collider. The problem is player can't walk toward the edge with his feets becasue of the it's collider. But player would probably want to walk toward the edge. Here is a sketch I've made. Is there a way to tweak this ?


How can I find the center position of two or more objects? using System.Collections using System.Collections.Generic using UnityEngine public class MoveCameraBehind MonoBehaviour public GameObject camera public List lt GameObject gt targets new List lt GameObject gt () public float cameraDistance 10.0f public bool behindMultipleTargets false public string cameraWarningMsgs "" public string targetsWarningMsgs "" Use this for initialization void Start() if (camera null) var cam GetComponent lt Camera gt () if (cam ! null) cameraWarningMsgs "Gettig camera component." camera transform.gameObject else cameraWarningMsgs "Creating a new camera component." GameObject NewCam Instantiate(new GameObject(), transform) NewCam.name "New Camera" NewCam.AddComponent lt Camera gt () camera NewCam if(targets.Count 0) targetsWarningMsgs "No targets found." void FixedUpdate() if (targets.Count gt 0) MoveCameraToPosition() public void MoveCameraToPosition() if (targets.Count gt 1 amp amp behindMultipleTargets true) var center CalculateCenter() transform.position new Vector3(center.x, center.y 2, center.z cameraDistance) if (behindMultipleTargets false) Vector3 center targets 0 .transform.position targets 0 .transform.forward cameraDistance transform.position new Vector3(center.x, center.y 2, center.z) private Vector3 CalculateCenter() Vector3 center new Vector3() var totalX 0f var totalY 0f foreach (var target in targets) totalX target.transform.position.x totalY target.transform.position.y var centerX totalX targets.Count var centerY totalY targets.Count center new Vector3(centerX, centerY) return center The CalculateCenter function make the targets(objects) to change positions and vanish away far away. Even if there is only one single target. What I want to do is if there is one object for example one 3d cube position the camera behind the cube. And if there are more cubes for example two or ten and the camera is somewhere else calculate the middle position behind the targets and position the camera in the middle behind them. To show what I mean in this example the view(like a camera) is behind the two soldiers in the middle position between them from behind. But what if there are 5 soldiers how can I find the middle position and then position the camera behind them like this example in the screenshot ?


For Blender Unity users Would Blender's UV Project Modifier work in Unity? So, say in Blender you have a Cube that you put a "UV Project Modifier" on, with an Empty (controlled by a Bone) as the Projector. In Blender when you move the Bone, the UV moves on the cube. Great! But now let's say you wanted to bring that to Unity. Would that still actually work (being able to move the UV around with bone movement) or would it be busted? I'm trying to test it myself and it seems a dud but I already struggle with Blender's export process so wanted to check here.


How can I port my Gear VR app (Java, OpenGL ES) to Unity? I want to port my Gear VR app (created in Java using the official framework) to Unity, so I can also support Microsoft's new ish VR headsets (not talking about the Hololens!). In my current app I'm using OpenGL ES to draw everything I need (the app reads coordinates and additional information about what it has to draw from a .txt file), which is GL LINE STRIP The .txt file gives it a bunch of coordinate triples (x, y and z, so single vertices), it then has to automatically connects them (usually without loops) Kind of plane Either display a rectangular plane with a texture (using the Gear VR framework's "GVRSceneObject") OR create an outline (usually first point last point) that then gets filled in a specific color (GL TRIANGLE FAN) AND that is a little bit transparent if it includes concave areas, it's using GL TRIANGLES and the .txt file has coordinates for single triangles that have to be displayed at the same time and filled (it's still a single object mesh!) What I need Unity to do (with 1. and 2.) Display a couple of 1. (could be up to 50 or more) and 1 of 2. at the same time (there'll never be more than 1 of type 2.!) Remove all of 1. (that are displayed at the same time) or 2. from the scene and or replace them with a couple of different 1. or another 2. Group a couple of 1. together, so you can remove them at the same time (which would make stuff a lot easier) Read .obj files (including their texture) from internal storage (Android) or the HDD (Windows) and display it them instead of 2. (the .txt file includes the path to the file and texture) Everything has to happen at runtime, since the app doesn't come with any .txt files or pre imported .obj scenes objects! My question is How can I do this with Unity, targeting Windows and Android?


Problem with repeating objects in array when already in the array When the player move forward then paint is instantiate and stored in the array, even if the paint is already in the array it will again be stored in the array. But I don't want to repeat any paint in the array. public GameObject array public GameObject paint int temp 0 private RaycastHit hit public float speed 10f public Text levelText public GameObject paint float maxdistance 0.51f Vector3 newtargetposition bool pos private void FixedUpdate() if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward,out hit, maxdistance)) if (hit.collider.gameObject.tag "Obstacle") move false if (move) PlayerMove() public void PlayerMove() if (move) vector3 positions transform.position new Vector3(0f, 0.5f,0f) when player move then paint instantiate y position array temp Instantiate lt GameObject gt (paint, position, Quaternion.identity) temp newtargetposition position Debug.Log("newtargetposiiton " newtargetposition) if (temp 150) if (newtargetposition position) what can i do here i dont want to paint here because position store in newtargetposition,it is repeat array temp Debug.Log("newtargetpositions " newtargetposition) temp gameOver.SetActive(true) SceneManager.LoadScene(1) when player move forward store position in array when player move back already fillup position again store in array


Unity How to create C classes with different properties like Objects in javascript and put them in an array? I just started my gamedev journey on unity this week and while I have a background with coding, I'm still somewhat of a beginner. Last year I made a text UI based game on the web browser with javascript and have been trying to make the same game on Unity. One of the main features of my game is that you press a button to "go hunting" and I had an array filled with enemies that were objects with different properties such as health, mana, attack, etc... Then I'd randomly pick one of those objects from the array to be chosen as my enemy that I'd fight. I've been trying to figure out the best way to do this with C and I might just be overthinking this. As a bonus, I'd also like to be able to see the individual enemy objects in the array in my inspector if possible so I could tweak the stats within unity. I've looked at scriptableObjects and different things but I am having a hard time putting it all together in an array from within unity. System.Serializable public class playerClass public string playerName public int lvl public int maxHealth public int health public int maxEnergy public int energy public int exp public class playerScript MonoBehaviour public playerClass player This is how I created an object for the player, I want to do something similar for the enemies but put them in an array so I could randomly pick from them. If there is a better way to do this I'd also welcome some advice ) thank you


Trouble GamePad input on iOS but works perfect on Android I am having trouble getting input from on iOS devices (iPhone 6 Plus and iPad). Here is my code, if (Input.GetKey (KeyCode.JoystickButton14)) A chr show "A" if (Input.GetKey (KeyCode.JoystickButton13)) B chr show "B" ........................................... if (Input.GetKey (KeyCode.JoystickButton11)) Select chr show "SELECT" And in OnGUI() GUI.Label (new Rect(0,0,100,100), "Pressed Button " chr show, guiStyle) Code works perfect on Android device. I also have tried following if (Input.GetButton ("JSButton")) JSButton chr show "JS Button 14" Please Help Me!


How can I toggle between single shots when clicking the mouse left button and automatic none stop shooting when clicking the mouse right button? I'm talking in build not in editor ! using System using System.Collections using System.Collections.Generic using UnityEngine public class Shooting MonoBehaviour SerializeField private Transform firePoints SerializeField private Rigidbody projectilePrefab SerializeField private float launchForce 700f SerializeField private Animator anim SerializeField private bool automaticFire false SerializeField private bool slowDownEffect false private void Start() anim.SetBool("Shooting", true) public void Update() if (isAnimationStatePlaying(anim, 0, "AIMING") true) if (Input.GetButtonDown("Fire1") automaticFire false ) automaticFire false if (anim.GetBool("Shooting") true) anim.Play("SHOOTING") LaunchProjectile() else if ( automaticFire true amp amp Input.GetButtonDown("Fire2")) automaticFire true if(automaticFire true) anim.Play("SHOOTING") LaunchProjectile() private void LaunchProjectile() foreach (var firePoint in firePoints) Rigidbody projectileInstance Instantiate( projectilePrefab, firePoint.position, firePoint.rotation) projectileInstance.AddForce(new Vector3(0, 0, 1) launchForce) projectileInstance.gameObject.AddComponent lt BulletDestruction gt ().Init() bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName)) return true else return false I tried to do it in the Update using the automaticFire variable but it's not working fine. When clicking first the left mouse button it's shooting singles but then when clicking the mouse right button it's shooting automatic but then when clicking the left mouse button again it's not back to single shots again it's staying on automatic. The idea is right click mouse button automatic fire left button each time clicking the left mouse button the automatic should stop and then single shots with the left mouse button. And this way to toggle between the Fire1 and Fire2. Fire1 left mouse button click Fire2 right mouse button.


Unity update sizeDelta in OnValidate based on Layout Group computed values I'm trying to update the sizeDelta of a RectTransform in OnValidate. I'm trying to grab the computed values from a Layout Group. Here's what I've got if UNITY EDITOR void OnValidate() UnityEditor.EditorApplication.delayCall Resize private void Resize() if (this null) return RectTransform parentRect (RectTransform)gameObject.transform RectTransform textRect (RectTransform)tabText.transform textRect.sizeDelta new Vector2(parentRect.rect.height, parentRect.rect.width) layoutElement.preferredHeight parentRect.rect.height endif At first this seemed to be working, but it only works the first time OnValidate runs. Subsequence invocations of Resize() sets the sizeDelta to Vector2(0, 0). I'm wondering what causes this and if there's a way to avoid it. If I remove the delayCall, the values are correct, but I get warnings SendMessage cannot be called during Awake, CheckConsistency, or OnValidate I'd like to do this at edit time since there's no need to compute this stuff at runtime.


Oculus Rift DK1 and DK2 compatability issues For a project I need to make a multiplayer game using Unity and the Oculus Rift. My project works fine with the DK2 but it turns out the second rift is a DK1 and it won t work with Unity. I was thinking the best way forward would be to use an older version of the Oculus Runtime and Unity. Does anyone know what versions of Unity and the Runtime I need to have both the DK1 and DK2 work with Unity?


OnDrag does not work, but OnMouseDown works There is a code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class DragAndDropGame MonoBehaviour, IBeginDragHandler, IDragHandler Camera MainCamera void Awake() MainCamera Camera.allCameras 0 Debug.Log(MainCamera) public void OnBeginDrag(PointerEventData eventData) Debug.Log("OnBeginDrag") public void OnDrag(PointerEventData eventData) Vector3 newPos MainCamera.ScreenToWorldPoint(eventData.position) newPos.z 0 transform.position newPos void OnMouseDown() Debug.Log("OnMouseDown") OnMouseDown fulfills, but the implementation ofIBeginDragHandler, IDragHandler not. What can be wrong?


Why does this raycast code give me a NullReferenceException? The Error in the code is NullReferenceException Object reference not set to an instance of an object for if (hitxx.collider.tag "soldier") Please help! Thanks in advance void Update () Physics.Raycast (eyeenemy.transform.position, (eyeenemyfront.transform.position eyeenemy.transform.position) 20,out hitxx) Debug.DrawRay (eyeenemy.transform.position, (eyeenemyfront.transform.position eyeenemy.transform.position) 20,Color.green) if (hitxx.collider.tag "soldier") gameObject.transform.LookAt (soldier.transform.position) Debug.Log ("chuchu")


Why does Unity save textures in bitmap format for APKs and IPAs? Why does Unity save graphic resources in Android apks and iOS ipas in a bitmap format(width height bpp)? I want to save my resources in a small apk, but instead of 1mb for an image Unity stores 11mb for a single image.


How do I hide an Input field? I have in my hierarchy tab a Canvas. Inside the canvas I have an Input Field that holds a placeholder and a text. I read the documentations and didn't find how to hide the Input field. I want that if a if statement is true, then it will show the input field. Else you won't see it. How can I implement it? EDIT I thought about an idea to test If I press the O key on the keyboard it disappears, and if I press again it appears and so on. This is what I tried bool shown true Use this for initialization void Start () Update is called once per frame void Update () GameObject inputField GameObject.Find("InputField") if (Input.GetKeyDown (KeyCode.O)) shown !shown inputField.SetActive (shown) I play the scene and when I press the O key I get NullReferenceException Object reference not set to an instance of an object If I double click on the console message it highlights me the if (Input.GetKeyDown (KeyCode.O)) line. Something not good does the SetActive(bool) method, I suppose.


How to attach an UI button to a prefab and follow it in Unity2D My plan is creating a button above my prefab (a tree) and whenever my character is detected, the button will appear and allow me to click on it to active a dialog. I just want my trees are randomly spawned and stay still so it's not "follow" actually but I would like to know in that case too. I did some researches but most of them were about Text and HP MP things, which weren't used by UI system. One more thing, I kinda new to code so it would be fantastic if I got a full code (Button follow only). Thanks in advanced.


How to find and modify specific entity or gameobject in Hybrid ECS? I am rotating 3 cubes in Unity with Hybrid ECS and the code goes like this public class RoatateECS MonoBehaviour public float moveSpeed 10f class RotateSystem ComponentSystem struct RoadComponets public Transform transform public RoatateECS rotateECS protected override void OnUpdate() foreach(var e in GetEntities lt RoadComponets gt ()) e.transform.Rotate(0f, e.rotateECS.moveSpeed, 0f) Inside OnUpdate all three cubes are rotating, I want to rotate the second cube in the opposite direction but how would I find a specific cube and modify it ?


how to put elements around circle with equal distance? I know circle formula and know how to draw it. but I want put 4 points on it with equal distance from each other. how can I do that? I work with unity.


How can I unify the collision handling of melee spell attacks in a networked environment? I am trying to figure a good way to create the battle system of a game. The game is fast paced and the gameplay needs to be precise (think hack n slash) What I would like to achieve is a simple and unified system that could manage any type of attacks, that could be tweaked. My first idea is to use physics shape For example an arrow will just be a little capsule moving forward, an explosion would be a growing sphere collider, and melee combat could be done by spawning a box in front of the player. One problem I have with this is that I'd like to have an authoritative server for multiplayer, which means I shouldn't use too much actual physics. So, is there any standard way people program these sort of systems, do you know any good starting point better than just using physics?


Do I have to use new keyword for unity single game object? I'm using Unity4. Do I have to use new keyword for single game object? look at the following code. 1. GameObject obj new GameObject() obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject 2. GameObject obj obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject is it the same?


How to Fetch a Frame Number from Animation Clip I'm trying to find out how to fetch the frame number from an animation clip accurately. I don't want to get a value between 0 and 1 that shows as a percentage as a decimal how much of the animation has played (example 0.5 the 5th frame of 10 frames) because it doesn't seem to be accurate. This also seems impractical, so is there a way to accurately fetch a frame number from an animation clip? Thanks.


Should I use Coroutines to change variables in inspector smoothly? I want to change the aperture of the depth of field in the camera smoothly by using Mathf.SmoothDamp and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions? Code using System.Collections using UnityEngine using UnityEngine.UI using UnityStandardAssets.ImageEffects public class GameStartController MonoBehaviour public Button startButton public GameObject cubeSpawner Use this for initialization private void Start() startButton startButton.GetComponent lt Button gt () public void StartGame() EnableCubeSpawner() SpawnStartingCubes() HideStartMenu() StartCoroutine("FocusCamera") PlayBackgroundMusic() Enables the cube spawner, so it can start spawning cubes private void EnableCubeSpawner() cubeSpawner.SetActive(true) private void SpawnStartingCubes() cubeSpawner.GetComponent lt CubeSpawner gt ().GenerateStartingCubes() private void PlayBackgroundMusic() var audio GameObject.FindWithTag("Audio").GetComponent lt AudioController gt () audio.PlayBackgroundMusic() private void HideStartMenu() startButton.transform.parent.GetComponent lt CanvasGroup gt ().interactable false startButton.transform.parent.GetComponent lt CanvasGroup gt ().alpha 0f private IEnumerator FocusCamera() var camera GameObject.FindWithTag("MainCamera").GetComponent lt Camera gt () var velocity 0f while (Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture) gt 0.001f) Debug.Log(Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture)) camera.GetComponent lt DepthOfField gt ().aperture Mathf.SmoothDamp(camera.GetComponent lt DepthOfField gt ().aperture, 0f, ref velocity, 0.3f) yield return null camera.GetComponent lt DepthOfField gt ().aperture 0f


Admob is load failing by No Fill error I m using official admin plugin for Unity implementing Reward video. But it s only working for test unit id, when I replacing it to my own unit id, it just failing load by error No Fill . Even when I add test device, still happening the issue. How can I fix this?


Blinking color shader Currently i'm using Unity3D, and i want to make one variable blink along time in a fragment shader. Now i have code like this half4 frag(v2f i) COLOR float4 r OutlineColor r.a r.a SinTime return r But this blinking is too slow and not suit me, any ideas ?


What is the geometrical interpretation of Input.GetAxis("Mouse X")? According to the documentation, Input.GetAxis("Mouse X") produces a range of values from 1 to 1. However it will produce another range if it is setup to be delta mouse movement. Returns the value of the virtual axis identified by axisName. The value will be in the range 1...1 for keyboard and joystick input. If the axis is setup to be delta mouse movement, the mouse delta is multiplied by the axis sensitivity and the range is not 1...1. Question I don't understand what the value means geometrically. Is it a displacement between two points each in consecutive frame updates? If so what is its unit? Pixels, points, centimeters, etc?


OnCollisionEnter only triggering if colliding object starts inside collider Despite the absurdly high number of "OnCollisionEnter not working" threads around the internet, no one else seems to have had this specific problem. To start off with, I have a spherical "shield" object around my ship, which has a shader designed to give off impact effects when hit by an object. To trigger the shader impact effect, you need to give it the position from which do the effect. So, the easiest way to do this is to give the shield a Collider and, whenever OnCollisionEnter is called, it sends the contact.point details to the shader. That's not the difficult part. The part that isn't working is that OnCollisionEnter is not being called when the laser bolt fired at the shield actually collides with the shield. Both the shield and the laser bolt have Sphere colliders, both are not triggers. Only the shield has a rigidbody, which is not kinematic. void OnCollisionEnter (Collision collision) Debug.Log (Time.time) if (collision.transform.tag "Impact") Debug.Log ("go") Does the shader stuff That script is attached to the shield object. Not only is "go" never being logged, but neither is the Time, so OnCollisionEnter is not being called. The odd thing about this scenario is that, OnCollisionEnter will be called by objects that begin inside the shield's collider so if I start the laser bolt inside the shield, then the function gets called as usual. But when I start the laser outside the shield and Translate it into the shield, nothing happens. For the life of me, I can not work out what's going wrong with it.


How do I make dialogue only appear once? So I made it so when I walk over a NPC it brings up 12 lines of dialogue, and you press E to get to the next line. When the dialogue is over you can keep pressing E and it will bring the dialogue up every time. I want it so it only brings the dialogue up once. How do I do that? This is my script for it using System.Collections using System.Collections.Generic using UnityEngine public class dialogHolder MonoBehaviour public string dialogue private DialogueManager dMan public string dialogueLines public float questComplete Use this for initialization void Start() dMan FindObjectOfType lt DialogueManager gt () Update is called once per frame void Update() private void OnTriggerStay2D(Collider2D other) if (other.gameObject.name "Shrump") if (Input.GetKeyUp(KeyCode.E)) dMan.ShowBox(dialogue) if (!dMan.dialogActive) dMan.dialogLines dialogueLines dMan.currentLine 0 dMan.ShowDialogue()


Health zone heals player but I have a problem Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this? Here is the health zone script. public PlayerHealth playerHealth public float healthGain 2f void OnTriggerStay2D(Collider2D other) if (playerHealth.currentHealth lt playerHealth.maxHealth) playerHealth.currentHealth (int)healthGain playerHealth.healthBar.SetHealth(playerHealth.currentHealth) if (playerHealth.currentHealth gt playerHealth.maxHealth) playerHealth.currentHealth playerHealth.maxHealth playerHealth.healthBar.SetHealth(playerHealth.currentHealth)


Unity Shader Outlined Uniform uses undefined Queue 'Geometry 1' my outline shader was working fine but suddenly it started throwing this error. the game still works fine in the editor though but when i try to build it gets stuck on the step Packing assets sharedassets0.assets this is my shader Shader "Outlined Uniform" Properties Color("Main Color", Color) (0.5,0.5,0.5,1) MainTex ("Texture", 2D) "white" OutlineColor ("Outline color", Color) (0,0,0,1) OutlineWidth ("Outlines width", Range (0.0, 2.0)) 1.1 CGINCLUDE include "UnityCG.cginc" struct appdata float4 vertex POSITION struct v2f float4 pos POSITION uniform float OutlineWidth uniform float4 OutlineColor uniform sampler2D MainTex uniform float4 Color ENDCG SubShader Tags "Queue" "Geometry 1" "IgnoreProjector" "True" Pass Outline ZWrite Off Cull Front CGPROGRAM pragma vertex vert pragma fragment frag v2f vert(appdata v) appdata original v v.vertex.xyz OutlineWidth normalize(v.vertex.xyz) v2f o o.pos UnityObjectToClipPos(v.vertex) return o half4 frag(v2f i) COLOR return OutlineColor ENDCG Tags "Queue" "Geometry" CGPROGRAM pragma surface surf Lambert struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 c tex2D( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG Fallback "Diffuse" i tried looking on the internet but couldn't get any help on this error.


Colliders slightly intersecting each other any solution? Consider this simple scene In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider. And the problem if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall. This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist. Is there a workaround? How can the box smoothly move across the floor without colliding with the seam? Notes This does occur with capsule colliders but rare and is not very noticeable. A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks. This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity position of the transform.


How can I resize the Unity Facebook SDK's login dialog to fit my vertical phone screen? I have a Facebook login button for my iOS game, but Facebook's login panel is entirely too big The panel is cut off on both sides. It allows for input, but I cannot see most of it. My aspect ratio is 2 3 for vertical phone screens. I tried to use FB.Canvas.SetResolution and .SetAspectRatio both did nothing. I have not attempted to view this on an iPhone yet, only in my Unity debug view. I have never worked with Facebook SDK before, and can't find this issue discussed elsewhere, so help would be appreciated!


In Unity, can I make a GameObject within a prefab disabled by default? If I create a simple object hierarchy in my scene... ExampleGameObject Child1 is active Child2 is not active ...how can I accurately store this as a prefab? If I drag ExampleGameObject to a new prefab, then instantiate that prefab, both Child1 and Child2 will be active, which isn't what I want.


How to make an illusion where the contents of a 3D shape change based on which face you look through? I remember coming across a Unity 3D tutorial where there was a technique where the contents of a 3D shape change based on which face you are looking at, similar to this screenshot from Antichamber What is this techique called? And how do I implement it into a Unity 3D project? Thanks in advance.


How to physically move a rigid body up the stairs? When an object is controlled by a CharacterController, it is easy to make it climb ramps with a certain slope, or climb steps with a certain height. When the object is controlled by a RigidBody instead, it can still climb ramps naturally I just use AddForce and it walks on ramps just like on any other surface. I do not have to add any special logic for a ramp. However, it does not climb stairs. Is there a natural "physical" way to make the RigidBody climb stairs, without explicitly checking that there are stairs ahead?


Game states passing data between scenes I'm not entirely sure if I'm doing this right, but I always considered the scene system in Unity as some sort of state management (rather than e.g. a level system) which allows to group the contents (entities, components) into the usual main states of the game (menu, ingame), which can then be invoked or replaced together. Now I have a very specific concern and I have no clue how to deal with that in Unity, mostly because of it's abstractions from code and other restrictions My game features a procedurally generate terrain where as I'd like to tweak the generator before actually launching it. The tweaking is done in some sort of 'pre game' state (as part of the main menu) where the values are stored in e.g. TerrainData model class. Usually in other engines, I'd to it like this Providing an UI within the menu state to tweak the parameters of the game Storing the parameters in a view model (and data model) Instantiate the ingame state (which requires said data model in the .ctor Pass the data model to a generator and start the generation Now, here are the main problems Most types in unity (scenes, monobehaviors) do not allow constructors because they use it for themselves It doesn't seem possible to instantiate scenes manually (there's only e.g. Application.LoadLevel("") which only takes the name of the scene, not a instance reference etc. it doesn't seem possible to pass data between scenes, without reverting to awkward workarounds such as singletons, playerprefs, DontDestroy etc. which are all not really suitable for this case. So, how can I properly solve this? Is there a better way to manage states rather than scenes? Prefabs maybe? Backlink to UntityAnswers question http answers.unity3d.com questions 1149480 game state management and passing data between sce.html


Custom 2D physics on unity I have seen a lot of people think that for a 2D platformer game, Unity2D physics is not really the best approach, and recommend implementing your own physics. I found the idea interesting, but I don't know how to approach the issue. Using 2D Rigidbodies, and setting them as kinematic, allows you to ignore unity's physics. But how would collisions be handled without relying on Unity collision system?


Trying to 'stamp' an arbitrary assortment of pixels to a texture2d that may be rotated at an arbitrary angle This one is hard to explain but I'll try to not to overcomplicate it. Engine is Unity, for reference. I have a system where an object has a 2d texture to display a custom splat map. The user can 'paint' to this texture, which uses world space coordinates of the mouse to see which pixel should be painted to. They can also paint larger shapes, which are essentially just implementations of square circle drawing algorithms that choose what pixel coordinates to paint to based off the starting world space coordinates. This works fine while the object texture are unrotated, but if I rotate the object an arbitrary amount of degrees (say, 45 for the most extreme result), like squares and circle etc are drawn to the texture with missing pixels. I assume this is because the 'grid' of the texture is now rotated, and because I'm still trying to 'stamp' the shape in the original world space orientation (without respect to the rotation), the pixel 'sizes' or coordinates aren't the same? I can't post screenshots as I'm at work, but this is what my desired output would be (Ignore the pixelisation, had to use an online crappy paint program), where the first square is the object in its original rotation, with a red square stamped on to it as expected. The second square is after the object is rotated 45 degrees, and the yellow square stamped on it is what I want (and what is currently appearing with missing pixels in my implementation). EDIT And here is the actual result I'm getting, pixels per unit is 16. The first square was stamped, the rect then rotated 135 degrees, and then the second square was stamped (shown with the missing pixels) Anyone have any idea how I would go about drawing onto a rotated texture like this without ending up with missing pixels? I can post code snippets build images later. EDIT This is the code executed on the object to register a single pixel draw (very loosely), which uses the RotatePointAroundPivot function to get the pixel on the original pixel grid location in world space by rotating the point against the transforms current rotation. This works perfectly for individual pixel draws from mouse position clicks, but with the larger shapes I end up with the issue described void DrawToTex(Vector2 worldPos) worldPos RotatePointAroundPivot(worldPos, transform.position, transform.rotation.eulerAngles) (xPixelCoordinate, yPixelCoordinate) GetPixelCoordinatesFromWorldPos(worldPos) pixels xPixelCoordinate, yPixelCoordinate color public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) return Quaternion.Euler(angles) (point pivot) pivot public void DrawSquare(Vector2 worldPos, int size) (int startXCoord, int startYCoord) GetPixelCoordinatesFromWorldPos(worldPos) Literally just gets an array of the correct size int , squareMatrix GetSquareMatrix(size) sizeHalved size 2 pixelWorldSize 1f pixelsPerUnit pixels per unit is 16 in my build for(int x 0 x lt size x ) for(int y 0 y lt size x ) int newX startXCoord sizeHalved x int newY startYCoord sizeHalved y Vector2 pixelWorldPositionToDraw worldPos new Vector2((newX startXCoord) pixelWorldSize, (newY startYCoord) pixelWorldSize) DrawToTex(pixelWorldPositionToDraw) (int, int) GetPixelCoordinatesFromWorldPos(Vector2 worldPos) float xMin bounds.min.x float yMin bounds.min.y float distFromStartX worldPos.x xMin float distFromStartY worldPos.y yMin float xScaled distFromStartX pixelsPerUnit float yScaled distFromStartY pixelsPerUnit int xPixelCoordinate (int) xScaled int yPixelCoordinate (int) yScaled return (xPixelCoordinate, yPixelCoordinate)


How to generate multiple particles at once? I am tying to create a cartoony balloon pop animation. I want there to be particles that come from all sides of a sphere. However they should all come at once, in a single burst. What I've done is this. I generated a particle system as a child of the sphere. I set the shape to sphere, reduced the duration, and increased the rate. However it doesn't seem like any particles are being generated at the same time still, only one is created at once. How can I make all of the particles come at the same time?


How to build a hidden 3D snapping grid effect? Looking to build a 3D grid similar to the image below taken from Google Blocks. Seems like it consists of these main components A set of spheres that can go transparent. A stencil that follows the controller's location. When stencil overlaps with spheres, they show up, otherwise, alpha fades to zero. Any advise on how to approach building this?


Get Closest point between a Box 3D and a Point I have a point A (x, y, z), and a Box Center (x, y, z), Size (Width, Height) How to get the closest point in the box from the point A ? In Unity I can create a bound, and I can find the non rotated position like that Bounds bounds mesh.bounds Vector3 closestPoint bounds.ClosestPoint(pointA) But then If the bound is rotated, the result is not correct. So I have 2 options Find the way to rotate my closestPoint from the pivot. Find the math formula myleft. If someone can help ! thanks. EDIT here a video the red point is the one find with bound.ClosestPoint the yellow point is the one find with Vector3 closestPointInverse currentTarget.InverseTransformPoint(closestPoint) https youtu.be RMRRtSaJv8w I have also tryed to do my own rotateFromPivot function public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) return Quaternion.Euler(angles) (point pivot) pivot When I use it, I get the same result with the InverseTransformPoint method.


How can I move two couple of objects? Now it will move all the objects of allLines and instancesToMove at the same time. But I want to take each time one object from the allLines and one from the instancestoMove and move this two together then the next two objects and so on. if (animateLines) counter for (int i 0 i lt allLines.Count i ) endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(startPos, endPos, counter 25f speed) if (Vector3.Distance(instancesToMove i .transform.position, endPos) lt 0.1f) DestroyImmediate(instancesToMove i ) instancesToMove.RemoveAt(i) DestroyImmediate(allLines i ) allLines.RemoveAt(i) Both allLines and instancesToMove are List


Can I export animated models from Unity? Into what formats? I have an animated 3D model from the Unity Asset Store that I would like a new animator to touch up (the license allows this). But they need it in a format they can use (in Maya or... something else?). All I have been able to find so far is how to export from the Editor into Unity Package format scripts to export the mesh (only?) into OBJ format 1 Is it possible to export a textured and rigged model from Unity? If so, into what formats and how? 1 ObjExporter and ExportOBJ


Recursively find neighbors I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors. Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow. private List lt Bubble gt FindAllRecursiveNeighbors(Vector2Int originPosition) List lt Bubble gt allNeighbors FindNeighbors(originPosition) List lt Bubble gt result new List lt Bubble gt () foreach (Bubble bubble in allNeighbors) if (result.Contains(bubble)) continue result.Add(bubble) Recursion starts here. foreach (Bubble bubble in result) List lt Bubble gt neighbors FindAllRecursiveNeighbors(FindPositionOfBubble(bubble)) foreach (Bubble neighbor in neighbors) if (result.Contains(neighbor)) continue result.Add(neighbor) return result


Unable to list target platforms. Please make sure the android sdk path is correct For some reason, I am unable to test my android program because of this error. Here are some pictures of the errors. This error is not allowing me to test my app on my test Android device, I have tried uninstalling and reinstalling, checking if it is acatually the root folder, everything, PLEASE HELP! 1st error CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. C Users jayso AppData Local Android sdk tools bin avdmanager.bat list target c stderr stdout ERROR JAVA HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA HOME variable in your environment to match the location of your Java installation. exit code 1 UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunAndroidSdkTool (System.String toolName, System.String arguments, Boolean updateCommand, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.ListTargetPlatforms (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit) UnityEditor.Android.AndroidSDKTools.GetTopAndroidPlatformAvailable (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK SDKPlatformDetector.GetVersion (UnityEditor.Android.AndroidSDKTools sdkTools) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK SDKComponentDetector.Detect (UnityEditor.Android.AndroidSDKTools sdkTools, System.Version minVersion, UnityEditor.Android.PostProcessor.ProgressHandler onProgress) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (System.Version minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (Int32 minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.BuildPlayerWindow BuildPlayerAndRun() 2nd Error Error building Player CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. C Users jayso AppData Local Android sdk tools bin avdmanager.bat list target c stderr stdout ERROR JAVA HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA HOME variable in your environment to match the location of your Java installation. exit code 1


Activating particle system after 2 triggers on enter I would like that particle system must play indefinetely at some position after two triggers on collision are triggered on enter. When game starts, particle system is deactivated. I have make this script where I can attach particle system into prefab and I have set spawnpoint position. 1) Is it possible to activate particle system differently (without Instantiate) ? 2) How to make that two triggers on enter activate particle system? One trigger is not enough. using System.Collections using System.Collections.Generic using UnityEngine using System.Collections using System.Collections.Generic using UnityEngine public class spawn object MonoBehaviour public Transform spawnpoint public GameObject prefab public int i 1 Use this for initialization while (if lt 2) void OnTriggerEnter () Instantiate (prefab, spawnpoint.position, spawnpoint.rotation) i


How to convert RotateAround speed to directional speed in Unity? I am currently using transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond Time.deltaTime) to make an object rotate around another object. This works well, but I want to make the object stop rotating around and instead move in a certain direction at the same speed that it was rotating. However, I can not figure out how to convert the degreesPerSecond into a directional speed. My goal is to have something like this if(rotating) transform.RotateAround(transform.position, Vector3.forward, degreesPerSecond Time.deltaTime) else transform.position transform.right DegreesToDirectionalSpeed(degreesPerSecond ) Time.deltaTime float DegreesToDirectionalSpeed(int degrees) Code that I don't know goes here Any tips on how to achieve this?


How do I set meshCollider.cookingOptions to MeshColliderCookingOptions.Everything in code? I'm procedurally generating some meshes for a project, and I need to add colliders to them. The meshes are generating fine, but after setting the shared mesh in the mesh collider, I need to be able to set the cookingOptions to Everything. In the inspector, I can do this fine and the colliders work correctly. Since I am generating these at runtime, I can't really do this after making a build. How do I go about doing this? Works Correctly Does not Work Correctly


What's the proper way to use static objects and singletons in Unity? I have a GameObject in Unity, which I've attached this script to, in order to make it function as a Static Singleton using UnityEngine using System.Collections public class SceneStatics MonoBehaviour private static SceneStatics instance public static SceneStatics Instance get if (instance null) instance new GameObject ("SceneStatics").AddComponent lt SceneStatics gt () DontDestroyOnLoad(instance) return instance public void OnApplicationQuit () instance null I have two other scripts that I'd like to be able to access from scene to scene. What's the proper way to do that? Do I attach my Inventory and Room scripts to the same game object as the SceneStatics? If so, how do I access them? Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent? Alternatively, what happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics? Or is the intended use that I simply make any other static items I need properties of the SceneStatics class? (I.e., add in a Public static Inventory and Public static Room attributes)?


GUI.Button inside GUI.Window not responding I am trying to do some GUI work with unity but am having some issues. I call a window with this code fortuneRect GUI.Window(0, fortuneRect, fortuneWindow, "Your future") and inside the window I have a button if(GUI.Button(new Rect(10, 10, 150, 20), "save fortune")) Debug.Log("save fortune button press") writeToFile("Button pressed!", "fortune.txt") Debug.Log("After save fortune button press") but the button doesn't fire any of its events on click. I tried commenting out the writeToFile but even with only Debugs in the body it doesn't fire.


Is it possible to apply a texture to a 2D sprite in unity 2 d? I want to take an (animated) 2 d sprite and apply a texture to it. Basically, I want every non transparent pixel to be covered by the texture (color is disregarded). I understand I can probably accomplish this using masks but I am worried that may not be the most performant solution. I know you can put textures onto 3 d models, so I was wondering if there was a similar process for 2d sprites. Below I have a graphic demonstrating what I want. What I have tried so far I see there is an option to add a material to a sprite, so I tried creating various materials. 1. Default material When I tried applying this material to my sprite, the sprite disappeared entirely. I suspect because this default material type only works on 3D objects 2. Sprite Material I figured sprites probably expect sprite materials, so I tried creating one. However, there does not appear to be anywhere to upload an image to use as a texture. This appears to only be useful for adding tints to sprites.


Find closest point on NavMesh if current target unreachable I have a mock environment set up with a cube that has a specified "Not Walkable" layer. I'm using NavMeshAgent and NavMeshPath to set destinations of the player. The way I'm setting paths is by ray casting points on the terrain by mouse clicking. I'm having trouble figuring out a way to fix if I click on the cube that has a "Not Walkable" layer, the player just runs into the cube and tries to reach that point. I've read about the FindClosestEdge function in unity but I don't think that's exactly what I'm looking for. So basically I need the target location to change to the nearest point next to the cube when I click on the cube. Any ideas?


How can the player select his weapon among many? I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https youtu.be Dn BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded? I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project. sorry for the bad english


Not able to find the constraints option in the Rigidbody component I am working on a game tutorial right now and I need to freeze constraints for a model prefab. I add a Rigidbody component and I want to freeze rotations on the x and z axes. However, I am not able to find the option in the component. Is there another way to access rotation constraints (I do not want to code the constraints at the moment)? Or is there something I am missing in the new version. Please do let me know. Thanks I am using Unity 5.6.7f1 Personal


Gravity not being applied to character, using character controller So I just copy and pasted the unity example class to use with my character controller. public float speed 6.0F public float jumpSpeed 8.0F public float gravity 20.0F private Vector3 moveDirection Vector3.zero void Update() CharacterController controller GetComponent lt CharacterController gt () if (controller.isGrounded) moveDirection new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) moveDirection transform.TransformDirection(moveDirection) moveDirection speed if (Input.GetButton("Jump")) moveDirection.y jumpSpeed moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) The code seems to work okay if I comment out the isGrounded check statement (which means that gravity isn't being applied). So what could be the reason that the gravity is not being applied to my character controller?


Couldnt visualize the mechanism describe by the code Was reading this article http www.jgallant.com 2d liquid simulator with cellular automaton in unity but couldn't understand the mechanism in quot CalculateVerticalFlowValue quot . Is the remaining liquid represent the tile just above the tile quot destination liquid quot ? Would appreciate if can provide simpler example to visualize the mechanism as I couldn't see the logic behind this code. using UnityEngine using System.Collections.Generic public class Liquid Max and min cell liquid values float MaxValue 1.0f float MinValue 0.005f Extra liquid a cell can store than the cell above it float MaxCompression 0.25f Lowest and highest amount of liquids allowed to flow per iteration float MinFlow 0.005f float MaxFlow 4f Adjusts flow speed (0.0f 1.0f) float FlowSpeed 1f Keep track of modifications to cell liquid values float , Diffs public void Initialize(Cell , cells) Diffs new float cells.GetLength (0), cells.GetLength (1) Calculate how much liquid should flow to destination with pressure float CalculateVerticalFlowValue(float remainingLiquid, Cell destination) float sum remainingLiquid destination.Liquid float value 0 if (sum lt MaxValue) value MaxValue else if (sum lt 2 MaxValue MaxCompression) value (MaxValue MaxValue sum MaxCompression) (MaxValue MaxCompression) else value (sum MaxCompression) 2f return value


Objects stick together on Collision I have a ball which has CircleCollider2D attached to it. It is also rigidbody. When it lands on a platform, it jumps . The platform is static, with Edge Collider attached. It also has a platform effector attached with quot Use One Way quot selected. Most of the times it works fine, but some times, the ball lands on the platform and instead of bouncing, just sits on the platform. When ball lands on the platform, following code is executed rb.AddForce(upForce, ForceMode2D.Impulse) upForce is Vector2(4,10) image shown below Why is this happening?


Are the prefabs stored in RAM or in the Hard disk? (Unity3D) I have many prefabs objects (65 MB) in an Unity3D project. My game use 100 different levels with combinations of the prefab objects. What is better create 100 scenes or create only one scene where the prefab objects are placed with data from a XML?. Each Scene load your own prefab objects? Are the prefab objects loaded in the RAM when the scene is loaded or are stored in the hard disk and then loaded in the RAM when come in the scene?


Matching collider to character mesh size in different postures What's the optimal method in Unity to match the size of a Capsule Collider to the actual size of the game object it is part of? To understand what I'm trying to do let me give an example I have a 3D player character with a Capsule Collider that is used to check collision. The character can go into various postures, e.g. crouch, prone, jump. I'm having difficulties to match the height of the collider to the height of the character when crouching or jumping because depending on the used animations the character's height is smaller by various amounts when crouched or jumping. All I could do so far is set a multiplier for a specific posture by that the collider scales but this is very inefficient, especially when the character tries to jump onto a higher ground. There seems to be no way of knowing the exact size of a mesh. I'm not sure if it might help to loop through all child meshes (torso, hair, etc.) in a game object and obtain their bounds through SkinnedMeshRenderer.


Creating a list of buttons dynamically in code I have a list of contacts. I need to create a scrollable list of buttons that are created dynamically so I can add each contact name as the button text. How would I do this all in code? My biggest concern is making sure the sizes stay consistent. I haven't had to do that in code before. EDIT And here is the code to add the buttons to this for (int i 0 i lt count i ) if (i gt 0) crt.sizeDelta new Vector2(crt.sizeDelta.x, crt.sizeDelta.y initHeight) GameObject contactButton Instantiate(Resources.Load("Contact Button")) as GameObject contactButton.transform.parent contactsList.transform contactButton.GetComponentInChildren lt Text gt ().text names i


Box collider rigid body eventually moves through static collider I found this question, but I'm not sure if it applies to my problem. I'm hacking together a Pong style game, and my problem is with the walls (box collider, no rigid body) not completely stopping movement of the player paddle (box collider, yes rigid body.) Sufficiently fast mouse movement eventually moves the paddle through the wall. There is initial resistance, but I would expect Player Paddle to stop moving abruptly at the wall. How can I make this happen? I'm new to Unity colliders game dev. My player paddle simply moves up and down (Z axis) with up down mouse movement public class MouseMovement MonoBehaviour public float speed 10f Update is called once per frame void Update () var translation Input.GetAxis("Mouse Y") speed translation Time.deltaTime transform.Translate(0, 0, translation) I exported an asset package that reproduces the problem. My problem objects are Player Paddle, Upper, and Lower https www.dropbox.com s yx9svb51nywdvgg pong export.unitypackage?dl 0


Tracking small moving targets in Vuforia I am trying to track up to two small moving objects the size of a small toy car (about 7x4x4 cm 3x2x2 ) from a 75cm 2ft distance. I m aware that the distance size ratio is about 20, which is off by factor compared to the by Vuforia recommended ratio. I've tried frame markers and while frame markers are super fast close up, they don't work well at a distance. I'm hesitant to use expensive object recognition on moving targets. I ve tried black and white QR codes and AR markers as image targets but Vuforia seems to have trouble recognizing them, even though the QR code has a five star rating. I m considering two more options 1) an optimized 4x4cm color image target 2) add LEDs to the objects and track the LEDs, for example like this https www.youtube.com watch?v IoL0bIGk uE My questions 1) Are there specific tips for creating small image targets (I have read the generic image target optimizations tips assume not all those tips apply to small targets) 2) Is there an easy way to track LEDs in Vuforia?


How do I check if there is already an object in this scene with the same name upon reloading the scene? If the title wasn't clear enough (I don't really know how to explain it), basically I have an Audio Manager that is DontDestroyOnLoad. I also have a pause menu, that takes me back to the main menu, and in the main menu, I can reload the scene again. The problem is, upon reloading the scene, multiple copies of AudioManager is created in DontDestroyOnLoad, and I don't know how to solve it. My AudioManager script to give you a reference (only the important parts) using System.Collections using System.Collections.Generic using UnityEngine public class AudioManager MonoBehaviour region Instances private static AudioManager instance public static AudioManager Instance get if (instance null) if instance doesn't exist, find an AudioManager instance FindObjectOfType lt AudioManager gt () if (instance null) if instance still doesn't exit, then it will create a new one instance new GameObject("Spawned AudioManager", typeof(AudioManager)).GetComponent lt AudioManager gt () return instance private set instance value endregion region Fields the audio source can only play one looping sound at a time private AudioSource musicSource private AudioSource musicSource2 purpose of having 2 musicSources is that we can use them to achieve effects like CrossFade private AudioSource sfxSource private bool firstMusicSourceIsPlaying endregion private void Awake() Make sure we don't destroy this instance DontDestroyOnLoad(this.gameObject) Create audio sources, and make them as references musicSource this.gameObject.AddComponent lt AudioSource gt () musicSource2 this.gameObject.AddComponent lt AudioSource gt () sfxSource this.gameObject.AddComponent lt AudioSource gt () loop musicSource musicSource.loop true musicSource2.loop true If you are reading this, thanks for taking your time and try to help me!


How to solve problem with Terrain Flashing and then disappears when flying away? I am making flight simulator( my first Unity project) , the biggest challenge so far is terrain, so whenever I fly away from it (not that far) the terrain starts flashing and disappears which is just green mountains, so when i come back to it, i have no idea where its position is, but it suddenly appears (again flashing) when I am close , the terrain size is normal but it's on top of a huge other terrain (about 100,000 100,000 which is the max),I tried changing pixel error and base map distance, no change, I looked at big terrain solutions online, but non of them really helped me, Any advice? Thanks


Unity 5 The Editor has stopped working Windows 7 64bit As soon as I press the play button to attempt to run any of my updates games crashes the editor immediately and I can't run my games. Does anyone know how I could debug this or where to start? Does Unity keep a log of errors when it crashes? I have both a 2D and 3D game that do not work and the editor is not throwing any errors or telling me there are compile time issues. EDIT If it makes any difference it is the 64bit version and I am using a Student Pro License


Discoordinated Chromatic Aberration Effect The game Teleglitch heavily utilizes the CA effect with screen distortion. I am trying to achieve this effect. Issue 1. How to not apply the effect onto the floor? (solved) They render the screen then apply the CA effect. However, the floor is not rendered with the post processing effect. Issue 2. How to have discoordinated position for each rendered CA effect? Currently I have three offsets for each channel red, green, and blue. However, I cannot assign different offsets for the channels for certain areas only. What would be a way to have discoordinated positions?


UnityEditor.SyncVS.SyncSolution putting wrong language version in generated files I'm working on getting our Unity projects building in bamboo for our build server. We have a cli step that runs through the Unity commands for creating a build. It works fine on several projects, but for some reason this particular project I'm working on I'm getting an error that states I need to use c version 7.2 or newer. If I log in to the build server and open the .csproj files in notepad and check the language version, it's setting them to 7.0. However, if I deactivate the cli step so that the build job only clones the project, then manually log in and open unity and go through the process so it generates the .csproj files, then check them, the language version is set to 8.0. The project works fine locally on my own pc. And it works when setup manually on the build server pc, but when ran through the cli step, it generates them at an earlier c version. This leads me to believe there is a problem with the UnityEditor.SyncVS.SyncSolution step in my commands. I'm just not sure what it could be, or why it's behaving differently for this project as opposed to other projects that are using the same code base (where the problem is said to occur), same Unity version, same build server, etc. Anyone else experience this issue or have any thoughts on a solution?


Why is Unity ignoring my camera on Android? I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app. Here's what it should look like Here's what it ends up looking like My game is forced in portrait, and I want to keep it that way. I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera I think it is just using the canvas. I tried many different things, including changing the scaling and setting the anchors. None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor. Why is Unity ignoring my camera on Android?


How can I look up an object given only the name of its type? This question came from a fellow developer on Twitter, and I figured StackExchange would be a better format for explaining amp sharing the answer. To paraphrase the question I'm setting up an in game dev console in my Unity game, where a user should be able to call any method on any MonoBehaviour in the scene. I want to use something like FindObjectsOfType lt gt , but because it's coming from a string input by the user, the class name is unknown at compile time. I also want this to work universally, on any MonoBehaviour, not just ones I've specially instrumented or registered with the console system. Is there a way to find instances of a type with a particular name, and call methods on them, using something like reflection?


Emulating 3d trajectory in top down 2d game? As the title suggests, I am wondering if it's possible to emulate a 3d arrow trajectory to a top down 2d game? If you would look at this clip of Age of Empires 2 game, especially when archers are firing from bottom to top. Can the parabola arc of the trajectory (in that certain view angle) be emulated in a 2d orthographic, top down game? So that the arrows would look like they're in 3d space. I know it's tricky but I wonder if there's some computation available for this. If you could point me in the right direction or some sample code I would be very grateful. I've only implemented this projectile motion in a side scroll view. Thank you in advance.


Failed to spawn server object, Unity UNET I'm familiar with Unity and programming but I'm new to this site. So I have an issue with clients on Unity. I start servers with no errors, flawless. But when I join a server as a client I get a bunch of the error mentioned in the title. What causes this issue? I am using the UNET networking components. I think it's lines like these, when executed by a client NetworkServer.Spawn (objectNameHere) How can I fix it if that's the case? Edit After hours of having this issue I have become so frustrated that I think it's best I take a break. I'll check back on this site from time to time.


Updating GameObject Position in Unity 5 I have a simple Sprite called Player that has the follow components (Transform, Sprite Renderer, Box Collider 2D, Rigidbody 2D, Player Controller Script). In my Player Controller script I want to update the player's position when a key is pressed. using UnityEngine using System.Collections public class PlayerController MonoBehaviour Vector2 playerPos Use this for initialization void Start () playerPos gameObject.transform.position Update is called once per frame void FixedUpdate () if (Input.GetKey("d")) playerPos new Vector2(playerPos.x 0.2f, playerPos.y) This script is attached to my gameobject but whenever I press or hold down the 'd' key, nothing happens to the player. Does anyone know how to fix this?


Unity 5 Google Cardboard VR SDK Frame Rate I am running the Google Cardboard's official demo which doesn't really have much things on the scene (https developers.google.com cardboard unity download) on my Personal Unity 5 on my Nexus 5. The fps is around 40 and I am wondering if the fps is so low because of my Nexus 5's hardware specs or is there a way to optimize the fps in Unity or some configuration in Google Cardboard's SDK?


Is There a Way To Keep Precision When Transforming GameObjects I've seen this issue before, but it's never been a particular issue for me until today. I have each "room" of a dungeon created with a class script that contains details of that room. During the process of building the dungeon, rooms may be mirrored or rotated. When I rotate the y axis, it updates properly the first time, going from 0 to 180, but if I mirror it back and forth, it begins to get very small variances away from true 0 and 180. Over time, this could impact some things. The code I'm using to do this is public void RoomMirror() transform.Rotate(0, (transform.localRotation.y 180) ? 0.0000f 180.0000f, 0) Mirror !Mirror Swap(ref east, ref west) I added the four places in the float to try to overcome this issue, but it doesn't seem to be making any difference. Thanks!


App icon on phone looks squished in Unity I am working on a 2D platformer. And I am alomost finished!! I am trying to work on adding the app icon. The icon that you would see on your phone. I imported the picture and added it to player settings. But when I put my game on my phone the icon looks squished. These are the settings that I imported it on Texture Type (sprite 2D and UI) sprite mode Single Filter mode Blinear (not pixel art) Here is a link to a screen shot on my phone of the icon https www.dropbox.com s jbgciscda7nykjd app 20on 20phone.png?dl 0 Ok I am getting closer to an solution now. My first problem was that the image was not square as staed below. But now the image is smaller compared to the rest of the app icons. the resolution of teh image now is 2000X2000 Here is a screenshot of what it looks like now https www.dropbox.com s t45vylzpi3chnsf App Icon 2.png?dl 0


how do I tile this generated terrain infinitely around the player? i made a script that instantiates cubes with for loops and perlin noise. is there any way i can tile this infinitely around the player? here is the script for the generation of one tile public GameObject grass public int mapSizeX 50 public int mapSizeZ 50 public float heightScale 20f public float detailScale 20f float seed Use this for initialization void Start() if (instance null) instance this for (int x 0 x lt mapSizeX x ) for (int z 0 z lt mapSizeZ z ) int y (int)(Mathf.PerlinNoise((x seed) detailScale, (z seed) detailScale) heightScale) GameObject g Instantiate(grass) as GameObject g.transform.position new Vector3(x, y , z) g.transform.SetParent(this.transform)


How to move a player along Waypoints with Rigidbody.MovePosition in Unity? I have a player with a Rigidbody, I want it to follow along the Waypoints. I have used MoveTowards but it seems also not to work however. I want to use MovePosition to add force while grinding. I commented a code that could maybe work but I got an error on that, check ADDFORCE lines. Here is my code public GameObject waypoints public float grindSpeed public float turnSpeed public int currentWaypoint private Animator anim private Rigidbody rb public bool isGrinding false void Start() anim GetComponent lt Animator gt () rb GetComponent lt Rigidbody gt () void FixedUpdate() MoveAlongWaypoints() if(isGrinding) anim.SetBool ("isOnGrinding", true) else if(!isGrinding) anim.SetBool("isOnGrinding", false) void MoveAlongWaypoints() if(isGrinding) TRANSLATE transform.position Vector3.MoveTowards(transform.position, waypoints currentWaypoint .transform.position, grindSpeed Time.deltaTime) ADDFORCE Vector3 movePosition transform.position movePosition Mathf.MoveTowards(transform.position, waypoints currentWaypoint .transform.position grindSpeed Time.deltaTime) rb.MovePosition(movePosition) ROTATE var rotation Quaternion.LookRotation(waypoints currentWaypoint .transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, rotation, turnSpeed Time.deltaTime) if(Mathf.Abs(transform.position.x waypoints currentWaypoint .transform.position.x) lt 1 amp amp (Mathf.Abs (transform.position.y waypoints currentWaypoint .transform.position.y) lt 1) amp amp (Mathf.Abs (transform.position.z waypoints currentWaypoint .transform.position.z) lt 1)) rb.useGravity false currentWaypoint void OnTriggerEnter(Collider other) if(other.gameObject.tag "GrindWayPoint") Debug.Log ("Waypoint!!") isGrinding true


Does duplication happen quicker than generation? I am evaluating performance of bullet instantiation methods in Unity. I have a thing against prefabs. So each bullet is made from a function that sets the shape material, scripts and behaviors (tracking, velocity, duration, etcetera). Call this the "ammo type" if you like. Here are my instantiation methods Generate one bullet from script. Disable it. Instantiate(duplicate) new bullets from this bullet and enable them when gun fires. Each time the gun fires, generate a new bullet from the script. Still technically a duplicate but arrived at through a different method. Which of these would have better performance? Would it be a drastic difference or a minor one? The first method makes much more sense than the second. However there is a problem with delegates not being transferred when duplicating. Thus I am considering the second method and wondering how bad it would be on performance. For more information on the problem with delegates when duplicating a prefab read this post. I am happy to clarify any of the above should you find my explanation lacking.


Change Time.timeScale during an animation event Unity I have an animation. A few seconds after this animation starts I set an animation event that is correctly being triggered. This animation event calls a method where I am trying to modify Time.timeScaleand set it to 0.05f. This event is calling the following method public void Slowmotion() Time.timeScale 0.05f Time.fixedDeltaTime Time.timeScale 0.02f But this Slowmotion method is not working. Any ideas on what may be happening?


Why the OnCollisionEnter is not working? This script is attached to the wall(3D Cube) with a box collider using System.Collections using System.Collections.Generic using UnityEngine public class LockedRoomTrigger MonoBehaviour private void OnCollisionEnter(Collision collision) Debug.Log(collision.transform.name) But when the player is moving and hit the cube it's not getting to the Debug.Log I used a break point on the Debug.Log line. A screenshot of the cube wall with the box collider component and the script attached to it. The problem is not with the player since if I'm moving with the player near doors they open so the player does trigger things and also not walking through walls. This is a screenshot of NAVI. NAVI is a bit in front of the player and moving with the player and part of the player in the game like a friend helper. NAVI is the one that collide and hit stuff if doors walls not the player since the NAVI is a bit in front of the player. NAVI have only a box collider And this is the Inspector screenshots of the player. I will add two screenshots since it's not getting inside in one screenshot The player is a first person view


Allow a game object to pass out of a collider but not back in Unity In my game I have enemies that shoot projectiles out at the player, the only way for the player to get rid of them is by guiding them into a structure. An example of my enemy shooting a projectile. The problem I have is that sometimes the enemy spawns on top of one of these structures as seen below. This results in the projectile exploding colliding with the structure the moment it is spawned. I'm not entirely sure how to go about fixing this issue. I have tried to find a way to disable the collider on the projectile for a few seconds but I couldn't get the timer right. I also think this might cause some odd game play issues. The second thing I tried was a platform effector, however I could only get it to form a circle and this didn't work out because my structures are of all different sizes and shapes. If anyone could point me into the right direction or even help me find a better solution I'd be extremely grateful. Thanks ublic class MultiBullet MonoBehaviour public float speed 1f private Rigidbody2D rb Use this for initialization void Start () rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () rb.velocity transform.up speed private void OnTriggerEnter2D(Collider2D collision) Add explosion Effect if (collision.gameObject.tag "Player") Add game over screen here Debug.Log("Player Killed") Destroy(gameObject) Debug.Log("BOOM") Destroy(gameObject) if(collision.gameObject.tag ! "BulletIgnore" amp amp collision.gameObject.tag ! "Cloud") Debug.Log("BOOM") Destroy(gameObject) Just a simple class to handle when projectiles collide with objects.


How to do gear physics I've realized this gear using primitive. My object is Main cylinder with with a Rigidbody and a script who rotate Y axis All Prism as child who has MeshCollider I've got also a pivot for each gear. The problem is that the right gear not rotate when "prism" collide with others. The collision not happen. Any ideas ? Thanks


Unity Texture huge areas with decals I'm using 1024 textures for smaller buildings and 2048 for larger one's. Basic workflow 1) Unwrap in Blender 2) Smack a concrete texture on it 3) paint some dirt here and there. Result This only works for small buildings. Here is an example from Battlefield 2, they put a small 128x128 brick texture and tiled it across the entire building and added Dirt on top of that. Is there a way to do this using Unity or do I have to create my own custom shaders? (God forbid)


How can I put a Unity3D game on an Xbox 360 disc? I've made a simple shooter in Unity that I'd like to play on an Xbox 360. Mass production not required, just a one off game, completely non profit. Perhaps burning to a DVD? Is it a relatively simple procedure to burn the game to disc? I have a nasty feeling the Xbox 360 needs to be chipped. Is this the case?