How can I prevent pixel artifacts on programatically generated textures? In the game I'm developing, rooms can be of various sizes, which means I need to vary the size of the floor texture appropriately. The way I've solved this problem is to generate a Texture2D programatically, and set each pixel to be transparent (or not) as appropriate appropriately. I get something like this Where, if you look at the top left, you'll clearly see the pixel artifacts from the floor texture against the dark blue background. When I run into this with static textures, the fix is simple. Set the Texture's wrapmode to clamp instead of repeat. But when I try to do that programatically... (and change nothing else!) I get this I'm not quite sure what's happening, or why setting the wrapMode changes the results so markedly. Anyway I can avoid the pixel artifacts? I suppose it's possible to add an extra border around the generated texture (so that all edges can be transparent), but that doesn't seem a particularly clean solution. Code is here void DebugFloorTextureMerge() sizeVector makes up the rectangle circumscribing the room's parallelagram Vector2 sizeVector new Vector2(roomBounds.topRight.x roomBounds.bottomLeft.x, roomBounds.topLeft.y roomBounds.bottomLeft.y) get the texture of the filled sprite Texture2D patternTexture (Texture2D) floorTexture.image make a new texture of the size of the room. Texture2D fillTexture new Texture2D( (int) sizeVector.x, (int) sizeVector.y, TextureFormat.ARGB32, false) COMMENTING THIS LINE OUT MAKES THE TEXTURE WORK WITH ARTIFACTS fillTexture.wrapMode TextureWrapMode.Clamp LEAVING IT IN MAKES THE FOLLOWING CODE WORTHLESS int patternX 0, patternY 0 Vector2 pointVector Color transparent new Color(0,0,0,0) for(int x 0 x lt sizeVector.x x ) for(int y 0 y lt sizeVector.y y ) pointVector new Vector2(x,y) if(roomBounds.Contains(pointVector)) get the next pixel fillTexture.SetPixel(x,y, patternTexture.GetPixel(patternX, patternY)) else pixel was not in the room, so set it to transparent. fillTexture.SetPixel(x,y, transparent) resultx x resulty y increment the pattern counter and reset if necessary. if you only increment this when Contains is true, you'll warp the texture patternY if(patternY gt floorTexture.fillSize.y) patternY 0 increment the pattern counter and reset if necessary. also reset y, so the pattern will line up properly. patternY 0 patternX if(patternX gt floorTexture.fillSize.x) patternX 0 set the PixelChanges. fillTexture.Apply()


Creating color texture from greyscale heightmap in shader I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects. I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here. Shader "Custom Planet" Properties height("HeightMap", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 struct Input float2 heightMap float minHeight 0 float maxHeight 1 float inverseLerp(float a, float b, float v) return saturate((v a) (b a)) UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float hv inverseLerp(minHeight, maxHeight, IN. heightMap) o.Albedo hv ENDCG FallBack "Diffuse"


Development decision how to proceed regarding OpenGL There is a 3D app developed by someone with OpenGL almost 2 years ago. The development is not finished by the previous developer and I'm assigned the task to finish it, based on customer requests. I started the development almost a week ago and I've fixed some OpenGL related issues and added some features. But, there is something that really bothers me and I just thought I'd need advice. The voices noises in my head mind that bother me If we stick to our OpenGL, eventually we will lose the Apple ecosystem, and will consequently lose being cross platform. OpenGL is low level, for a simple thing like detecting user clicks on 3D objects, I need to spend much development time. If we get high level with Unity engine or Unreal engine, we have no problem with any platform even VR AR. The development time with these engines appears to be much faster. Even with regard to licensing, they are flexible and provide free ones. As people say, Unity Unreal is like buying a car and OpenGL Metal D3D is like buying a wheel. Maybe my life as a developer would be much easier if Unreal Unity engine is used rather than a lower level tool like OpenGL. Now, I'm goint to talk to my boss regarding above thoughts. I want to ask him if it makes sense to let OpenGL go and just switch to an engine. But before talking to my boss, I just thought I'd ask here to see if it makes any sense or if I'm missing something.


Terrain Navmesh build, rebuild smaller pieces of the bigger navmesh terrain. UNITY when the area is very big and AI characters are required to walk a larger distance, it would be beneficial to have the large navmesh ready for finding a path. when we change the height of the terrain in runtime small areas of the terrain should be updated. so the buildnavmesh method is kind of an overkill. and the localnavmesh builder as a large type would be inefficient. how do we dynamically change a small part of a larger navmesh? advice or help would be highly appreciated.


Unity Animation Controller Is the "atomic" attribute in 4.6.3 the same as the "has exit time" attribute in 5.0? I'm viewing a tutorial based on Unity 5.0. In this version, I see an option whose name is Has Exit Time But on my Unity, version 4.6.3, I don't have this option. Instead I have an option called Atomic. My guess is that these options mean the same thing. That is, if this box is checked, then the controller should finish playing this state before moving to a new state. But I'm not sure here. If my guess is wrong, which option is equivalent to Has Exit Time in Unity 4.6.3 ? Thanks )


(Unity) Proper way to save ScriptableObjects changed during play mode? I was wondering what the "correct" way to save scriptable objects in Unity that are changed during Play mode. So far I have something that works changes PartyMember Lalala PartyMemberDictionary.Find("Lalala") Lalala.HP 17 print("Lalala's HP " Lalala.HP) then saves AssetDatabase.Refresh() EditorUtility.SetDirty(Lalala) AssetDatabase.SaveAssets() Note Lalala is a direct reference to a PartyMember scriptable object in my Assets Resources folder. I'm still a little shaky on this approach, however. I got this directly from reading this question https forum.unity3d.com threads scriptableobject asset problem the changes wont saved to disk.229664 But the commentator did not explain what each of these three lines of code mean. AssetDatabase.Refresh() EditorUtility.SetDirty(Lalala) AssetDatabase.SaveAssets() Can someone explain these to me? I'm not sure I understand them fully. I assume "dirty" indicates that data changed please correct me if I'm wrong. In this link https docs.unity3d.com ScriptReference AssetDatabase.SaveAssets.html it asserts that SaveAssets() saves all unchanged asset changes to disk, so why do I need the other Refresh and SetDirty Functions? In this link http answers.unity3d.com questions 11531 why doesnt my scriptableobject save using a custom.html The OP says "as I found out after some trial and error AssetDatabase.SaveAssets doesn't actually save the asset as expected." ... so confused at this point. That leaves me hesitant to continue until I understand what's going on. Perhaps the Refresh and SetDirty cement the job? Also, in this link https docs.unity3d.com ScriptReference EditorUtility.SetDirty.html it mentioned that Undo.RecordObject is preferred. Based on your experiences, is this true? Is EditorUtility.SetDirty() obsolete in this day and age already? I don't want to use it if I have to change my code in the future. At the end of the day I simply want something that works.


Unity UI Animation Transition So I'm fine with gameplay coding, but menus are something I'm still very new to. I was watching Unity's own video on how to deal with Buttons and I thought I'd try mock up my own button animation much like they had. It works wonderfully, there's just one minor issue. So a Button can go from 'any state', so either pressed, highlighted or normal (or disabled but I'm not using that). When I hover it works but it'll go straight back to normal once it's 'time' 'cycle' has completed. I figured that to fix this, I ought to add a transition between Highlighted and Normal. This does work, providing I say that 'Normal' must be true before transitioning between the 2. Here's my issue however when I click, the button hits pressed fine, then goes back to highlighted, and won't go back to normal unless I just click the background anything that isn't the Button. How can I get it to go straight to normal once the mouse is no longer on the button? I thought maybe a trigger collider with OnExitTrigger type function but that seems messy, isn't there a way to do this IN animator?


Simulate wind in a powder game I would like to create a game similar to powder game. I've got a 2d array that stores different types of powder such as sand, water, gas, and fire. I've managed to get these to all move around successfully. I would now like the powders to react to wind. For example if there is fire it should push air upwards. If the air is moving upwards it will move other bits of powder around. The way I've been trying is to have two more 2d byte arrays. One for the wind x direction and another for the wind y direction. The fire will then add an amount to the cells and each update will add the wind x and y to the piece of powder that is on that cell. This almost works but pushes the powder much to fast. The difficulty in doing this is that the powder is on a grid while the wind could be going a variety of directions. What is the most efficient way of doing this?


How to detect mouse over for UI image in Unity 5? I have an image that I have setup to move around and zoom in and out from. The trouble is the zoom can be done from anywhere in the scene, but I only want it to zoom when the mouse is hovering over the image. I have tried to use OnMouseEnter, OnMouseOver, event triggers, all three of those without a collider, with a collider, with a trigger collider, and all of that on the image itself and on an empty game object. However none of those have worked...So I am absolutely stumped...Could someone help me out here! Here is my script private float zoom public float zoomSpeed public Image map public float zoomMin public float zoomMax void Update () zoom (Input.GetAxis("Mouse ScrollWheel") Time.deltaTime zoomSpeed) map.transform.localScale new Vector3(map.transform.localScale.x zoom, map.transform.localScale.y zoom, 0) Vector3 scale map.transform.localScale scale new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0) map.transform.localScale scale


A Pathfinding lose target after spawning from script? I have been using A Path finding to enable object tracking. It works fine if I have both objects on the scene at the same time. However, if I were to use a script to spawn the seeking object instead, it will only track the first path to the object and not repath again. I am using the default AI Follow script and a prefab variable as the object to be tracked (which is an empty child game object to a moving character). Code import Pathfinding var tankTurret Transform var tankBody Transform var tankCompass Transform var turnSpeed float 10.0 var targetPosition Vector3 var seeker Seeker var controller CharacterController var path Path var speed float 100 var nextWaypointDistance float 3.0 private var currentWaypoint int 0 function Start() targetPosition GameObject.FindWithTag("GTO").transform.position GetNewPath() function GetNewPath() Debug.Log("GETTING NEW PATH!") seeker.StartPath(transform.position,targetPosition,OnPathComplete) function OnPathComplete(newPath Path) if(!GetNewPath.error) path newPath currentWaypoint 0 function FixedUpdate() if(path null) return Debug.Log("NO PATH!?") if(currentWaypoint gt path.vectorPath.Length) return var dir Vector3 (path.vectorPath currentWaypoint transform.position).normalized controller.SimpleMove(dir) tankCompass.LookAt(path.vectorPath currentWaypoint ) tankBody.rotation Quaternion.Lerp(tankBody.rotation, tankCompass.rotation, Time.deltaTime turnSpeed) if(Vector3.Distance (transform.position,path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint Any help will be greatly appreciated.


Comparing performance I wanted to create a portal. This portal looks like a semi transparent texture rotating on a cylinder At first I created such a portal using a Particle System. Then I realized that this might be an overkill and built another portal the following way I put a cylinder in the scene, put the texture on it and added a script that would rotate the cylinder. The visual result of the 2 approaches (Particle System vs. Mesh approach) is perfectly the same. Now I wanted to test which one performs better. Am I right to assume that I should write a script which creates 10.000 portals of type A or B in the scene and have a look at some statistics (not sure yet which where to find them), or is there anything more convinient to test performance? Thank you!


Unity animation skips first loop I have my player's animation controller managing two simple states idle walk. States are switched via bools and everything works fine aside from the fact that the idle state doesn't render the first run of the animation loop. To make it more clear when I start the game, in the animator I see the idle animation properly starting immediately (the azure bar loads immediately) but the player gets actually animated only after the first run of the animation, and the same goes when exiting the walk animation back to idle. This is the animation structure, that very first idle cycle run in the controller but the player actually stands still... Here's the function that move the player and set relative bools for animation switching public void MovePlayer(float horizontalInput) bool onEdge playerTransform.position.x lt 2.5f playerTransform.position.x gt 2.5f float animSpeed Mathf.Clamp(Mathf.Abs(horizontalInput) 1f, 0.5f, 1f) anim.SetFloat("movingSpeed", animSpeed) if(horizontalInput lt 0.2f amp amp !onEdge) anim.SetBool("movingL", true) else if (horizontalInput gt 0.2f amp amp !onEdge) anim.SetBool("movingR", true) else anim.SetBool("movingL", false) anim.SetBool("movingR", false) nextPosX Mathf.Clamp(playerTransform.position.x (horizontalInput playerSpeed Time.deltaTime), 2.5f, 2.5f) playerTransform.position new Vector2(nextPosX, 0) The movingL R bools are set true when the horizontal input pass a certain threshold and are set to false (back to idle) under that threshold. Hope this is clear enough...


Can I set offset size in scene window in Unity? When I add component like RigidBody2D or BoxCollider, Can I set offset size in scene window in Unity? Other than manually set value in inspector form, then look in scene window whether it is fit or not?


How to keep two objects in the same zone when they collide? I made a zone out of a cylinder with zero height. When one sphere moves to that zone it is fine but if another one moves to the same zone it only shows one sphere. I tried to add a rigid body for each sphere but they collide inside the cylinder and both fly. I want both of them to collide but stay inside the cylinder zone with a distance between them like 2 units.


Unity How to keep sprites sharp and crisp, even while rotating How can I maintain crisp, sharp edges on sprites, while avoiding the aliasing caused by rotation? None of the things I've tried produce a pixel perfect non rotated block, while allowing rotation without aliasing Click here for the sample project, which also has some extra images in it. Click here for my Unity Forums Thread Ideally, this is what it would look like From Photoshop, not Unity. Flawless edges, smooth corners, and very faint aliasing when rotated. Screenshot from Github project Row 1 Non rotated Perfect edges, pixelated corners Rotated Pixelated everywhere Row 2 Non rotated Perfect edges, smooth corners. Rotated Pixelated edges, smooth corners Row 3 Non rotated Blurry everywhere. Rotated Blurry everywhere Row 4 Non rotated Not quite perfect edges, pixelated corners Rotated Blurry everywhere Row 5 (MY BEST SOLUTION SO FAR) Non rotated Semi blurry everywhere. Rotated Semi blurry everywhere Texture for "no border padding" texture Texture for "with padding" texture Shader Method (Note I'm a total shader newbie) I created a fragment shader to draw the block. It has AA (via smoothstep) built in, and throttles it on as block is rotated (so that there is no AA when it's not rotated) This has some problems A (geometry) shader doesn't seem like the correct solution for this problem at all, since I'd have to make a shader for all the geometry that has this problem. But maybe there is a shader that can apply AA to a texture, that doesn't do anything for vertical or horizontal (non rotated) edges? Corners of block with AA turned off are pixelated This doesn't seem too difficult to fix I'd probably want it to work identically to row 2 (non rotated) Not sure how much AA to apply (when rotated) so that it's as sharp as possible for a given screen DPI. I thought this is what mip maps were good for, since the highest possible res texture should be chosen. (Another reason why a texture based solution seems best) Other things I've tried Vector graphics (per Unity's vector package) Unity's vector package required 4x MSAA to look right, which was too intensive for mobile devices MSAA Creates blurry graphics (is there a way around this?)


Why even use coroutines in Unity? I have been thinking about the use of Unity's coroutines recently, and while I've used them in the past, and am already aware of their bad reputation (although I've also seen posts on the unity forums of people who seem to absolutely swear by them), the more I think about it, I'm kind of struggling to see any compelling reasons to use them at all instead of simply creating a new component and simply performing the logic of the coroutine in said new component's Update method. By using a IEnumerator coroutine inside of another component, it seems to me like all it accomplishes is decreasing the cohesiveness of individual components and the re usability of the component using them. Is there any convincing argument to actually use coroutines in Unity and would I be missing out by simply not using them? Are there any scenarios I'm overlooking where their use would either be required or prove incredibly useful?


Unity UI subpixel rendering antialiasing with Image.fillAmount? I'm using DoTween to tween the fillAmount of a UI Image. When I check the value, it changes smoothly, and in the scene view it appears to transition smooth. However it appears jerky in the game view, and seems to step for each pixel, so it seems resolution dependent. Is there any way to have the UI render subpixels (?) or antialiased so it uses colors between green white to have it appear to move more smoothly? Thanks!


Rifle bullets projectiles in Unity, raycasting or rigidbody? Hello again gamedevers ) I'm trying to create a fairly simple FPS shooter game. Im using a Rigidbody FPS Controller prefab from Unity. I have a rifle model attached to that, with a further gameobject for the bullet spawn location on the rifle. I can see in the Editor, that the bulletSpawn object already knows which way it's supposed to be facing (ie. Z axis is pointing correct direction). I've never really used Raycasts before except mobile games to select an object on screen, but my head is telling me that this might be the best way to make realistic bullets. I've been reading about, particularly this http answers.unity3d.com questions 22800 raycast shooting.html It suggests to use Raycasts and I understand how to call a ray from the bulletSpawn and set it's direction, and to see what it hits. But what I don't understand is how fast the ray will travel, and how to limit the speed of said ray. I'm not sure if this is a good way to acheive the gunfire or whether it might be better to create Rigidbodies and addforce() to them. You guys are always so helpful and often make things MUCH easier to understand that travelling through dozens of old posts and the docs which I cant always follow along with. How to achieve this effect?


Load Unity game launch options from file I have a need to disable the resolution dialogue when the game launches, but have a config file that will have all of the dialogue options (resolution, quality, monitor (monitor is most important, because none of the solutions to change the active monitor after launch have worked out with a decent result)). Is there a way for a unity game to load options from a file instead of the resolution dialogue?


LeanTween How to check if gameObject is destroyed? I am trying to animate a gameObject using LeanTween which has got destroyed already. The MissingReferenceException occurs in LeanTween.setOnUpdate() The null check doesn't work either (gameObject ! null) I have used LeanTween.cancel(gameObject,false) but it still throws an exception.


Is WWW reliable for downloading a large AssetBundle? I have a very large AssetBundle. More than 200MB. Is WWW reasonable for downloading it from my server? I heard that you can't tell the timeout it has. I intend to use it for iOS and Android. Since clearly the download will last more than 5 minutes for a lot of people, is it reliable or will it time out? Should I instead make my own application in my server to transfer the bundle's bytes using sockets?


Unity3D Retry Menu (Scene Management) I'm making a simple 2D game for Android using the Unity3D game engine. I created all the levels and everything but I'm stuck at making the game over retry menu. So far I've been using new scenes as a game over menu. I used this simple script pragma strict var level Application.LoadLevel function OnCollisionEnter(Collision Collision) if(Collision.collider.tag "Player") Application.LoadLevel("GameOver") And this as a 'menu' pragma strict var myGUISkin GUISkin var btnTexture Texture function OnGUI() GUI.skin myGUISkin if (GUI.Button(Rect(Screen.width 2 60,Screen.height 2 30,100,40),"Retry")) Application.LoadLevel("Easy1") if (GUI.Button(Rect(Screen.width 2 90,Screen.height 2 100,170,40),"Main Menu")) Application.LoadLevel("MainMenu") The problem stands at the part where I have to create over 200 game over scenes, obstacles (the objects that kill the player) and recreate the same script over 200 times for each level. Is there any other way to make this faster and less painful?


Should I combine multiple tiles of terrain as one mesh in Unity3D? I have a tiled terrain, generated by multiple noise algorithms. Currently, each tile is it's own GameObject, that has a handler for an OnMouseOver event. The area that is loaded at a time consists of 9 chunks that each contain 4096 tiles. This totals to 36864 tiles that are loaded at a time. On top of this, there are actual objects on top of these tiles. Is there any considerable performance difference if I were to combine some of these tiles into a single GameObject and mesh?


Prevent navmesh blocking I'm writing a tower defense game in Unity, inspired by Desktop Tower Defense. Creeps spawn on one side of the screen, and if they make it to the opposite side, the player takes damage. The board starts out unobstructed, and the player builds towers that shoot at creeps while also blocking their path. They can funnel creeps along a path by strategic placement of towers. I have a terrain GameObject with a NavMesh, each creep has a NavMeshAgent, and each tower has a NavMeshObstacle. This works fine, the creeps go toward the goal and avoid the towers. The problem is that the player is not allowed to block off all of the paths to the goal. If placing a tower would leave no routes open to the goal, it is not valid to place a tower there. I can detect this after the tower is placed, but I want to warn the player and prevent the placement from happening at all. I also don't want to even briefly block the path to the goal by temporarily placing a NavMeshObstacle in an invalid position, because it might be exploitable by players by repeatedly attempting to place a tower there. How can I predict whether placing a NavMeshObstacle will completely block a route between two paths, while NavMeshAgents are actively traversing the NavMesh?


How to assign separate controller axes to Player1, Player2? I need to have two players moving in a level for a school project and my player controller is already set up for using axis inputs (as opposed to discreet buttons) for directional input. I already know I can assign custom key inputs from the inspector if I just declare a public variable (initialization optional because there is a drop down list in the inspector) public KeyCode jumpInput KeyCode.Space How can I assign custom directional axis inputs from the inspector? I already have alternative horizontal and vertical axes defined in my preferences, I just need to know how to assign them. Been putting this project together for 36 CONTIGUOUS hours and I am ready to put it (and myself) to bed. Thank you in advance for your time. EDIT My confusion was coming from (beyond being awake too long) thinking that I needed a special data type (like KeyCode) for an Axis, and couldn't find it in the reference. But I didn't consider making a public string and plugging that into the input. This way, I just need to know what I named the new axes and use that for the public string.


objects disappear before time I created a little pool in order to better manage my enemies, to which, an enemySpawner object calls to retrieve a clone and show it on screen public class ObjectPool MonoBehaviour public static ObjectPool current public GameObject objectForPool public int poolAmmount 20 public bool growth true List lt GameObject gt objectsForPool void Awake() current this Use this for initialization void Start () objectsForPool new List lt GameObject gt () for (int i 0 i lt poolAmmount i ) GameObject obj Instantiate(objectForPool) obj.SetActive(false) objectsForPool.Add(obj) public GameObject GetPooledObject() for (int i 0 i lt objectsForPool.Count i ) if (!objectsForPool i .activeInHierarchy) return objectsForPool i if (growth) GameObject obj Instantiate(objectForPool) objectsForPool.Add(obj) return obj return null Update is called once per frame void Update () The call(EnemySpawner update) void Update () transform.position new Vector3(transform.position.x (speed Time.deltaTime), 0, transform.position.z) if (transform.position.x lt boundary.xMin transform.position.x gt boundary.xMax) speed 1 if (Time.time gt nextSpawn) nextSpawn Time.time spawnRate GameObject clone GetComponent lt ObjectPool gt ().GetPooledObject() if (clone null clone.activeInHierarchy) return clone.GetComponent lt EnemyMovement gt ().SetPlayerShip(playerShip) clone.transform.position transform.position clone.transform.rotation transform.rotation clone.GetComponent lt Health gt ().RestoreHealth() clone.SetActive(true) The problem here is, that my enemies are being deactivated on mid trajectory https youtu.be ZGHC6wwGX1E I know my issue is in my pooling, but I can't figure out what I'm doing wrong


Missing shadow why? In these scene, i can't figure why, my player, and object it place, can't cast shadow on floor. All other static objects in scene cast shodow correctly. There is a floor with it's material, then there is also a Reflection probe. Is Reflection Probe something that influence shadow cast correctly ? Follow, floor proprieties Floor material proprieties My Lights My scene


How should I texture objects in Blender to use in Unity? I need to model some things to use in Unity. How should I texture objects (road, tree, etc.) in Blender? I almost lost all textures when I exported and loaded them into Unity.


Unable to Merge Android manifest error is showing up I used Google Admob to put ads in my game but as soon as I hit build and run this error showed up I used a Github file and imported into my unity project, I will link it right here https github.com unity plugins Unity Admob. CommandInvokationFailure Unable to merge android manifests. See the Console for more details. C Program Files (x86) Java jdk1.8.0 101 bin java.exe Xmx1024M Dcom.android.sdkmanager.toolsdir "C Users jayso AppData Local Android android sdk tools" Dfile.encoding UTF8 jar "C Program Files Unity Editor Data PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Error Temp StagingArea AndroidManifest main.xml 21, C Users jayso OneDrive Documents Tap Happy Temp StagingArea android libraries play services ads 10.2.0 AndroidManifest.xml 2 Main manifest has but library uses minSdkVersion '14' Error Temp StagingArea AndroidManifest main.xml 21, C Users jayso OneDrive Documents Tap Happy Temp StagingArea android libraries play services ads lite 10.2.0 AndroidManifest.xml 7 Main manifest has but library uses minSdkVersion '14' Error Temp StagingArea AndroidManifest main.xml 21, C Users jayso OneDrive Documents Tap Happy Temp StagingArea android libraries play services base 10.2.0 AndroidManifest.xml 2 Main manifest has but library uses minSdkVersion '14' Error Temp StagingArea AndroidManifest main.xml 21, C Users jayso OneDrive Documents Tap Happy Temp StagingArea android libraries play services basement 10.2.0 AndroidManifest.xml 2 Main manifest has but library uses minSdkVersion '14' Error Temp StagingArea AndroidManifest main.xml 21, C Users jayso OneDrive Documents Tap Happy Temp StagingArea android libraries play services gass 10.2.0 AndroidManifest.xml 2 Main manifest has but library uses minSdkVersion '14' Error Temp StagingArea AndroidManifest main.xml 21, C Users jayso OneDrive Documents Tap Happy Temp StagingArea android libraries play services tasks 10.2.0 AndroidManifest.xml 2 Main manifest has but library uses minSdkVersion '14' stdout exit code 1 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.BuildPlayerWindow BuildPlayerAndRun()


Visual Studio Code Unity AutoComplete still not working I am having an issue with Visual Studio Code AutoComplete for Unity. Some of the autocomplete is working, such as void Start(), void Update(), but most of the rest of Unity Autocomplete is not working such as GameObject, Rigidbody, Input.GetKey, etc..) I know VScode and Unity are not connected like how Unity and Visual Studio are, but it seems that a lot of people make it work somehow, so I thought it is possible to make it work without much trouble. I have the extensions needed to make it work (C , Unity Tools, Unity Snippets Code etc...) I have set vscode as my script editor (Unity Edit Preferences External Tools) I installed .NET Core SDK and .NET Framework 4.6 Targeting Pack I tried uninstalling Unity and vscode but that didn't work either... How can I solve this?


Unity Animator not properly following animation transitions I have an Animator that has 3 different states. Walking, Climbing, and End of Climb. The diagram is shown below I have 2 bools, isClimbing and isWalking. When isClimbing is set to false it transitions to End of Climb. Then when I set isWalking to true, it transitions to Walking. However, when I do this, for some reason the animator starts back at Climbing then moves to End of Climb then moves to Walking. It seems everytime I change a parameter, it completely restarts the state machine back to the default Climbing state and then moves forward. I do not have code, and have been triggering this through the UI. What am I doing wrong?


Automated Unity iOS command line build on Mac I am doing the iOS builds for a group of Unity (Unity3d) game developers. After pulling the latest git updates, I start up the Unity editor on my Mac and choose "Build Settings", select the iOS target platform, press Build, specify a destination folder and that is it. Can this exact process be done automatically via the terminal prompt?


Random range of items? I want to add random function into this script. If boxDestroyed is true, three items pop up. What i need is to give random number of items between 0 to 3. public GameObject items new GameObject 3 public bool boxDestroyed false void LateUpdate () if (boxDestroyed true) Vector3 position transform.position foreach (GameObject item in items) if (item ! null) int amont Random.Range(0,3) Instantiate(item, position, Quaternion.identity) Destroy(gameObject)


How do I procedurally animate a cell eating another cell? The entities in my game are soft body, amorphous cells. I'd like to create an animation where enemies are engulfed by the player's cell. That is, I want to generate a "cell eating another cell" effect. See this video for the type of motion I want https www.youtube.com watch?v iO vOFFf1uQ I'm considering using fluid dynamics to achieve this, but I'm lost as to where to start. I'm working in Unity2D, and Fluvio doesn't seem to provide what I need. Does anyone have advice on the best way for me to proceed?


Is Unity 2017 random number generator deterministic across platforms given the same initial seed? Is unity engines random number generator deterministic across platforms given the same initial seed or should I implement my own? I know there have been some modifications to the random number generator recently. Answers are appreciated, I don't have the devices on hand to perform any tests and I haven't yet found a direct statement on the matter.


Unity3D Mathf Lerp too fast when timescale increases I have an image with a fill amount component controlled by a Mathf Lerp. The problem is, the time for completion of the Mathf Lerp function decreases more than expected when the timescale increases. When the timescale is equal to 2 the function should take half the time to complete but it takes less than that. Any idea why? public static float demolishTime 6.0f public void OnClickDemolish() InvokeRepeating("demolishProgress", 0f, 0.1f) void demolishProgress() progress (Time.deltaTime demolishTime) demolishProgressBar DemolishManager.demolishState .fillAmount (float)Mathf.Lerp(0, 1, progress) if (progress gt 1) demolishCompleted()


How do I gain access to objects in order to change their properties in Unity? I have created a GUI text object named "GUIText" in the Unity editor, and I want to change what the text says via code (I'm using C ). How do I access GUIText1 to change its string properties? I want to be able to write code like this GUIText1.Text "" In general, I'm not sure how to get access to any sort of object created in the editor (a mesh or a light for example). How do you access them in code? I already know how to write the scripts and trigger them.


How to set keys for emission on off for a prefab? I am making a prototype for a Mario game and am having difficulty completing a canned animation for a prefab. There is an item box asset that has 3 materials and an "ItemGet" animation. One of these materials has an active emission property that is supposed to turn off during a specific frame of the "ItemGet" animation. These boxes will have an "Active" and "Inactive" state. While "Active", the item box just bobs up and down and IF Mario hits the trigger, the "ItemGet" animation plays (and the player gets a unique item). The box then becomes "Inactive". While "Inactive", no animations play, the emission effect is gone and the trigger cannot be reactivated. Challenges finding the correct property to set a keyframe for in the Animations panel. Making sure Active versions of the prefab remain Active after any ItemBox becomes Inactive and that all materials don't change when GetItem plays. Ideas Instead of keying the emission on off property (assuming that exists and does what I think it does trouble finding it), swap the materials. ( . . . ), swap the mesh. Can somebody please help me find a viable way to finish this animation that fits this object's intended use case?


Unity Rendering Pass Before Refraction not showing In the documentation it states Before Refraction Draws the GameObject before the refraction pass. This means that HDRP includes this Material when it processes refraction. To expose this option, select Transparent from the Surface Type drop down. I have selected the Transparent option for surface type but the Before refraction rendering pass is not in the drop down list for rendering pass. How can I get it to be there? Are there some other option that might be disabling it?


Can't change materials of model from FBX I was used 5.x before, and that version when I loaded FBX, Unity generated each material automatically, so I can change them like assigning textures or change shader. And now I switched to 2017.3, and when I imported FBX, now Unity didn't generate materials anymore. I can see the properties of each material but every parameter is locked. It seems materials are inside of model and can't change like animation clips. Some of model has multiple materials, so I can't generate manually and assign them. I'm creating mobile game so I really need to change the shader to mobile shader, not standard(PBR). How to change materials of model from FBX in Unity 2017.3? Note that model created from Blender 2.7c and exported as FBX.


How to store XMLs in Unity for web player deployment? I've created with Unity a short demo that works as a standalone .exe on Windows, and I was interested in deploying it as a web player game too. When I run the game on the web player, though, I get this error in the Unity console StreamingAssets is not available on this platform. I have some XMLs I parse at runtime in the StreamingAssets folder. Where can I put them in a web player build so to be able at runtime to load them? Thanks for your answers.


First Person Mouse Aiming For one segment of my game, the player is in a fixed position (no movement) and has to aim and shoot at enemies in a first person 3D perspective using the Mouse. The player is holding a wand that shoots projectiles (which I have working) and I need it to rotate and aim towards the cursor as an aiming reticle. I also want to limit how much the player can rotate, so they can look around, but can't turn more than 180 degrees (sort of like this). However, I'm a designer and am having trouble programming this myself. I haven't been able to find a proper solution. So far, I've been able to cobble the following code together, but the aiming is super wonky and doesn't properly point to the mouse position, making it impossible to actually aim at anything. I would really appreciate some help with figuring this out. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerShoot MonoBehaviour public float magnifier 0.5f public Rigidbody shotPrefab public Transform barrelEnd public float shotSpeed 500 public Rigidbody sparkPrefab Update is called once per frame void Update () Ray mouseRay Camera.main.ScreenPointToRay (Input.mousePosition) float midPoint (transform.position Camera.main.transform.position).magnitude magnifier transform.LookAt (mouseRay.origin mouseRay.direction midPoint magnifier) if (Input.GetButtonDown("Fire1")) Rigidbody shotInstance shotInstance Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody shotInstance.AddForce(barrelEnd.forward shotSpeed) sparkBlast() Particle recoil effect void sparkBlast () Rigidbody shotSparks shotSparks Instantiate(sparkPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody Destroy (shotSparks,0.5f)


How do I get access to the PS4 platform tools for Unity? I know that you can go to the "Xbox ID" program to get all the resources you need for the Xbox platform (developer forums, Unity SDK, etc.). but there is not really information about how to get the PlayStation tools. ...Well other than the contact sales button in Unity which links to Unity and not Sony (oddly enough). So where does someone who hopes to put their games onto one of the Sony platforms (PS4, Vita, PS3, etc) go to get the build tools (and other things) they need? Do Sony contact you about it if they're interested or is it really only for developers who are considered above Indy?


Elongated and straight terrain perlin noise Why am I getting this kind of results with my perlin noise ? The terrain is wide or elongated or straight at the variations of the noise function. This is the way I generate terrain public void GenTerrain() for (int x 0 x lt this.size.x x ) for (int y 0 y lt this.size.y y ) float xCoord (float)(x offsetMirror origin.x) this.size.x scale float yCoord (float)(y offsetMirror origin.y) this.size.y scale float noise Mathf.PerlinNoise(xCoord, yCoord) if (noise gt 0.6f) this x, y .terrainType TerrainType.Grass else if(noise gt 0.5f) this x, y .terrainType TerrainType.Sand This is the way I add chunks of terrain void Start() maps new Dictionary lt Vector2Int, Map gt () Res.LoadMaterials() void AddNeighbours(Vector2Int position) int length 32 for(int x length x lt length x ) for(int y length y lt length y ) Vector2Int addPos new Vector2Int((x size) position.x, (y size) position.y) CheckAndAddMap(addPos) void CheckAndAddMap(Vector2Int addPos) if (!maps.ContainsKey(addPos)) AddMap(addPos) void AddMap(Vector2Int origin) Map map new Map(new Vector2Int(size, size), origin) maps.Add(origin, map) MapMesh mapMesh new MapMesh(map) foreach (KeyValuePair lt TerrainType, MeshData gt kv in mapMesh.meshes) MeshData meshData kv.Value TerrainType terrainType kv.Key GameObject go new GameObject( quot Mesh quot ) go.transform.SetParent(this.transform) go.transform.localPosition new Vector3(mapMesh.map.origin.x, mapMesh.map.origin.y, (int)kv.Key) MeshFilter meshFilter go.AddComponent lt MeshFilter gt () meshFilter.mesh meshData.mesh MeshRenderer mr go.AddComponent lt MeshRenderer gt () mr.material Res.mats terrainType.ToString() Update is called once per frame void Update() Vector2Int playerPosition ConvertPlayerPositionToTiles(ShootBehaviour.PlayerInstance.transform.position) AddNeighbours(playerPosition size) private Vector2Int ConvertPlayerPositionToTiles(Vector3 position) Vector2Int result new Vector2Int() result.x (int)position.x size result.y (int)position.y size return result


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


Unity 3d auto move player forward script Trying to write a basic script to attach to the player on Unity 3D, I want them to move forward automatically. I'm guessing that will be part of the Update function and using transform, but that's about as far as I get. I'm assuming it's a Transform.translate function too, but not sure what parameters to use to move forward 1 m s automatically (for example). Also, how do I block W and S keys moving forwards and backwards, and instead use the for up and down? (My character is 'floating' and I'm looking to incorporate space harrier style controls) Thank you!


Unity. Input in function for UI button OnClick I am trying to create multiple selections for some items on my UI. To perform multiple selections of items I want a user to hold left control button. But then I add if (Input.GetKeyDown(KeyCode.LeftControl)) Logic It registers in debugger what LeftControl is pressed but it skips all logic in brackets. This function is public and created for UI button. Is Input and Button.OnClick compatible at all?


How to design prefabs in Entity Component Systems In Unity (and I presume other game engines) you can create "prefabs" which are blueprints for game objects. They contain a list of components, and default values for those components. Prefabs can be instantiated many times, which is an efficient way of creating many objects of the same kind. One feature in particular of prefabs is that you can modify an attribute on a single instance of a prefab, without modifying the prefab itself. Similarly, you can modify the prefab, which will propagate the change to all instances. I've been working on an implementation of the Entity Component System (for a high level description of ECS see this question How to implement n body in an Entity Component System), and I got stuck on how to implement prefabs efficiently in ECS. I think it's a powerful capability of EC design, and implementing this on native ECS would be awesome. I can come up with a few approaches Create archetypes, which are predefined lists of components (Unity approach). This does not let me set initial values for the components, nor override them (there is nothing to override). Easy to implement, but doesn't really do what I want it to do. Create a "prototype" entity from which other entities are cloned, including component values. With this design I can override individual attributes, but when I update the prototype, the clones don't get updated. Create entities with a reference to a "base" entity. When getting a component from an entity, first look in its component list, then try the base entity. This way when I update a base component, base instances change as well. To override a base component I can simply add it to the instance entity. Of these three approaches the third approach comes closest, but I don't see a straightforward way to extend it so I can override a single attribute. How can I make this work?


Photon disconnected without any error warning message I'm making online game with Photon and Unity. It was working fine, but suddenly players are disconnected without any warning or errors. It just happens sometimes fast, sometimes slow, but always happened. Before user disconnected, it seems it's little laggy and soon player disconnected. So I changed the log level to all, and saw this message was printed right before player disconnected. DisconnectByServerLogic current State Joined What is meaning of this? I changed Photon App to new one, but didn't worked. I spent hours to figure out why this is happening, but no progress. There is only one part that disconnects player, it's event function that invokes user pressed exit game, but it never called and there is no more function that disconnects. If this causes from my code, I can fix it, but there is no code for disconnect and also there is no information why user keep disconnected. Only information that I found was just above message but I don't know what that means. Is that mean Photon forcely disconnects player? I'm stuck here in almost day but I couldn't find any problem in my code. I'm using Free photon plan, and result of analysis 4 CCU 1 Rooms Max(I don't know what this means) 15,558 Msg s per Room Max 895.0 MB Bandwidth 0 Rejected Players If someone who knows this problem, it will be very appreciate it gimme some advice. Thanks.


Character Controller Lag Massive Teleportation Through Walls I'm working on a fairly robust game with another developer and we've been having a really serious issue with (I believe) the character controller. Specifically, if there's ever a large lag spike (as there are somewhat frequently the code's not well optimized in some parts) there's a chance that the character controller will wing right through all nearby colliders and fall out of bounds. It happens pseudo randomly, but I've noticed that it seems to be somewhat predictable, such as standing next to certain objects (nothing weird about them just tables with colliders). The lag often is a cause of large chunks of a level having SetActive(true) called on them in one frame or multiple objects being instantiated in one frame. These objects sometimes have colliders rigidbodies attached but don't seem to be in any direct contact to the character controller. I can very consistently make it happen by moving towards certain walls (again, very normal walls) and alt tabbing while my character is still moving also seems to cause the issue predictably, which is VERY strange. Has anyone ever experienced anything like this with the character controller? I'd give a code sample but honestly not even sure where from the codebase would be pertinent other than if (Time.deltaTime lt 0.15f) if (applyGravity amp amp noClip false) moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) Which seems awfully straightforward to me. Obviously moveDirection gets changed elsewhere in the function too but it's all similarly bland. I'm pretty experienced with this sorta' stuff and it doesn't ring wrong to me at all. Some other stuff. Checked that moveDirection isn't a huge number Tried eliminating Time.deltaTime from the equation Fairly sure colliders aren't ending up inside of the player while a lag spike happens (again, alt tabbing will do it too) Geometry surrounding the player is clean (box colliders, mesh colliders on well developed meshes) Nothing strange like rapidly setting any components on or off is happening to my knowledge. Anyone have any experience with this sort of issue?


Character Controller and Reverse Gravity So I have a Game object with Rigid Body, a Character controller and my Movement script. On a specific condition I am reversing gravity. The problem is that the velocity.Y when the gravity is reversed, keeps increasing to the infinity. If I try to reset it like in the first if statement (which works for normal gravity) the object keeps bouncing from the ground. Gravity scale is either 1 or 1 in order to reverse gravity and movement. This is the code void Update() isGrounded Physics.CheckSphere(groundCheck.position, 0.4f, whatIsGround) Move() void Move() Reseting States for new cycle , unless the object is falling if (( isGrounded amp amp velocity.y lt 0)) velocity.y 2f isRunning false isJumping false isFalling false else if (velocity.y lt 0 amp amp ! isGrounded) isFalling true Moving on X axis float x Input.GetAxis(KeyInputMove) if (x ! 0) isRunning true moveDirection gravityScale transform.right x controller.Move(moveDirection moveSpeed Time.deltaTime) Perfoming jump if (Input.GetButtonDown(KeyInputJump) amp amp isGrounded) velocity.y (float) Math.Sqrt(1 2f globalGravity) isJumping true velocity.y gravityScale globalGravity Time.deltaTime controller.Move(velocity Time.deltaTime) Updating animation states animator.SetBool( quot Grounded quot , isGrounded) This is the idle state animator.SetBool( quot Running quot , isRunning) animator.SetBool( quot Jumping quot , isJumping) animator.SetBool( quot Falling quot , isFalling) private void OnTriggerExit(Collider other) Reverse Gravity and Model Rotation if (other.gameObject.tag quot Portal quot ) transform.Rotate(0,0,gravityScale 180) gravityScale 1


SerializationException Type UnityEngine.MonoBehaviour in assembly UnityEngine,l is not marked as serializable I am trying to save persist some data between my scenes but I keep getting the error SerializationException Type UnityEngine.MonoBehaviour in assembly UnityEngine, Version 0.0.0.0, Culture neutral, PublicKeyToken null is not marked as serializable. Here is my script public static void SaveState() BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " EmpireGame", FileMode.OpenOrCreate) SaveClass sc new SaveClass() food Player.food.amount, wood Player.wood.amount, iron Player.iron.amount, stone Player.stone.amount, buildingList new List lt Building gt (), sc.buildingList playerBuilt Debug.Log("State Saved!") bf.Serialize(file, sc) file.Close() Serializable class SaveClass public int food, wood, iron, stone public List lt Building gt buildingList I've narrowed it down to public List buildingList being the offending code, but I don't know how else to save this list. I think the MonoBehaviour part of it is the "" as it inherits from MonoBehaviour. I've read Unity Docs Serialization Watched persistence saving and loading data Saving Data In Unity I've looked up so many Q amp A's over this but still can't figure it out.


Best way to connect multiplayer users with each other (matchmaking) on a low powered server? OK so I am using unity to make a multiplayer game, but I'm not sure how to connect players with each other over the internet. Unlike other questions, this isn't a general problem of working out how to do UPnp or using unity's matchmaking server. My issue is that my server that I would use is a simple low powered pc (running normal windows 10, no idea how to use windows server). I think it is powerful enough to match players with each other, but not to host more than one or two actual games. The other issue is that I have a residential internet connection with a dynamic ip that changes every few months. However the speed should be ok (150Mb s download, 20Mb s download). Also, I'm not planning to spend money on a monthly basis for a server (like unity's matchmaking service) as I plan to spend as little as possible (So far I've paid 12 to Microsoft for a dev account and I've received a 200 voucher from them so my current spending is 189!) So my question is should I use my server (would it work), are there any online services that are very cheap to use, or is there another way to make this work? Only other thing is I could use the free 20 users at once on unity's matchmaking, but would this limit be too small? EDIT just for information, my game is a simple tank shooter. I was thinking about limiting the amount of tanks in a game somewhere around 8 20. The bullets in my game are physical objects with rigidbodys and they move at a slower speed (if you've ever played tank trouble, it looks like that). The world is in 3D. There is a potential for there to be up to a hundred bullets in a scene at once at the worst. After hosting a LAN world with 7 players connected for about 20 30 minutes, windows reports the data usage being around 3 4MB.


Gizmos not being drawn until GameObject selected I have implemented Scene loading in my game and have three scenes Persistent, Main Menu and Game By default, the player is loaded into the Persistent scene, which immediately loads the Main Menu, and when the player clicks on Play, Main Menu is unloaded and Game is loaded. Now, the two active scenes are Persistent and Game. However, I have a script with OnDrawGizmos on a GameObject in the Game scene. It seems that by default gizmos only begin to be drawn when I click on that GameObject, sort of activating it, and everything works fine. This used to just work before because Game was my only scene and Unity automatically selected that first GameObject. Now, with multiple scenes, no GameObject is selected by default and my gizmos won't draw until I manually click on it. How can I solve this?


Unity Blender's Armature messes up Faces The Model itself is fine when imported but when I activate the Animation all Normals and lighting get Inverted from the Bones. Result Import Settings Import Settings Blender Armature Settings Blender Export Settings


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


Finding Endpoint of line in Unity I have a startpoint, magnitude(length) and direction and want to find endpoint to construct the line here is the code to make question more clear private Vector2 GetEndPoint(Vector2 startPoint, Vector2 direction, float magnitude) Vector2 endPoint some stfuff with parameters return endPoint And this is the visualization of what I want Hope I am clear enough, any suggestions is welcomed


Unity blue sprite always showing on top regardless of order I have 3 SpriteRenderer SpriteRenderer Green Sprite SpriteRenderer Blue Sprite SpriteRenderer Brown Sprite The problem is that the blue sprite always shows on top of the others. I even tried to keep the SpriteRenderer in the same order and change the images but no matter which SpriteRenderer I put the blue image into it always shows on top. I have the sorting layer set to 0 for all 3 and I cannot change them because I will have to change so many other objects in the game.


Creating 3D gravity in zero G tied to mass in unity with c As a total beginner, I've been working on a patch job script for a gravity mechanic in an open space sim, I want to derive all my objects from this "Block ALPHA" object and its' set of variable attributes, so it's important that I get it right before moving on. The idea is simple enough, call an array of all interactive objects' coordinates and apply a basic equation to simulate gravitational pull. After some tinkering I have a piece of code that ticks all the boxes AFAIK, but I can't for the life of me figure out the syntax error I've made... I've been up all night massaging the script to fit my needs, but in the best cases it only raises one error "expected ' '" Maybe I'm just tired, maybe I broke the code, but trying to place parentheses only seems to bring more errors Here's the code as it is so far complete with the compiler error and suggested fix (in red), which does no good whatsoever using UnityEngine using System.Collections public class DynamicWeightAnalysis MonoBehaviour Strength of attraction from your game object, ideally this will be derived from a calculation involving the objects volume and density eventually public float RelativeWeight Here, we name our target objects GameObject blockALPHA Initialise code void Start () here, we define our target objects further by searching for the predefined tag blockALPHA GameObject.FindGameObjectsWithTag("Block ALPHA") Use FixedUpdate because we are controlling the orbit with physics void FixedUpdate () " EXPECTED" this is where we define the graverage coordinates Vector3 graverage (Vector3 blockALPHA) if (blockALPHA.Length 0) return Vector3.zero float x 0f float y 0f float z 0f foreach (Vector3 pos in blockALPHA) x pos.x y pos.y z pos.z return new Vector3(x blockALPHA.Length, y blockALPHA.Length, z blockALPHA.Length) Vector3 offset here we get the offset between the object and the average position of all objects offset graverage transform.position This is the variable for square magnitude calc float magsqr Offset Squared magsqr graverage.sqrMagnitude Check distance is more than 1 to prevent division by 0 (because my blocks are all 1x1x1, any closer and they'd be intersecting) if (magsqr gt 1f) Create the gravity make it realistic through division by the "magsqr" variable GetComponent lt Rigidbody gt ().AddForce((RelativeWeight graverage.normalized magsqr) GetComponent lt Rigidbody gt ().mass) I don't doubt that I've overlooked something stupid, but it's my first stab at proper coding, so, no shame in asking Thanks D


How to Make UI Open and Close on Keypress I've been working on a 2D RPG and have been trying to make a script that will open or close the public UI element that is selected in properties. I don't receive any errors, but I do receive a warning that says Assets Scripts KeyManager.cs(7,18) warning CS0414 The field 'KeyManager.activeUI' is assigned but its value is never used Here's the script that is connected to my canvas using UnityEngine using System.Collections using System.Collections.Generic public class KeyManager MonoBehaviour private bool activeUI public GameObject UI void Start() activeUI false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.I) amp amp (activeUI false)) activeUI true UI.SetActive(true) else if (Input.GetKeyDown(KeyCode.I) amp amp (activeUI true)) activeUI false UI.SetActive(false)


Unity material has shiny white outline I have two different projects open in Unity. But my grass material appears different in each project, despite all the parameters being the same. See this image On the left is the desired appearance. But on the right my material has a strange white ish outline. How do I get rid of it? I have tried copying the material between the projects, and the problem seems to be independent of the available lighting


How to await player input using Coroutines How can I accept player input using Coroutines, pausing execution of Unity while the player has not yet provided input? It seems like a simple problem, but I can't seem to figure it out. Here is my latest attempt. In this program I want to do some logic and pause in the middle, continuing only when the player has inputted some data. Someone please tell me I'm on the right track O using System using System.Collections using System.Collections.Generic using UnityEngine public class InputTester MonoBehaviour int choice 1 valid choices for this example are 0 and 1 void Start() StartCoroutine(DoSomeLogic()) IEnumerator DoSomeLogic() print("Starting...") print("Awaiting your choice 0 or 1. ") yield return StartCoroutine(WaitForKeyDown(KeyCode.Alpha0) WaitForKeyDown(KeyCode.Alpha1)) how to combine these two into a single method that gives the player a choice? print("Continuing...") switch (choice) logic based on the choice IEnumerator WaitForKeyDown(KeyCode k) while (!Input.GetKeyDown(k)) yield return null SetChoiceTo(k) private void SetChoiceTo(KeyCode keyCode) switch (keyCode) case (KeyCode.Alpha0) choice 0 break case (KeyCode.Alpha1) choice 1 break StopAllCoroutines() how do I stop all the coroutines that accept player input? print(choice)


How can I improve my touch slide mechanic to be more smooth and fluid? I have the following C code, but it leaves me with two problems void FixedUpdate() if (Input.touchCount 1) this.transform.Translate(Input.touches 0 .deltaPosition.x 0.009f, 0, 0) Firstly, the gameobject (which is a sphere in my case), has a tendency to leave the ground and fly into the air. Additionally, it is not as smooth and snappy but fluid as I would like it to be. If you look at some of the following gameplay videos, you will see the kind of movement I am looking for. "Splashy!" Gameplay "Sky Ball" Gameplay "Balls Race" Gameplay More specifically, from actually playing each of the above games, there is a certain "ratio" that seems to be operating in regards to each swipe gesture and the actual movement of the ball. That is, the ball does not go exactly where the finger goes, for it is slightly ahead, if that makes sense. What I mean is, the device is only so wide, yet for that width, the ball can always reach it's required destination on either end of the horizontal axis. This must mean that for every pixel the finger moves, the ball moves a little bit more to fit that pixel density of the screen. In other words, in the case of "Splashy!", it's clear that even if the finger moves the entire distance across the screen, the ball moves more than double that distance. By "smooth", "fluid", and "snappy", I mean that the swiping gesture is very responsive. It moves where you want it to and does not over or undershoot. Additionally, the "snappy" effect is present when you stop swiping. The ball seems to "snap" into it's end position. My question, then, is what is the best way to improve my script as to achieve the polished mechanic I am looking for, as is depicted in the above videos? Also, how can I keep the sphere on the ground without constraining any axes on the rigidbody? I am using Unity3D with C . I would appreciate any help you could provide. Thank you.


How can I rotate an object based on another's offset to it? I have a 3D model of a turret that con rotate around the Y axis. This turret has a cannon that is significantly off the center of the object. I want the cannon, not the turret, to aim at a specified target. I can only rotate the turret, however, and thus I don't know what equation I need to apply in order to accomplish by objective. The following image illustrates my problem If I have the turret "LookAt()" the target, a laser originating from the cannon will completely miss said target. If this were a completely top down scenario, and the cannon were exactly parallel to the turret, then my logic tells me that the fake target should be located at a position that's equal to the actual target plus an offset that's equal to that between the turret and the cannon. However, in my actual scenario, my camera is angled 60 , and the cannon has a slight rotation. The following image illustrates the scenario I'm not sure exactly why, but if I apply that same offset, it only seems to work while aiming at certain distances from the turret. Is my logic flawed? Am I missing something fundamental here? Final Edit the solution provided by JohnHamilton latest update solves this problem with perfect precision. I have now removed the code and images that I used to illustrate my incorrect implementations.


Unity Changing color of 2D sprite distorts sprite shape In my 2D game, my circle shape for example, appears round, but when I change the color then it turns into a low poly circle with 8 16 points, more like a potato. Is there any way around this? myColor new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, visibility) Color32 negativecolor new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, (byte)(255 visibility)) MaterialPropertyBlock props new MaterialPropertyBlock () props.SetColor (" Color", myColor) rend.SetPropertyBlock (props) props.SetColor (" Color", negativecolor) backchildrend.SetPropertyBlock (props)


How to manage input state in Unity3D? In Unity3D how do I manage input among many components, especially in relation to "blocking" input messages to certain components? To make my question clear, an example Component 1 Input Manager Manages a list of components that require input. They do this via a Register method, which adds the component to a List. Each registered component can poll input via this method public static bool GetKeyUpAndActive(KeyCode keyCode, MonoBehaviour entity) return Input.GetKeyUp(keyCode) amp amp List.Contains(entity) This feels clunky, as each entity needs to pass itself to the manager, and the manager has to keep a list of registered input events. Component 2 Script Manager Manages scripts such as "Open Dialogue Box, say "Hello", play SFX, add Item x to inventory. Script manager responds to input, for example, if over component, and Input.Action is pressed, run this script. Component 3 Dialogue Manager Manages the dialogue box, pretty stock standard stuff. It also responds to input, pressing Input.Action will cycle through the dialogue boxes, until it reaches the end, then returns back to the game. The main issue I am facing is that the script manager and the dialogue manager are responding to the Input.Action during their own updates. So Script 001 responds to Input.Action which triggers an open dialogue box, but because dialogue manager also responds, it has already cycled through to the next dialogue box. I think the Input Manager is breaking encapsulation. I also feel like I'm missing an obvious component here, maybe I need a stronger subscriber pattern to follow, or should there be a separate state manager, and if so, should the input manager only send events provide methods to components in the correct state, or should components check the state machine themselves?


How is actual object size in a scene calculated? I've got stuck with 'pixel per unit' parameters and object scale. I've created two different sprites. A background picture, 1000x1000 pixels, and another one for a 'player', 200x200 pixels. I've added two empty game objects, with default transform, so positions are (0 0 0) and scale is (1 1 1). I added a sprite renderer to both of them, and assigned the required sprites. Both sprites have 1 pixel per unit. And the 'player' in the scene looks much more bigger than the background. I expect that if ppu 1, then the background would have a size of 1000 units, a player 200 units and it would be 5 times smaller. What am I doing or understanding wrong? What is an actual object size?


Unity WheelCollider motorTorque acceleration with ps4 triggers I'm fairly new to Unity and i'm struggling to find some answers. Every car script and wheelCollider tutorial I can find is based in the horizontal and vertical axis and that works great. But I'd like to move the car while holding a trigger and brake the car while holding another trigger (ps4 controller. Inputs are already mapped and working), but I need some help on that. This is the part of the script that handles the acceleration float motor maxMotorTorque Input.GetAxis("Vertical") foreach (AxleInfo axleInfo in axleInfos) axleInfo.leftWheel.motorTorque motor axleInfo.rightWheel.motorTorque motor Is there anyone that can point me in the right direction or possibly provide some example scripts? Thanks in advance.


How does transvoxel algorithm work and how can I implement It? After wasting over three days of researching on DuckDuckGo Google, trying to understand transvoxel paper and existing implementation, I come here to clarify the subject for me and made it easier for the next person who wants to implement it. Here is the transvoxel's homepage which explains well what the algorithm solves. So now I'm happy to find something that solves my current problem, so I would like to implement it to my code, but the website doesn't explain how to implement it or sharing code (except tables). So I was looking for existing implementation of the transvoxel algorithm Transvoxel (XNA) Looks great but this solution all in one (octree, caching, voxel, etc.) I really tried to understand the transvoxel class into this one, but no. Transvoxel (OGRE3D) Looks great too but again, all in one. I tried too to understand, I translated the code from C to C , but no again. Finding for marching cube was so easy, one class copy amp paste, one public function. So I gave up the idea to use existing implementation. Why not implementing it myself? (Sadly I don't have the skill to fully understand what the paper said, for example the ambiguous case). The first thing I didn't understand was if transvoxel is a modified marching cube or a seconds layer that modify the work of the marching cube. In the C code (second link of the list) the code uses a implementation of marching cube and transvoxelize each border, on the paper they talk about 19x19x19 voxel data on 16x16x16 chunk and about a modified version of marching cube. So do you guys can explain me how the transvoxel algorithm works and how can I implement it on my existing project? My existing project is an Unity3D project which uses marching cubes for an infinite world, LOD chunk are ready, the only one thing missing is fixing crack between different LOD level chunk.


Unity 3D mirror, sync player spawn name I am using Mirror for doing my little multi player car racing project which I want to rename the game object automatically after the NetworkManager auto create the game object. Here is my NetworkManager code using System.Collections.Generic using UnityEngine using Mirror public class MyNetworkManager NetworkManager public List lt GameObject gt spawnPos public override void OnServerAddPlayer(NetworkConnection conn) Transform start spawnPos numPlayers .transform GameObject player Instantiate(playerPrefab, start.position, start.rotation) player.name quot car quot (numPlayers 1).ToString() NetworkServer.AddPlayerForConnection(conn, player) This NetworkManager works good in the Host PC. However, when the client connecting to the host, the name showing in the inspector on client PC is still like car(Clone). Does anyone know how to deal with this problem? Thank you for your help.


In Unity displaying long lists of information to screen? Tables? Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers) But I cannot seem to find a way to display all these infos in a table with columns such as Name Age Company etc I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also. Any ideas for this in Unity specifically? EDIT I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject. EDIT 2 D i've found this https docs.microsoft.com en us aspnet mvc overview older versions 1 models data displaying a table of database data cs would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)? Thanks for any help


simple 2d car AI unity I have a top down Car Game. how can I implement AI for the Cars? how the car follow the way points? I want AI cars also rotate itself along the path. I tried this solution using System.Collections using System.Collections.Generic using UnityEngine public class waypoint MonoBehaviour public List lt Transform gt waypoints private Transform currentWaypoint public float speed 5f private float closeEnouth 0.5f int point 0 void Start() currentWaypoint waypoints point Update is called once per frame void Update() Quaternion rotation Quaternion.LookRotation(waypoints point .position transform.position, transform.TransformDirection(Vector3.forward)) transform.rotation new Quaternion(0, 0, rotation.z, rotation.w) float dist Vector3.Distance(waypoints point .position, transform.position) transform.position Vector3.MoveTowards(transform.position, waypoints point .position, Time.deltaTime speed) if (Vector3.Distance(this.transform.position, waypoints point .position) lt closeEnouth) if (point 1 lt waypoints.Count) point and the car moved in the path but it moves reversed and if arrives the final node it stops and corrects its direction and console displays "Look rotation viewing vector is zero" error. Thanks in advance


Move objects in array with positions array I am trying to get a line of spheres to move around but all i get is the first sphere to move and get the rest to follow as one instead of building a sort of a train of spheres. Any idea how to alter the code to get it right? In the code bellow i get the first pbject in listBalls to move nicely along the Bezier curve but the rest move as one and overlap with the first sphere too. void Update() t Time.deltaTime 0.2f ballPosition Mathf.Pow(1 t, 3) p0 3 Mathf.Pow(1 t, 2) t p1 3 (1 t) Mathf.Pow(t, 2) p2 Mathf.Pow(t, 3) p3 positions.Add(ballPosition) listBalls 0 .transform.position positions j for (i 1 i lt listBalls.Count i ) Transform ball listBalls i .transform Transform nextBall listBalls i 1 .transform if ((ball.position nextBall.position).magnitude gt 1f) ball.position positions j j Feels like it should be something easy, setting the N 1 balls to same position as the first ball must be wrong. I tried setting them at positions j 2 but it didn't work either. Edit the Spheres should start rolling left to right one after the other eventually all 10 should be on the screen and when they reach P3 they should restarting the rolling. listBalls is the List with 10 spheres positions is the List with 50 Vector3 positions along the curve. ! enter code here 2 2


Rigidbody2D without pushing eachother on collision TLDR How to stop movement if two Rigidbodies collides? Also, here's a potato video of the problem https gfycat.com ComposedArcticBetafish Say I have three objects in a scene Player Enemy Rock The player and enemies is moving freely, but the rock is static. So I attached a Rigidbody2D on player and enemy to move them around with script. All of them has a Box Collider 2D. Now, if I (Player) move into an Enemy, I will start to push it (changing its position). I don't want this. I can set the Enemy's mass to something large, but then two enemies can still push eachother. I don't want this. If I try kinematic solutions I've found, but then they can move through the rock. I want Player can not move enemies Enemies can not move players Enemies can not move each other Nothing can move or go through the rock Enemies can not move through player Player can not move through enemies I keep reading that if I'm moving colliders, I should also use Rigidbodies for performance. But I can't see how I get this to work with Rigidbodies. How do I set it up? Or should I move away from rigidbodies and set it up myself?


Player area in navmesh? In my game, If i click on terrain my soldier goes there. In my terrain there is no place without a navmesh. So, I want to make area where player moves his soldiers on it. If he clicks outside this area, soldier will not move there or moves to closest point inside the area to this outside. Could invisible wall do this ? Image.Image2. update To solve this, make any object fit your area. then, use mouse to detect that object.


How to correctly instantiate prefab in Unity I made a prefab and drag drop it to the Tile Prefab slot as shown in the picture In my code using System.Collections using System.Collections.Generic using UnityEngine public class GameGrid MonoBehaviour private int width private int height private int , gridArray private float cellSize SerializeField GameObject tilePrefab default public GameGrid(int width, int height, float cellSize) this.width width this.height height this.cellSize cellSize gridArray new int width, height Debug.Log(width quot quot height) for(int x 0 x lt gridArray.GetLength(0) x ) for(int z 0 z lt gridArray.GetLength(1) z ) GameObject tile Instantiate(tilePrefab) tile.transform.SetParent(transform, false) tile.transform.localPosition GetWorldPosition(x,z) private Vector3 GetWorldPosition(int x, int z, int y 0) return new Vector3(x, 0, z) cellSize 1.It throw out error, ArgumentException The Object you want to instantiate is null, it is very strange because I have the Prefab assigned in the inspector, what could ran wrong, and it is strange that the console did not tell me which line is wrong. 2.Another error is quot You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed quot , it confused me because I did not new anything. 3.This line of code quot tile.transform.SetParent(transform, false) quot I copied from other resource which I do not fully understand, I looked to the Unity menu still did not get any idea of what it does, it setParent but what parent property this function tries to setup, is it trying to set its parent's transform or what? Thanks very much I'm still new to Unity. EDIT Here is my testing.cs public class Testing MonoBehaviour Start is called before the first frame update void Start() GameGrid grid new GameGrid(20, 10, 1) 1.Remove the default assignment is not working either. 2.Regarding to the setParent, I do not have a parent, then what parent this child is attached to, if this function will instantiate a parent, then no information is provided to the creation of the parent, still confused.


Unity keyboard GUI navigation priority I noticed something strange while playing with my menu on keyboard. I have four items arranged in a square (i.e. the top left item should be able to navigate to the top right and the bottom left). If I hover over top left, hold the right key, and then tap down, the cursor moves to the top right and then to the bottom right. However, if I hold the down key and then tap right, it moves to the bottom left and does not move to the bottom right. This also happens on the reverse side, so it seems as if vertical navigation is being given preference over horizontal. If a vertical key is being held, horizontal navigation is impossible. How can I turn this off? My buttons are all set to Automatic navigation, and when I turn Visualize on, they all look like they're connected properly.


Add singleton to an existing gameobject in Unity via script I did notice that if I assign scripts that generate singleton classes (for my managers), to an empty game object, everything works fine. Now I would like to start the scene with the empty game object, attach the main game manager singleton, and in the game manager singleton I would like to attach to it the other manager singleton classes. Although I am not sure how you actually do so. Do you run addComponent to the main game manager, and they will be attached to the existing gameobject? The gameobject that I use for the main gamemanager is set to not be destroyed on load the doubt is if I should run addComponent on the scripts, or create a reference from the gamemanager script and instantiate it from there. I did look for examples on the subject, but the only thing that I found is the reference to add a script to a game object and I am not sure if that's actually what is supposed to be done.


Google Play Services somehow authenticates without internet connection This question is asked in the context of the Google Play Services plugin for Unity. Following the documentation for the Google Play Services plugin for Unity, I called the Social.localuser.Authenticate() function in my game to check if the player is authenticated (ie logged in to google play services). Here is the authentication code that I am currently calling void Awake () PlayGamesPlatform.Activate() Social.localUser.Authenticate((bool success) gt if (success) GetLeaderboardData("FirstLoad") else loadingText.text "Failed to connect to Google Play Services." StartCoroutine("WaitAndStart") authenticated success success returns true even without an active internet connection ) This works fine with an active internet connection. However, if the player has logged in before, and then launch the game without an internet connection, this function somehow returns true. It doesn't make sense (at least not to me) that the player can authenticate without an active internet connection. Does anyone know if this was intended? (Or if I made a mistake of some sort somewhere?) Should it have been indeed intended (and the method is checking against a cache of some sort), is there no method to check if the player has an active connection to google's servers? Something along the lines of PlayGamesPlatform.CheckConnection()?


Roofs not appearing in Unity My buildings are fine until I import them to Unity. None of the formats I've come across( FBX, DAE, 3DS Max, Blender Files, any of the Autocad formats, OBJ, PRJ, WRL etc.), have roofs when importing the buildings as one cohesive file into Unity. In Sketchup, Blender etc. they all appear fine. Does anyone have suggestions?


Process for Creating Imposters (For Unity) I'm still working on making a sports stadium with crowd etc. I've been reading a lot about 'Imposters' and 'Billboarding'. I want to explore and learn the imposters technique. But I am stuck at step 1 I have a stadium model made which is empty (no seats or people). All I want at the moment is seats. I have the model made in Maya for a seat. Do I need to make (and import to Unity) both a low poly and high poly version of the model. How exactly is an 'imposter' asset stored in data (specifically if used in Unity)? Do I need to make 2d images textures of many angles of the seat? I do have more questions, but these may be enough to get me started. Thanks as always for any help.


Unity Interactive menu with sprites changing with buttons I have a menu where the player gets to choose which team and kit he will use to play. However I don't really know how to change the sprite each time the left or right arrows are pressed. I already have the sprites for each team, league and kit the only thing I am missing is the way to arrange it via script. Thanks.


Pong tutorial Unity Logic question I've been following this Pong tutorial, which is great https noobtuts.com unity 2d pong game. The C , unity components etc I understand. But what I am having trouble with is understanding the logic of how it reverses the direction of the ball depending on where it hits. I know that what it is doing is condensing a new Y value to 1, 0, 1, via the hitFactor function, which returns that value and then sets that to the new Y (so going up or down) based on the relative ball position to the paddle, divided by the height size of the paddle. But that's the bit I don't really truly understand, how does that work and why? I have been using Debug.log to send all the different parts of it to try and understand, as well as visually looking in Unity and trying to figure it out from there via the inspector, but I'm just having a mental block. To me I can vaguely see how this code is finding a relative position and then dividing by the height of the paddle to somehow condense it to this range but I'm really just stuck on it in my head.(the hitfactor function itself is basically where I am stuck) Here's the function float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight) ascii art 1 lt at the top of the racket 0 lt at the middle of the racket 1 lt at the bottom of the racket return (ballPos.y racketPos.y) racketHeight And in context with the collision if (col.gameObject.name "RacketLeft") Calculate hit Factor float y hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y) Calculate direction, make length 1 via .normalized Vector2 dir new Vector2(1, y).normalized Set Velocity with dir speed GetComponent lt Rigidbody2D gt ().velocity dir speed I'm sure this is a very basic thing, but I am struggling with this type of thing. I am on Khan academy, starting from very basic stuff and working my way up, so no doubt maybe when I get to vectors I might understand this more, but I'd like to try and really get my head around this particular issue. Sorry for the very basic question, I have been dabbling in C and Unity for a while, but I have realised my weakness is really in the basic core logic of some things....I am a composer by day but I really enjoy trying to get back into this side of my brain, I guess it's super dusty in there hahaha. Thanks so much in advance for any help, I truly appreciate it.


How to detect if I click on an object (2D) using Raycast? I need to know this for a little popup I made in my game, I want to avoid using OnMouseDown because I have multiple cameras so I was wondering how I'd be able to detect a mouse click event on an object using Raycasting, as I can't figure it out Thank you!


AssetBundles with shaders that contain include to cg hlsl I have a shader that contains some includes to other cg hlsl scripts. If i put that shader into an AssetBundle, how am i suppose to handle the cg hlsl scripts? Are they not necessary anymore because they are compiled into the shader during the AssetBundle build process? Unity version is 5.6.6f2 Or do i have to put the cg hlsl scripts into the AssetBundle too? If that is the case, how do I load them during runtime such that the Shader finds them? Someone suggested me to inline them, but I would like to avoid it if possible.


Character getting slow when reached to speific path point I have manually placed some cube on the floor and aim to walk my character on those cube as they are appearing in the hirarchey and here is the walk code. if (Vector3.Distance(pathPositions pathIndex , walkingCharacter.transform.position) gt 0.5f) Vector3 newPosition pathPositions pathIndex walkingCharacter.transform.position walkingCharacter.transform.position newPosition Time.deltaTime walkingSpeed walkingCharacter.transform.rotation Quaternion.LookRotation(newPosition) else pathIndex I have walk in place animation which is working fine and the above code moving my character to specific points but not smoothly. As my character approach to specific path point it get slow then suddenly move towards next point. What i am doing wrong. Here is the video of the problem maybe it will helpful to understand the problem.


UNet send message by Client.Send error I'm try to implement client server communication base on UNET. The problem i got now is send custom message to server, but the Client.Send always show error without my understanding. So what i'm wrong? I jus try to implement from scratch, not inherit from NetworkManager. Here is the code using UnityEngine using System.Collections using UnityEngine.Networking public class ZMessageTransfer NetworkBehaviour private static ZMessageTransfer instance public static ZMessageTransfer Instance get return instance NetworkClient m Client public class MessageType public static short Login 1001 public class LoginMessage MessageBase public string username public string password void Awake () instance this public void SendLoginMessage(string username, string password) LoginMessage loginMsg new LoginMessage() loginMsg.username username loginMsg.password password m Client.Send(MessageType.Login,loginMsg) Server using UnityEngine using System.Collections using UnityEngine.Networking using UnityEngine.UI public class ZMatchServer NetworkBehaviour public int listenPort public int maxConnection public bool enableNAT public Text currentPlayer public Text currentLog private int onlinePlayer void Start () Network.InitializeSecurity() Network.InitializeServer(maxConnection,listenPort,enableNAT) NetworkServer.RegisterHandler(ZMessageTransfer.MessageType.Login,OnPlayerLogin) void OnPlayerLogin(NetworkMessage netMsg) var loginMsg netMsg.ReadMessage lt ZMessageTransfer.LoginMessage gt () string username loginMsg.username string password loginMsg.password currentLog.text "Player send login " username " " password void OnServerInitialized() Debug.Log("Server Initialize completed! ") currentLog.text "Server Initialize completed! " void OnPlayerConnected(NetworkPlayer player) onlinePlayer 1 currentPlayer.text "Current player online " onlinePlayer.ToString() currentLog.text "Player connected" Debug.Log("Player connected " ) void OnPlayerDisconnected(NetworkPlayer player) onlinePlayer 1 currentPlayer.text "Current player online " onlinePlayer.ToString() currentLog.text "Player disconnected" Client using UnityEngine using System.Net using System.Collections using UnityEngine.Networking using UnityEngine.Networking.Types public class ZNetworkConnection NetworkBehaviour SerializeField private string serverURL SerializeField private string serverIP SerializeField private int serverPort NetworkClient m Client private static ZNetworkConnection instance public static ZNetworkConnection Instance get return instance void Awake() instance this void Start () ConnectToServer() protected void ConnectToServer() Network.Connect(serverIP,serverPort) public void LoginToServer(string username,string password) ZMessageTransfer.Instance.SendLoginMessage(username,password) protected void OnConnectedToServer() Debug.Log("Connected to server complete ")


Unity vr device support I have been looking for a list of VR devices that unity supports (or that you can use to develop VR games with). However i have been unable to find a list. Currently im looking at BOBO VR Z4 But to make sure i do not make any incorrect purchases so it would be really helpful to know supported devices. Also it is worth noting i'm going to be using the newest version of Unity. (which is currently version 5.6)


Rendering a distant star field in Unity using a separate camera for near stars I'm currently working on a hobby project which is a universe simulator (exclusive to stars) built in unity3D. In order to deal with the raw scale of the universe I'm trying to implement two co ordinate systems. In my project I have two cameras camera1 is the first co ordinate system where all stars are loaded as high detail 3D objects. While camera2 is used for gathering a list of points within this "extended" frustum. I want to display these stars from camera2 on the farplane of camera1 in a lowdetail 2d manner. I'm new to game development so this may be completely wrong my plan was to generate a mesh from all the points in cameras2 frustum (this mesh now respresents my points in world space). I have a variable that represents the conversionFactor between the two co ordinate systems. I will convert this mesh into projection view using the my conversionFactor in the translation component. I will display this projection view on my camera1 farplane selling the illusion of far away stars? Please let me know the flaws in my deisgn! any help is much appreciated


How to implement a component based model for menus in Unity? I'm trying to create a "sims like" context menu when an item game object is clicked. This comes as an add on question from this question How to design context menus based on whatever the object is? Specifically Each object of class Item would have a list of components like Equipable, Edible, Sellable, Drinkable, etc. An item can have one or none of each component (for example, a helmet made of chocolate would be both Equipable and Edible, and when it is not a plot critical quest item also Sellable). The programming logic which is specific to the component is implemented in that component. When the user right clicks on an item, the components of the item are iterated and context menu entries are added for each component which exists. When the user selects one of these entries, the component which added that entry processes the option. You could represent this in your XML file by having a sub node for each component. Example lt item gt lt name gt Chocolate Helmet lt name gt lt sprite gt helmet chocolate.png lt sprite gt lt description gt Protects you from enemies and from starving lt description gt lt edible gt lt taste gt sweet lt taste gt lt calories gt 2560 lt calories gt lt edible gt lt equipable gt lt slot gt head lt slot gt lt def gt 20 lt def gt lt equipable gt lt sellable gt lt value gt 120 lt value gt lt sellable gt lt item gt When I read this, it reminds me of an interface in programming. My question is, how do you implement this? Perhaps a better question is "is the answer still valid" but it does seem relevant to me. What have I tried? Nothing at this point, because I'm not sure where to start. Given the example above, I'd guess that Item would have a list of... interfaces? that it could implement? This is why I am a bit confused. I want to add, this isn't just a UI issue. I found a few radial menus in the store, my issue is how to populate the menu depending on what game object is clicked.


Activate and Deactivate Collider with Click I'm having some trouble working with this, it's basically a sword that points toward your mouse position, and when you Left Click, a Trigger Collider is activated and then deactivated, but I can't get it to work. Here is my code void Attack() Activates the Sword Collider polygonCollider2D.enabled true Debug Line Debug.Log("Collider Active") StartCoroutine(Wait(0.1f)) polygonCollider2D.enabled false IEnumerator Wait(float seconds) yield return new WaitForSeconds(seconds) I did it this way hoping that the Wait method would give the game enough time to react to an active collider, and using some Debug.Log(). I know that the collider actually activates, but it does not react to other colliders. I keep wondering if this is the proper way of working with this. If it's not, do let me know.


How do I use Android's adaptive icons in Unity? As of API 26, Android uses something called adaptive icons. When targeting API 25 and lower, my app's icon looks fine But when targeting API 26 , it shows up in a white circle like so How can I target API 26 while utilizing Android's adaptive icons? What if I want to target API 26 , but not use Android's adaptive icons?


trying to get an int grid of values from unity tilemap I'm trying to get a 2 dimensional grid of values from a tilemap and found this which seems to do the trick tileMap gameObject.GetComponent lt Tilemap gt () foreach (var position in tileMap.cellBounds.allPositionsWithin) Debug.Log(gameObject.name " " position) TileBase tile tileMap.GetTile(position) if(tile.name ! null) Debug.Log(tile.name) However, something strange happens as it produces two values, when I only have one tile on the tilemap and when I uncomment my .name log above it only works for the second value and errors for the first. Any help of the best way of finding values from tilemaps would be great.


camera.render reads a file in the middle of a gameplay Why does camera.render read a file in the middle of a gameplay? This causes a lag in my game