How to put the game object to the upper left corner of the screen in Unity and make it visible entirely on all screens of mobile devices I have game object which displays health indicator in my 2d video game in Unity. This gameobject contains a lot of sprites and i put it into left top corner of the screen. In my game editor it is visible entirely but on my mobile device is visible only half of it. How can i make it visible entirely on all screens? Can anyone help me to solve this problem please. P.S. I have some ideas how to do this 1. Create health indicator from GUITexture elements. But it is not good for me, because health indicator consists of a lot of small elements and it will take a lot of time for me to resize every GUITexture according to my needs. Put my gameobject with health indicator into another gameobject with zero transform, and then put parent GO into top left screen using Camera.main.WorldToViewport method. But may be there is more easy way to do this?


Jumping onto higher ground Collider issues What's the general solution to the following character animation problem (I'm using Unity)? You have a character with a capsule collider and a jump animation that allows you to jump onto higher ground (such s boxes, etc.). The character shouldn't be able to jump unrealistically high so she goes into a crouched posture while in the air and the collider is scaled accordingly in an animation curve. However when the character jumps onto the box to land, the character animation (and collider) want to extend back to wards the ground but there is not enough space and either collision detection fails and the character falls into the geometry or the collider starts a collision fight with the box and keeps bumping up and down, keeping the character in an airborne state. Please see screenshots to get a better idea... What would be a good way to work around this problem?


Blue, Red and pink Materia Hi guys i just started using unity recently but today after working on some animation blending, most (not all) prefabs changed to look like this What's the cause, and how can i fix it? i tried creating a new project then copied my Asset directory to it but still. also when i try importing a new character i still see the same. Material structure.


How to make it so my cursor is not behind the UI? My cursor keeps going behind the UI how to make it go above?


Can animation parameters only be changed in scripts? I have a very simple animation parameter in the Animator, a boolean that is "true" when a shooting animation is playing (to stop the game logic from allowing more shooting during a gun recoil animation). I assumed I'd be able to access this in animations, i.e. setting it to true when a shooting animation started, and false when it ended. But I just can't see how to access it in my animations. It's not available under "Add Curve". Am I missing something? I can do this in other ways, but this just seemed like the cleanest.


Push Notification to start a scene I was wondering whether I can use APNs in iOS to trigger an event in my game, like start a scene without user clicking the notification. Is it possible to use remote push notifications for events like this?


Is it possible to have two trigger zones around the same GameObject in unity? I have created a trigger zone to make sure that only only gameobject passes through it at a time. The moment the gameobject1 entered the trigger zone, it is given a particular tag but I am not how to stop other gameobjects from entering the zone. Is it possible to have two trigger colliders attached to a same object like an outer and inner trigger such that only one gameobject is allowed to pass through the inner one while all other gameobjects wait at the outer one.


How do I find a component, deferring to the children or parent if there is none? I'm trying to create a function in C in Unity that will take a GameObject and a Component, and return an attached Component from the base, child, or parent elements. If the target GameObject does not contain the requested Component, I wish to look to any children. If there are no children, or the children do not contain the requested Component, I wish to look to the parent. How do I find a component, deferring to the the children or parent if there is none?


Unity using WWW to download image from web. Not working from my own website, but does from other urls I have this script attached to a RawImage file in my games UI public class DownloadImage MonoBehaviour string url "http megabrogames.rf.gd pic.jpg" string url "https i.imgur.com xBSyvRx.jpg" IEnumerator Start () WWW www new WWW(url) yield return www GetComponent lt RawImage gt ().texture www.texture Both jpg files are the same. One I uploaded to Imgur, this works. The other is on my own website. The url to my website works fine, I have checked in on two computers and several browsers. All I get is the red question mark. But if I uncomment the other one instead it all works perfectly. My problem is that I have hard coded the url into the game, and I want to change the image each week. It has to be the same URL for that to work, but i think with Imgur it will auto assign whatever url it feels like. thanks for any help


Image effect console error I have imported image effects from asset store in my project. When imported, I've got 5 error messages Assets Standard Assets Effects TonemappingColorGrading Editor TonemappingColorGradingEditor.cs(370,134) warning CS0618 UnityEditor.TextureImporterFormat.AutomaticTruecolor' is obsolete Use textureCompression property instead' What to do ?


Unity scene preview keyboard controls I am learning to use Unity, and found I disliked the way moving around the scene editor is implemented. The left and right arrow keys move the scene quot camera quot left and right as expected, but the up and down editor moves forwards and backwards. Is there a way to change the controls to make it more like a quot traditional quot WASD movement, similar to how Minecraft on touch devices does it (up, down, left, and right moves exactly as it sounds, and rotation is by clicking and dragging the mouse)? Thank you for your time.


Ping Pong bat is not detecting the collision with the wall I have been learning Unity for last couple of days. I want to make one simple ping pong game. The idea is simple. The game has a Sphere as a ball, a plane as ground, 2 rectangles as bats and 4 rectangles as walls. Look at the image It is a 2 players game. One player will use 'W' and 'S' key and another player will use 'Up Arrow' and 'Down Arrow' on the keyboard to move the bat up and down. But I have a problem here. If a player moves the bat at the limit (up or down), the bat does not detect the collision with the wall. It just goes through the wall. Look at the image. The bats and the walls have Box Collider, but still the problem persists. So what should I do so that the bat detects the collision with the wall.


Instantiate unity sometimes lags the game some times it doesnt I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object A. When i use this object my script instantiates the objects without any freezes or any other problems. Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object B. Now when i want to instatiate object my my game freezes a few frames upon instantiation. Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case. See here a screenshot for object A, and its components See here object B and its components Per request the code that does the instantiation of the objects public class ForLoopVisualization1 MonoBehaviour public DetectorAreaScript ElementDetector public GameObject TowerElement public Transform TowerElementsParent public bool WigglyTower false public float ElementSpacing, Wiggeliness private Collider BuildElementCollider private Transform BuildElementTransform private Vector3 TowerElementPos private int TowerElementCount, CreatedElements private bool StartBuildingTower false private float Delay 0.5f, TowerElementSize Use this for initialization void Start () ElementDetector.DetectedData OnObjectEnterDetector Destroy(TowerElement.GetComponent lt Rigidbody gt ()) TowerElementSize TowerElement.GetComponent lt Collider gt ().bounds.size.y TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) Update is called once per frame void Update () if(StartBuildingTower amp amp CreatedElements lt TowerElementCount) Delay Time.deltaTime if(Delay lt 0) CreatedElements var te Instantiate(TowerElement, TowerElementPos, Quaternion.identity) te.transform.SetParent(TowerElementsParent) if(WigglyTower) TowerElementPos new Vector3(Random.Range( Wiggeliness, Wiggeliness), TowerElementSize ElementSpacing, Random.Range( Wiggeliness, Wiggeliness)) else TowerElementPos new Vector3(0, TowerElementSize ElementSpacing, 0) Delay 0.4f else if(StartBuildingTower) StartBuildingTower false StartCoroutine(EjectVar()) add when bugs are fixed.. void OnObjectEnterDetector(System.Object sender, DetectedVariableData data) if(data.DetectedObjectType DetectedType.Variable) var vals ElementDetector.DetectedVariable.GetVariableValue() TowerElementCount vals.IntValue if(CreatedElements gt 0) foreach (Transform child in TowerElementsParent) Destroy(child.gameObject) CreatedElements 0 TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) StartBuildingTower true IEnumerator EjectVar() yield return new WaitForSeconds(0.8f) ElementDetector.EjectDetectedElement(new Vector3( 1, 0, 1)) If something is unclear let me know so i can clarify the post!


unity update boolean from other script So my problem is that the color of the sprite should only change if the Boolean is true. My theory is that the Boolean isn't being update. So how do I update the Boolean the whole time and see if it is getting changed. Thanks Guys, public class controlborder MonoBehaviour private SpriteRenderer m spriteRenderer public float loopdelay 2f public static bool startstop public void Start() m spriteRenderer GetComponent lt SpriteRenderer gt () StartCoroutine(Changecolor(2f)) public void Update() private IEnumerator Changecolor(float loopdelay) while (true) startstop control.changecolorborder lt this bool Debug.Log(startstop) while (startstop) yield return new WaitForSeconds(1F) int random Random.Range(1, 4) if (random 1) m spriteRenderer.color Color.blue else if (random 2) m spriteRenderer.color Color.red else if (random 3) m spriteRenderer.color Color.green else m spriteRenderer.color Color.yellow


Creating a content pipeline for a Unity I have a game with lots of assets, such as data files, images, etc. My understanding is that Unity is optimized to know about all resources at build time. i.e. binding those assets to Scene GameObjects or prefabs. And for performance reasons, dynamically loading files from the Resources folder is discouraged. My question is how can I set up a "content pipeline" for converting my asset files stored outside of Unity into a format that Unity expects. With the XNA toolset you can create a separate project and "build" the content into a bundle. Is there way to achieve similar results in Unity? Or is the best I can do creating an external tool, and simply copying files into my Unity Textures or Unity DataFiles folder and generate the Unity metadata files myself? If there isn't an off the shelf solution, do you have any experiences or recommendations with solving this problem?


Setting Camera's Viewing parameters manually I am working on Context aware camera in Unity. in this project i have to set parameters of the camera each frame manually depending on what camera sees on the screen. New View (v) direction is given and Up (u) and Right (r) vectors should be such that they minimize torsion with previous frame's u and r. I have deployed the following code to accomplish the given task Vector3 viewNew m Normal Vector3upNew Vector3.Cross(viewNew,m CameraPrevTransform.right).normalized Vector3 rightNew Vector3.Cross(viewNew, upNew).normalized ... transform.forward viewNew transform.up upNew transform.right rightNew The problem is it seems like Unity tries to automatically adjust parameters when one of the directions (up, forward, right ) are set. Is there a workaround ? is it possible to get more control of the camera?


TextMeshPro Shader choices difference (when to use) Actually I can see the visual difference that bitmap sprite shows blurry text like this pink distance field seems like missing texture distance field surface grey and lastly distance field masking overlay seems to show the correct expected result so what's the difference between those two? (masking overlay)


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


Position Unity UGUI ScrollRect Content Position from Script I have a map in my game the user can interact with. I am using Unity UGUI ScrollRect to let the user move the map on the screen. Only one area of the map is visible at a time and you can scroll it to get to the desired level (just like in King games). The content of this map system is an Image and level buttons which are all children of the map image. I want my ScrollRect to point to the current active level when the map loads. For example, if I am on level 30 then on loading the map level the content of the ScrollRect should be on the portion of the map where level 30 is. I can't find anything regarding managing ScrollRect's content position


Flipped camera with Google VR I just imported latest Google VR SDK into Unity and made a simple scene that has only Main Camera, plane, and single zombie just standing there with T Pose. In Main Camera, I added GvrPointerPhysicsRayer component, and it has GvrReticlePointer as child object. Running in Unity Editor seems fine but when I build and run, whole world is just flipped. I can't find any related issues about this anywhere, and struggle with this almost a day. Why camera flipped and how do I fix it? What am I missing? Using Unity 2019.1.0f2 and gvr unity sdk 1.200. Any advice will very appreciate it. P.S. I saw the warning message in project settings default orientation Virtual Reality Support is enabled. Upon entering VR mode, landscape left orientation will be the default orientation unless only landscape right is available. This message never disappear whatever default orientation selected.


How can I access a GameObject variable in mono script from editor script? In the mono script using UnityEngine public class TileTest MonoBehaviour public GameObject prefabPathOnTerrain Then in the editor script at the top private SerializedProperty prefabPathOnTerrain Then inside OnEnable() private void OnEnable() prefabPathOnTerrain serializedObject.FindProperty( quot prefabPathOnTerrain quot ) And then inside a method I want to use it as a GameObject And instead using CreatePrimitive to use Instantiate But doing GameObject go Instantiate(prefabPathOnTerrain) Will not work. public void TerrainObjects(GameObject gameobject) Terrain terrain Terrain.activeTerrain var cube GameObject.Find(string.Format( quot Terrain 0 1 quot , gameobject.transform.localPosition.x, gameobject.transform.localPosition.y)) if (cube ! null) return if (cube null) GameObject go Instantiate(prefabPathOnTerrain) cube GameObject.CreatePrimitive(PrimitiveType.Cube) cube.transform.localPosition new Vector3(terrain.transform.localPosition.x gameobject.transform.localPosition.x, 0, terrain.transform.localPosition.z gameobject.transform.localPosition.y) cube.transform.localScale new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1) cube.transform.parent GameObject.Find( quot Terrain Map quot ).transform cube.name string.Format( quot Terrain 0 1 quot , gameobject.transform.localPosition.x, gameobject.transform.localPosition.y) cube.tag quot Terrain Map quot


ScreenToWorldPoint returning wrong position even when given Z plane I have a NavMeshAgent placed on a character model. When I log agent.transform.position I get (4.5, 0.1, 4.5) which is correct (this is a 2.5d game and movement happens along the x and z axes). I am trying to set up a script so that when I click a location on the screen, the character will turn to face that location. The problem I'm facing is that the coordinates returned by Camera.ScreenToWorldPoint are not correct Vector3 mousePos Input.mousePosition mousePos.z Camera.main.nearClipPlane Vector3 targetPos Camera.main.ScreenToWorldPoint(mousePos) Debug.Log(agent.transform.position) Logs (4.5, 0.1, 4.5) Debug.Log(targetPos) Logs (0.1, 16.7, 0.7) In this example, I'm clicking on the same place as the agent but the targetPos is not nearly the same. The y axis of targetPos is static (the same no matter where I click), which seems correct. However the values for x and z are not correct. How do I get the correct coordinates for a click? edit I have this workaround, but I want to know how to solve the original question still RaycastHit hit if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100, rotateTargets)) Vector3 targetPos hit.point targetPos.y agent.transform.position.y Vector3 direction (targetPos agent.transform.position).normalized Quaternion rotation Quaternion.LookRotation(direction) agent.transform.rotation rotation agent.updateRotation false return true


Best approach for destructible car in Unity I'm developing a simple racing car game. I'm wondering what is the best approach to manage visually car destruction. For instance i think one option (expensive) is to build car 3d model with 'separate' mesh, each for any component (bump, door, glass) and relative cooliders.. Other options ? Thanks


Smooth Flat shaded meshes cause shadow artifacts (understanding the source of the problem) I'm using blender to create assets to use in Unity3D, and I'm having some trouble understanding how the smooth flat shading interacts with shadows, I'm sorry if it has been asked before, but all the "related" answers refer only to the shading of the object itself, not the shadow it casts. I'm a 3D artist, I do not understand Unity and the mechanics behind it the same way I understand 3D stuff, I'm also trying to understand if the problem lies in the 3D object or some configuration in Unity. I'm using a real time directional light. 1 and 2 are flat shaded. 2 has open geometry while 1 has closed geometry, both have such artifact but it's clearly seen on 2. 3 and 4 both have closed geometry. 3 is fully smooth shaded while 4 is flat shaded. Solution A Mess around with Bias and Normal Bias. With Normal Bias at 0, the shadow artifacts are gone but the mesh itselt gets some other artifacts. Solution B Use Two sided shadows, this method completely fixes the problem, in any situation, but it adds another draw call and makes it more expensive (I'm not 100 sure it does) is this an optimal solution? This same issue was discussed in a closed group but no one could give me a conclusive answer. However, someone who works with 3DS Max said that exporting a mesh with proper smoothing groups does not result in these artifacts, I tested that in 3DS Max and it did not work I think I did it the right way, but I'm not 100 certain. For all the proposed methods, I tested several times, with diferent mesh modifier and exporting options. I'm using mostly .fbx but I also tested in .obj format (which includes a specific option for smoothing groups in blender). Smooth shaded objects work perfectly, flat or smooth flat shaded objects result in this drama. Please help me to bring light to this issue, I might be blind to some obvious aspect, I'm confused because in the other discussion I was presented with contradicting arguments without conclusive proof of anything. Now I don't know if the problem lies with Blender export or Unity configuration. Let me know if I can provide more information.


Running Unity Build through Command line I recently developed a game in unity and would like to build it to a standalone application using the command line. Is there a way to do that? Specifically, without opening the Unity Editor how can I use the command line to build my project to a standalone application? I am using Linux.


Static variable not holding its value I am creating a real time multiplayer game in Unity 3d. When a game ends I set a static boolean value called "waitingToEndGame" to true. In Update() it waits a few seconds before moving to a new scene like this if (waitingToEndGame) waitTime Time.deltaTime if (waitTime gt 5f) showGameScores false waitingToEndGame false if (type "Multiplayer") MultiplayerController.Instance.LeaveGame() GameObject levelManager GameObject.Find("Level Manager") levelManager.GetComponent lt LevelManager gt ().LoadLevel("MainMenu") DisableAllMovingObjects() My problem is that even though I am setting the boolean value to true it acts as if it doesn't change and it doesn't make it into the code above to move to the main menu. I even had debug statements printing here as well and they seem to just suddenly stop.


Why my object Triggering too far? I have some issues with detecting the collision when OnTrigger2d, as you can see in my screenshot below, that actually too far from the object. this my script private void OnTriggerEnter2D(Collider2D collision) if (collision.tag quot Obstacle quot ) anim.SetBool( quot isDeath quot , true) GameManager.instance.GameOver() private void OnTriggerExit2D(Collider2D collision) if (collision.tag quot Obstacle quot ) anim.SetBool( quot isDeath quot , false)


Objects aren't rotating in sync This is a follow up question to How to reapply force applied to one object to another object I want to make two objects move, react to collisions and other stuff as if they were one. For example, Objects A and B are entangled. When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall. I tried changing position speed every frame, but this only works when done in one direction. Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it. Edit This is the new code which only fails when multiple collisions happen at once using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(Rigidbody)) public class EEScript MonoBehaviour public List lt EEScript gt activeObjects public new Rigidbody rigidbody public Vector3 lastPosition Start is called before the first frame update void Start() rigidbody gameObject.GetComponent lt Rigidbody gt () Update is called once per frame void Update() lastPosition transform.position private void OnCollisionEnter(Collision collision) foreach (EEScript entangled in activeObjects) if (entangled this) continue Rigidbody rb entangled.rigidbody if (rb is null) continue rb.velocity rigidbody.velocity rb.angularVelocity rigidbody.angularVelocity entangled.transform.position entangled.lastPosition transform.position lastPosition


How to prevent intepolated texture in fragment shader (Unity CG) Think about minecraft all the textures in minecraft have a very nice crisp pixelated look. Well, I'm trying to write a shader that will do this but it appears "sampler2d" returns some sort of interpolation between pixels of the underlying texture. I'm pretty new to shader writing and I'm not even sure if it can be done but I'm hoping to get a nice crisp blow up of small textures rather than a blurry one like this If anyone knows a way to make a shader crisp rather than interpolated like this (using Unity), I'd be thrilled to know as this hitch is pretty detrimental to what I'm trying to accomplish... Here's the subshader as it is right now (it's skipping all the light calculations and just outputting the sampler as I'm just trying to resolve the blurry texture sampling) SubShader Pass Tags "LightMode" "ForwardBase" CGPROGRAM pragma vertex vert pragma fragment frag user uniform float BlendVal uniform sampler2D DiffuseTex uniform sampler2D NMTex uniform sampler2D PixelMap uniform float4 DiffuseTex SV uniform float4 SpecColor uniform float SpecIntensity uniform float4 RimColor uniform float RimIntensity uniform float RimCoefficient unity uniform float4 LightColor0 struct vI float4 pos POSITION float3 norm NORMAL float4 uv TEXCOORD0 struct vO float4 pos SV POSITION float4 uv TEXCOORD0 float3 worldPos TEXCOORD1 float3 normDir TEXCOORD2 vO vert(vI i) vO o o.uv i.uv o.worldPos mul( Object2World, i.pos).xyz o.normDir normalize(mul( float4(i.norm, 0.0), World2Object).xyz) o.pos mul(UNITY MATRIX MVP, i.pos) return o float4 frag(vO i) COLOR float3 lightDir float3 viewDir normalize( i.worldPos WorldSpaceCameraPos.xyz) float atten float3 normDir normalize(i.normDir) float4 RimLight float4 DiffuseLight float4 SpecularLight float2 UVCoord i.uv.xy float4 test tex2D( PixelMap, UVCoord) float4 Clrx0 lerp( Directional Light if( WorldSpaceLightPos0.w 0) lightDir normalize( WorldSpaceLightPos0.xyz) atten dot(lightDir, normDir) point light else float3 dist i.worldPos.xyz WorldSpaceLightPos0.xyz lightDir normalize(dist) atten (1 length(dist)) (dot(lightDir, normDir)) DiffuseLight atten LightColor0 SpecularLight atten LightColor0 SpecColor SpecIntensity pow(max(0.0,dot(reflect(lightDir, normDir), viewDir)), 1) (1 tex2D( DiffuseTex, i.uv.xy).w) RimLight atten LightColor0 RimColor RimCoefficient pow((1 saturate(dot( viewDir, normDir))), RimIntensity) saturate(dot(lightDir, normDir)) float4 totalLight DiffuseLight SpecularLight RimLight float4 fin float4(UVCoord.xy,0,0) return test Fin totalLight ENDCG


How can I create a custom PropertyDrawer for my Point struct? I created a Point struct System.Serializable public struct Point public int x public int y I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a Vector2 field. I have the following script in the "Editor" folder using UnityEditor using UnityEngine CustomPropertyDrawer(typeof(Point)) public class PointEditor PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) EditorGUI.Vector2Field(position, label, property.vector2Value) It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the Point instance from inside the OnGUI method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective Point is also changed?


unity spriterenderer scale to fit screen portion let me explain what i have. a camera that render only a sprite ( sprite renderer) and what i'm looking for is to scale that sprite renderer to fit a screen portion (not the entire screen) for example 0.145 (normalized) anyone can help me? fix i mean, from 0 to 0.145 so the entire area ( it will be a 125x125 image ) so i need to keep the aspect ( same width and height) and i'm using orthographic camera


Is a mesh OK to use for grass if there will be 1000's of them across the terrain? Am creating a low poly game in Unity 3D for PC. The terrain is made in Blender, so it's a fixed size, but quite large for the player to explore. I want to add things such as grass and flowers, but am not sure the best practices are for creating those types of assets. Is using a mesh for small clumps of grass the wrong way to do this if there will be 1000's of them? I will likely be using the occlusion culling system Unity provides, but I'm not sure if I still need to look at doing things such as grass in a different way for performance sake.


Speech recognition in Unity 5 for Android I've been working on a game in which the player have to say particular words to perform various tasks. For example, if the player says "boat", a boat pops up in the game. The game I'm building is specifically for offline play, on an Android device. Just for reference, there is a game titled "Pah!" which implemented this offline speech recognition for one specific word. In this game, when you say "pah", the GameObject moves jumps. I've tried everything from speech to text to forums, and even tried Google and used using Windows.Speech, but nothing works. From what I've learned, I need to use the Google speech API for Android speech recognition. I am a bit new, when it comes to Java. I gave it a try and created a basic script, which I thought might take at least one input in speech from the player, but Unity disagrees and says it couldn't recognize the script. I created another script in C , by taking help from tutorials, but when I switch the platform from Windows to Android it doesn't work, because Unity.Windows.Speech is a Windows namespace I am blank, and hence, this question. I have googled, visited forums, and even looked at YouTube videos for an answer. I came across a few Unity assets which I paid for, and they are all garbage. If anyone could help me, how do I implement speech recognition in Android, using Unity 5?


How does the Unity3D entity system work? I saw the Java Artemis Entity Component System and thought of the entity system in Unity3D. In Artemis for example you can only add one component type to each entity and the logic is not in the component. In Unity3D it's completely different. Can someone explain me how the entity system in unity 3d works? I mean, is Unity3D a real entity system, or is it something else?


collision detection and normals from rigidbody Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody? Here is a stripped down version of the script I'm using for collisions. Used in other scripts (Necessary) public GameObject ground null public Vector3 groundNormal public bool onGround Used internally public bool isColliding public float slopeLimit Character Controller public CharacterController controller void Start() controller GetComponent lt CharacterController gt () void Update() Check if the player is colliding with anything (Character Controller) if (controller.collisionFlags CollisionFlags.None) isColliding false else isColliding true Check if the player is standing on the ground if (isColliding amp amp groundNormal ! Vector3.zero) onGround true else onGround false void OnControllerColliderHit(ControllerColliderHit hit) Check for floor if (Vector3.Angle(transform.up, hit.normal) lt slopeLimit) Store floor object data ground hit.gameObject Store ground surface normal groundNormal Vector3.Normalize(hit.normal) else reset variables ground null groundNormal Vector3.zero slopeLimit is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later. Edit Currently I'm using controller.collisionFlags to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the isColliding bool to true using Rigidbody.OnCollisionStay would be simple, but setting it to false without use of another void function seems difficult. is that possible at all?


Import Blender model into Unity with Textures I tried a very straightforward import of the Monk model from https opengameart.org content monk into Unity 5.6.1f1, and ended up with no color texture on the model. Why?


How can I get my physically based sky to be blue all the way down? I'm rendering with a physically based sky. I want to get a very simple light blue background but below the horizon the sky becomes grey brown. How can I get it so that the sky is blue all the way down? As if the edge of the city was the edge of the world. I also want to make the blue sky brighter, especially at the bottom.


How to make high quality gifs of Unity game play I've seen several Unity game play gifs, mostly on twitter. Are there any tools for making high quality gifs in Unity that are quite flexible? For example, I video recording tool that captures the game window and allows users to make gifs of portions, possible specifying the desired quality. Generally, I am looking for a tool that is quite flexible (has a lot of options for capturing gifs) and possibly game window video. UPDATE Some examples are here and here. Generally, several of the gifs that are hash tagged madewithunity a really high quality.


How to stop the Unity Editor from continuously rendering? Look closely at the image below. Even though the game is not running the scene shows that green wheel is spinning. This means the scene is being rendered constantly and my battery is dying. I know Unity used to not do this and was in fact one of the reasons I liked Unity over some other engine that defaulted to always running and would make my laptop fans start up even when just sitting idle in the editor. Is there any way to get Unity to render on demand. Meaning, only render when I interact with it, when I move the camera or change a setting like it used it? I saw in preferences there's an "interaction mode" setting but the best it can be set to is don't render faster than 30fps. That's not useful. Is there some other setting to get the editor to only render when interacted with?


Limit the boundary of Touch a game that I currently working on is in a way that player should actually draw a rainbow on the screen by tap and drag gesture in order to make a hills for the car. but the issue that i currently facing on is if the player wants to pause the game by touching the right most button on the screen above, the game will stop but the hill that he was drawn will remove. I actually not have any idea how can i put exception for that button on the screen because everytime i calculate the whole pixels on the screen for drawing hills. do you have any idea how can i solve this issue ? btw, this is my code if it's required http pastebin.com VnLAQbzW


Using keyword NonSerialized causes Property to disappear from Inspector I have the following class to represent items in an inventory System.Serializable public class InventoryItemInfo MonoBehaviour public int Row 0 public int Col 0 public int Rotation 0 public InventoryItemType ItemType public int Amount public int EffectiveWidth 0 public int EffectiveHeight 0 public int Width 0 public int Height 0 public bool Selected false public Vector3 TilePosAccordingToCurrentRotation public Vector3 TileScaleAccordingToCurrentRotation NonSerialized public Transform TheNicelyPositionedMesh HideInInspector private int iCurRow 0 private int iCurCol 0 private int iRotationToCheckForDirtyness 1 public Vector3 DefaultRotation public bool Initited false public bool Dirty true private bool bInitialRotationGotten false (...) With the keyword NonSerialized , the property "TheNicelyPositionedMesh" disappears from the Unity Inspector. I don't see why. Why is that keyword coupled with the visibility in the Inspector? Thank you!


When to destroy Google AdMob InterstitialAd object? There are a few answers on this question but they don't give a satisfactory answer. I am using a singleton AdManager class that persists throughout the game. I am not sure if I should destroy the instance of InsterstitalAd each time after displaying an ad. This answer says that an InterstitalAd object can only be used once, however in my current implementation I use the same instance multiple times without any ill effect. using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement using GoogleMobileAds.Api public class AdManager MonoBehaviour public InterstitialAd interstitialAd private string InterstitialAdId "test code" public static AdManager Instance null void Awake() MobileAds.Initialize(initStatus gt ) RequestInterstitialAd() SceneManager.sceneLoaded OnSceneLoaded Singleton class if (Instance null) Instance this else if (Instance ! this) Destroy(gameObject) DontDestroyOnLoad(gameObject) void OnSceneLoaded(Scene scene, LoadSceneMode mode) DisplayInterstitialAd() public void RequestInterstitialAd() interstitialAd new InterstitialAd(InterstitialAdId) interstitialAd.OnAdClosed HandleOnInterstitialAdClosed interstitialAd.LoadAd(new AdRequest.Builder().Build()) public void HandleOnInterstitialAdClosed(object sender, EventArgs args) interstitialAd.LoadAd(new AdRequest.Builder().Build()) public void DisplayInterstitialAd() if (interstitialAd.IsLoaded()) interstitialAd.Show() public void DestroyInterstitialAd() interstitialAd.Destroy() As I understand the InterstitalAd object refers to a UI element, while the actual content of the ad comes from AdRequest, so I can reload the ad content without affecting the InterstitalAd object. Do I need to call DestroyInterstitalAd() after each time after an ad is displayed? I want to prevent any memory leaks from happening during long plays.


How to do pixel per pixel modeling in unity3d? So generally I want to have api like pixels.addPixel3D(new Pixel3D(0xFF0000, 100, 100,100)) (color, position) where pixels is some abstraction on 3d sceen objet.So to say point cloud. It would have grate use in deep space stars modeling... I want to set each pixel by hand (having no image base or any automatic thing)... So point is modeling something like Or look at alive flash analog here How to do such thing in unity?


Distinguish between HTC Vive controller grip buttons in Unity In Unity, I can check for grip button presses via the SteamVR API like so if(controller.GetPressDown(SteamVR Controller.ButtonMask.Grip)) ... This results in either true or false so I can only check if any grip button was pressed but not specifically which one. For Unity's Input API the documentation states 1 The grip trigger differs between platforms The HTC Vive controllers each have two grip buttons but both map to the same axis. The value for these buttons is 0.0 when not pressed and 1.0 when pressed (intermediate values between 0.0 and 1.0 are not possible). Source https docs.unity3d.com Manual OpenVRControllers.html In this case it is again not possible to differ between the two grip buttons. Is there any way in Unity to check which one of the grip buttons of a HTC Vive controller is pressed?


Rotating a gameobject in the Inspector doesn't change direction When I add a Cube to a scene, the blue axis ( forward) of the cube points into a certain direction. When I now change the Y rotation of the cube to 90 in the inspector, the blue arrow doesn't rotate. I would have expected it to rotate with the rotation that I have defined for the cube. What is happening here? To explain more in detail why this is bothering confusing me I want to rebuild the RE4 inventory (which is actual 3D). The items in this inventory can be moved within the "grid" To do that I have created a suitcase and then I added a gun to it As one can see, I have assigned the facing direction properly The blue axis ( forward) points into the direction of the gun. Now I wanted to rotate the gun in such a way that it is shown like in the original RE4 inventory. To do that, I apply a rotation of Y 90. The gun looks correctly now However, the blue axis now faces the wrong direction in my opinion. Why does it not rotate along with the rotation of the gameobject? This really confuses me because now when I want to move the gun left or right, I have to change its X position value instead of changing the Z position value. This just seems wrong to me. Can somebody tell me what I'm missing here? Thank you.


Draw wireframe models for Gear VR app in Unity I want to create a 3D Android app for Gear VR that does lets me do the following Read an input file with a bunch of coordinates of points (including information about how they should be connected) Draw a wireframe model with these points Walk around and through the model in first person to look at it from different angles using a gamepad controller. I don't want to directly interact with it! (Maybe have more than one model displayed at the same time, including filled ones) Is it possible to draw 3D wireframe models in Unity using coordinates instead of using already finished models that were created in Blender Maya etc, and if so, how?


Unity trigger problem I have been making my first game but I have encountered a small problem. To show the text when you win, you have to go into a block with the OnTriggerEnter line. I cannot get to this block however, because when I put my player (a sphere) as a trigger it just passes through the ground. How do I fix this?


How to run a long task without freezing my game? I have a component that is in charge of generating a level at runtime, and this is an operation that takes quite some time. As a consequence, I experience a hang when this operation is executed (when the scene is loaded). This problem can be summarized to the fact that SceneManager.LoadSceneAsync in fact is not async at all in its second phase, when it initializes all the objects. There are three approaches I have searched for and thought about Slicing the operation as explained on this video This is non trivial, I would have to rewrite chunks of code for the sake of avoiding a few seconds hiccup at scene load. Furthermore, the person explaining in the video says that they changed Unity source code which I don't have access to. Running the operation in a background thread This is definitely interesting, it would require minimal changes. The only problem is that at some point I have to create Unity objects (GameObject, Mesh etc) and this is not possible when outside Unity thread. I was thinking more or less of this code to be run on the background thread class Builder public void Build() 1. do something long 2. create Unity object with result from 1 something like that await RunInUnitySynchronizationContext(() gt new GameObject(...)) 3. do extra stuff on the result of 2 The thing is I have no idea at all on how that second step should be written, if possible at all. Use a non animated Loading screen and wait for it to finish This is the simplest and effectively does away with the problem by 'just' hiding it. Question What's an effective approach to solve this problem?


Unity AudioClip lags when played My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left click inside the game window. Steps I've tried for fixing it Uncompressing the .wav sound file. Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story. How the issue occurs When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and or lagging. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI RequireComponent(typeof(AudioClip)) RequireComponent(typeof(AudioSource)) public class GameProcess MonoBehaviour public Canvas Game public AudioClip explosion AudioSource beatBox Transform btn Vector3 canvasMin Vector3 canvasMax Vector3 pointerMin Vector3 pointerMax Vector3 pointerPos void Start () btn Game.transform.FindChild("Pointer") canvasMin Game.GetComponent lt Collider gt ().bounds.min canvasMax Game.GetComponent lt Collider gt ().bounds.max pointerMin btn.GetComponent lt Collider gt ().bounds.min pointerMax btn.GetComponent lt Collider gt ().bounds.max beatBox GetComponent lt AudioSource gt () void Update () if (Input.GetMouseButton(0)) beatBox.PlayOneShot(explosion) if (!(pointerMin.x lt canvasMin.x) !(pointerMin.y lt canvasMin.y)) if(!(pointerMax.x gt canvasMax.x) !(pointerMax.y gt canvasMax.y)) btn.transform.position Input.mousePosition else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0)


Unity store data in database Is it possible to store assets used in a Unity game (2D or 3D) in the database? I think it is less efficient but want to have single source of truth and maybe have the game contact the database everytime it loads to get the new updates.


How to make rhythm game long notes in Unity? I'm making a rhythm game for a university course and I can't figure out a way to make the long sustained notes. For reference, this is what I mean taken from Guitar Hero I already have a system working for regular notes. The way I do it is that the notes are stored in an external file as numbers which represent the absence or presence of a note as well as what type of note it is, separated into musical bars 000 010 020 001 There are three lanes for the notes to be, and this means that in this particular bar there are notes wherever it's not 0 (with the numbers being different types of notes). I had thought of using this system to create long sustained note start and end markers (say 3 and 4) and that create another game object which would be the line between the start and end markers. But the way my note generator works is that the notes are not all generated at once because that'd be pretty heavy. Instead, the notes are generated at a certain time taking into account its speed so that it's instantiated and will reach the player's activator when it's supposed to. The following is a part of my note generator code, put in the Update method if current song time time offset is greater than time taken for all executed bars so far spawn the next bar's notes if (songTimer timeOffset gt (barExecutedTime barTime)) StartCoroutine(PlaceBar(noteData.bars barCount )) barExecutedTime barTime And here is the PlaceBar coroutine go through all notes in a bar creates an instance of note prefab depending on which note is meant to be spawned private IEnumerator PlaceBar(List lt SongParser.Notes gt bar) for (int i 0 i lt bar.Count i ) if (IsThereNote(bar i .bottom)) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .bottom, true), new Vector3(bottomLane.transform.position.x distance, bottomLane.transform.position.y, bottomLane.transform.position.z 0.3f), Quaternion.identity) if (bar i .middle ! 0) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .middle, false), new Vector3(middleLane.transform.position.x distance, middleLane.transform.position.y, middleLane.transform.position.z 0.3f), Quaternion.identity) if (bar i .top ! 0) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .top, true), new Vector3(topLane.transform.position.x distance, topLane.transform.position.y, topLane.transform.position.z 0.3f), Quaternion.identity) yield return new WaitForSeconds((barTime bar.Count) Time.deltaTime) So if I were to make start and end markers, the start marker would not know where the end marker is because it doesn't exist. Could anyone help please?


View individual UI Rect boxes when multiple UI elements are selected? I have 2D UI layout with multiple text boxes over the canvas, I need to easily be able to see where the Rect boxes for each are positioned, so that I can see where the safe areas are for placing buttons etc. Selecting each individual item shows its own individual Rect box, but selecting multiple items just shows one big box around all of them. Is there a way of selecting multiple items and see each individual Rect box? It's extremely time consuming having to go and check each one individually.


UnityEditor related classes can not be referenced. Why? I have two classes. Both of them are placed in the editor interface field folder. using System using UnityEngine namespace editor.interface field public class RequiredInterfaceAttribute PropertyAttribute public readonly Type type public RequiredInterfaceAttribute(Type type) this.type type using UnityEditor using UnityEngine namespace editor.interface field CustomPropertyDrawer(typeof(RequiredInterfaceAttribute)) public class RequireInterfaceDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) if(property.propertyType SerializedPropertyType.ObjectReference) var requiredAttribute this.attribute as RequiredInterfaceAttribute EditorGUI.BeginProperty(position, label, property) property.objectReferenceValue EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true) EditorGUI.EndProperty() else var previousColor GUI.color GUI.color Color.red EditorGUI.LabelField(position, label, new GUIContent( quot Property is not a reference type quot )) GUI.color previousColor I have another class. using editor.interface field using UnityEngine namespace interface user.implementations public interface IInterface public class InterfaceUser MonoBehaviour SerializeField RequiredInterface(typeof(IInterface)) UnityEngine.Object interfaceImplementation The RequiredInterface(typeof(IInterface)) line throws the following error The type or namespace name 'RequiredInterfaceAttribute' could not be found (are you missing a using directive or an assembly reference?) Assembly CSharp csharp(CS0246) I can not understand why does not Unity see the RequiredInterfaceAttribute class and how could I make it see it.


Creating Saving and Loading Materials in Runtime I'm trying to create a material during runtime like this In my Assets I have a Render Texture and one Material I created an Script where I attach the Render Texture to Material I save in my project a PNG Image File for later use public void CreateAndSaveMaterial() RenderTexture.active renderTexture Texture2D tex new Texture2D( renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false) tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0) tex.Apply() File.WriteAllBytes(Application.dataPath url, tex.EncodeToPNG()) tempObject.mainTexture tex RenderTexture.active null The PROBLEM 1.The Material works in rutime, after quit playing, the Material resets ( 2.The created PNG File not working only if the file is reimported in Unity, I tried with AssetDatabase.CreateAsset(obj, fileName) AssetDatabase.SaveAssets() AssetDatabase.Refresh() But unsuccessfully, works only in Editor not in build app ( Any suggestions? Thanks in advance!


How can I return the class as a Transform in the array instead of each property? public class TransformInfo public string sceneName public string name public Transform parent public Vector3 pos public Quaternion rot public Vector3 scale Then the method public static TransformInfo LoadTransformInfo() string jsonTransform File.ReadAllText( "d json json.txt") if (jsonTransform null) return null TransformInfo savedTransforms JsonHelper.FromJson lt TransformInfo gt (jsonTransform) return savedTransforms The return is But then when using it var test TransformSaver.LoadTransformInfo() Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info. So I can do for example Transform test1 test 0 Instead make a loop and assign each property from the Test to the new Transform test1.


Leaderboard Testing on Google Play Services I have a shared Google Play Developer account so that he allowed me to publish a game app. Next, I want to know if in order to test the online highscore is to upload the APK and publish it first before adding a new game at the Game Services section. One thing, according to this link and this link on setting up Google Play Services, these tutorials on implementing code for the leaderboard is possibly applied on the Manifest. Is it still the same in Unity if I added the lib folder onto the plugins folder of the Unity project and how?


Unity protect MonoBehaviour derived classes from instantiating via new in C When the class hierarchy grows and you deal with a lot of custom types in your project, it sometimes becomes hard to remember which types are allowed to be created via new and which types are derived from MonoBehaviour and therefore can't be created via new but must instead be attached to the GameObject as a Component. Is it possible to have some safety mechanism for this? The goal would be to have two base classes to control the ability to use new on a certain type. Ideally resulting in a compile time error instead of an easy to miss warning in the console ("You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. Blah blah."). My attempt to make the constructor protected, like this public class UnCreatableBase MonoBehaviour protected UnCreatableBase() using new should be not allowed public static T Create lt T gt () instead this method allows object creation return GameObject.Instantiate (Resources.Load ("Prefabs " typeof(T).Name) as GameObject).GetComponent lt T gt () public class CreatableBase public CreatableBase() new is ok here still allows me to write var whyDoesThisWork new UnCreatableBase() I can access the protected constructor even from an outside scope. Now, the obvious solution would be to make constructors of MonoBehaviour derived classes private. Manually. All of them. Manually. I was wondering if there's a way of achieving the same in a more generic way.


Voxel terrain generation performance problems I am trying to create a minecraft clone to practice some stuff in Unity including Raycasting, terrain generation and player controlls. Terrain is generating without any problem with a perlinNoise. My problem is the then following performance problems. The terrain is only 1 block high with no underlying blocks. Each block constist out of 6 quads with a 64x64 texture. I generate terrain at 200 x 200 size. I can't imagine why 4000 voxels with such simple textures can lag out whilst my pc runs objects with 50k tris and complex textures without any problem. My code ... public int xVoxels 200 public int zVoxels 200 ... for (int x 0 x lt xVoxels x ) for (int z 0 z lt zVoxels z ) voxel script parameter GameObject newVoxel GameObject.Instantiate(voxel) Vector3 position new Vector3() position.x xVoxels 2 x position.z zVoxels 2 z PerlinNoise stripped out for testing position.y 0f newVoxel.transform.position position Solutions I tried Combining meshes Combining all meshes to a single one per material worked wonderfully... until I wanted to interact with each voxel determined by Raycasting from the Camera, I had a raycast hit to the combined mesh and not to my determined voxel Generating the planes myself Instead of using the unity plane object I generated all vertecies myself, same performance problems


How to use a decal logo tatoo texture on a object or character? It appears I've misunderstood the purpose of Standard Shader's "Secondary Texture" options. If I wish to map temporary details to an object, what is the Unity appropriate way to do this? I am referring to effects like the following Tatoos Blood Spatters Logos Decals etc... I'm aware that I could have two materials, but this is render inefficient, and I avoid hackish workarounds when I can. Standard practice? EDIT Per the comment below, I will elaborate slightly In my specific case I'd like to have one of two scenerios 1 Areas where a logo can be inserted (player created), pre uv assigned. 2 Drag drop logo placement, similarly, but without constraints. This would mean of course passing UV boundaries.


How to "merge" multiple intersecting circles so that only the outer edges of each show? In my RTS (In Unity) each unit or building has strategic circles in a similar fashion to SupCom. If you have multiple units or buildings selected it looks like the picture to the left. I want to make it look like the picture to the right, where anything inside the outer edges of their circles is no longer shown. I draw these using vectrosity, mentioning this just in case vectrosity provides a way of doing this, or can be modified to do this. The circles are essentially just an array of points with lines drawn in between them. How would I go about "merging" the circles inside of their overlapping area? This is similar to How to make unit selection circles merge?, however I am not interested in a shader solution. Edit To re explain the above. I'm not seeing how the answers are applicable. I've read through the other thread before posting, which is why I posted it here to avoid this exact thing (being marked as a duplicate). I have an array of points with straight lines in between them to create a circle like effect. This is not a true circle, but a really granular polygon. I am interested in solutions that are achievable in C within Unity, not with shaders or with rendering mechanics. Edit2 Another picture based on one of Roberts suggestions This seems viable, though computationally expensive. If I have a circle made up of 250 points, and 50 circles all intertwined that's 615,500 checks in a worst case scenario.


stop object while falling The object have forwardForce. using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 800f void Start() void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) Now, the issue is I want to stop that object while falling down(not on that ground anymore).The camera will keep running but, I just want to stop that object. Which means if the is not on ground anymore than velocity 0


Is it possible to configure a unity project so it only runs on a device? I am want to give someone a sample Android Unity project and I want them to be able to run it only on a device, not the simulator. Is there a way that I can configure the project so that it will only run on a device?


Sprites do not refresh reimport with ScriptedImporter using the SpriteEditor I've created an importer for Aseprite Files with the ScriptedImporter classes. I'm working on supporting the latest features of Unity like the secondary texture and this should work without bigger issues. The current issue I'm facing is when I change the sprites in the Sprite Editor or from a feature of my own, the asset won't get changed in the project window unless i switch to another folder and switch back. Do I have something wrong in my importing order or is something missing? I tried to refresh or reload the asset in the AssetDatabase but that didn't worked. The OnImportAsset method looks like the following. I implemented the ISpriteEditorDataProvider to support the sprite editor. public override void OnImportAsset(AssetImportContext ctx) name GetFileName(assetPath) aseFile ReadAseFile(assetPath) GenerateAtlasTexture() if (spriteImportData null spriteImportData.Length 0) SetSingleSpriteImportData() GenerateTexture(ctx.assetPath) ctx.AddObjectToAsset("Texture", texture) ctx.SetMainObject(texture) foreach (Sprite sprite in sprites) ctx.AddObjectToAsset(sprite.name, sprite) With the GenerateAtlasTexture method I create a sprite atlas out of the aseprite file. I had to create my own SpriteImportData class because Unitys struct won't get stored through the serialization process and I have to store the import settings of each sprite in a way. The GenerateTexture method uses Unitys own TextureGenerator class to generate the textures or sprites and store them in a instance variable called sprites. Here is the link to the repo. It is currently in the "sprite editor" branch. https github.com martinhodler unity aseprite importer tree sprite editor Thanks a lot


Upon import, isosphere is missing To build my tank for a Unity game, I am using Blender. Currently, I am making a turret consisting of an isosphere with half of the faces removed (I needed the bottom to be "flat") with some minor visual edits, two cylinders (one is the hatch, the other the antenna), and a cube to act as a hinge The inside is hollow. When I imported it to Unity (drag and drop from File Explorer straight to Unity Assets folder), the entire isosphere was missing as you can see from the preview I have tried to correct the normals with CTRL N as mentioned in other Blender forum pages but it still doesn't work. How exactly do I make my isosphere appear in Unity? NOTE This works if imported as a .fbx file but I would much prefer the file to be a .blend file instead (which is default).


Find the coordinates between two points based on third You can see two points in this picture. Points are surrounded by collider which is set to trigger. Points can either be Vector3 or Vector2, shouldn't make any difference. I need to get the coords on gray line if mouse enters the trigger, at the exact point where mouse and gray line form 90 degree angle. Gray line is just an straight line between 2 points. All the data left point coords right point coords mouse coords Is it possible with the data I have and how?


How can i save field member value of Scriptable Object when it changed on inspector at runtime? Class Foo(monobehavior) has a scriptableObject and it is exposed to Inspector. When i change its value on inspector on runtime, it is saved. but when i try to change its value by script on runtime, it is never saved. what the different? and is there a way to save changed value of scriptableObject on runtime? without using json.. or something. Thanks and sorry for my bad english.


Should I scale gravity for small objects? If I am working with objects that are small in real life, but in the Unity world they are scaled larger, should I increase the Gravity with the scale of the objects? For example, if an object of size one would actually be 10 cm across, would gravity scaled to be 10x make the object behave more like a small object would in real life. I know objects fall at the same rate, but the rate is the same so small objects fall more in proportion to their size don't they?


Algorithm to fill a shape defined by 4 pixel points? I'm developing an application in Unity3D where a user can define 4 pixel points on screen, and what I would like to do is fill this shape with pixels using Unity's SetPixel. While I can do this easily for square or rectangular shapes, I was wondering if there is any efficient code or algorithm to do this for more irregular four sided shapes, such as trapezoids etc. Note Filling the shape with a mesh is not an option. So far the best option I can think of is to draw the outline, then draw a line from each pixel point of every outline, to every other outline point, but I'm not sure that's very efficient.


2.5D platformer how to darken building edges? I was wondering how I could go about creating a vignette type effect some sort of volumetric shadow for the 'cross section' parts of a 2.5D level. The effect I'm going for can be seen in 'This war of mine' where the edges of the rooms and walls floors that are facing the camera have been darkened and blurred. (see below). I thought about creating the edges in photoshop and then blurring them and putting them in, however the blur scales weirdly as I'm re scaling the sprites so it looks really fake and not like a visual effect. Is there perhaps a 2d shader I could use or make? Any help on this would be appreciated! Cheers My photoshop attempt to recreate


How to change transform.position code to Rigidbody.AddForce? Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF vec.y camR vec.x) Time.deltaTime MoveSpeed That's how i do my movement, but i need to change it to Rigidbody.AddForce 'cause the way that i use right now makes my character doesn't collide with objects perfectly. Note What i mean with "perfectly" is, if you walk to the corner of walls, you can pass through it and that's the thing that i want to prevent.


What are my options for building a centralized server architecture for a Unity game? I have made in the past multiple offline game, and would like to make my first online game. I have very basic knowledge of server structure. The game is a multiplayer RTS game, with ONE server (If possible in c ), where player can build base, attack other player and move around a world. it is in real time, but slow paced, so not many actions, and every time a user make movement it take let's say an hour to move. The game is planned for Android iOS and (maybe) but not at all for the moment, web. The game itself is easy, but the server I don't know where to start and I have been struggling in the last 3 days to find a informations and answer to my question. Most of the example I found are P2P client hosted server, this do not apply to my case, I want a single server that runs outside of Unity and that I can run on a computer as stand alone. My question problems are. 1) for a mobile game, I have seen in some post that UDP TCP Socket are not available in 3g? is this true ? If so, what should I Use ? I was thinking of websocket since MAYBE i make a web version, but I don't know if it's a good idea, and apparently it is not built in in Unity. 2) Related to my 2) is there any c library that work in Unity and would fit my game needs? a user would probably load a map, and interact around 20 times with the server during the gameplay. I believe a simple server that get and send message only is largely enough, but I don't know what to use. Start from scratch? then what should I use, TCP ? Socket? WebSocket ? 3) Should I use photon ? I've seen is free to test until 20CCU, and since for probably the next 6month I will be alone on it it's OK, then at release let's say I have 100 player, is not that expensive. Is it a viable solution? I found it a bit overkill for my needs, but it looks documented and easy to start. Will I still learn stuff if I "cheat" like this? Thank you for your time


How can I stop Substance's runtime texture caching? Procedural textures with the Substance Engine seem to update very quickly if you turn off caching, modify one exposed variable at a time, modify it frequently, and even then only after you've attempted to modify it 2 or 3 times. However, I want basically the opposite. For example, units have a "blood" variable that generates blood differently on them as they take damage, as well as a "battle wear" variable that generates scratches and dents, but doesn't revert when they heal. So to force a variable not to cache, I have to set it to some dummy value, then back to normal, then call RebuildTexturesImmediately. How can I tell Substance not to cache a variable at runtime, so I can change it once and have the texture regenerate quickly?


Unity3D How to play 360 video without VR mode? i followed the official Unity tutorial to make an inverted sphere and play a 360 video inside it and i managed to do it but the problem is i can't build the project to my phone because it says i have to turn on virtual reality support from player settings but the thing is i don't want to because when i do that it also turns on VR mode(that split screen view). what i want is to play a normal 360 video(full screen) and navigate using the gyro of phone just like Youtube. Youtube provides a button to toggle between headset and non headset mode.


How to change object curve path in playmode in Unity? I would like to make some sort of this simulation below, where user can interact with the white rod and drag it into the magnetic fields, which in resulting the blue line that represent the magnetic field of the permanent magnet to move in semi circular motion. I managed to get that kind of effect using animation I wish I do not have to make an animation for it by manipulation path for the sphere to be automatically correcting it's own path after colliding with the round object since the sphere will suddenly moving faster than usual when colliding with much bigger round object. I have tried using splines etc, but most tutorial I've seen are not editable in play mode, which is I cannot alter any of the curve values inside my script. So can anyone could provide me some insight or another better alternative than this? I've been stuck here for three days now. Thanks! EDIT


Change item rotation axis in inventory item visualization I'm learning unity and i'm trying now make an inventory, i made a simple interface, and now i'm trying to make a item visualization. I look for some codes from web and i found this one using UnityEngine public class TurnObject MonoBehaviour protected Vector3 posLastFame public Camera UICam Update is called once per frame void Update() if(Input.GetMouseButtonDown(0)) posLastFame Input.mousePosition if (Input.GetMouseButton(0)) var delta Input.mousePosition posLastFame posLastFame Input.mousePosition var axis Quaternion.AngleAxis( 90f, Vector3.forward) delta transform.rotation Quaternion.AngleAxis(delta.magnitude 0.1f, axis) transform.rotation I know some code, but I'm not good with geometrics. In this code when I move my mouse horizontal way, my object turn in the Y axis. And that's good. But when I move my mouse vertical the object move in the X axis instead of Z axis. Is there a way in this code for change this? I really have difficulty to understanding geometrics in Unity.


Help with Javascript touch button I tried many buttons but I can't connect them with the (Java)Script. So I made 2 gui buttons one for jump which was easy because I have an if statement and if it's true then jump. But I have problems with the crouch button. Bellow is my script but I can't figure out how I can do this from Update in function Gui. (Or if you know how to connect buttons with JS functions, please tell me it's always a better option D ) This is my script pragma strict private var tr Transform private var dist float distance to ground function Start() tr transform var ch CharacterController GetComponent(CharacterController) dist ch.height 2 calculate distance to ground function Update() var vScale 1.0 if (Input.GetKey("s")) vScale 0.5 var ultScale tr.localScale.y tr.localScale.y Mathf.Lerp(tr.localScale.y, vScale, 5 Time.deltaTime) tr.position.y dist (tr.localScale.y ultScale) function OnGUI () if(GUI.Button(new Rect(15, 330, 200, 100), "Shrink"))


How to switch between sprites in Unity So I made an empty game object in inspector, called it "squareTest", and I clicked and dragged 3 sprites in. One is the square being black, one is the square being red, and one is the square being green. What I want to do is this In the code, it starts by default as the black sprite. Whenever 'x' happens, the sprite changes to the red square. And whenever 'y' happens, it changes to the green square. BTW, x and y could mean anything. I just want some logic to it, as in if (password "Open sesame") Change square color My game programming experience is from Pygame, and this problem could have been solved like this (using a sprite sheet that goes from left to right) if Condition square spritesheet.current frame 5 screen.blit(square spritesheet.texture, (x, y), (self.current frame self.frame width, 0, self.frame width, self.frame height)) screen.blit goes (image, (x, y), (start chopping X, start chopping Y, end chopping X, end chopping Y) Unfortunately, I do not have a clue how this could be accomplished in Unity. I do not know if this is possible with an animator controller. I just want to know if this is possible, and how it could be achieved, with or without an animator. Thank you very much! The different colored squares are different textures, and I do not need transitions between states.


Quaternion.LookRotation with Joystick I am having an issue i cannot seem to figure out within my code. What this code does at the moment is that it rotates the 3D Model around the z axis but i need it to rotate around the y axis. Any help would be greatly appreciated. void Update () Vector3 moveVector (Vector3.up joystick.Horizontal Vector3.left joystick.Vertical) if (joystick.Horizontal ! 0 joystick.Vertical ! 0) transform.rotation Quaternion.LookRotation(Vector3.forward, moveVector)


Get all OffMeshLink objects in Unity What I'm trying to do is to make an edit mode script that gets all off mesh links and makes some of them bi directional(depends whether a jump is possible). My (obvious) attempt was FindObjectsOfType lt OffMeshLink gt () However, it returns only the links I have created manually. My question is the following how to access the off mesh links generated by unity in the baked NavMesh? Any help would be greatly appreciated.


Find position in arc depending on the direction of the agent So what I am trying to do is to find a random point on the (green quot ) arc around the enemy Sorry for the bad drawing but Red (no go) Green ( Points the allied can go to) I know that unity has the following function Radius 5 randomDirection (Random.insideUnitCircle target.position).normalized Vector3 finalPosition target randomDirection Radius However, this is for a full circle. How can I achieve the closest half circle?


Visually updating the position of a game object controlled by an animator controller I have a game object that is controlled by an animator controller. In order to activate the next animator state, the user is supposed to grab this game object, and then move it from Point A to Point B. As a test, in said game object's Update() method, I added the following line this.transform.localPosition Vector3.up When running the game, I can see that the y coordinate of the game object's position increases every single frame, just as intended. However, visually, the game object's position is not changing at all it remains in the same place all the time. What should I do to ensure that game object's position is also visually updated? EDIT Here are the properties of the animator I am using EDIT If relevant, here is the skinned mesh renderer for said game object


Unity3d High level literature Is there any high level literature for mid professional programmers for Unity? There are a lot of tutorials for beginners, but I can't find anything about main API, pipeline or engine architecture. Recommend, please!


I need to access a variable from another script in Unity I have been trying to aimlessly make a unity game around a 3d aim trainer and I have been trying to set up the targets that pop up. For now, I just wanted to create targets that pop up once every second at a maximum of 3 targets at one time ever. I have already set up the random spawn of the targets and the removal of them with the help of raycast shooting and made a max of 3 targets, however, to make the max of 3 targets I used an integer with a simple targetCount 1 and the deletion of the target is being done on a different script as seen below. My problem is making the targets respawn once being shot after spawning the first 3 targets. I tried to use getComponent to reach the targetCount variable in my Target code to just simply targetCount 1 every time I delete a target so that as long as the variable doesn't reach 3, it will continue to spawn targets however I was having some troubles. Please let me know if you have any ideas This is my target spawning code using System.Collections using System.Collections.Generic using UnityEngine public class GenerateEnemies MonoBehaviour public GameObject theTarget public float xPos public float yPos public int targetCount 0 void Start() StartCoroutine(TargetDrop()) IEnumerator TargetDrop() while (targetCount lt 3) xPos Random.Range( 6, 11.5f) yPos Random.Range(2.4f, 9) Instantiate(theTarget, new Vector3(xPos, yPos, 13.5f), Quaternion.identity) yield return new WaitForSeconds(1) targetCount 1 And this is my Code attached to my target using System.Collections using System.Collections.Generic using UnityEngine public class Target MonoBehaviour, IDamageable SerializeField private TargetStats targetStats private int currentHealth public GenerateEnemies generateEnemies private void Awake() generateEnemies GetComponent lt GenerateEnemies gt () private void Start() currentHealth targetStats.maxHealth public void DealDamage(int damage) currentHealth damage CheckIfDead() private void CheckIfDead() if(currentHealth lt 0) Destroy(gameObject) GenerateEnemies.targetCount 1


AudioClip is empty saving recording from Microphone EDIT I updated the code to what I have currently. I'm not sure why but, the editor and my platform complained when I put the WWW in a co routine, it seems to load the audio clips to the object but I cannot play them. In a script attached to the object I wait until the Audio Clip is loaded before I try to play it. So I am trying to record some Audio through the microphone and then save an AudioClip to the disk as a .wav file and also save the filepath as a playerpref and then later I can come back and load the string into a url but, for some reason the Audio Clip doesn't get loaded properly as I can see that there is an audio clip on my audio source in runtime but, it has no name and it has no sound on it. However, when I press play in the inspector I can hear my sound I am using SavWav.cs to save my audio clips to .wav files. Here is the url(filepath) I am sending to my load method string filename string.Format( "CapturedAudio 0 n.wav", Time.time) string filepath Path.Combine(Application.dataPath, filename) Here is the method I am using to get the AudioClip private void SpawnObject(string savedNames, Vector3 savedPositions, Quaternion savedRotations) GameObject cubeToSpawn Instantiate(cube, savedPositions, savedRotations) WWW www new WWW("file " savedNames) cubeToSpawn.GetComponent lt AudioSource gt ().clip www.GetAudioClip(false, false, AudioType.WAV) The obj is just a cube with an AudioSource attached to it that I instantiate prior to calling this method above. The filepath works fine for saving but, for some reason it doesn't want to load the audio clip. Any help would be greatly appreciated.


Code optimalization Mass selecting units (RTS) Yo fellow game developers! So recently gamedev became my favorite hobby and I started working on my RTS game module which would then let me create different RTS games with just few changes (W3 inpiration 3). Anyway I am new to optimalization since my previous games had quite serious optimalization issues so I need your help with a pieace of code! I am having a mass selection of units with drawn rectangle on screen. I've got it all worked out but now I am wondering if there could be anything done about optimalization for cycling through list of units every time my mouse position changes even for a little bit. This is inside my Update function. There is much more in there so i cut it out but this is the piece I am worried about void Update() ...previous code blah blah blah... if (Input.GetMouseButton(0)) oldPos2 point2 point2 Input.mousePosition if (oldPos2! point2) performance optimalization Debug.Log ("Performing selection") if (Vector2.Distance(point1,point2) gt selBoxIniDist) isSelecting true foreach (var item in Game.Units) if (IsWithinSelectionBounds (item.gameObject)) item.Selected true else item.Selected false ...rest of the code here... So as i told you, there is no problem with the code. I just need your opinion if there could be any changes especialy to this part of the code. Or maybe general advices for optimalization. Even tho I am checking every update if the mouse moved (so I dont cycle every update) I still feel like checking every "milimeter" 5 times if any of the units are contained in the viewport rectangle is a little bit overkill just for the selecting units. At the end of selection I usualy end up with around less than 100 cycles. What do you think? EDIT I might as well add a method that checks if the unit is in the viewport bounds and a utility method that calculate the bounds. Just so you why I am worried about performance. Checking if bounds contain unit public bool IsWithinSelectionBounds( GameObject gameObject ) if (!isSelecting) return false var camera Camera.main var viewportBounds Utilities.GetViewportBounds( camera, point1, point2) return viewportBounds.Contains(camera.WorldToViewportPoint(gameObject.transform.position)) Static utilities public static Bounds GetViewportBounds( Camera camera, Vector2 screenPosition1, Vector2 screenPosition2 ) var cam Camera.main var v1 cam.ScreenToViewportPoint( screenPosition1 ) var v2 cam.ScreenToViewportPoint( screenPosition2 ) var min Vector3.Min( v1, v2 ) var max Vector3.Max( v1, v2 ) min.z camera.nearClipPlane max.z camera.farClipPlane var bounds new Bounds() bounds.SetMinMax( min, max ) return bounds


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


Populate triangles array when you already have sorted vertices array Input is a Vector3 of verticies. Length is unknown, it could be anything above 2 so these vertices form all kinds of multifaceted shapes with 3 being a triangle and 6 hexagon ish. Poor example to visualize vertices Vector3(..), Vector3(..), Vector3(..), Vector3(..), Vector3(..) Coordinates in that array are ordered counterclockwise. I also have the coordinates of center point that these verticies form (look at illustration below) it doesn't have to be used but if it helps.. Few examples of which shapes can occur and which cannot Now I need to build meshes out of them. For each shape I need Vertices array (which I already have, nicely ordered) Triangles array 3 indices (from vertices array) per triangle until all vertices are covered How to populate triangles array with these relatively easy shapes where each vertex has "direct line of sight" to every other vertices? Number of vertices is unknown of course.


Lerp UI Color outside update method? I'm able to Lerp the color of a UI panel within the Update method. However I'd like to trigger behavior a single time when needed. If I put it in a method and call it it only changes for a brief time and doesn't fully complete. I could probably set a bool flag within the update method but that seems sloppy.


ScriptableObjects events execution order? Given the code CreateAssetMenu(fileName quot newGameManagerInstance quot , menuName quot Game Game Manager Instance quot ) public class GameManagerSO ScriptableObject private GameManager instance public GameManager Instance get return instance set instance value private void Awake() Debug.Log( quot 1 quot ) private void OnEnable() Debug.Log( quot 2 quot ) private void OnDisable() Debug.Log( quot 3 quot ) private void OnDestroy() Debug.Log( quot 4 quot ) I have two questions Why the output in console when I enter play mode is quot 3 quot and then quot 2 quot ? Shouldn't OnDisable be executed after OnEnable? I'm using this scriptable object to hold an object reference only (I don't have the need to serialize the object, it's just a handy way I found to pass that reference through scenes without committing to singletons) can I code all initialization code for the object in OnEnable method? Can I assume it will always execute before any MonoBehaviour read it? Also


Quat.AngleAxis broken on one axis I have a scene in my game where you create your own designs by placing static meshes and manipulating their scales, positions, and rotations. For the rotations I'm using Quaterion.AngleAxis as so if (toolMode PositioningTool.Rotate) switch (grabbedCollider.transform.name) case "X" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.right) break case "Y" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.up) break case "Z" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.forward) break where delta is the mouse movement for that frame, focus is the object I am manipulating, and transform is the transform component of the ToolArm that the player interacts with. toolarm.position is set to focus.position every frame my problem arises when I try to do a rotation on my x axis. my other axis will spin 360 and beyond, spinning in circles endlessly. when x axis is used, it only rotates from 90 to 90 (as seen in the unity editor). What am I doing wrong?


How to render a grid of dots being exactly 1x1 pixel wide using a shader? I would like to render a grid with many dots, all equally spaced and being exactly 1 pixel wide. What I was able to achieve so far is this What I would like is (simulated using image editing program) Here is the shader I wrote (which give result of 1st image). This is rendered as a giant quad. Shader quot Custom Grid quot SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct vertInput float4 pos POSITION float4 uv TEXCOORD1 struct vertOutput float4 pos SV POSITION float4 uv TEXCOORD0 vertOutput vert (vertInput input) vertOutput o o.pos mul(UNITY MATRIX MVP, input.pos) o.uv input.uv return o fixed4 frag (vertOutput output) SV Target float4 uv output.uv float x step((uv.x 100.0 0.025) 1.0, 0.05) float y step((uv.y 100.0 0.025) 1.0, 0.05) float c min(x, y) return float4(c, c, c, 1.0) ENDCG Is it possible to achieve what I want using a shader ? What is needed from first draft is to control the size of each dot. I have tried to use partial derivatives (ddx and ddy) but was not able to make it work.


Synchronize objects' movements moved by coroutine function I'm using Unity version 5.3.5. I'm having problems to synchronize the movement of three different objects from point A to point B and vice versa. To move the objects I use the following code public float time public Vector3 endPos private Vector3 startPos void Start() startPos transform.position void FixedUpdate() if(transform.position startPos) StartCoroutine(Move(gameObject.transform, startPos, endPos, time)) if(transform.position endPos) StartCoroutine(Move(gameObject.transform, endPos, startPos, time)) public IEnumerator Move(Transform thisTransform, Vector3 startPosition, Vector3 endPosition, float time) float i 0f float rate 1 (time) while(i lt 1) i Time.deltaTime rate thisTransform.position Vector3.Lerp(startPosition, endPosition, i) yield return null As long as all of the objects have the same "time" value, their movements is correctly synchronized regardless the distance that they have to cover. The problems arises when they all have different "time" value. For example, if they have to move backwards and forwards from startPos(0,0,0) and endPos(5,0,0) with the following "time" value Object A time 1 second Object B time 2 second Object C time 4 second After 4 second, they should all be again at the same start position. However, what happen is that the fastest object (Object A) has a delay over the other two and this delay increase over time. How can i fix this problem?


How can I keep two racing players synchronised? I am working on a Unity mobile game, much like a multiplayer version of Temple Run. I'm seeing a fluctuating network latency (generally 200 500ms) because of the mobile platform. The two player characters are shown as running along the same path and must do simple actions (jump, slide, powerup, etc.) to pass obstacles. When a message comes late, the game assumes the remote player passed an obstacle. This usually works well, but in case a player is killed by an obstacle, I want the remote player to appear to die on the same obstacle position as local player. Due to latency, the remote player appears to have crossed the obstacle before the message announcing their death even arrives. How can I keep the players synchronised? I tried moving the remote player back to the local players death position immediately as the death message arrives, it looks awkward visually and might raise other syncing issues.


How can I implement a more realistic momentum system in Unity 4.5? I'm just starting out with Unity and am making a simple environment where there is a sphere and a ramp. When the sphere approaches the ramp everything is fine. As soon as the sphere hits the ramp is where I'm having trouble the velocity is instantly reduced and when it goes off the end of the ramp, instantly returns to the velocity as though it were on the ground. I'm not sure if this can be changed by some settings in Unity or I would have to write some code. Here's the physics code I have so far (in C ) public class PlayerController MonoBehaviour public float speed void FixedUpdate() float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rigidbody.AddForce(movement speed Time.deltaTime)


Rotate smoothly object to angle (Y axis) of the collided object Well, let's say I have two planes, one which I am moving, and another one that I collide with, that has a different y rotation. I want to make that, once both planes collide, the plane the user controls changes it s rotation to the collided plane rotation.I ve achieved it simply equaling both planes transform.rotations, but that was just a testing, i would like to rotate the plane smoothly. I have tried with eulerAngles, and Quaternion.Lerps, but it doesn t work, or I am not following well the sintaxis. I know that a rotation and the eulerAngles are different values. There seems to be a solution with the dotween scripts, but I would like to learn the right approach to do it, rather than make it directly with dotween. Here I paste the trigger enter code, with the methods I tried (are commented). I guess that the rotation origin would be another issue. void OnTriggerEnter(Collider col) if (col.gameObject.tag "Plane") Debug.Log ("Yup...Angle " col.gameObject.transform.rotation.y) this.transform.rotation col.gameObject.transform.rotation newAngle 0 (this.transform.eulerAngles.x, col.gameObject.transform.eulerAngles.y, this.transform.eulerAngles.z) this.transform.eulerAngles(newAngle, 2 Time.deltaTime) this.transform.rotation Quaternion.Lerp (this.transform.rotation, col.gameObject.transform.rotation, Time.deltaTime 0.1f)


How do I make night cycle like Dino Chrome? I want to add a day night system cycling to my runner game like the game Dino Chrome. The condition is when the score reaches 100 it will be night then when it reaches 100 again will be day. I tried with this code but nothing changed in my game if ( GameManager.instance.score 100 0) fadeToBlack !fadeFromBlack if (fadeToBlack) cam.backgroundColor new Color(Mathf.MoveTowards(cam.backgroundColor.r, 1f, fadeSpeed Time.deltaTime), Mathf.MoveTowards(cam.backgroundColor.g, 1f, fadeSpeed Time.deltaTime), Mathf.MoveTowards(cam.backgroundColor.b, 1f, fadeSpeed Time.deltaTime), cam.backgroundColor.a) if (fadeFromBlack) cam.backgroundColor new Color(Mathf.MoveTowards(cam.backgroundColor.r, 255f, fadeSpeed Time.deltaTime), Mathf.MoveTowards(cam.backgroundColor.g, 255f, fadeSpeed Time.deltaTime), Mathf.MoveTowards(cam.backgroundColor.b, 255f, fadeSpeed Time.deltaTime), cam.backgroundColor.a) Eventually I want to change all game object colors via script with smooth, but for now I just want to apply a change to the camera background. and this is my whole script public static ObstacleManager instance private void Awake() instance this public float maxTime float timer Header( quot CommongObstacle quot ) public GameObject Obstacles Header( quot BirdObstacle quot ) public GameObject buwungObstacle Header( quot MeteorObstacle quot ) public GameObject Meteor public Transform spawnpoint int choosedSpawnMeteor int choosedObstacle Header( quot NightCycle quot ) public float fadeSpeed 2f public bool fadeToBlack, fadeFromBlack public Camera cam Start is called before the first frame update void Start() cam GetComponent lt Camera gt () Update is called once per frame void Update() if ( GameManager.instance.isStarted) timer Time.deltaTime if (timer gt maxTime) GenerateObstacle() if ( GameManager.instance.score gt 400) GenerateBuwungObstacle() timer 0 if ( GameManager.instance.score 100 0 amp amp activeFade null) fadeToBlack !fadeToBlack Color color fadeToBlack ? Color.black Color.white activeFade StartCoroutine(FadeTo(color)) kelipatan 200 public void GeneratedMeteorObs() choosedSpawnMeteor Random.Range(0, spawnpoint.Length) GameObject meteorGo Instantiate(Meteor, spawnpoint choosedSpawnMeteor .position, Quaternion.identity) public void GenerateObstacle() choosedObstacle Random.Range(0, Obstacles.Length) GameObject obstacle Instantiate(Obstacles choosedObstacle ) public void GenerateBuwungObstacle() choosedObstacle Random.Range(0, buwungObstacle.Length) GameObject obstacle Instantiate(buwungObstacle choosedObstacle ) Store the fade in progress (so we don't accidentally double start it) Coroutine activeFade Perform a fade over time, then clear the activeFade variable when done. IEnumerator FadeTo(Color destination) Color start cam.backgroundColor for (float t 0 t lt 1f t Time.deltaTime fadeSpeed) cam.backgroundColor Color.Lerp(start, destination, t) yield return null cam.backgroundColor destination activeFade null


RPC's in Legacy Unity, what to use in Unity 5.1? I have created a small experiment in 5.1, a server has an AI character pathfinding around a map over a grid, so its a straight line node to node before it reaches the end. I would like for the client to also view this pathfinding character. Using the networking scripts built in it sends fine, however the client see's a stuttering character and not something smooth like the server sees. So my solution to this is that when the server calculates the new node for the character to go to that the location of this node is sent to the client, the client moves its character to the node and so on. So instead of constant transform data being sent, the clients AI can go to the node and wait for the next node location to be sent, therefore being smooth. In previous versions of Unity I would've used RPC's, but this is labelled as Legacy now, what can I use now to send a node location from the server to the client?


Unity how to remove standard sky but keep the lighting? How can I remove the standard Unity sky (to have an empty space with no texture around my scene), but keep all the lighting effects from it?


How to add time delay in Unity C So I'm trying to make a camera zoom in, but Thread.Sleep doesn't work. Here is the code void Start() for (int a 0 a gt 1000 a a 1) Debug.Log( quot Done! quot ) Thread.Sleep(100) The error code is this Assets StartScene CamScript.cs(12,13) error CS0103 The name 'Thread' does not exist in the current context


Set a minimum distance with navmeshagent I am totally newb. How to set a minimum distance between AI chasing a player if AI has navmeshagent if (Vector3.Distance(transform.position, target.position) gt minDistance) enemy.destination player.position What I need is it works similar to this code below if (Vector3.Distance(transform.position, player.position) gt minDistance) transform.position Vector3.MoveTowards(transform.position, player.position, moveSpeed Time.deltaTime) But using destination property or SetDestination