Is my collision free location script working? I've recently been learning C and I wanted to take one of my 2D tutorials to Unity. I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction generated random location, calculating Vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors. But, because I'm still only just learning C , I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something? Vector3 spawnLocation new Vector3 (Random.Range (minSpawnX, maxSpawnX), Random.Range (minSpawnY, maxSpawnY), Camera.main.transform.position.z) Vector3 spawnPoint Camera.main.ScreenToWorldPoint (spawnLocation) Vector2 lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Vector2 upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) ! null) spawnPoint.x Random.Range(minSpawnX, maxSpawnX) spawnPoint.y Random.Range(minSpawnY, maxSpawnY) lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner)) I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working. I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.


Render Occluded pixels to gray color In 3d space, objects can be occluded by another objects. By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn. But, sometime we need to render the occluded object or pixels for game play. To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels. This is the sample images for the case. I guess this can be achieved by some sort of shader. How can I make this effects in Unity 3D Engine? Any hints or idea plz.


Is there a way to turn collision detection system off completely in Unity? My world setup is 2D Top Down. All collisions are disabled from the collision matrix. There are no collisions in the scene as I wanted, but as I perceive, Unity is still trying to calculate collisions in the background. So I'm experiencing serious frame rate drops because of Physics2D.Simulate when I have about 2k colliders moving over each other on the scene. I followed the suggestions about colliders and rigidbodies on the API exactly (so I know the stuff about not to move static colliders without rigidbody, that's not the case here), but I somehow can't manage to tell Unity that I don't want her to calculate "possible" collisions. I only want colliders for Raycast2D, OverlapCircle and making movements a bit realistic. Thanks in advance for all suggestions.


MCS character mouth open is this mo cap animation problem? I have MCS Female Character where I can assigned Mocap to my character. I have downloaded mixamo animation and assigned this to the character but the problem is, the character mouth remains open. I am not 3d artist or animation guy, so here are my question. How can I solve mouth open problem in unity? What is the reason that mouth is open? Either mocap data has open the mouth or what else problem?


How to reduce lag when rendering 40,000 sprites in Unity? I am attempting to render 40,000 sprites a grid of 200x200 with each grid node having a sprite renderer. All the way zoomed out I get about 20 frames per second. What would be the best way to optimize this? Eventually I want to have an even larger grid. The grid has to be changeable mdash I need to be able to change the ground floor for that specific grid node.


Regarding Profile Pictures of Facebook Friends Background I am creating a Leaderboard of Facebook friends in unity. Question Can we download and save the images of Facebook Friends on the device of the user for the purpose of reuse? I would like to store the images of the FBFriends on the user's device so that there is no need to download the same pictures everytime the game is restarted. Is it legal to do so? I asked the same question in Facebook Developers forums but I did not get any response. Kindly guide me. How do devs build a leaderboard of Facebook friends normally? Thankyou.


How can I toggle enabled on a specific script within an object in Unity? I have the CarController script inside my car GameObject. I need to set it to disabled at the start so the countdown timer can start the race. I thought I knew how to do it but once again I have failed Any ideas why this doesn't work?? void TogglePlayerEnabled(bool b) playerCar.GetComponent lt CarController gt ().enabled b void ToggleAiCarEnabled(bool b) aiCar.GetComponent lt CarController gt ().enabled b If I use a print line saying "Toggled" or something, that appears in console as expected. But the CarController script seems like it stays active as both me, and the AI car can just drive whilst the countdown is happening still. Here's the full class public class GameManagerControl MonoBehaviour public GameObject playerCar public GameObject aiCar public int sceneChangeZValue private string countdown "" private bool showCountdown true Use this for initialization void Start () Update is called once per frame void Update () TODO This will change the scene when the track ends. if (player.transform.position.z gt sceneChangeZValue) SceneManager.LoadScene("race track lake") if (showCountdown) StartCoroutine(GetReady()) call this function to display countdown IEnumerator GetReady() countdown "3" TogglePlayerEnabled(false) ToggleAiCarEnabled(false) yield return new WaitForSeconds(1.5f) countdown "2" yield return new WaitForSeconds(1.5f) countdown "1" yield return new WaitForSeconds(1.5f) countdown "GO" TogglePlayerEnabled(true) ToggleAiCarEnabled(true) yield return new WaitForSeconds(1.5f) showCountdown false countdown "" GUI void OnGUI() if (showCountdown) GUI.color Color.red GUI.Box(new Rect(Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box(new Rect(Screen.width 2 90, 75, 180, 140), countdown)


Player with Character Controller and children colliders won't collide properly I have a player that consists on a root object with the Character Controller attached and some children with its components. Those have box colliders attached. When moving the player I want to be able to collide with other objects using the box colliders, but it won't, instead it will only collide with the Character Controller. As you can see in the image, the red object didn't stop when the collider crashed with the framed cube, but it did when it did with the Character Controller. There is any way to use the player colliders instead of the Character Controller for collision detection?


How to make a script on a prefab act on a particular scene instance? I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it. Actionables are prefabs, which have an Actionable component, with the same setup (at the moment). Once the player is happy with the location of their Actionable, they click LMB, which activates onClick callback, which is supposed to call Planet.Build(), which adds the Actionable on the Planet permanently (saves it into an internal array). I also have a quot Turn Off quot Button, which calls stopBuilding() when clicked, disabling the preview placement. When stopBuilding() is invoked by the button click, everything works as expected. I also want to be able to call Planet.stopBuilding() (which, by removing the actionableModel, disables hover preview on the Planet) from Planet.Build(), such that the player does not need to click the Turn Off button described above after building an Actionable. Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly. How do I access the scene object Planet from Actionable prefab? Here is my Planet and its stopBuilding method so far public class Planet MonoBehaviour private GameObject actionableModel ... public void stopBuilding() For debugging only Planet planet GameObject.Find( quot Planet quot ).GetComponent lt Planet gt () Debug.Log(planet.actionableModel) Debug.Log(this.actionableModel) And here is the Actionable component which has a UnityEvent property onClick, which calls stopBuilding() on a click event. public class Actionable MonoBehaviour public class OnClick UnityEvent lt GameObject gt public OnClick onClick new OnClick() ... void OnMouseDown() onClick.Invoke(gameObject)


How to handle back press in Unity? By back press on Android, I want to close all the open windows first then exit the game, I see everywhere it's suggested to check input key in Update void Update() if (Input.GetKey(KeyCode.Escape)) if (AreAllWindowsClosed()) Input.backButtonLeavesApp true But my issue with this is that it's calling the code in every frame and also may handle a single press multiple times! Isn't there a single BackPressed event in Unity for this simple task?


How can I make billiard without using Rigidbody? Unity's physics engine isn't deterministic (ie. the results aren't always the same on all computers) so I haven't Idea that how billiard games Implemented.Is there a way to Implementing fake and deterministic physic in unity? I mean I want to make billiard without using Rigidbody http www.bezzmedia.com swfspot tutorials flash8 8 Ball Pool I found this open source project that didn't use physic! this is what I need but unfortunately it's full c and I haven't enough time to convert it to c http downloads.sourceforge.net foobillard foobillard 3.0 win32 2 bin.zip


Velocity and drag in unity So I have an object that is bouncing around the screen randomly, physics still works on it so it will speed up or slow down depending on what it hit and when. To try to normalize the speed I want to apply force or drag when ever it goes above or below the thresh hold. My question is, do I need to make note of the direction the object is moving to add force? Or can I just add force to the way it is currently traveling?


Collision and changing the scene. C I'm running into a problem where I want to create some code that such that if an object (Cube) is destroyed, it to changes to another scene. Here is my code public class Move MonoBehaviour void playerWalk() var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) void OnCollisionEnter(Collision col) if (col.gameObject.name "Cube") Destroy(col.gameObject) void Update () playerWalk() if (Input.GetKeyDown(KeyCode.B)) print("hello") What do do I need to do?


Difference in light between Unity 5.5.2f1 and Unity 2019 The lighting is different between Unity 5.5.2f1 and Unity 2019. Please see the attached image. I dislike the way the lighting is done in the 2019 version. Both verions are installed out of the box, without any additions. What do I need to change set up inside Unity 2019, in order to have the exact lighting as in 5.5.2f1 version?


Masking cameras for Voronoi splitscreen I would like to mask a camera to only render to a certain (non square) region of the screen, to be used as an overlay, for splitscreen, or any other application. The goal is obviously to prevent any unnecessary rendering from that camera, so I specified performance, but I'm also happy to hear the easiest to implement option as well. What I'm considering so far Stencil shader on a mesh in front of the camera but my understanding is that doing so would require modifying all shaders on world objects, which isn't ideal. Is there an easier way I'm missing? Transparent mesh with a cutout I could cut out a hole in a mesh and the solid part would block rendering of objects behind it, but I'm not sure how to make that part be transparent so other things can render I'm using Unity 2019 LTS and the built in render pipeline I feel like there must be a simple answer I'm missing but maybe I'm wrong?


Why is there such a difference in between my scene and game? Here I have 2 screenshots of my problem By the way my water shader works with Screen position and Scene Depth. I can include them here if needed. Here is my shader(GoogleDrive) Added Now it looks like that when I move window quot game quot to the side Added Here's graph's screenshoots P.S. I think it's something in unity's settings but not in shaders(not sure).


How to create a correct Unity package copy, which will not be replaced when you import? I create a "Package 1" consisting of section A (unique) section B (which will be repeated in all my other packages). This package works correctly is he is alone. Next, I create a "Package 2" consisting of section C (unique) Section B (from Package 1). To save time, I replaced the texture maps in the materials belong to old section A parts and replace this part on section C (directly on models in the Mesh.) I renamed most objects in the scene and in the package as a whole. I delete all prefabs of section A and create prefabs section C , because they are not pick up name changes. The prefabs of section B , I left as is. Now when I import Package 2 in the scene that already contains the Package 1 , it begins the mess Package 1 Files are replaced by Package 2 , even them are named differently. How to avoid it? I can t create each scene from scratch, unfortunately it will lead to the insane time consuming. Huge thanks for your support!


How can I create a copy of an object in Unity? I'm new to unity. How can I make some copies of my GameObject in Unity by scripting? I have tried this by the way public GameObject stone 3 void Start () for (int i 0 i lt 10 i ) Instantiate(stone 3, new Vector3(i 2.0f, 0, 0), Quaternion.identity) I can't really understand why it's not working.


Customising character appearance though textures At the moment I am contemplating adding character customisation to my game, however I am unsure what approaches are available when it comes to using textures decals to add facial features (like facial hair, hairstyle, scars blemishes etc). The character in question is stylised with a cel shader like effect. So what are some approaches to take? Should I be using shaders to blend textures together by having the normal diffuse texture and then a mask texture to add facial hair or are there better more efficient results to achieve what I want? Would another possibility be to use a shader and then bake the resultant blended texture to a new diffuse texture and use that? To clarify, the customisation will be through textures only and not through adding changing meshes


Does destroying object at List element make it null? I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it? My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null? I've tried reading about this but it's hard to find an exact answer. Thanks for the help. For reference, here is the code that I came up with based on my current assumptions about lists public List lt BasePickUp gt pickUpQueue new List lt BasePickUp gt () public bool pickUpActive false void Update () if (pickUpQueue 0 ! null amp amp !pickUpActive) pickUpActive true pickUpQueue 0 .ActivatePickUp() Edit I have been playing with the if statement conditions, and even if I change pickUpActive to true, it somehow still manages to get inside the if statement to the breakpoint there. How is that possible? The condition says pickUpActive must be false, and yet it blows right by it. When I set the first condition to pickUpQueue ! null, I get an error for index out of range once, when it is set to check the first element, as it is in the above code, I get an index out of range every frame. I finally changed it to pickUpQueue.Count ! 0, and that finally kept it from getting into the if statement. If anyone can help me understand what is going on with my bool, and to understand exactly how to handle this list, I would greatly appreciate it! Thanks!


Why does my disable z depth test shader do not work? I wrote the following shader which purpose is to force draw a mesh over the rest, regardless z depth Shader "Custom AlwaysOnTop" SubShader Tags "Queue" "Overlay" "RenderType" "Overlay" ZTest Always CGPROGRAM pragma surface surf Lambert struct Input float4 color COLOR void surf (Input IN, inout SurfaceOutput o) o.Albedo 1 ENDCG Fallback "Diffuse" It works great, however transparent objects still get draw over it. Setting the queue as Overlay should have solved the problem. White AlwaysOnTop shader Green Transparent diffuse Blue Diffuse The left face of the white cube should be white, no tinted in green.


Problem with the Layer System Tilemap Layer from Unity This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem. My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall. Side Information The Wall Tile is one piece, which covers two tiles. Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything. There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer. What I see as answers Split the wall tile into two tiles and let the wall part be on another layer, then the roof part. Split the character into two parts and do the same thing. Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start. What I tried Trying around with layers and order in layers. Trying around with the tile atlas (adding the sprite, removing tiles)


How does the Unity coordinate system map to screen pixels? If I have a GameObject, say at x 0, y 0, and I want to move it for a 40 pixel to x how can I make that? In don't understand which is the unit of measurement in Unity. If I make something like this where mov is 40 the sprite goes out of screen! void Start() transform.Translate(new Vector3(mov, 0, 0)) it seems like the correct values must be very low, say 0.6, 1, 3, etc. But why?


is there a way to alternate between two state machines? I'm programming an enemy on Unity that has two state machines, one controlling the quot normal quot behaviour of the enemy (that consists in three states idle, patrol and chase) and another one controlling the battle behaviour of the enemy (that consists in three more states attack, dodge and run away). I'm doing these state machines by using enums, like the following code public enum StateMachines NORMAL, BATTLE public enum NormalStates IDLE, PATROL, CHASE public enum BattleStates ATTACK, DODGE, RUNAWAY I want to loop between the Normal and Battle state machines but I have one problem that is they always get executed at the same time. Is there a way I can alternate between state machines through code in a single script (by conditions)? Thank you!


Is it efficient to use colliders on UI canvas in Unity? Basically I have a task where the player will be able to drag an object (as UI Image), and place it inside a bag (another UI image). What's the best optimized way to do so? As I researched, I do not think that using colliders for images is the "best" way to do it. Additionally, I was thinking about checking if the position of the image while dragging overlaps an element however, I do think that would be performant as that would require checking the position on each frame instead of "OnTriggerEnter". What would be the best way to implement such function? Thanks amp Regards, HurpaDerpa


Whats the best way to light up a scene in unity? What I want is a darkish scene with like neon style lights Currently is use the bloom post processing effect but sometimes it doesn't render well on my main camera and looks not as good as it does in the scene My game view with main camera My aim is to get the lighting similar to look like Brackeys party killer game How may I achieve this


Creating dependent values in the Unity inspector I want to create a few values which will be dependent on each other. Specifically, I want total sum of few values always be 100 In unity inspector no matter how I tweak them. E.G. int total 100 int one 20 int two 30 int three 45 int four 5 How can I make other values adjust automatically if I tweak one of them in Unity Inspector?


Leaderboard setup for Android I am totally new for this setup. I am trying to implement google Leaderboard. I followed the step by step process showed in "This Link". i opened windows Google play games setup Android setup. In Android setup i named the class name and copy and paste the xml code from play store account This Picture Shows this then i clicked setup button. i got two popup boxes, Shows below, in console i got messages Note All my software's are updated version only. first i used jdk 64bit. now i uninstalled 64bit and i installed jdk 32 bit. still i got the same problem Anybody Please help. Edit 2 using This video now i fixed the error JAVA HOME not set. then in unity i tried to do the same. Now it displays another message shown below


Can I use two Collision Boxes on the same GameObject? I have two Collision Boxes on the same GameObject. I don't want the Collision Boxes to be triggers. I want the Collision Boxes on the actual GameObject, not its children. For example, if I want to check for a headshot. My reason for not wanting triggers is that a trigger is already being used. My reason for not wanting children is for cleanliness. I understand there are work arounds. I was wondering if there was a more direct approach. When there is a collision, how can I check which Collision Box is hit?


Why should I use getcomponent? I have already referred the animator by using the statement, Animator anim But,What is the use of getcomponent in awake() function.What happens without it.


Is it efficient to have a only data MonoBehaviours on lots of game objects? I'm working on a voxel based game and this solution would make the implementation of networking and other features a lot more easier, it is less error prone, easier to edit in the Editor, etc. So the question is How bad is it performance wise to have lots of MonoBehaviours in the scene, if they don't implement any of the MonoBehaviour methods? (So they only have primitive data stored in them)


Unity 2D graphical glitch cuts sprite diagonally While making a game in unity, we found a graphical glitch that only happens on one of our mobile devices (a htc) where the screen will be oddly sliced by a triangle as shown in this image I've searched online but found no problem. We're using unity 2D, it only does it on the HTC but we have no idea why. The background is a 3D quad with a texture wrapped around it (so we can make it move with the character when the character is running, without having one large background). Any help would be greatly appreciated. Thanks


Unity Multiplayer functionalities or Google's plug in? I want to add multiplayer matches to a game I'm making for Android PC, and something echoed in my mind would the network functionalities Unity provides work in Android? I ask this because Google has a free plug in for their services, but Unity also offers possibilities. Also, using any of the above, do I need to pay to rent a server? Or, for example, since we need a paid developer account to register our game at Google Play Store, the servers are part of the deal?


How can I create a stretchy, breakable pizza cheese material? I want to create realistic pizza and allow user interact with it. What I want What I created I created model of the pizza (8 pieces) in Blender, then imported it into Unity. The piece of pizza looks very artificial, mostly because it is "rigid triangle". How can I make the cheese stretch and break when the user moves a piece?


Unity Checkpoint System that remembers NPC interactions Environment changes? I have already implemented a checkpoint system that respawns the player at the last checkpoint they cross through. Now imagine this NPC A interacts with NPC B NPC B walks over to a nearby car A bird flies over the car and takes a dump Player dies tragically (lol) Player respawns at the last checkpoint X Given that checkpoint X is achieved after watching all these NPC interactions, how can I fast forward skip these interactions when respawning the player? The build I have right now respawned at the correct location but of course, the NPC interactions happen again even though they were supposed to end before reaching that last checkpoint (if that makes any sense ) I understand that this can be achieved by saving all the last known locations of the NPCs, flags that indicate whether the bird took a dump (true false). For example, this seems quite tedious for a game like Uncharted GTA where a lot of interactions happen at the same time. My initial thought was to somehow fast forward the entire game to a point where all these interactions are done and dusted. That way, I can safely respawn the player knowing that they don t see something they ve already seen. Sorry for the detailed post Any tips on how this can be accomplished?


Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.


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


Unity FP Character Can't Look Vertically I have a FP Character and well, it can't look vertically. Its happened about 3 times now, each time I just replaced it with the standard assets prefab, first few times it worked fine, but then after a little while, I suddenly couldn't look vertically. I have checked and double check the vertical clamping on the prefab and they haven't been touched. I really need my player to be able to look vertically as soon as possible, could someone show me how to fix this? Thanks in advance!


how to work more efficient with UI elements im working on a mobile android game that has many levels and same UI. for every level i have to assign the object and function of every button in every scene level. is there more effiecient way that there will be no need to assign all functions in every scene? thank you for helping


Unity fails to effectively split spritesheet I'm very new to game development and I find it very difficult to split the spritesheets available at opengameart.org. All of them are kind of jumbled together without any fixed grid. The resource I learned from always used neatly assembled sprite sheets and Unity would have no trouble in automatically splitting them. But almost all are randomly placed and Unity cannot split them. For example And below is the automatic splitting in unity How do you guys get the sprites from such spritesheets in unity? Some guidance would be appreciated. Thank you


Changing color of only one gameobject So i have this script the checks if my mouse cursor is over the block and if it is i want the block to change color using System.Collections using System.Collections.Generic using UnityEngine public class BasicBlockFunction MonoBehaviour public GameObject Block public Color StartingColor public Color HighlightColor Color color Ray ray RaycastHit hit Use this for initialization void Start () Update is called once per frame void Update () MouseOver() void MouseOver() ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit)) print(hit.collider.name) Block.GetComponent lt Renderer gt ().material.color HighlightColor else Block.GetComponent lt Renderer gt ().material.color StartingColor I want to change the color only for the gameobject i have my mouse on.


Fresh Unity Visual Studio 2017 install error Installed Unity 5.6.3p2 (my projects's current version) on a new machine. When I opened the project in Visual Studio 2017 I got a prompt to update the .NET framework from 3.5 to (I think) 4.2.x. I confirmed the upgrade for all projects in the solution but now all I get is this If I close and reopen visual studio I no longer get the upgrade prompt. I tried downloading .NET 3.5 to no avail. Any information is appreciated.


Create sprite renderer using custom material I have done following thing. Create Material Attach sprite with texture type as Texture Add sprite renderer component to game object Assign material to it that I create in last steps There is no sprite available for selection. Following image illustrate my problem correctly. So my question in how to create sprite renderer with custom material?


Why when using Lerp and StartCoroutine to Lerp between 3 and 3 it's not working? private bool alreadyFading false Then private void OnTriggerEnter(Collider other) if (other.tag quot Teleporting Object quot ) if (!alreadyFading) StartCoroutine(Teleport( 3, 3, 5f)) And IEnumerator Teleport(float from, float to, float duration) alreadyFading true var timePassed 0f while (timePassed lt duration) var factor timePassed duration var value Mathf.Lerp(from, to, factor) material.SetFloat( quot DissolveAmount quot , value) yield return null material.SetFloat( quot DissolveAmount quot , to) alreadyFading false Using a break point it's getting to the Teleport function but it's not changing the values from 3 to 3. It does nothing to the shader to the property DissolveAmount. I want it to change the value from 3 to 3 with duration once not ping pong. but it's not just it's just don't do anything.


Folding selected Parent Game Object in the hierarchy I am folding selected parent gameObject with this editor script. It all works well but it also folds other expanded gameObjects which should not happen. For example under two different parents, if I collapse one parent gameObject, even the other parent gameObject gets collapsed. How do I not let this happen? The problem is at rootGameObjects.AddRange (SceneManager.GetSceneAt (i).GetRootGameObjects ()) It takes the root gameObject in a scene but not the selected gameObject in the hierarchy. Here's the rest of the code using System.Collections.Generic using System.IO using UnityEditor using UnityEngine using UnityEngine.SceneManagement public static class CollapseTools private static int wait 0 private static int undoIndex public static void CollapseGameObjects () EditorApplication.update CollapseGameObjects CollapseGameObjects (new MenuCommand (null)) MenuItem ( quot GameObject Collapse GameObjects quot , priority 40) private static void CollapseGameObjects (MenuCommand command) This happens when this button is clicked via hierarchy's right click context menu and is called once for each object in the selection. We don't want that, we want the function to be called only once if (command.context) EditorApplication.update CollapseGameObjects EditorApplication.update CollapseGameObjects return List lt GameObject gt rootGameObjects new List lt GameObject gt () if UNITY 2018 3 OR NEWER Check if a prefab stage is currently open var prefabStage UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage () if (prefabStage ! null amp amp prefabStage.stageHandle.IsValid ()) rootGameObjects.Add (prefabStage.prefabContentsRoot) else endif int sceneCount SceneManager.sceneCount for (int i 0 i lt sceneCount i ) rootGameObjects.AddRange (SceneManager.GetSceneAt (i).GetRootGameObjects ()) if (rootGameObjects.Count gt 0) Undo.IncrementCurrentGroup () Selection.objects Selection.objects undoIndex Undo.GetCurrentGroup () Selection.objects rootGameObjects.ToArray () EditorApplication.update CollapseHelper EditorApplication.update CollapseHelper private static void CollapseHelper () if (wait lt 1) Increase the number if script doesn't always work wait else EditorApplication.update CollapseHelper wait 0 EditorWindow focusedWindow EditorWindow.focusedWindow if (focusedWindow ! null) focusedWindow.SendEvent (new Event keyCode KeyCode.LeftArrow, type EventType.KeyDown, alt true ) Undo.RevertAllDownToGroup (undoIndex)


Unity moving an object around a radius I'm trying to move a 2D object around the mouse position, However, i want to constrain the object from rotating unnaturally around itself, i want it to basically rotate around a radius, similar to how a boat moves. I've provided the boat example below of what i am trying to achieve, the game is called battleboats.io and their rotation around the mouse will not skid, it looks natural like propellers pushing from behind. Here's my code for achieving this in unity public Camera camera public Rigidbody2D rigidbody private float rotationSpeed 200f private float acceleration 4.4f Vector3 GetMousePosition(Camera c) return c.ScreenToWorldPoint(Input.mousePosition) void Update() Vector3 direction GetMousePosition(camera) transform.position direction.Normalize() float rotationAngle Vector3.Cross(direction, transform.up).z rotation rigidbody.angularVelocity rotationAngle rotationSpeed forward momentum rigidbody.velocity transform.up acceleration Any help is appreciated. What i currently have and the result of my code is illustrated in the below gif.


Unity Adjusting 2D physics for different mobile resolutions I created a test project to see how different mobile resolutions affects Unity's 2D Physics. They way I handled the resolutions was to contain all the objects (including non UI objects) in a Canvas and use a Canvas Scaler component to adjust for multiple resolutions. Although this approach is probably not one of the ways the Canvas was not meant to be used, it works well when working with a single orientation. Despite the quick solution to handle the multiple resolutions, there seems to be the issue of the physics acting differently depending on what aspect ratio is being used. Images can be viewed here http imgur.com a p5wmf The green and blue blocks both have the Rigidbody2D and Box Collider 2D components. The floor (big white block) only has a Box Collider 2D component. As you can see from the images above, the different aspect ratios cause the blocks to collide with the floor at different times. Also, when using rigidbody.addforce in the Y direction, the different aspect ratios cause the blocks to jump at different heights. Obviously these issues could cause an unfair advantage in a game with support for several resolutions. So how would I go about adjusting the physics so that the blocks fall and jump at the same rates relative to the different resolutions? Also if there is a more practical way to adjust for multiple resolutions that doesn't involve a plugin and doesn't break physics, let me know!


How can i change the Camera component height in FirstPersonCharacter? The player looks very short. I changed his scale to 2,2,2 but the camera is in the middle it's like the player head is in the middle and not near the top. In the screenshot in the Hierarchy i have a FPSController and the FirstPersonCharacter with the Camera is child of it. The FPSController scale set to 2,2,2 like the two soldiers. But you can see when i'm getting closer to the soldiers it looks like i'm looking at them from the ground. I need to move the camera only up somehow. And this is the camera and the firstpersoncontroller before running the game


How do I calculate sprites frame usage on my platform's ram? I plan on building a 2d game for mobile and possibly pc. I also plan on using sprites frames for the animation of my 2d game. What's stopping me from doing so is because I can't figure out if the sprites frames containing the animation is gonna use up a lot of RAM on my device. Does anybody here know what I'm talking about?


RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.


Sorting layer issue with multiple sprites and a Tilemap in Unity I have a particle system that draws a blood splat. I have a Tilemap that represents terrain. However, the blood splats, which are on a sorting layer in front of the terrain, are somehow rendered both in front of and behind the terrain. I have encountered similar problems before where the particles had some different Z value than the terrain, but that is not the case this time (3D view) Here are the Inspector panels for these objects. First terrain The renderer for the upper (in Y) blood particle system And for the lower (in Y) system And finally my sorting layers, where Base is behind Foreground What might cause this behavior and how can I fix it? Edit Here is the entire BloodSplat prefab


How can I set up a 2D circular boundary in Unity? I wanted to create a virtual analogue stick on Unity. I figured a very simple, 2 part method setting up a tether to the middle of a doughnut container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve. I initially tried to create a 2D circle collider around the doughnut container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut container). Thus was done with multiple if statements if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f However, when testing the code out, the cursor still exceeded the boundaries given Minimum reproducible code for the cursor public class menuScript MonoBehaviour public float speed public Vector2 originPoint private Vector2 currentPoint Start is called before the first frame update void Start() Vector2 originPoint transform.position Update is called once per frame void Update() currentPoint transform.position float step 50 Time.deltaTime float vertical Input.GetAxis( quot Vertical quot ) Time.deltaTime speed float horizontal Input.GetAxis( quot Horizontal quot ) Time.deltaTime speed if (horizontal ! 0 vertical ! 0) transform.Translate(horizontal, vertical, 0) if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f else transform.position Vector2.MoveTowards(transform.position, originPoint, step)


Unity world asset streaming TL DR What approach should i use for streaming a maps assets? My Unity project so far saves terrain meta data (in a flat file for now) and then streams the map as the player moves. Upon completing this, it was clear that if I wanted to stream anything, its information would need to be stored somewhere. With all this said, do I store my entire map's information in a local db or something? For example, where object X must be, where objects C must be, etc etc. Instantiate everything at run time when that particular tile gets streamed. This seems like a solution an inexperienced game dev (me) would come up with.


Get a Vector2 Based on Object Rotation in Unity I feel like there is an obvious answer to this but I can't find it. Is there a function in unity that gives you a Vector2 (or 3) based on the rotation of an object. for example z rotation 0 gt (0, 1) z rotation 90 gt (1,0) z rotation 180 gt (0,1) z rotation 270 gt ( 1,0) I could just write this in my script the long way, but I feel like there might be a function for it in unity


Bullet is not instantiating properly in Unity So I'm trying to make a simple weapon where I just instantiate a bullet at the Shoot Point's gameobject position. For some reason when I press down on my mouse the bullet just flies up. Any ideas on why this could happen? Vector3 velocity bullet.transform.forward 1000 GameObject bulletGameObject Instantiate(bullet, shootPoint.transform.position, Quaternion.identity) Rigidbody bulletBody bullet.GetComponent lt Rigidbody gt () bulletBody.velocity velocity Destroy(bulletGameObject, 4f)


Unity blur only selected layers I'm messing around with Unity 2017's post processing tools while making a 2D game that benefits from the parallaxing effect using a perspective camera. Please note that the game is mostly made using sprites. Now, I have a playerGround, a backGround and a foreGround. I wish to blur the background and foreground only but not the playerground. I'd like to know how to do this as playing with the focal length didn't do anything, everything receives the same blur amount regardless of the distance from camera.


Unity gizmos vs. referenced game objects I'm designing a Unity script that I intend to be highly reusable and as easy as possible to setup within the editor. To this end, a number of properties of this script really need some kind of visual representation on screen. It is an unresolved question to me whether the design of the script should require references to placeholder game objects, OR just Vector3's and float's that have associated gizmos drawn for them. Normally a gizmo would be a natural choice, except that Unity gizmos are not directly manipulable (as far as I can tell). Because of this shortcoming I'm having to consider whether depending on references to placeholder game objects is a more designer friendly approach ultimately, in spite of the extra setup required, and that it might be counter intuitive when the placeholder game objects disappear at run time (which my script would do). Is there a community standard or preference here in this case? Can a Unity experienced game programmer designer speak to which approach they feel is more intuitive or more convenient to setup, when using a 3rd party script? Or is this just splitting hairs as long as I ship an example prefab with my script?


Transparent image changing color to very light when used on light background in Unity I'm trying to use this transparent image (transparent brown, with a transparent white shadow) over this background in Unity UI. But the end result is not similar to what I see in photoshop at all. What I expect and what I have inPhotoshop What I get in Unity How can I fix this?


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


Force Reload VS soution Explorer when adding new c Script via Unity3d? When I create C script (Create gt C Script) via Unity3d or delete it from Unity3d Visual Studio shows me the warning window. it's annoying. Is there any way to force "ReloadAll" in solution Explorer without the window?


Make platform's visibility distinct from background I have a 2d infinite runner type game which background is changing its colors constantly. Meanwhile the color of the platforms stays the same. This way the platforms at some point(when their color is the same as the background's) become "invisible" for the player. How can I creatively, shortly and conviniently avoid this problem with unity? P.S. I've tried adding glossy material to it but it didn't work.


Achieve same effect as a FixedJoint2D but also match RigidBody2D forces Trying to make an object that is affected by rigidbody physics in exactly the same way as the object it's linked to. So torque, velocity, and any resultant torque or velocity from a collision. This image demonstrates what I mean I've tried using FixedJoint2D, my objects share velocity but do not share torque, applying torque doesn't do anything to either object, it seems locked. I tried using other joints, such as DistantJoint2D(doesn't match y value, only separation value), TargetJoint2D(immediately negates velocity), RelativeJoint2D(The closest to actually working, but glitches out when torque is applied, it acts on a centre of mass between the two connected objects and the objects sort of spin around each other, sometimes getting closer together or farther apart) I also can't just apply the transform position and rotation to the second object, since these objects will be colliding with moving objects. The objects that they collide with slide into the squares and are pinched away when using this method. So I need to know if there is a way to use the FixedJoint2D or RelativeJoint2D or another method or joint that I do not know of to achieve this same effect. Perhaps applying the collision forces happening to one object to the other but it needs to be immediate and I don't know how to apply the collision from one object to another.


In unity how can I make a checkpoint system I have a 2D platformer and if my player dies, he goes back to the start, but I want there to be checkpoints. My current Respawn script using System.Collections using System.Collections.Generic using UnityEngine public class Respawn MonoBehaviour public GameObject PlayerPrefab public Transform SpawnPoint void OnTriggerEnter2D(Collider2D other) if (other.gameObject.tag quot Trap quot ) PlayerPrefab.transform.position SpawnPoint.transform.position I don't know how to implement checkpoints into this.


How can i properly display 2D Pixel sprite's pixels without distortion while it's moving ? (in unity) Introduction to what i'm trying to do Hi, I'm trying to make a 2D Pixel Platformer Game in Unity. Before that i used godot and for some reasons (not about the engine) i switched to unity. And in Unity there are things need to handle by myself, and they were handled by the engine in godot (i guess), because godot is more suitable and compatible with 2D Pixel games (i guess). So i am not sure why the problem happens The Problem In the scene, my pixel sprite is playing his Idle animation (he's only breathing so you can think of that as head and the body moving 1px up and down repeatedly) While playing that simple animation, if my sprite is big enough on the screen, there is no problem and it looks pixel perfect animation is playing without distortion (or disruption idk what was the right word). But if the character looks smaller on the screen, i mean if i scale the character down or keep the scale same and make camera's angle of view bigger, so character looks smaller (not too small a regular platformer character size), What happens is character's eyes visibly goes thinner and thicker as the character plays his animation (head and the body moving 1px up and down repeatedly). Character's eye is 2 black pixels side by side thats it. While the animation playing it kinda distorts. Height changes. Yes I fixed it somehow but.. I fixed it, but idk how and seems like a temporary fix AND i don't think that is how it's supposed to be fixed because we wrote code, I'm okay with writing code for fixing it but first i want to know what was the problem and how to fix it in editor. aaand it just seems weird to write code for simply having a properly functioning pixel sprite animation. How did i fixed it ? just watched this video and added the same script to the camera i have no idea how it worked and why my animation problem was occuring at the first place. What I'm asking for Pleaaaase somebody explain all that to me, why is that happening what are the possible and proper fixes. i'm researching for days and i thought unity had a "big community a lot of tutorials too easy to learn" TL DR when playing animation pixel sprite character's some pixels distorts version Unity 2019.3.3f1 I imported sprite the right way (Filter mode Point(no filter) Compression none, Pixels per unit 16 (that option seems suspicious maybe the problem is about that pixels and units thingies)) I can provide more information about project or directly send you the whole project if you can't reproduce the error. I'm just too curious and want to learn how to have a proper 2D display setup and finally start the fun part coding mechanics etc. since a code about camera solved the issue the problem might be unity's camera settings because unity has no 2D special camera component while godot has Camera2D and Camera3D seperatly. These are just my guesses please teach me what you know.


Lightmapping runtime combine children Is it possible to have lightmapping on runtime generated combine children in Unity? It is possible to bake combined meshes when they are done in the editor, but the .apk .ipa size increases too much.


How to obtain a camera stream from Unity without rendering it to the player's screen? I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen? One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player.


Unity C Modifying eulerAngles with slider issues I'm using a slider to rotate an object on the z axis. The slider has a value of 1 360 (Whole Numbers) when the slider is moved, I use that value for the eulerAngles z axis value. (NOTE The object is part of a child parent 'string' of instantiated objects and it should only ever rotate on the local z axis). This method is working for some objects in the 'string', but not others. When it's not working, the object I'm trying to rotate spins wildly on the z axis because the objects z value is not a reflection of the slider value (I tested this in the inspector). I can't figure where these 'random' slider values are coming from. Here is the rotation function I'm using for the sliders On Value Change event public void SliderRotate () Target.transform.eulerAngles new Vector3( Target.transform.eulerAngles.x, Target.transform.eulerAngles.y, mySlider.GetComponent lt Slider gt ().value) BTW If I change the x and y values to zero, the problem goes away. However, the objects then loose their correct orientation to their parent (I need the x and y to stay where they are). Thanks in advance for any insight you can offer into this issue. Windows Unity 5.3.5f1 Here is an image that might help clarify


How could I get composite rigid body into unity I am developing a game, in unity, that has accurate destruction physics and from my understanding unity uses plain old rigid body physics. I was wondering if there was a way to bring composite rigid body physics into unity through a plug in or library or some other way? Thanks, nova edit So composite rigid body physics is almost exact like normal rigid body physics. But the main difference is that in composite rigid body physics all of the assets will not be considered physics based objects until an outside force hits them. For example a building and all of that parts it is made out of will not be processed as physics based objects until say a rocket hits it. This method of composite rigid body physics uses much less memory because it is only processing what is being affect and not everything else.


Creating orientation Quaternion from forward vector Suppose that I have an orientation Quaternion Q, I can compute its forward vector from V Q Vector3.forward easily. Inversely, suppose that I have its forward vector V, how do I compute Q? I know that is not possible, please tell me what's needed beside V, in order to compute Q. Motivation behind the problem I have a forward direction of a game object, I want to find out its up direction and its right direction. I can find out all these 3 directions if I have the orientation Quaternion.


How to select light as sun source I tried to add a sun in the lighting setting. I have a directional light in my scene, but i can't select it as sun source in lighting setting. The light does not appear in the list. Does anyone know what is wrong ?


Finding x and z value in the direction of another object In my game you can drive a car and it has an arrow point to an object you need to drive towards. The arrow pops up above the car using the same x and z value as the car but adding 2 to the y value. What I am trying to do is push the arrow out a little bit toward the object it is pointing to. This way it looks like it is rotating in a circle around the car instead of rotating about it's own center point. This is what I am doing right now if (!(Vector3.Angle(car.transform.forward, obj.transform.position car.transform.position) lt 40f)) arrow.SetActive(true) temp car.transform.position temp.y car.transform.position.y 2f arrow.transform.position temp temp obj.transform.position temp.y arrow.transform.position.y arrow.transform.LookAt(temp)


How to animate material change to get a status bard effect, in unity Imagine a long cube, like a bar, that has a dark material, and you want to animate changing its material to a light material, but do it gradually from one end to the other, like filling up a tube, or like a progress bar that fills from one end to the other. Is there a way to achieve this in Unity? Or do you need to generate the animations in Blender or similar and control them in unity?


How can zoom into my object when that object is being clicked? Suppose that I have the three game(cube,Quard,sphere) object. When I click on a particular game object suppose think I have clicked on the cube,the cube object should get zoomed in on the screen. how can I do that? How do I center and zoom into my cube game object after selecting the cube? I think it has something to do with the camera but how do I center the view with the camera? I have used the below code for zooming the object.For one object its working.But when I place different object and apply this code then when i click on one object all the three object is getting zoomed. Can anyone help me out in solving this issue Here is the code function OnMouseDown() OrthoZoom(1.5) function OrthoZoom(size float) var cam Camera.main while (cam.orthographicSize ! size) cam.orthographicSize Mathf.MoveTowards(cam.orthographicSize, size, speed Time.deltaTime) yield


How do I draw lines to a custom inspector? I have a custom editor to which I want to be able to draw a basic line graph. I have much of the functionality down, but I have only been able to test as much via the debug. I am yet to figure out how to draw the actual lines to the inspector. How do I draw lines to a custom inspector? I have found plenty of online resources, in regards to custom drawing to the editor. However, everything I find pertains specifically to drawing in the scene view nothing seems to work inside of an actual inspector. The two general methods I have found involve using Handles.DrawLine and the GL library. Neither appear to work however, I have only been able to test functionality with blind coordinates, so far. I can not find anything in regards to actually determining the local coordinates of the area on the inspector where I wish to draw. Perhaps I need to start with an initial "origin" position, Perhaps I need to start with a local area defined by a Rect. I simply don't know. It has also been a while since I had to use OpenGL, directly. It is entirely possible I am simply doing it wrong, to begin with. Here is my current graph method private void DrawVelocityGraph(float velocityValues, float minimumVelocity, float maximumVelocity) float velocityValue velocityValues 0 float increment 0 Vector3 lineStart Vector3.zero Vector3 lineEnd new Vector3(horizontalIncrement, velocityValue verticalIncrement) GL.Begin(GL.LINES) for(int i 1 i lt velocityValues.Length i ) if(velocityValue velocityValues i amp amp (velocityValue minimumVelocity velocityValue maximumVelocity)) Handles.color VelocityGrapherColours.outOfRangeColour else velocityValue velocityValues i Handles.color VelocityGrapherColours.lineColour lineStart lineEnd lineEnd.x increment lineEnd.y velocityValue verticalIncrement GL.Vertex(lineStart) GL.Vertex(lineEnd) GL.End()


Optimizing spawning 500 objects every 3 seconds Using Object Pooling, assuming I'll like to spawn 500 cubes once every three seconds. How do I make it performance friendly? I need ideas, not the code itself.


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


Loading scene doesn't reactivate gameobjects I have some levels and a main menu. When starting the game from the main menu (in the editor debug mode) I can select a level a load it, no problem. However, when I wish to go back to the main menu using SceneManager.LoadScene(index) A whole lot of my gameobjects throw exceptions like The gameobjects is destroyed, but you are trying to access it and Missing reference exception and so on. However, when i start the level from the editor (and not using the main menu), I can go back to the main menu, it works as it should. NOTE that I don't have any persistent gameobjects. I do have singletons, but no persistence here. Any ideas what could cause the issue?


How to apply fast slow camera transition I know there is a lerp function there that smoothens the camera but I wanted it to work the other way around. Lets say starting position of the player is at the left side of the camera screen and when the players goes around the right edge (or as long as more than half width) screen travelled I want to camera to snap to the player but with smooth transition and this is the hard part I wanted to make the camera move fast as long as it is less than half of the players distance travelled and apply a slow speed as the camera travels more than half the distance of player.


Shader works in Editor but not on iPhone I am using the next script for a painting asset found on this website. As you render the faces of your mesh in the uv space of the mesh, you are reconstruction the islands one triangle at the time. On the edges of the island, it can be that due to underestimation the rasterizer doesn t consider a pixel which is actually in the island. For these pixels, no pixel shader will be executed and you will be left over with a crease. (text and image taken form the website) The basic idea is that every frame, after the paint texture has been updated, I run a shader over the entire texture, and using a filter and a pre baked mask of the uv islands, extend the islands outwards. The problem is that it does not work on iPhone. There is no error, no weird coloring, it is like that script does not get applied. I am not sure where the problem is coming from..maybe the for loops or the command buffers used in c . Shader "Unlit FixIlsandEdges" SubShader TAGS AND SETUP Tags "RenderType" "Opaque" LOD 100 Pass DEFINE AND INCLUDE CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" DECLERANTIONS struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex uniform float4 MainTex TexelSize sampler2D IlsandMap VERTEX FRAGMENT v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) float map tex2D( IlsandMap,i.uv) float3 average col if (map.x lt 0.2) only take an average if it is not in a uv ilsand int n 0 average float3(0., 0., 0.) for (float x 1.5 x lt 1.5 x ) for (float y 1.5 y lt 1.5 y ) float3 c tex2D( MainTex, i.uv MainTex TexelSize.xy float2(x, y)) float m tex2D( IlsandMap, i.uv MainTex TexelSize.xy float2(x, y)) n step(0.1, m) average c step(0.1, m) average n col.xyz average return col ENDCG I've read somewhere that using tex2D in for loops is a big no no, so I changed that to a tex2Dlod but the same thing happens. You can check out the Git project here I am completely lost on this one and google isn't very helpful. Thank you for any comments.


Unity transform.rotation not giving real value i confused , when the object is at 0 rotation ( not rotated yet ) , it giving real value ( 0 ) , but when the object is rotated 180 degree , transform.rotation is giving false value ( 1 ) , this is the screenshot If the picture is not clear enough , go here https i.stack.imgur.com miWIE.png . Then this is my script that debugged the code and rotate the object void RotateFlip() GameObject databasegameobject GameObject.Find ("database") database databasechange databasegameobject.GetComponent lt database gt () Debug.Log ("current object rotation is " theiconarrow.transform.rotation.z " degree ") if (databasechange.pengertianmenustate 2) if (theiconarrow.transform.rotation.z 0 ) theiconarrow.transform.Rotate (new Vector3 (theiconarrow.transform.rotation.x, theiconarrow.transform.rotation.y, 180), Space.World) if (databasechange.pengertianmenustate 1) if (theiconarrow.transform.rotation.z 180) theiconarrow.transform.Rotate (new Vector3 (theiconarrow.transform.rotation.x, theiconarrow.transform.rotation.y, 180), Space.World) I don't understand why this thing happened , is this a kind of bug or what ? I am sorry if this already asked somewhere , but i just don't know how to find it at search engine ( neither here ) . Extra question ( optional ) is there any application to build app with easy coding and not an game engine ?


Finding out which Panel was clicked in function I have a panel with 10 sub panels in it. I am using Event Trigger to intercept the messages from these sub panels OnPointerDown event calls some function in the some script of an Game Object. Is there a way to know in the function which of the sub panels was clicked. That way I can use the same function for all the sub panels or should I make individual function for each of the sub panels.


Why does collision only work when keys are being pressed? My player object containing a rigidbody that is controlled using Input, is not colliding with an enemy unless keys are pressed. When no keys are pressed, the enemy simply goes through the player without collision. I'm using Unity 5.6.1f1. I figured the problem is in the Patrol class because when I don't attach the script to the enemy object the collision appears to take place fine. But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the enemy object move between points in patrolPoints which are just some empty's in the game world. So, I would like to know if I'm doing it right or is there another way to do it. Patrol.cs public class Patrol MonoBehaviour public Transform patrolPoints public float speed private int currentPoint private bool forward Use this for initialization void Start () transform.position patrolPoints 0 .position currentPoint 0 forward true Update is called once per frame void Update () if (transform.position patrolPoints currentPoint .position) if (currentPoint lt patrolPoints.Length 1 amp amp forward) currentPoint else currentPoint forward false if (currentPoint 0) forward true transform.position Vector3.MoveTowards (transform.position, patrolPoints currentPoint .position, speed Time.deltaTime)


Unity Change base class variable to a derived class in inspector dynamically In an item system I'm trying to create I'm using prefabs to store an item's default values, and then grab that item from the prefab to use in runtime. It works well, but I was wondering if there was a way to dynamically change a variable with a base type to a derived type, probably with a custom editor, so that I wouldn't have to make separate classes for each derived type. This is the how I'm imagining it would be like public class ItemPrefab Monobehaviour public ItemTypes itemType public Item item public enum ItemTypes meleeWeapon, rangedWeapon Item is an abstract base class, and MeleeWeapon and RangedWeapon are serializable derivatives. With that, I'm trying to do something to the effect of this switch (itemType) case ItemTypes.meleeWeapon item item as MeleeWeapon break case ItemTypes.rangedWeapon item item as RangedWeapon break I was wanting it to be the same as the below, just less scripts. public class MeleeWeaponItemPrefab Monobehaviour public MeleeWeapon item public class RangedWeaponItemPrefab Monobehaviour public RangedWeapon item Edit Here is my item system so far (I just included MeleeWeapon because I didn't want this to get too long). public abstract class Item Header( quot Basic Info quot ) SerializeField private string name quot quot SerializeField private Image icon null SerializeField private GameObject itemPrefab null SerializeField private float weight 0 SerializeField private int maxStack 0 private Guid gUID public string Name gt name public Image Icon gt icon public GameObject ItemPrefab gt itemPrefab public float Weight gt weight public int MaxStack gt maxStack public Guid GUID get return gUID private set gUID Guid.NewGuid() public abstract class Weapon Item public abstract void Attack() System.Serializable public class MeleeWeapon Weapon Header( quot Weapon Attributes quot ) SerializeField private MeleeWeaponTypes weaponType default SerializeField private float damage 0 SerializeField private float chargeDamage 0 SerializeField private float meleeSpeed 0 SerializeField private float chargeTime 0 SerializeField private float chargeCooldown 0 public MeleeWeaponTypes WeaponType gt weaponType public float Damage gt damage public float ChargeDamage gt chargeDamage public float MeleeSpeed gt meleeSpeed public float ChargeTime gt chargeTime public float ChargeCooldown gt chargeCooldown public override void Attack() attack I have other stuff in Weapon and its derivatives but I removed it to keep the base idea more simple. Anyway, I then have prefabs with a MonoBehaviour that hold a derived type of Item, like I showed above, as data containers that I use to instantiate items during runtime.


unable to see sprite in scene Getting error as floating point precision limitation I am trying to create game object by dragging image from project window to scene I am getting error as due to floating point precision limitation it is recommended to bring the world coordinates of game object within smaller range I am following ruby's adventure tutorial in unity learning


How to develop custom Unity graphics? Processing is a Java library for working with computer graphics, providing methods by which to draw primitive objects, custom meshes, etc., as well as mathematical methods (such as Simple Harmonic Motion) by which to animate and control them. p5.js is an equivalent library for JavaScript and working with graphics on the web. You also have openFramworks which is similar but for C . How can you achieve similar graphics capabilities in the Unity Game Engine? Suppose, for example, I wanted to build a game like Duet. I can imagine how I might go about creating those graphics in Processing or p5.js, but not in Unity and C . How can you have that kind of creative freedom to build and draw in Unity? Thanks.


How can I scale my UI elements to the lesser screen dimension in Unity 5? I want to create a custom mobile pad for my game. The mobile pad consists of two parts (both inside an ui canvas) The D Pad, which will be anchored to the bottom left side. The button group will be anchored to the bottom right side. I would like to resize the element on different resolutions, so that the element (in my case, the D Pad is an image) Has a size of 20 of the minimum of the width and the height. Has pivot of x 0.5, y 0.5. Having anchor of left bottom, its coordinates are (15 , 15 ) wrt the minimum of the width and the height. What I tried is to use an Aspect Ratio Filter in the D Pad image with ratio 1, but it did not work as intended (the coordinates led the image to an unexpected place). Note I am a n00b to Unity. I don't know whether it is right but my Canvas Scaler scales by Constant Pixel Size These images should illustrate what I want to achieve What should I do to make it work like in the pictures? Edit I attached this behavior, based on answer, to handle the change by runtime RequireComponent(typeof(UI.CanvasScaler)) class CanvasSmartScaler MonoBehavior private CanvasScaler scaler void Start() scaler GetComponent lt CanvasScaler gt () void Update() OMITTED CODE here I set the scale mode as in the Editor but right now i am in my mobile device and cannot remember the exact lines if (Screen.currentResolution.width lt Screen.currentResolution.height) scaler.matchWidthOrHeight 0 else scaler.matchWidthOrHeight 1 And attached that behavior to the canvas. However, for my debug exe (just for debug purposes) it always picks the 1 case regardless how do I resize the window. What am I missing?


How to avoid game starting before start button is clicked? I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game before the user presses start. Is there a way to make the GameObjects only appear after the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right. This is my first game ever, so hope the code provided is relevant. Enemy.cs void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") GameManager.cs public void StartGame() powerup.transform.rotation) score 0 UpdateScore(0) isGameActive true titleScreen.gameObject.SetActive(false) void Update() enemyCount FindObjectsOfType lt Enemy gt ().Length if (enemyCount 0) roundNumber SpawnEnemyIntruders(roundNumber) Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation) void SpawnEnemyIntruders(int enemiesToSpawn) for (int i 0 i lt enemiesToSpawn i ) int enemyIndex Random.Range(0, enemies.Length) Instantiate(enemies enemyIndex , GenerateSpawnPosition(), enemies enemyIndex .gameObject.transform.rotation) public void GameOver() restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) isGameActive false PlayerController.cs void Start() playerRb GetComponent lt Rigidbody gt () playerAudio GetComponent lt AudioSource gt () StartButton.cs void Start() button GetComponent lt Button gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () button.onClick.AddListener(StartThis)


My money will only save for one game run I am trying to make a money system my problem is that the money value only saves for 1 game run then the value returns to 0. Here is my code. What should I do. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Money variables public Text cash Use this for initialization void Start () if (counter lt 9 amp amp counter gt 1) money money 2 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 10 amp amp counter lt 20) money money 5 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 21 amp amp counter lt 30) money money 15 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 31 amp amp counter lt 40) money money 25 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 41 amp amp counter lt 70) money money 50 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 71 amp amp counter lt 100) money money 75 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 101 amp amp counter lt 200) money money 100 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) else if (counter gt 201) money money 150 PlayerPrefs.GetInt("money", money) PlayerPrefs.SetInt("money", money) cash.text "Credits " PlayerPrefs.GetInt("money", money)


Take a screenshot from camera problem I use script below to take a screenshot from camera. It's working fine. However, when I take a screenshot again (pressing k multiple times), its old image is not clear from the memory and it keep drawing over same image over and over again. If object is moving while taking screenshot multiple times, image I will get all frame combine into one image with every frame in the same image. What should I do to fix this problem? using UnityEngine using System.Collections public class HiResScreenShots MonoBehaviour public int resWidth 2550 public int resHeight 3300 private bool takeHiResShot true public static string ScreenShotName(int width, int height) return string.Format(" 0 screenshots screen 1 x 2 3 .png", Application.dataPath, width, height, System.DateTime.Now.ToString("yyyy MM dd HH mm ss")) public void TakeHiResShot() takeHiResShot true void LateUpdate() takeHiResShot Input.GetKeyDown("k") if (takeHiResShot) RenderTexture rt new RenderTexture(resWidth, resHeight, 24) camera.targetTexture rt Texture2D screenShot new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false) camera.Render() RenderTexture.active rt screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0) camera.targetTexture null RenderTexture.active null JC added to avoid errors Destroy(rt) byte bytes screenShot.EncodeToPNG() string filename ScreenShotName(resWidth, resHeight) System.IO.File.WriteAllBytes(filename, bytes) Debug.Log(string.Format("Took screenshot to 0 ", filename)) takeHiResShot false Debug.Log("Capture!!")


Is It Possible To Reset UI To Initial State At Runtime Without Any Direct Assignments? Is it possible to reset UI to it's initial state (the state when game started) without directly reseting elements one by one? Thanks in advance. Edit I'm asking for runtime. (ResetToPrefabState doesn't work at runtime.)


How do I make my rigid body rotate a fixed angle value each time I click the movement keys Ive tried some experiments with the character rotation, but I dont want it to rotate when he touches something, but I also need to unfreeze the Z axis rotation or else the character doesnt rotate when I press a key. My code is this right now, each time I press play (with the Z axis unfreeze) the character just turns like 10 degrees each time I press a key and he is still interacting with objetcs, I dunno what I can do and I might need some help public float speed 2f private Rigidbody rb private float midJump 1 private Rigidbody rB Character Movement void Start() rb GetComponent lt Rigidbody gt () void Update() rb GetComponent lt Rigidbody gt () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0f, moveVertical) rb.AddForce(movement speed) Character Jump if (midJump 1 amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector3(0, 45, 0) midJump 2 Character Rotation else if (rb.velocity.y 0.0) midJump 1 if (Input.GetKeyDown(KeyCode.D)) rb.AddRelativeTorque(new Vector3(0, 0, 90)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.A)) rb.AddRelativeTorque(new Vector3(0, 0, 90)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.S)) rb.AddRelativeTorque(new Vector3(0, 0, 180)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.W)) rb.AddRelativeTorque(new Vector3(0, 0, 0)) rb.angularVelocity Vector3.zero


Unity Animator animations fail to play only when triggered by user input I have a unity animator setup like so. When the game runs, I can trigger each state in the state machine with user input. I can use HasExitTime flag to trigger the animation, and it will play through and loop infinitely as expected. However, when I try to use the GearChange trigger, the state machine progress bar plays, the correct box is triggered, but the animation itself doesn't play! I'm at a total loss as to what the problem is here, as everything else is exactly the same, minus the user input. The console isn't showing any errors, the animation simply doesn't respond to the state machine. What am I missing here? Unity version 2020.1.0f1 So I deleted the animator, and setup everything again the exact same way. Now the animation won't play, period. The state machine progress bars are still triggered as expected, but the animation won't play. In the transition preview, the animation won't play there either.


Unity UNet without a lobby How do you get an ordered list of participants (network players)? Please imagine a turn based multiplayer game. Right now there's no lobby in place and connections are established using Unity's Network Manager HUD. Now on the server, how can you get a list of all the match participants? Preferably ordered something like the player on the host should be player 1, the first player who joined the match should be player two, the second player who joined should be player three.... Any advise is welcome, thank you.


Changing text occurs error move initialization code to the Awake or Start function I have GameManager class that has Log method using UnityEngine using UnityEngine.UI public class GameManager MonoBehaviour public static GameManager Instance SerializeField private ScrollRect m GUIConsoleContainer SerializeField private UnityEngine.UI.Text m GUIConsole ... void Awake() Instance this ... public void Log(string message) m GUIConsole.text m GUIConsole.text message " n" GameManager class has static instance, so I can invoke Log method in anywhere like this GameManager.Instance.Log("Helloworld") However it works only first time. After invoke Log again, Unity gives me this error message get isActiveAndEnabled can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEngine.UI.Text set text(String) I assigned reference of m GUIConsoleContainer and m GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error. How should I avoid this error message? Using Unity 2018.2.1f1. p.s. Error coming from here, another class called NetworkManager void OnReceivedBytes(IAsyncResult result) try if(m Socket null) return int resultLength m Socket.EndReceive(result) if(resultLength 0) Shutdown() return Log("Received " m RecvBuffer 0 ) lt lt Error coming from here ... ... And this is where it call OnReceivedBytes using UnityEngine using UnityEngine.UI using System using System.Collections using System.Net using System.Net.Sockets public class NetworkManager MonoBehaviour private Socket m Socket void Start() m Socket new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) m Socket.Connect("localhost", 1337) if(m Socket.Connected) Log("Connected.") m Socket.BeginReceive( m RecvBuffer, 0, m RecvBuffer.Length, SocketFlags.None, new System.AsyncCallback(OnReceivedBytes), null ) else Log("Failed to Connect.") ...


Is there a way to customize the Game view Editor GUI? I need to add a simple slider like scale slider in Game view to change the timescale because I usually test my games by changing timescale.


Tell Unity to use a certain LayerMask to raise or not OnDrop (for a class that implements IDropHandler) I am trying to make a draggable GameObject that can be dropped within a container but when i'm releasing the mouse button even though the mouse is over the container (and the dragged object too) OnDrop isn't raised on my container. To make it work i must pick the dragged GameObject right at its edge so that the mouse is over the container but not the draggable when i release the mouse button According to what I've seen drag and drop handled by unity is based on Raycasts and Raycasts could be configured to ignore objects that are in certain Layers thanks to a LayerMask the problem is that i wasn't able to find anything to apply a LayerMask Is there a way to do this or any workaround that could let the drop target know that a dragged was dropped on him?


How to deal with cheat avoidance and trusted client issue I hope not to be off topic here. At the moment I'm dealing with networking programming for the game I'm working on and I found different possible scenarios. I started to build code using a Platform as a Service such as Photon Unity Network which offers a quite simple system to sync players through its cloud. The problem is that by using the cloud you must have at least a trusted client in order to prevent cheating from players. I wish I could learn what is best to deal with this problem considering that opting for a client server structure would be the best but I'm a bit worried about rental purchase pricing. Is there a cheap way to have a working game server?


In GameCenter realtime multiplayer how to identify who is host? In GameCenter real time multiplayer how to identify who is a host?


Unity How to serialize show private fields and custom types in Inspector? By default, Unity only serializes public fields. How can I serialize private fields and custom types to show them in inspector?


How to create in game menu attached to unit I'm creating a game similar to Banner Saga, except my game will be in 3D, with a camera that can move around and zoom in and out. What I want is for a menu to appear after the user clicks on a unit. This menu must always be visible and facing the camera. The menu that has the foot and sword symbols is what I want. How can I get a similar result in 3D? The new Unity UI canvas isn't really suitable, since the camera will move around, and the menu must stay next to the unit. The menu elements can't be covered up by things in front of it, like other units. Thanks


Downloading 10 images and storing their data with WWW I would like to download 10 images, and store their texture data into my list. I don't really know how to do that I heard that for this you use the WWW class, so I went List lt byte gt StartDownload() List lt byte gt result new List lt byte gt () for (int i 0 i lt 10 i) WWW request new WWW("http www.example.com " i ".png") result.Add(request.texture) return result Which of course doesn't work, but I'm not sure why.


How can I change some tree's radius and length in C script in Unity3D? So, I have this little tree stem. It only has its initial node. All I would like to do is make it grow in length and radius in Update(). How can I do that?


Input.GetAxisRaw not returning zero after releasing the key In my WebGL Project here is the way for camera navigation (Movement Rotation) on Update event void UpdateMovement() bool accelerate Input.GetKey(KeyCode.LeftShift) Input.GetKey(KeyCode.RightShift) moveDirection new Vector3( Input.GetAxisRaw("Horizontal") moveSpeed, 0, Input.GetAxisRaw("Vertical") moveSpeed) moveDirection new Vector3(Input.GetAxis("Horizontal") moveSpeed, 0, Input.GetAxis("Vertical") moveSpeed) moveDirection transform.TransformDirection(moveDirection) if (Input.GetButton("Up")) moveDirection.y moveSpeed else if (Input.GetButton("Down")) moveDirection.y moveSpeed if (Input.GetAxisRaw("Mouse ScrollWheel") gt 0) moveDirection.y moveDirection.y scrollSpeed else if (Input.GetAxisRaw("Mouse ScrollWheel") lt 0) moveDirection.y moveDirection.y scrollSpeed moveDirection (accelerate ? speed moveSpeed) controller.Move(moveDirection Time.deltaTime) void UpdateRotation() if (!Input.GetMouseButton(1)) return rotationX Input.GetAxis("Mouse X") lookSpeed rotationY Input.GetAxis("Mouse Y") lookSpeed rotationY Mathf.Clamp(rotationY, 90, 90) rotationZ Input.GetAxis("Mouse ScrollWheel") transform.localRotation Quaternion.AngleAxis(rotationZ, Vector3.forward) transform.localRotation Quaternion.AngleAxis(rotationX, Vector3.up) transform.localRotation Quaternion.AngleAxis(rotationY, Vector3.left) All working fine but the problem on WebGL canvas when I rotate the camera using mouse and comes out of the bound of WebGl canvas meanwhile, I also continuously press horizontal or vertical key, then release input key doesn't work. Remember I logged the key Input.GetAxisRaw("Horizontal"),Input.GetAxisRaw("Vertical") input and found that it is not reset to zero on release. Debug.Log("Hr GetAxisRaw " Input.GetAxisRaw("Horizontal")) Debug.Log("Vertical " Input.GetAxisRaw("Vertical")) Normally when I don't use camera rotation using mouse and during this time, when i release the horizontal vertical key, it works fine.


Why is the Position Handle placed at certain distance away from vector3 unit in Unity? I have a vector3 value that I am setting in inspector and I am drawing a ray using OnDrawGizoms to draw that vector line. However, the position handle I made using Handles API to set the vector3 value is placed certain distance away from the vector unit. It's not placed exactly at the end point of the vector line that is drawn and I am not sure why. My goal is to just make a handle to position a vector3 value. EDIT For some reason, the handle is positioned correctly for y position alone but not for x and z positions. Here is my code In this script, it is the localTargetPosition vector3 value that I want to make my handle for. public class MovePlatform MonoBehaviour public Vector3 localTargetPosition new Vector3(5, 0, 0) public Vector3 m initialPosition get return initialPosition set initialPosition value private Vector3 initialPosition, targetPosition, targetPosDebug public float speed 3 public bool loop void Start() initialPosition transform.position SetTargetPosition(localTargetPosition) void Update() transform.position Vector3.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) if (transform.position targetPosition) if (loop) SwitchDirection() public void SwitchDirection() if (transform.position initialPosition) SetTargetPosition(localTargetPosition) else targetPosition initialPosition private void SetTargetPosition(Vector3 localPosition) targetPosition initialPosition transform.TransformDirection(localPosition) targetPosDebug targetPosition void OnDrawGizmos() if (Application.isPlaying) Debug.DrawLine(initialPosition, targetPosDebug, Color.red) else Debug.DrawRay(transform.position, transform.TransformDirection(localTargetPosition), Color.red) This is the script used for making handle CustomEditor(typeof(MovePlatform)), CanEditMultipleObjects public class MovePlatformEditor Editor protected virtual void OnSceneGUI() MovePlatform movePlatform (MovePlatform)target Vector3 initialPosition movePlatform.transform.TransformPoint(movePlatform.m initialPosition) Vector3 targetPosition movePlatform.transform.TransformPoint(movePlatform.localTargetPosition) EditorGUI.BeginChangeCheck() Handles.Label(targetPosition, "Target", "button") targetPosition Handles.PositionHandle(targetPosition, movePlatform.transform.rotation) if (EditorGUI.EndChangeCheck()) Undo.RecordObject(movePlatform, "Move Handles") movePlatform.localTargetPosition movePlatform.transform.InverseTransformPoint(targetPosition) Handles.color Color.yellow Handles.DrawLine(initialPosition, targetPosition)


Texture not working on object I have a project that I'm having a bit of trouble with. Let me try and explain. In short, I'm trying to apply a texture to an object, but instead it is a solid color. I built a building in "Autodesk 123d design", and exported it as stl. Then I used an online converter to convert it to obj, then added that to the unity scene. I created a material with a texture and tried to apply it to the object, but it was a solid color. I think the UVs on the object might be messed up. I tried some things in blender, but had no luck. Any ideas on how I can fix this? Edit Here is the 3D model I'm working with http www.123dapp.com 123D Design Conisbrough Castle Keep 4578568


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


Adding 90 degree Y rotation into script I'm using the following script to move a spray bottle around a head. It should looke like in a barber shop. The code works fine I have assigned the script to the spray bottle, and I have set the head as the target. One thing that is wrong is that the spray bottle needs to have a 90 yaw rotation in order to face the head. I have tried the wildest things to include these 90 degrees, all produced weird results. Could anybody state how to include this 90 Y rotation into the script? Thank you very much! using UnityEngine using System.Collections AddComponentMenu("Camera Control Mouse Orbit with zoom") public class MouseOrbitImproved MonoBehaviour public Transform target public float distance 5.0f public float xSpeed 120.0f public float ySpeed 120.0f public float yMinLimit 20f public float yMaxLimit 80f public float distanceMin .5f public float distanceMax 15f private Rigidbody rigidbody float x 0.0f float y 0.0f Use this for initialization void Start () Vector3 angles transform.eulerAngles x angles.y y angles.x rigidbody GetComponent lt Rigidbody gt () Make the rigid body not change rotation if (rigidbody ! null) rigidbody.freezeRotation true void LateUpdate () if (target) x Input.GetAxis("Mouse X") xSpeed distance 0.02f y Input.GetAxis("Mouse Y") ySpeed 0.02f y ClampAngle(y, yMinLimit, yMaxLimit) Quaternion rotation Quaternion.Euler(y, x, 0) distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 5, distanceMin, distanceMax) RaycastHit hit if (Physics.Linecast (target.position, transform.position, out hit)) distance hit.distance Vector3 negDistance new Vector3(0.0f, 0.0f, distance) Vector3 position rotation negDistance target.position transform.rotation rotation transform.position position public static float ClampAngle(float angle, float min, float max) if (angle lt 360F) angle 360F if (angle gt 360F) angle 360F return Mathf.Clamp(angle, min, max)


Unity Animator bool transitions keep re entering state while true My StateMachine is triggered in a loop as long as transition boolean is true. I have made sure my code only runs once, where I set the animation bool animator.SetBool("talk", true) This does trigger the transition but the problem is that it re triggers every frame as long as the bool is true. I had the same issue with a normal state earlier, but there I could turn off "Can transition to self" which solved it. However a StateMachine does not have that option. I want the animation to play until the bool is set back to false, so using a trigger would not be good here. EDIT For some reason it seems the "Transition duration" is the one resetting my animation. So if I change that to 3, it re enters every 3 seconds, and so on. This seems really weird? How do I just make sure that the animation plays until its done, then it re enters (to choose another random talking animation from my StateMachine), as long as talk true?


Shader which supports vertex colors and pixel lights? From my question at Unity Answers Hello everyone, I'm facing a bit of a problem here I need a shader which has the ability to colour individual vertices and be lit pixel by pixel. Until recently, I was planning to use just vertex shading, since I couldn't find any info about this. The thing, it looks like this Bad shading 1 and Bad shading 2. As you can see, it is horrendously bizarre and even glitchy. Here is the shader I'm using right now (ShaderLab syntax) Shader "Alpha VertexLit Colored" Properties Color ("Main Color", Color) (1,1,1,1) SpecColor ("Spec Color", Color) (1,1,1,0) Emission ("Emmisive Color", Color) (0,0,0,0) Shininess ("Shininess", Range (0.01, 1)) 0.7 MainTex ("Base (RGB) Trans (A)", 2D) "white" SubShader ZWrite Off Alphatest Greater 0 Tags Queue Transparent Blend SrcAlpha OneMinusSrcAlpha ColorMask RGB Pass Material Shininess Shininess Specular SpecColor Emission Emission ColorMaterial AmbientAndDiffuse Lighting On SeparateSpecular On SetTexture MainTex Combine texture primary, texture primary SetTexture MainTex constantColor Color Combine previous constant DOUBLE, previous constant Fallback "Alpha VertexLit", 1 I searched around on the Unity forums, wiki and also on Google, but I found no resources for this. I really need the vertex colours here, it's a crucial element of the graphic style of my game, and is the simplest way to do what I want. Any help is immensely appreciated. Does anyone know if such kind of shader exists?