How to get a random Vector 2 within a range I'm working on a game and I need the objects that get spawned to launch within a range of angles, so like in the horrible 2 second paint image seen below, I need to grab a random vector within that range of arrows, and then the ball will go off in that direction. I'm just not sure how to get a vector within a range like that. This is in C and Unity, the game is 2D. Any ideas?


How to instantiate a gameobject multiple times in unity during runtime? After destroying a gameobject in unity, how to instantiate it and make it do the exact same thing what the gameobject before getting destroyed was doing? My gameobject is a car which follows a path made out of nodes. After it is destroyed at a particular node, I want to instantiate it at a particular point which is the spawnSpot in my code, then I want it to follow the same path again and then get destroyed again and get instantiated again and follow the same path again and so on. Right now, I am able to make my car follow a certain path and then destroy it at a certain node and and instantiate it and make it follow the same path again. Then my car is destroyed again and instantiated again but this time it does not follow the path and stays right at the spawnPoint. I am using the destroy and instantiate functions in fixed update. Here's the relevant part of my code private void Destroy() if(currentNode nodes.Count 1) Destroy(this.gameObject) private void Instantiate() if(currentNode nodes.Count 1) Instantiate(prefab, spawnspot, Quaternion.identity) P.S. prefab is the gameObject.


Restrict object movement inside irregular shaped container I want to restrict object movement inside an area. My object follows cursor position. I have already done that for the area border using Mathf.Champ to the translate because the borders are square shaped (got the idea from Unity Restrict movement inside a gameobject (2D)). The thing is that inside the box area there can also be other shapes (colliders) which I don't want my object to go over. I know people suggest using physic collisions, but my game needs a unit perfect positions so I can't use physics due to physics' default contact offset (the one physics use to detect collisions). Here is a short video of what I have https gfycat.com cookedsmartannelid As you can see, movement is restricted (clamped) inside the box area but I want the movement to also be restricted to not go over the black area. Is there a way to be able to do this with just clamping or do I need a raycast system or something like that?


What information would I need to calculate proper placement of my Unity 3D orthographic HUD elements? I have a Unity project and I have managed to create a 3D HUD by creating a separate (orthographic) camera for rendering elements on the UI layer. I already have some objects appearing in the HUD and rendering correctly. What I want to do now is calculate the proper position and scale of these elements to make sure they are in the upper left corner and only take up 60 of the vertical space. I am optimistic the necessary information is available to C script components, but I have no idea which formulas and which members or methods (probably on the Camera object) can tell me what the X Y bounds of the orthographic view are (for whatever the current aspect ratio is).


Unity 5 missing Standard Assets I have Unity 5 and when I make a new project, there are no assets that are usually there (Character Controller, Terrain, etc.). How do I fix that?


Having trouble setting a game object as a child of another. What is wrong here? So I'm trying to raycast on mouse click if it hits any thing make that object a child of the sender (in this case the parent). Below is my code... public class PhysGun MonoBehaviour private GameObject Player void Start () Player GameObject.Find("Player") Update is called once per frame void Update () Vector3 fwd transform.TransformDirection(Vector3.forward) if (Input.GetMouseButton(0) amp amp Physics.Raycast(transform.position, fwd, 10)) this.transform.parent Player.transform transform.SetParent(Player.transform) Debug.Log("There is something in front of the object!") The script is attached to a child of the player and I will eventually attatch it to a motion control (Vive). What am I doing wrong exactly? I've tried multiple ways to do this and none of them work (or present any errors). Also to clarify the issue it's not parenting the game object hit by the ray cast to the Player like I want it to.


Effect culling on uneven terrain I'm trying to integrate a "ground particle" effect (like a fire circle or similar) in Unity3d, however since i'm using uneven terrain as my terrain mesh, the effect gets culled behind terrain parts that above it. To better ilustrate it I created an image as attachment I want for the effect to always be displayed regardless of it's "depth". How can this undesired effect be avoided resolved properly ?


How to place an object at the mouse position? How can I place a object to position where I clicked in just x,y axis not in z, I am trying to achieve it with Vector3 mousepos Camera.main.ScreenToWorldPoint(Input.mousePosition) object.transform.position new Vector3(mousepos,mousepos) but it does not seem to work, in fact the object doesn't even move.


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


Why is the camera tilting around the z axis when I only specified x and y? My goal is to program a camera to point towards the mouse cursor. I attached the following script to the Main Camera. using UnityEngine using System.Collections public class CameraController MonoBehaviour public float sensitivity Update is called once per frame void Update () transform.Rotate (Input.GetAxis ("Mouse Y") 1 sensitivity, Input.GetAxis ("Mouse X") sensitivity, 0) I "told" the camera to rotate around the x and y axes. Whenever it does this, the camera tilts sideways. When I checked the rotation of Main Camera, I saw that the z rotation had changed. Why is it rotating around the z axis when I left it at 0?


Unity 2019.3 HDRI SkyBox I am trying to create an HDRI SkyBox out of 6 textures but after I create the cubemap with Assets Legacy Cubemap and drag it in the HDRI Sky I get an all white environment. Is this a problem with the textures or maybe I am missing some setting?


Why the renderers Renderer array are all null? using System using System.Collections using System.Collections.Generic using UnityEngine public class LightsEffect MonoBehaviour public List lt UnityEngine.GameObject gt waypoints public int howmanylight 5 public Generatenumbers gn public bool changeLightsDirection false public float delay 0.1f private List lt UnityEngine.GameObject gt objects private Renderer renderers private int greenIndex 0 private float lastChangeTime private void Start() waypoints new List lt UnityEngine.GameObject gt () objects new List lt UnityEngine.GameObject gt () if (howmanylight gt 0) UnityEngine.GameObject go1 UnityEngine.GameObject.CreatePrimitive(PrimitiveType.Sphere) duplicateObject(go1, howmanylight) LightsEffects() private void Update() LightsEffectCore() public void duplicateObject(UnityEngine.GameObject original, int howmany) howmany for (int i 0 i lt waypoints.Count 1 i ) for (int j 1 j lt howmany j ) Vector3 position waypoints i .transform.position j (waypoints i 1 .transform.position waypoints i .transform.position) howmany UnityEngine.GameObject go Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity) go.transform.localScale new Vector3(0.3f, 0.1f, 0.3f) objects.Add(go) private void LightsEffects() renderers new Renderer objects.Count for (int i 0 i lt renderers.Length i ) renderers i objects i .GetComponent lt Renderer gt () renderers i .material.color Color.red Set green color to the first one greenIndex 0 renderers greenIndex .material.color Color.green private void LightsEffectCore() Change color each delay seconds if (Time.time gt lastChangeTime delay) lastChangeTime Time.time Set color of the last renderer to red and the color of the current one to green renderers greenIndex .material.color Color.red if (changeLightsDirection true) Array.Reverse(renderers) changeLightsDirection false greenIndex (greenIndex 1) renderers.Length renderers greenIndex .material.color Color.green In this line if for example objects count is 5 then there will be 5 renderers but they will be all null. renderers new Renderer objects.Count


Game not accepted in Google Play even though it's built in 64 bit (Unity) I tried building my game according to the google play rules, but I get the following error message "This release is not compliant with the Google Play 64 bit requirement The following APKs or App Bundles are available to 64 bit devices, but they only have 32 bit native code 1. Include 64 bit and 32 bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code that it needs. This avoids increasing the overall size of your app." According to the documentation (https developer.android.com distribute best practices develop 64 bit) for Unity I should get a working version when I do Set Scripting Backend to IL2CPP Select the Target Architecture ARM64 checkbox Build as normal I've built the game both as APK and as AAB, but neither are accepted. I am using Unity 2018.3.14f1. I have downloaded this NDK https dl.google.com android repository android ndk r16b windows x86 64.zip and put the content to C Users MyName AppData Local Android


How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity? How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity? I have a component with some scripts on it Script1 and Script2. Inside the Script2.OnDestroy method I have the following line of code GetComponentInParent lt Script1 gt (). I want that line of code to return Script1 whenever I click the Play button inside Unity editor to stop my game. While right now it returns null.


Implementing getters for a singleton script in unity Ok the title might be a bit confusing but what I want to do is make a getter that returns the class, exactly like unity does with the camera.current. You should just be able to go class.current and get the running instance of the class but I have no idea how to do this as it would most likely be a static method but how would you return the class form a non static class without some sort of out of class variable? or do you have to make the class static?


Preventing the mouse from breaking keyboard navigation in UI? I am trying to achieve the following, a behavior like Windows Explorer where mouse and keyboard play nice together. Here's a GIF along explanations first I click one of the folders using the mouse second I click the background area, folder is not focused but still selected third I move to the next folder below using the keyboard To sum it up, mouse and keyboard play well together. Now in Unity it's an entirely different story, here is a fairly simple menu created using the actions in Hierarchy context menu, nothing special Here's what happens I click one of the buttons using the mouse I move down to the next button using the keyboard I click in the blank area, button loses focus I try to move down to the next button using the keyboard, nothing happens I have tried a couple of things like disabling Raycast target on images, disabling background panels or making them opaque but without success. How can one make Unity UI behave like Windows Explorer's one ? (where clicking in the blank area with the mouse does not break keyboard navigation)


What edition of VS is installed by Unity and what are its capabilities? My brother just installed Unity on my desktop, and it seems like it installed Visual Studio 2017 as well. I was planning to install Visual Studio before this, so I was wondering what kind of version is this edition of VS? Is this like a bare bones version? Does it work like a standalone version without lacking features? Can I use it just as a regular IDE to program in? I typically program in C , and I never used Unity before, so I'm not sure if this version of VS is only suited for Unity.


In Android, is it possible to get the first version of the app the user installed from the Play store? I have an app currently in alpha, and I am thinking of moving to beta soon. Once I do this step, I want to re initialize local files as the game changed quite a bit (local scores, etc.), and display a "Thank you for testing the alpha version" message and whatnot. To do this, I would like to check whether the first time the user installed my app from the app store was during the alpha, i.e. whether the version corresponds to one of the version of alpha. I found that it is possible to get the time the app was first installed, but haven't found a way to retrieve the version. Short story long is there a way to get the version of the app the user installed it for the first time? P.S. If possible, I would like to achieve this in Unity


How do I generate a sphere mesh in Unity? I'm making a game and I need a way to generate a sphere mesh in Unity for whatever reason. It needs to be generated by code and not be a pre made sphere or a sphere primitive as I need to edit in generation later on.


How can I send commands to only certain clients? I am building a multiplayer game server with Unity. In the game there are players moving around the map. Now, because this map is quite large compared to the number of players, I was thinking to have the server send each clients' position only when they are nearby, and then slow the rate down when they are far away. At first I was using the convenient SyncVar to do sync everyone's position, until I discovered its shortcomings, that is there is no conditional way to either sync or not a certain value. I came out with this player synchronization class so far (I removed all optimizations for simplicity) public class PlayerSyncPositionConditional NetworkBehaviour Vector3 lastPos void FixedUpdate () TransmitPosition() ClientCallback void TransmitPosition () CmdProvidePositionToServer(transform.position) Command void CmdProvidePositionToServer (Vector3 pos) transform.position pos Now, what this code does is nothing more than sending its position to the server when I am looking at the dedicated server instance, each players' position is correct. Also, as expected, each client will not receive any updates. From my research, I found that instead of SyncVar, I can use Server and ClientRpc to dispatch commands from the server to all clients, so this Server public void MoveTo() RpcMoveTo(transform.position) ClientRPC void RpcMoveTo(Vector3 newPosition) transform.position newPosition this will run in all clients would move all clients to the transform current position whenever needed. Now, the problem is that those commands, apparently affect every client, while I only want to affect ones that are near each other. I know how to have the server issue the MoveTo at any rate I want, setup more than one interval, etc. but I don't know how to have it send only to certain clients at a single time. I am not asking for the code itself, but I am getting really confused with all these client server architecture concepts, which class does what, etc. so any heads up will be greatly appreciated.


How can I draw a linerenderer line between two vector3 positions using the mouse left button click? This code is drawing a line but it's not drawing it on the camera in front of the camera. using UnityEngine using System.Collections using System.Collections.Generic public class DemoScriptDraw MonoBehaviour private List lt Vector3 gt positions new List lt Vector3 gt () private LineRenderer lr private void Start() lr this.GetComponent lt LineRenderer gt () private void Update() if (Input.GetMouseButtonDown(0)) Vector3 pos Input.mousePosition pos Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z)) positions.Add(pos) if ( positions.Count 2) SpawnLineGenerator( positions 0 , positions 1 , Color.red) void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace true lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, end) The result is that the line is seen in the scene view window but not in the game view window


Hold touch at the screen to move object I'm using unity2D and C , and I have a code for touch screen if (Input.touchCount gt 0) Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) startTime Time.time startPos touch.position else if (touch.phase TouchPhase.Ended) endTime Time.time endPos touch.position swipeDist (endPos startPos).magnitude swipeTime endTime startTime if (swipeTime lt maxTime amp amp swipeDist gt minSwipeDist) swipe() And this code for swipe void swipe() Vector2 distance endPos startPos if (Mathf.Abs(distance.x) gt Mathf.Abs(distance.y)) if (distance.x gt 0) Debug.Log("Right swipe") if (distance.x lt 0) Debug.Log("Left swipe") if (Mathf.Abs(distance.x) lt Mathf.Abs(distance.y)) if (distance.y gt 0) Debug.Log("Up swipe") if (distance.y lt 0) Debug.Log("Down swipe") How can I add to this code hold function, for for example move object at the screen?


AddRelativeForce not working correctly I am stuck on the code for couple of days but couldn't figure it out. Therefore I turned out to look the answer here but couldn't find any that match the requirement Hope some One might help here is the code Part1 Step Horizontal Movement Use to get left and right movement if(Input.GetKey ("right") Input.GetKey ("left")) moveDir.x Input.GetAxis("Horizontal") get result of AD keys in X rigidbody.velocity moveDir speed Part2 Continuse Forward Movement if (Input.GetKey(KeyCode.UpArrow) Input.GetKey(KeyCode.W)) moveDir.z Input.GetAxis("Vertical") rigidbody.AddRelativeForce(moveDir 50) I have a Cube with added rigidBody Component. When pressed left or right key the cube should move in that direction and when key is released it should stop Part one when run commenting part2 code runs correctly the other movement that I am trying to achieve is the cube should move continuously.But the thing is when pressed up key it should increase the magnitude and when released it should maintain the magnitude and move constantly.This is also achieved successfull with the part2 code by commenting part1 code But when but run without commenting any of them part1 results are correct but part2 does not provide correct result which was obtained by commenting part1 code Is there any other way to obtain the same reult


Loading encounters and collisions questions within 2D I had three basic questions regarding the creation of a 2D sandbox openworld game much like Terreria. Only looking for a general overview opinion, nothing too detailed. Any links to literature that would help answer the questions below would also be helpful. First off Keeping track of the map using regions chunks, lets say 512 x 512 chunks. Is it recommended to pre load the surrounding chunks of the 'chunk in focus', so if the character enters either one there is no load time? Or do you simply load smaller slices of the chunk next door, in the direction of movement? Secondly. Do I need to add a collision box to every tile that is preloaded so any NPCs that are off screen but 'next door' can interact with the environment? Or is this going to be massively CPU intensive ? (512 x 512 x 9 tiles alone) Third and last question. Off screen RANDOMDLY GENERATED NPCs monsters I assume dont load and render as they enter the viewable area on the active chunk but are loaded and activated sometime before they are seen. What are the general strategies use to handle this? For Reference Using c with Unity, no third party frameworks plugins. Many thanks John


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


Unity 2D extendable rope I need the player to be able to drag a game object that is connected to a rope, and for the rope to extend with it. I have purchased Ultimate Rope Editor, but it looks like it was meant for Unity 3D, and I can't get it to work. Any solutions, or am i out of luck?


Unity Animation makes object spawn at x0 y0 z0 I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at x0 y0 z0 and is doing the animation there. Then I realized that it was the animation, that increases and decreases y position and y rotation, starting at 0. So, I need to make the animation, that increases and decreases position y and rotation y, without affecting the actual position, because it will be different the position of the coins each time. In a while I will upload a screenshot for describing better the problem. Any clue?


vuforia how do I force objects into a 2D plane I'm working on a game in which cards are placed on a table and then rendered in augmented reality. These objects have 3D physics attached to them which doesn't work as well if they are either rotated or if the system mistakes them for being higher or lower then they really are. Is there a good method to force Vuforia Unity to place all items in the same 2D plane and keep all of them upright compared to that plane? I currently have the following code using UnityEngine using System.Collections public class projectioncode MonoBehaviour Vector3 p1 Vector3 p2 Vector3 p3 Vector3 v1 Vector3 v2 Vector3 normal use a plane with the following 3 coordinates public void setPlaneByPoints(Vector3 point1,Vector3 point2, Vector3 point3) p1 point1 p2 point2 p3 point3 v1 p2 p1 v2 p3 p1 normal getNormal(v1,v2) public Transform projectTransform(Transform input) input.position projectPoint (input.position) return input projects a 3d point into space Vector3 projectPoint(Vector3 point) Vector3 vOToPoint point p1 vector between origin and point float dist Vector3.Dot (vOToPoint, normal) distance plane to point return point dist normal caclulates the normal of 2 vectors Vector3 getNormal(Vector3 v1,Vector3 v2) Vector3 res (Vector3.Cross (v1, v2)) res.Normalize() return res This seems to project objects onto a plane but the results tend to be inaccurate and result in weird movements, particularly when moving the camera around. This is what it looks like


unity3d Instantiate and fire bullet realtive to player rotation in 3D This is a top down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel. Also tried putting the script on the player itself but also didn't work. GameObject projectile Instantiate (bullet, transform.position, transform.rotation) as GameObject projectile.GetComponent().AddForce(transform.forward speed) The problem is the bullets doesn't behave as intended, instead they don't appear relative to the player rotation and they just go in a very different direction. Shouldn't "Transform.Forward" mean forward in the Z position regarding the object's transform ?


How to make a PROPER main menu (or any other UI windows modals) in Unity? So, I'm currently learning both about Unity for the first time as well as the 'new' 2D UI system, but I'm having a hard time figuring out how to make windows, modals dialogs, main menus etc. which are not only functioning, but also modular, reusable and written following proper coding standards. Most how to's, blogs, Q amp As or tutorials I find only cover the most basic parts of UI development (e.g. how to drag a button from the toolbar to the scene window in 2 hours). So basically, I'd like to have a main menu which meets those (very common) requirements A button which 'starts' the game (e.g. by simply loading another scene) A button which 'quits' the game, but also opens up a confirmation dialog before A button which opens up an options dialog, which again is composed of multiple parts (audio, video...) and finally, it should be possible to go back to the previous screen using a 'back key button', for example Escape What I started with is a canvas which I called GameMenu. This canvas has several nested canvases, such as MainMenu OptionsMenu OptionsMenuAudioPart OptionsMenuVideoPart CancelMenuModal Then I created a menu script which works as some sort of state machine public class MenuScript MonoBehavior private GameObject currentStateObject private GameObject previousStateObject public void SetState(GameObject newStateObject) if(newStateObject null newStateObject) return if(CurrentStateObject ! null) CurrentStateObject.SetActive(false) previousStateObject currentStateObject CurrentStateObject newStateObject CurrentStateObject.SetActive(true) Every button has now an event trigger attached which calls the SetState(...) method on MenuScript. However, I've got the following problems How do I pass multiple parameters to methods invoked by event triggers? As soon as I add another parameter to SetState(...), for example bool isModal false to tell the method that it shouldn't disable the previous state, then it disappears from the event trigger action selection menu. How to I register key press events within the event triggers? It's easy by script (Input.GetKey(...) etc.), but I didn't find one on the event type selection. How do I make e.g. event triggers conditionally? So that certain events cannot be called when certain states are active? I know I can solve all those problems within the script and make a fully functional main menu which does exactly what I want, but then... I cannot use it for something else I don't use the new Unity UI system, which makes me wonder what's the purpose of it I got to reference all involed game objects (the canvases, buttons etc.) in script, which makes it not really 'extendable' anymore as this means for every changed requirement, I have to alter the script (e.g. a new state, menu, button etc) The main goal in the end is a script which I can use for all kinds of UIs without writing the same logic over and over again just because it's another scene, game state etc.


How do I import 2d character assets in unity? I recently downloaded a 2d platform assets that came with a player model. The character came in a lot of pieces like an image of eye, another for torso, etc. How do I go about making these images an actual character. The asset also came with a few animations like blinking, jumping, etc. How do I apply these? I'm new to unity and game development(started about a few days ago) so please help even if this may sound like a really dumb question. I use Unity BTW if it changes what the answer would be. Link to asset https assetstore.unity.com packages 2d environments free platform game assets 85838


How to categorize textures into atlases I am going to use texture atlasing for the first time in my games, and at first it seemed like a great idea to split textures into atlases by categorizing them by terrain themes e.g ForestTextures, WinterTextures etc. But that could cause a problem when for example a flower has to use transparency shader and other models use a diffuse shader. So those cannot be atlased into the same texture. Thus, would atlasing textures into themes as mentioned before and then splitting them by shader like ForestDiffuse and ForestTransparent be good? Or is there a better way to categorize and build them?


Can't assign animation to animation variable declared in script Unity2D So I'm trying to have my script pause an animation when the user clicks. Here's what I have so far I defined the animation up at the top public Animation anim and then further down, void Update () if (Input.GetMouseButtonDown(0)) anim "myAnimation" .speed 0.0f Code gives no error, however in Unity I have a GameController object to which this script is attached to. The gamecontroller object has a vacant field into which I drop my animation to. The issue is that when I try and drag and drop my animation or try to place it into that field, nothing happens, I keep getting the error down at the bottom saying that "The variable anim of GameController has not been assigned." How do I go about assigning myAnimation to the variable anim? When I try and drag and drop my animation file to this, nothing happens. This is under the GameController script which I assigned to a GameController object.


How to output to the Oculus and a 2D screen? We'd like to present an Oculus game to a large group of people. Not everyone will have an Oculus headset, so we'd like to output to both the Oculus and a second display. The problem is that the project uses an Oculus plugin to render its output, so all they output is two distorted circles, which doesn't display well when not wearing the Oculus headset. I thought of making a second Unity client (the "audience" client, running on the same computer as the Oculus application) that receives the output texture of an "audience" camera from the client running the Oculus version. My question is Can I use the network to send the output of a camera to the "audience" client so I can set it up for the second display, bypassing the Oculus plugin? How would I get the input on the "audience" client to map it to the screen?


Unable to get accurate y position on terrain to spawn object all I am trying to spawn some crabbies and can't seem to get an accurate y height to spawn. I have a terrain created with GAIA Pro 2 and have tried a few things to get an accurate y value. When trying to get the y from the terrain data I keep getting a 0 for example newCrabStartPos.y mainIslandTerrain.terrainData.GetHeight((int) rayPosition.x, (int) rayPosition.z) getYPositionFromRay(rayPosition) 2.5f Here is my current implimintation IEnumerator SpawnCrab() while(spawnedCrabbies lt waveCount) GameObject instance Instantiate(Resources.Load( quot Whakin Crab quot , typeof(GameObject))) as GameObject instance.transform.position SetStartPosition() spawnedCrabbies 1 yield return new WaitForSeconds(spawnRate) Vector3 SetStartPosition() float minDistanceAwayFromGoal 10f float maxDistanceAwayFromGoal 50f float xpos Random.Range( 1f, 1f) lt 0 ? Random.Range( minDistanceAwayFromGoal, maxDistanceAwayFromGoal) Random.Range(minDistanceAwayFromGoal, maxDistanceAwayFromGoal) float zpos Random.Range( 1f, 1f) lt 0 ? Random.Range( minDistanceAwayFromGoal, maxDistanceAwayFromGoal) Random.Range(minDistanceAwayFromGoal, maxDistanceAwayFromGoal) Vector3 newpos new Vector3(xpos, 0, zpos) Vector3 rayPosition new Vector3(xpos, 100, zpos) Vector3 newCrabStartPos new Vector3(newpos.x, 15, newpos.z) newCrabStartPos newCrabStartPos goal.transform.position newCrabStartPos.y getTerrainDistanceFromRay(rayPosition) mainIslandTerrain.terrainData.GetHeight((int) xpos, (int) zpos) getYPositionFromRay(rayPosition) 2.5f return newCrabStartPos float getTerrainDistanceFromRay(Vector3 drawFromPosition) RaycastHit hit new RaycastHit() if (Physics.Raycast(drawFromPosition, Vector3.down, out hit, 100)) return (100 hit.distance) collider.gameObject.transform.position.y return 0


Drag and drop card game NullReference Exception despite object existing? I am trying to build a Hearthstone style online TCG. Right now I am just working on getting the cards to drag around on the screen. Since I'm new to Unity, I'm using this tutorial https www.youtube.com watch?v AM7wBz9azyU amp index 3 amp list PLbghT7MmckI42Gkp2cILkO2nRxK2M4NLo I've copied the code in the tutorial pretty much exactly. What I have looks like this public class dragable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler public Transform parentToReturnTo null GameObject placeholder null public void OnBeginDrag(PointerEventData eventData) Debug.Log("OnBeginDrag") placeholder new GameObject() placeholder.transform.SetParent(this.transform.parent) LayoutElement le placeholder.AddComponent lt LayoutElement gt () if (le) Debug.Log("Found it!") Found le here... else Debug.Log("No dice.") le.preferredWidth this.GetComponent lt LayoutElement gt ().preferredWidth can't find le why? le.preferredHeight this.GetComponent lt LayoutElement gt ().preferredHeight le.flexibleHeight 0 le.flexibleWidth 0 parentToReturnTo this.transform.parent this.transform.SetParent(this.transform.parent.parent) GetComponent lt CanvasGroup gt ().blocksRaycasts false The rest of the class doesn't seem to effect the problem I'm having. That problem being whenever I try to write to the LayoutElement le, the console returns a NullReferenceException error. But when I try to read le for instance, testing if it exists in the if (le) loop (which exists only for debugging this particular issue), it works fine. Also, if you watch the tutorial video, you'll see that there is a "tabletop" on the upper half of the canvas that you can drop cards on to this doesn't seem to work unless I comment out all code that tries to write to le's attributes. Anyone know how to fix this?


Character controller going down slopes When I go down slopes with character controller, if the speed is too high, the character just flies off the slope and lands at the bottom. I want my character to "stick" to the slope rather then just jump of it. I came up with code to do so, but it didn't turn out as I planned. Now the character just slides on the slope when I stop pressing the arrows (not staying at its place on the slope). Physics.Raycast (transform.position, Vector3.down, out hit) transform.position transform.position new Vector3(0f, distance hit.distance, 0f) Thanks for the help, i couldn't figure this out all day.


Power up spawns 2 3 times after a restart, but enemies spawn normally I have two spawning objects that use the same behaviour. They are being called in the same function and in the same situations. The only difference is the variable of time that classifies what's an enemy and what's a power up. The spawning of enemy objects is working fine no matter how many times I restart the game, the behaviour is the same. But with the power up spawning object, it spawns the right way sometimes, but in other times it spawns like 2 or 3 times in the same place. This only happens when I restart the game. How can I fix this bug? I'm not fluent in english. File 1 public float enemySpawnSeconds 2.5f public float powerUpSpawnSeconds 6f public void Start() gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () private void Update() GameSpeed() public void StartSpawnObjects() StartCoroutine(SpawnPowerUps()) StartCoroutine(SpawnEnemies()) public IEnumerator SpawnEnemies() yield return new WaitForSeconds(2f) while (gameManager.startGame false amp amp gameManager.gameOver false) Instantiate(enemies Random.Range(0, 2) , transform.position new Vector3(9.8f, yPosition Random.Range(0, 2) ), Quaternion.identity) yield return new WaitForSeconds(enemySpawnSeconds) public IEnumerator SpawnPowerUps() yield return new WaitForSeconds(2f) while (gameManager.startGame false amp amp gameManager.gameOver false) yield return new WaitForSeconds(powerUpSpawnSeconds) Instantiate(powerups Random.Range(0, 3) , transform.position new Vector3(11.1f, yPosition Random.Range(0, 2) ), Quaternion.identity) File 2 void Update() spawnPlayer() gameTimer() restartGame() public void spawnPlayer() if (startGame true) starting the game if (Input.GetKeyDown(KeyCode.Space)) Instantiate(player, player.transform.position, Quaternion.identity) spawned true startGame false uiManager.HideTitleScreen() spawnManager.StartSpawnObjects() public void gameTimer() if (startGame false) timer 0.0165447f game time public void restartGame() if (gameOver true) restarting the game timer 0f spawnManager.enemySpawnSeconds 2.5f if (Input.GetKeyDown(KeyCode.Space) amp amp uiManager.restart true) gameOver false uiManager.HideTitleScreen() spawnManager.StartSpawnObjects()


Unity Issue with Camera follow script I have a camera follow script which is attached to the main camera and it follows the players position and rotation. The player needs to be near the top of the screen. However when I hit play, the player is shown at the center of the screen. This is how it looks in the scene view and this is how it should reflect when I hit play. Here the quot y quot position is 2 and quot x quot rotation is 0. But when I press play, the quot y quot position is still 2 but quot x quot rotation changes to 14.9. And the player is shown at the center of the screen and not near the top. Here is the camera follow script SerializeField Transform target public Vector3 defaultDist SerializeField float distDamp .1f public Vector3 velocity Vector3.one Transform myT void Awake() myT transform void LateUpdate() SmoothFollow() void SmoothFollow() Vector3 toPos target.position (target.rotation defaultDist) Vector3 curPos Vector3.SmoothDamp(myT.position, toPos,ref velocity ,distDamp) myT.position curPos myT.LookAt(target, target.up) After I hit play, I want the x rotation to stay at 0 and the player to be shown near the top of the screen. Can someone please help?


How to achieve light effect on a car panel icons? I'm making a car and I want to make lightable icons on its panel. I want to add 'on' and 'off' effect to them separately. The Sprites are plane objects, with one material and UV texture for each plane. If I change material property it will change in all objects which use this material. I don't think creating 10 materials for 10 sprites is the best choice, what should I do in this situation?


VFX for Unity sci fi game Can someone please give me any tips guides on how to create hologram, disintegration amp freeze effects in Unity game? I have a sci fi shooter game in mind, and I would like to incorporate the above mentioned effects in it. I would like to achieve something like these Holographic effect 1, 2 Disintegration effect 1 Freezing effect 1 And I would prefer to achieve these without using a premium plugin. Budget issues.


Efficient modification of Texture2D at runtime for a 2D painting game in Unity3D I have spent some time looking for different solutions to be implemented in a mobile painting game I'm creating. At this time, everything is working but I have some serious performance problems on large screens and slow devices because I massively use setPixel setPixels and apply on Texture2D. I have come across 2 ways to speed things up 1) Tile the image in small chunks, every chunk would be a Texture2D, and just upload (calling Texture2D.Apply()) the modified chunks. 2) Another trick I could apply on top of the tiling solution is to catch changes in an array and write them down to the needed Texture2D chunk and apply it every X miliseconds if modified. I would like to know what other optimizations I could apply to this subject. Perhaps I should throw setPixel away and go with another more efficient way? Cheers.


Backing up non text based assets I'm using a Source Control Management tool (git) for backing up configurations, code etc. But how do I manage art assets and other game assets that are in binary formats, and tend to be big (animators, audio sources etc)? The working theory is to backup all assets using cloud storage services like Google Drive or similar. But how do you effectively manage your projects? That would work for me being solo, but if I added another team member, how would I effectively manage projects while multiple developers artists are contributing? I'm working with Unity, if it's relevant.


How to load scene after a set delay? I have tried using IEnumerator and Invoke("method",delay in seconds). My first scene is just an image with my studio name on it. I have script that will load the next scene ("Main Menu") 3 seconds after the first scene is loaded. For this, I tried using IEnumerator and Invoke with 3 seconds delay before calling Application.LoadLevel. However, on the device, game is launched, unity splash screen is displayed and "Main Menu" scene appears. it looks like the image scene loads while unity splash screen is displayed and by the time unity screen is completed, the image scene has done executing. Is there any way to ensure a scene stays on screen before loading the next scene? I could add a button that player should tap to start game. But I don't want to do that.


Problem with texture's quality in Unity . After setting a texture to GameObject, it looks bad. Some pixels can be seen and colors are distorted. The image itself is in good quality but after importing it to Unity, it looks ugly. Screenshot explanations left, image attached to the GUITexture GameObject middle, image before importing to Unity right, after importing (shown in inspector)


Add Atten property in Unity Shaderlab In Unity Shaderlab shader, Is there any way to apply Atten value? Using surface shader, and vertex fragment shader I can do it easily. But, I didn't find any reference to do that in Shaderlab syntax. Shader "Diffuse" Properties Atten ("Light Attenuation Power", Float) 1.0 lt how to apply? Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Transparency (A)", 2D) "" SubShader Pass SetTexture MainTex constantColor Color combine texture constant, texture constant this makes syntax error. constantColor Atten Color


Unity Instantiate GameObject from client on Network I am building a game where a weapon shoots prefab bullets. I am trying to make this a multiplayer game, so the bullets need to be spawned into the Network. What happens right now is that if I shoot a bullet from a host, the bullet is shot, but doesn't appear on the client screen. If I shoot the bullet from the client, the bullet doesn't appear on either screen. In fact, the function CmdShoot() isn't even called, as the Debug.Log("Hello") is not called. Here is the current code public class Gun MonoBehaviour private GameObject bulletPrefab void Update() if (Input.GetMouseButtonDown(0)) owner.GetComponent lt PlayerSetup gt ().CmdShoot(bulletPrefab, transform.position, owner.name, GetComponentInParent lt Weapon gt ().angle) public class PlayerSetup NetworkBehaviour void Start () Disable components if not local player Command public void CmdShoot(GameObject bulletPrefab, Vector3 position, string playerName, float angle) Debug.Log("Hello") GameObject bullet Instantiate(bulletPrefab, position, Quaternion.identity) bullet.name "bullet " playerName bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) Vector3.right bulletPrefab.GetComponent lt Bullet gt ().force) Destroy(bullet, 10f) NetworkServer.Spawn(bullet) Edit This piece of code doesn't work either, gives the same result. No error, but the function is also not called. The Input is detected though void Update() if (Input.GetMouseButtonDown(0)) CmdShoot() Command void CmdShoot() Debug.Log("Shoot") GameObject bullet Instantiate(gunComponent.bulletPrefab, gun.position, Quaternion.identity) bullet.name "bullet " transform.name bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(GetComponentInChildren lt Weapon gt ().angle, Vector3.forward) Vector3.right gunComponent.bulletPrefab.GetComponent lt Bullet gt ().force) Destroy(bullet, 10f) NetworkServer.Spawn(bullet)


Detect collision from a particular side I'm making a platform sidescrolling game. All I want to do is to detect if my character is on the floor function OnCollisionStay (col Collision) if(col.gameObject.tag "Floor") onFloor true else onFloor false function OnCollisionExit (col Collision) onFloor false But I know this isn't the accurate way. If I hit a cube with a "floor" tag, in the air (no matter if with the character's feet or head) I would be able to jump. Is there a way to use the same box collision to detect if I'm touching something from a specific side?


Resizing the camera view in Phaser 3 just like in Unity I started to work in Phaser 3 with a previous background in programming in Unity and I can't figure out how to zoom the camera view. In Unity, I can change this value, to resize the camera view Then, everything in its view becomes bigger or smaller and it does not affect GUI elements, and the camera still fills up the full game window. In Phaser I was trying to use those methods this.cameras.main.setSize(width,height) it just resizes the camera making it smaller, and everything outside the camera becomes black this.cameras.main.setViewport(x,y,width,height) just as above, but x and y ads padding this.cameras.main.setZoom(3) the closest effect I want to achieve, but it zooms to the center of the scene, scales GUI elements and messes the camera bounds I made an illustrative picture which can explain my problems better So how can I change the size of the main camera, to fit the game window and not scale the GUI, keeping the camera bounds at the same time?


Using one Vive controller default to left hand? We're making a sailing game in VR for Vive Pro, where you hold the rudder with your left hand using a Vive controller. We use just one controller because there's nothing to do with your other hand, and the rudder is on the left side of the player (it's a seated setup). The second controller will be charging, or it will be off while the game is being played. We use the Player prefab that comes with the Steam VR Unity Plugin, that has GameObjects for both the left and right hand, with the option to show controllers and or hand skeletons that move according to what controls you're using on the controllers. The problem is that when only one controller is on and detected by Steam VR, it decides to show the right hand, instead of the left hand that we're holding it with. When both controllers are switched on and connected, it works as expected. The left hand controller is at the player's left side as long as the unused controller is located at the player's right side. I tried putting a left handed skeleton on the right hand controller gameObject in the Player prefab, but that resulted in an unresponsive skeleton (not visualising the interaction of the player with the controller). How can we make it so that when using only one controller, it shows as the left hand? So what we want is like in this picture, hold the controller with one hand (normally the left hand) except always showing a left virtual hand in the application, and still mimicking whatever controls the user is pressing on the real controller.


What is a "Projectile"? I don't know what a Projectile os. I'm not sure whether a Projectile is a spawn point which spawn a number of object or a number of multiple objects. I'm referring to this website. How do I use Projectiles and what does it mean?


How do I check user's unlocked achievement and leaderboard scores via GPG plugin I need to load user's achievement and their scores from leaderboard in my game. But the Social.LoadScore() and Social.LoadAchievements() both returns a 0 size array in callback. When I checked the implementation in Google Play Gaming's PlayGamePlatform.cs, both the method has this summary Not implemented yet. Calls the callback with an empty list. So my question is How do I get this data in Unity? Has anyone tried any other method to get the data?


Embed Unity3D and load multiple games from a single app Is is possible to export an entire unity3d project game as an AssetBundle and load it on iOS Android Windows on an app that doesn't know anything about such game beforehand? What I have in mind is something like the web plugin does it loads a series of .unity3d files over http, and render inline in the browser window. Is it even possible to do something closer for iOS Android? I have read a lot of docs so far, but still can't be sure http floored.com blog 2013 integrating unity3d within ios native application.html http docs.unity3d.com Manual LoadingResourcesatRuntime.html http docs.unity3d.com Manual AssetBundlesIntro.html The code from the post at http forum.unity3d.com threads 112703 Override Unity Data folder path?p 749108 amp viewfull 1 post749108 works for Android, but how about iOS and other platforms?


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


How do I set up a bullet to fire towards the mouse pointer? I am making an FPS, in Unity. I have a player with a gun, and I have a bullet prefab. I changed the mouse pointer to look like a crosshair, but I don't know how to place the bullet where the crosshair is aiming. The player movement is on the x and z axis. I have done lots of research on the Internet, and couldn't find anything suitable most of what I found, I could not understand enough to change it according to my needs. How do I set up a bullet to fire towards the mouse pointer?


Detect when any part of a collider leaves a trigger zone on Unity 3D I've searched all over for a simple solution on this, and found posts as old as 2011, with a bunch of hackish ways to badly work this out. I want to detect when ANY part of a collider leaves a trigger area. Some solutions I found and why they won't work on my case Using onTriggerExit will only trigger when the collider is COMPLETELY out of the trigger area, making it not ideal for boundaries of maps. Calculating using bounds may work, but a bit complex when using a polygon collider with convex shapes. I'm new to Unity and I'd guess this would be a pretty simple, default behaviour for many games.. Really surprised me that I found zero good answers for this on the web (both in stack exchange and Unity forums). Any help would be appreciated.


How to navigate through google Map in unity I am working on loading the google map and navigating through the map. I have loaded the google map which shows the current location in unity. Now I need to show the direction from Place A to Place B.How Can I implement this in unity


Character Controller Rotation in Unity I am using the following code for moving a capsule Vector3 move new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) controller.Move(move Time.deltaTime playerSpeed) I am using the following code for the camera, which is a child of the capsule. (xRotation is intialized to 0.0f, and playerBody is a transform) float mouseX Input.GetAxis( quot Mouse X quot ) mouseSpeed Time.deltaTime float mouseY Input.GetAxis( quot Mouse Y quot ) mouseSpeed Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX) The character is always moving in the same direction, ignoring the rotation. How can I fix this?


How can I draw a linerenderer line between two vector3 positions using the mouse left button click? This code is drawing a line but it's not drawing it on the camera in front of the camera. using UnityEngine using System.Collections using System.Collections.Generic public class DemoScriptDraw MonoBehaviour private List lt Vector3 gt positions new List lt Vector3 gt () private LineRenderer lr private void Start() lr this.GetComponent lt LineRenderer gt () private void Update() if (Input.GetMouseButtonDown(0)) Vector3 pos Input.mousePosition pos Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z)) positions.Add(pos) if ( positions.Count 2) SpawnLineGenerator( positions 0 , positions 1 , Color.red) void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace true lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, end) The result is that the line is seen in the scene view window but not in the game view window


How do I adjust my rigidbody velocity on a local axes? I have an fps rigid body script, code listed here using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour Start is called before the first frame update SerializeField Camera cam SerializeField float camSpeed float yaw Vector3 direction Rigidbody myrigbody void Start() myrigbody GetComponent lt Rigidbody gt () Update is called once per frame void Update() cam.transform.Rotate(new Vector3( Input.GetAxis( quot Mouse Y quot ) camSpeed, 0, 0)) yaw (yaw Input.GetAxis( quot Mouse X quot ) camSpeed) 360f direction new Vector3(Input.GetAxis( quot Horizontal quot ), myrigbody.velocity.y, Input.GetAxis( quot Vertical quot )) private void FixedUpdate() myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0)) myrigbody.velocity direction The particular part I'm having trouble with is the last line myrigbody.velocity direction This code is moving my character perfectly, except that it doesn't adjust to my rotation in game. If i rotate 90 degrees to the right in game, and press forward, I will move to the left (from the players perspective), I will move in the same direction when i press forward (or any other direction) no matter how I have rotated. How do I alter the rigid bodies velocity while taking into account how the player has rotated?


Texture with Transparent background has black background in Unity please see the below image. I made a model in Blender that has eye meshes with UV mapped Pupils. But trying to import all this into Unity is causing tons of weird visual errors... The pupil png has a Transparent background but that background shows up as Black in Unity. Googling says to fix it by choosing 'Transparent' shader but all the ones I try end up cutting out the Eye mesh beneath it. Any help appreciated.


How does Unity's execution order work? I wonder how Unity's execution order really works. There's an ordered list at https docs.unity3d.com Manual ExecutionOrder.html, but how does this work when there are different gameobjects involved? Will Unity first run the specific function for all the monobehaviours in the scene before it proceeds to the next function? Or will each monobehaviour go through that specific order of functions before Unity goes to the next monobehaviour? Or is it more complex? It isn't really clear to me from the documentation. For example, normally Start() gets called before Update(), however when I was debugging, Update() on my Avatar prefab got called before Start() of my Camera child object. Is this supposed to happen?


Unity scenemanagement freezes I am very new to Unity, and coding in general. Anyways, I'm trying to load another scene on click, but when I try to do so in the editor, Unity freezes. Also, it, by chance it seems, worked twice when I newly added the script. Not always when I newly add the script, but twice. using UnityEngine using System.Collections using UnityEngine.SceneManagement public class GameMenu MonoBehaviour Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButtonDown(0)) SceneManager.LoadSceneAsync(sceneName "Wisp1") Can somebody help?


Asset Bundle hashes appear inconsistent The flow I see people discussing using is the following In your build asset bundles step, grab the hash of each bundle Store that on your server somewhere Fetch those hashes at runtime Use the Caching.IsVersionCached with that hash to detect if you already have a bundle If not download the bundle and cache it success If this is how you are supposed to do it, why does the main mainfest(example Android.manifest) which can be loaded into a class AssetBundleManifest, have a function to get the hashes for you unity doc I was able to just use that technique up until now, but I have hit a problem where it failed to detect a hash change properly and that function is not giving me back the same hash that I see in one of my other bundles .manifest file Hashes AssetFileHash serializedVersion 2 Hash a44a4d42247721b8bd6f32531f73f9e3 TypeTreeHash serializedVersion 2 Hash ea5a42e0fd8ea905efa7aa926a3b8944 I am under the impression that the first value above is what would should match what you had stored on your server.


Season Change Reveal Effect I was watching the teaser trailer for Seasons After Fall, and I was struck by the effect they use to transition between seasons (around 21 24 seconds) The level art, including the background and the foreground platforms, change from a sepia coloured autumn to a lavender winter, with the effect spreading outward from the player character a bit like water soaking through paper. It looks like more than just a palette change, as details in the leaf and bark patterns change in the transition. How could I achieve an effect similar to this in a 2D Unity game?


High performance screenshots in LWRP I'm trying to capture some screenshots for my game. They need to be saved as jpgs to a folder, latency is not an issue, I don't care if it happens over 10 seconds. My number one priority is to keep the game at a steady framerate. Some things I've tried I've tried ScreenCapture.CaptureScreenshot but that is super slow and the game hangs for a split second. I've tried the old method of texture2d.ReadPixels() and EncodeToJPG() but that was unbelievably slow. I also found a relatively new feature https docs.unity3d.com 2018.3 Documentation ScriptReference Rendering.AsyncGPUReadback.html I found a repo using this feature to capture screenshots asynchronously https github.com keijiro AsyncCaptureTest This requires the use of OnRenderImage(), but I'm using LWRP and OnRenderImage() isn't supported in scriptable render pipeline. Pulling my hair out Some metrics from my testing ScreenCapture.CaptureScreenshot is 200ms. ReadPixels() is 40 70ms. Texture.Apply() is 5ms. EncodeToJPG() is 35 50ms. File.WriteAllBytes() is lt 1ms. Also posted this question here and here


Unity Trying to add a simple light to a prefab A bit of a unity beginner here. I have a windmill prefab and I would just like to add a simple point or directional light to my prefab. I added the component for a light to the prefab and started the game, but it seems like no matter what I try, the light would not appear. I tried to move the component to the top in the Inspector window (thinking another component would overwrite the light properties). Any ideas? Or things Im doing wrong?


How to Save boolean properly on Playerprefs? I want to make a shop system if I buy the items, the items will be saved on Playerprefs, no need to buy again when I restart or re open the game, for that I already make it to setInt but I don't know when I call getInt. I tried to call it in the start method with a new int index but it doesn't work. This my script for store the itemsType System.Serializable public class m ShopItem public Sprite theIcon public int price public bool isBuyed false Then I make it list public List lt m ShopItem gt ShopItemsList new List lt m ShopItem gt () SerializeField GameObject ShopPanel SerializeField Transform theContent GameObject g Button buyBtn public GameObject itemTemplate void Awake() if (Instance null) Instance this else Destroy(gameObject) for (int i 0 i lt ShopItemsList.Count i ) Create a different PlayerPrefs for each Item in the Shop. PlayerPrefs.SetInt( quot isBuyed quot i, ShopItemsList i .isBuyed ? 1 0) private void Start() for (int i 0 i lt ShopItemsList.Count i ) g Instantiate(itemTemplate, theContent) g.transform.GetChild(0).GetComponent lt Image gt ().sprite ShopItemsList i .theIcon g.transform.GetChild(1).GetComponent lt TextMeshProUGUI gt ().text ShopItemsList i .price.ToString() buyBtn g.transform.GetChild(2).GetComponent lt Button gt () ShopItemsList i .isBuyed PlayerPrefs.GetInt( quot isBuyed quot i) 1 ? true false if (ShopItemsList i .isBuyed) DisableBuyButton() buyBtn.AddEventListener(i, OnShopItemBtnClicked) Debug.Log(ShopItemsList i .isBuyed) void OnShopItemBtnClicked(int itemIndex) if (m shopManager.Instance.HasEnoughCoins(ShopItemsList itemIndex .price)) m shopManager.Instance.UseCoins(ShopItemsList itemIndex .price) purchase Item ShopItemsList itemIndex .isBuyed true PPlayerPrefs.SetInt( quot isBuyed quot itemIndex, ShopItemsList itemIndex .isBuyed ? 1 0) disable the button buyBtn theContent.GetChild(itemIndex).GetChild(2).GetComponent lt Button gt () DisableBuyButton() add avatar m Profile.Instance.AddBallType(ShopItemsList itemIndex .theIcon) else NoCoinsAnim.SetTrigger( quot NoCoins quot ) Debug.Log( quot You don't have enough coins!! quot ) void DisableBuyButton() buyBtn.interactable false buyBtn.transform.GetChild(0).GetComponent lt Text gt ().text quot PURCHASED quot but the result is the same I have to rebuy when going to the main menu or restart the game. Can anyone tell me what's wrong with my script?


How can I switch between starting a coroutine vs running the routine all at once? I'm generating a level, and I have an optional delay to show the steps level generation one by one. If my generationDelay boolean is true, I want to use StartCoroutine to spread the generation out over time. If it's false, I want to call the same method but without StartCoroutine. The problem is that the method is type IEnumerator. I can make two methods one type of IEnumerator and one not. But I wonder if there is a way to use one method. In the first script top i did public bool generationDelay false Then in a method private void BeginGame() mazeInstance Instantiate(mazePrefab) as Maze if (generationDelay true) StartCoroutine(mazeInstance.Generate(generationDelay)) else mazeInstance.Generate(generationDelay) Then the other script where the method Generate is In the top public float generationStepDelay 0.01f Then the method Generate public IEnumerator Generate (bool generationDelay) if (generationDelay true) WaitForSeconds delay new WaitForSeconds(generationStepDelay) cells new MazeCell size.x, size.z List lt MazeCell gt activeCells new List lt MazeCell gt () DoFirstGenerationStep(activeCells) while (activeCells.Count gt 0) yield return delay DoNextGenerationStep(activeCells) I'm getting an error on the line WaitForSeconds delay new WaitForSeconds(generationStepDelay) "Embedded statement cannot be a declaration or labeled statement" And an error on the line yield return delay "The name 'delay' does not exist in the current context" The reason I want to use a bool variable is that when i'm using StartCoroutine it's kind of slow, even if I change the value of generationStepDelay to 0 it's kind of slow. And if I'm not using StartCoroutine and not using the Generate method as IEnumerator it will work fast. So i wonder what should I do and how?


Problems generating procedural mesh I have this code below that I found on catlikecoding that generates a procedural grid that I want to apply noise to, however once I go over a certain value it does expand vertically. Can anyone see why it wouldn't? For example, 100x100 However, 500x500 is clearly wrong Code used using UnityEngine RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)) public class Island MonoBehaviour public int xSize, ySize private Mesh mesh private Vector3 vertices private void Awake () Generate() private void Generate () GetComponent lt MeshFilter gt ().mesh mesh new Mesh() mesh.name "Procedural Island" vertices new Vector3 (xSize 1) (ySize 1) Vector2 uv new Vector2 vertices.Length for (int i 0, y 0 y lt ySize y ) for (int x 0 x lt xSize x , i ) vertices i new Vector3(x, y) uv i new Vector2((float)x xSize, (float)y ySize) mesh.vertices vertices mesh.uv uv int triangles new int xSize ySize 6 for (int ti 0, vi 0, y 0 y lt ySize y , vi ) for (int x 0 x lt xSize x , ti 6, vi ) triangles ti vi triangles ti 3 triangles ti 2 vi 1 triangles ti 4 triangles ti 1 vi xSize 1 triangles ti 5 vi xSize 2 mesh.triangles triangles mesh.RecalculateNormals()


Getting scene normals in Unity When I get the depthnormals with the shaderreplace script, it just replaces all the shaders in the scene and uses the meshes geometry to calculate the normals, ignoring the normalmap textures applied on them. How can I get the final rendered scene normals to a rendertexture like it appears in the editor windows normal debug mode that is used for deferred light calculations and ambient occlusion and such ?


Unity2D How to check for overlap using the job system Currently, I have implemented a job in unity for performance reasons. In that job, I am checking if a game object overlaps with the "detection circle". The job looks like this BurstCompile public struct CreateGridJob IJob public float diameter, radius public NativeArray lt int2 gt positionsArray public NativeArray lt bool gt isWallArray public float3 bottomLeft public int sizeX, sizeY public float3 right, up public LayerMask layer public void Execute() int x 0, y 0 for (int i 0 i lt positionsArray.Length i ) float3 point bottomLeft right (x diameter radius) up (y diameter radius) bool wall true Vector3 worldPoint point if (Physics2D.OverlapCircle(worldPoint, radius, layer)) wall false positionsArray i new int2(x, y) isWallArray i wall if (x sizeX 0) x y if (y gt sizeY) y 0 The problem course when I have to call if (Physics2D.OverlapCircle(worldPoint, radius, layer))as it can only be called in the main thread thus throwing an exception. The result of this job will be a grid to be used in pathfinding. Am I going in the right direction or is there a different way of doing this? Edit 1 Unfortunately no, not all are convex (can be changed if there's no other way). Here is an example of a concave asteroid There are many of these asteroids scattered across the scene. First, they are grouped in sectors, and each sector has its own asteroids. Sectors are independent of each other and are only connected through portals. For the simulation purposes, all (at least for now) sectors are active and generate their grid. But a single sector can have for example 200 asteroids. They are placed at random. Edit 2 Flow! A script generates sectors and their children. In this script on Update, I call the CreateGridJobHandle. which gets the Job handles and then I execute them. private void Update() if (Helper.IsStatusGraterOrEqual(GameStatus.FirstSectorGridSet)) NativeArray lt JobHandle gt jobHandleList new NativeArray lt JobHandle gt (Sectors.Count, Allocator.TempJob) for (int i 0 i lt Sectors.Count i ) JobHandle handle Sectors i .SectorGrid.CreateGridJobHandle() jobHandleList i handle JobHandle.CompleteAll(jobHandleList) jobHandleList.Dispose() for (int i 0 i lt Sectors.Count i ) Sectors i .SectorGrid.SetGridFromData() public JobHandle CreateGridJobHandle() CreateGridJob job new CreateGridJob() jobPositionsArray new NativeArray lt int2 gt (gridSizeX gridSizeY, Allocator.TempJob) jobWallsArray new NativeArray lt bool gt (gridSizeX gridSizeY, Allocator.TempJob) job.positionsArray jobPositionsArray job.isWallArray jobWallsArray job.diameter nodeDiameter job.bottomLeft transform.position Vector3.right GridWorldSize.x 0.5f Vector3.up GridWorldSize.y 0.5f job.sizeX gridSizeX job.sizeY gridSizeY job.right Vector3.right job.up Vector3.up job.radius NodeRadius job.layer WallMask return job.Schedule() After this, I just set the grid into 2d array and apply the isWall values. public void SetGridFromData() for (int i 0 i lt jobPositionsArray.Length i ) if (jobWallsArray i ) grid jobPositionsArray i .x, jobPositionsArray i .y .IsWall jobWallsArray i jobWallsArray.Dispose() jobPositionsArray.Dispose()


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


Moving a dynamically spawned object I would like to create an object dynamically when the player presses Q and use this object in Instantiate and in transform.Translate. The problem is that the translation must be outside the if that checks for the Q press, but it applies to the cube that I created inside the if. using System.Collections using System.Collections.Generic using UnityEngine public class instancier new object MonoBehaviour public float moveSpeed 5f void Update () if (Input.GetKeyDown (KeyCode.Q)) GameObject objet new GameObject ("objet") GameObject cube new GameObject ("cube") cube Instantiate( objet, new Vector3(1, 2, 3), Quaternion.identity ) cube.transform.Translate( Time.deltaTime moveSpeed, 0, Time.deltaTime moveSpeed, Space.Self )


How can I make custom character face editor In my game In an optimal way? In many games there Is section as customize character that you can make your own character.I always love to know how can I make something like It. Even old game have this feature? but how ? For Implementing It I need accurate separation for communating between values and facial parts size. So first I made multiple height map based on facial parts for modifying by vertex shader and work correctly but this method Isn't optimal.can I Implement It just by one texture? then I tried by using colorful mapping texture for detecting facial parts, but I have problem for getting color values from mapping texture In my shader code. mapping texture My problem Is that my vertex shader Isn't match with my mapping texture.for example If I change NoseLength other parts will changes.how can I tell to vertex shader which part is nose,forehead,lip,cheek,... In my colorful mapping. Here Is my Shader Code Shader "Custom Extrude" Properties MainTex ("Base (RGB)", 2D) "white" ModTex ("Vertex Modify", 2D) "white" NoseLength ("NoseLength ", Range( 0.05,0.01)) 1.0 LipSize ("LipSize ", Range( 0.05,0.01)) 1.0 CheekBones ("CheekBones ", Range( 0.05,0.01)) 1.0 ForeHead ("ForeHead ", Range( 0.05,0.01)) 1.0 EyeSize("EyeSize", Range( 0.05,0.01)) 1.0 SubShader Tags "RenderType" "Opaque" "Queue" "Transparent" Cull off CGPROGRAM pragma surface surf Lambert vertex vert pragma target 3.0 sampler2D MainTex sampler2D ModTex uniform fixed NoseLength uniform fixed LipSize uniform fixed CheekBones uniform fixed ForeHead uniform fixed EyeSize struct Input float2 uv MainTex void vert(inout appdata full v) float4 lipSize tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).g Green float4 nose tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).b Blue float4 eye tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).r Red float2 cheek tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).rg Yellow float2 forehead tex2Dlod( ModTex, float4(v.texcoord.xy, 0, 0)).rb Purple v.vertex.y LipSize lipSize v.vertex.y NoseLength nose v.vertex.y EyeSize eye v.vertex.y CheekBones cheek v.vertex.y ForeHead forehead void surf (Input IN, inout SurfaceOutput o) half4 c tex2D ( MainTex, IN.uv MainTex) o.Albedo c.rgb o.Alpha c.a ENDCG FallBack "Diffuse"


How can shader code duplication be reduced in Unity? In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code. On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again. How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?


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?


Unity How does Time.smoothDeltaTime work I can't seem to find any actual information on what Time.smoothDeltaTime does or how it works. I would assume it takes a rolling average of previous deltaTimes but how does it do that? Is the average asymptotic? How sensitive is it to outliers? What is it's actual intended use case? If anyone could explain how it works, or link to a resource on what it is doing it would be really helpful.


No animation clips in assets folder I'm trying to import an FBX file made in Blender into Unity so I can use the actions created in Blender in a Unity animation state machine. A lot of sites seem to suggest that simply dropping the FBX file into the assets will automatically import animation clips, but that doesn't seem to be happening. Unity does however recognize the discrete actions created. Tutorial image My screen image I used the Blender export settings "Include Animation" and "All actions", but not "Include Default Take" as people recommend. For reference, I'm trying to follow the animator controller tutorial at unity3d.com How can I retrieve my animation clips from the fbx file, or is there another way to insert them into the Animator? Thanks!


How to create a material that blends textures in Blender to Unity workflow I'm new to Blender and Unity and trying to figure out the best way to create a material that will use either vertex colors or a texture map to interpolate between other textures on a single mesh. This is the sort of effect you might use when you want to have a big grassy terrain mesh with a dirt path running down the middle of it and patches of rock here and there and instead of modeling each of those as separate pieces, you create a single shader that takes a grass, dirt and rock texture map and uses a fourth blending map to decide which to sample from. I come from a Maya background which provides an HLSL material shader that makes this straight forward. It's not as clear to me how to do this in Blender, and in particular the best way to set it up so that it imports into Unity cleanly. I suspect that setting up the shader using Blender's cycles shading network won't create anything Unity can recognize. Blender also has the Open Shading language, but again I'm unsure how well this will work with Unity. I could also bake all my textures, but this strikes me as wasteful of memory and bandwidth. I have experience with both HLSL and GLSL. Is trying to do this with custom shaders the best way to do about things? What's the best way to set things up so that both Blender and Unity are happy?


Unity Extending Game Object best practice What is best practice when wanting to add to GameObject class? I would like all GameObject to be able to change color IF they have a renderer. Ive tried using a helper class that takes a GameObject and lerps the color value but if i want it to have an update method it must inherit MonoBehaviour, and if it does inherit it then i cant instanciate that helper class. Now im thinking about creating a new class that manages a GameObject and inherits from Monobehavoiur. It would have one GameObject as a member that it can manipulate. But then i would have to instanciate it from somewhere. Hmmm unity has its logic but i havent found it yet. Is it clear what i am having problems with? Otherwise please ask.


Obscure primitive data types against cheating im trying to create lightweight value obscurer, against possibility to blatantly change primitive values in memory editor. Such as cheat engine. Here's what i have to far. lt summary gt Obscure for type int. lt summary gt public class ObscuredInt public ObscuredInt() this.value 0 public ObscuredInt(int value) this.value value private int a private int b lt summary gt Current obscure value. lt summary gt public int value get return a b set a Random.Range(int.MinValue, int.MaxValue) b value a usage ObscuredInt health new ObscuredInt(5) health.value 10 printInConsle(health.value) This works by simply never storing actual value, but rather a combination of two integers, which sum represents the value. That way the value is actually never cached long time in the memory. So finding it in a primitive way using cheat engine is not possible. My question I've seen other examples of obscuring, which involve conversion to binary or string hashing or other quite heavy operations. This example is of course much more lightweight, how is this example worse than more advanced hashing or conversions. What flaws do you see with this example? What can you suggest? Thank you


Counting shader animation "iterations" I'm writing a shader that animates "pinching" an image and releasing it. It's similar to this shader on shadertoy. One issue I have is that my shader should only "animate" once meaning the image should appear to "pinch", then "unpinch", but then stop. Like this example, it'll keep going since the animation ia time driven. Since the shader is called for each pixel I don't see any easy way to track how many "animation iterations" there have been for the entire image. I can handle animation via a Unity Update method, where I can easily control when to stop, but I'd rather do this entirely in shader if at all possible. void mainImage( out vec4 fragColor, in vec2 fragCoord ) vec2 uv fragCoord.xy iResolution.xy vec2 center vec2( .5 ) vec2 dir normalize( center uv ) float d length( center uv ) float factor .5 sin( iTime ) float f exp( factor ( d .5 ) ) 1. if( d gt .5 ) f 0. fragColor texture( iChannel0, uv f dir )


Unity Client and Multiplayer Networking Architecture My background is in Enterprise and SaaS web infrastructure. Zero information about games and how their networking works. I only know about the world of browsers and RESTful APIs. I'm planning on using Unity for the client FYI. Authentication and Authorization I'm planning to use Unity and Firebase. Seems like this is fairly standard HTTP connections during the auth faze. Nothing surprising here unless there is something I missed. The client authenticates against a service, Firebase in this case. And then all future calls after authentication are made using the returned credentials. Gameplay and Player State This part confuses me. I assume shooters use a UDP type protocol or some proprietary protocol on top of UDP. But can a game use a REST API and HTTP or TCP connections to send client updates? Clients would then poll the game server or have a long running connection open to request updates. For example the Auction House in WoW. Is there a long lived TCP connection open between the client and the server updating the auction house data every X seconds? Then when a player submits a purchase order that same long lived TCP connection is used to update the game server state? Or is it all literally a REST API like a SaaS app would use? Is my experience with browsers and Single Page Apps in an Enterprise environment applicable to a WoW auction house type situation? Thank you, Any tips or feedback is helpful at this point.


Unity Creating light that's visible to a shader but not to the camera player? I'm writing a vertex deformation shader that can react to the presence of certain objects. Originally I was passing coordinates to the shader with SetVector, but from my understanding having the CPU set properties on a shader is somewhat expensive. So another idea I had was to have the shader react to light, and do some matrix multiplication to have the shader deform itself based on the intensity of the light hitting it. My question is, how could I approach writing a shader that would react to a light source, when that light would be invisible to the camera player? In such a scenario I could write a fast amp reasonably simple shader that could react to a special light source that would allow it to dynamically react to the light's location and distance. Only, such a light source would need to be invisible to the player, since its just being used as a representation of location and distance (with the added benefit of mixing multiple different sources easily). Or is there some other equally fast better way to do this that I'm not thinking of? Thanks for the help! EDIT Imagine a shader that causes a surface to grow outwards when a certain type of object is near it, and its extrusion distance is proportional to the distance and "intensity" (some float) of the object. If there were several of these objects near the surface then it will form a pattern taking into account all of these nearby objects.


How do I know when the app is launched, loses focus and gets focus again on mobile? I searched in Unity Documentation but there are no information. I'd like to know which methods is called and what it returns in the following scenarios on Android App initially starts App goes in the background App is brought forward after being in the background As for IOs I know that the scenarios should be the following App initially starts OnApplicationFocus(true) is called App goes in the background OnApplicationFocus(false) is called OnApplicationPause(true) is called App is brought forward after being in the background OnApplicationPause(false) is called OnApplicationFocus(true) is called


Can I change the background color where a sprite is shown in the inspector? this is how a sprite shows in the inspector. It's white pixelart with transparent background. Is there a way to change the background checkered pattern color in the inspector so I can actually see the sprite? Note I don't want to change any color in the game, just the background in the inspector, in the editor, so there's some contrast and I can actually see the sprite pattern.


How to colour blend between two materials? I've been trying to get a material (with an image texture) to animate towards a colour mix with transparency, but either I'm attempting something the wrong way, or unable to find the right keyword to find about similar examples. What I'm trying to accomplish is to make a 3D character blush I have the face area on it's own material, with textures set, but that's where my problem is. If it was animating between two colours, I would simply use Color.Lerp, but since textures are included, that makes me think I have to somehow have a colour mix option for this. I've also tried to just use the built in animator to see if Unity would blend between the colours of two different materials, but after all it turned out to be an instant change on the new keyframe which leaves me to think so far my only exit could be to manually create several keyframes, and create several materials to get it close to acceptable. Although my knowledge about it is close to zero, is this after all only possible with a custom fragment shader? I don't know if there's a suitable package, or built in Unity feature that makes something like this possible, or if at all I'm approaching this problem the right way... Update This is the shader I'm using right now, from . It might be a little confusing since inputs are all abbreviated, so here are some example files that are being used.


What happens if I delete .meta files? In Unity, what happens if I delete the meta files? Or if I import files, but not their respective .meta files? What are some issues I could come across? Is there ever a reason I would want to delete meta files? I was asked this question recently, and I do not know the answer.


Time.fixedDeltaTime Time.deltaTime in Unity The old Unity 5.3 documentation said Time.fixedDeltaTime The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's FixedUpdate) are performed. For reading the delta time it is recommended to use Time.deltaTime instead because it automatically returns the right delta time if you are inside a FixedUpdate function or Update function. Note that the fixedDeltaTime interval is with respect to the in game time affected by timeScale. So, it was said (paraphrased as I get it) that Time.fixedDeltaTime returns the interval at which the FixedUpdate method should be called with respect to the timeScale. But the real interval could differ (for technical reasons) and that's why Time.deltaTime should be used instead to return a real time elapsed since the previous FixedUpdate call. The latest docs don't say that anymore https docs.unity3d.com ScriptReference Time fixedDeltaTime.html Does it mean that now FixedUpdate is called exactly at Time.fixedDeltaTime rate? Now it also says Unity does not adjust fixedDeltaTime based on Time.timeScale. The fixedDeltaTime interval is always relative to the in game time which Time.timeScale affects. Don't these two sentences contradict each other?


Unity new Input system lists actions and compare them to current input I have a scriptable object called Move that had a list with keycodes (for example to make a Hadouken) easy to use and compare with the current input made it with the old system, but with the new input system I don't know how to make a list of actions (actions that are in my Input Action Asset not new ones) and compare that with the current inputs (and also I do not have any idea how to make buffering inputs like the last input repeats 3 frames). I already tried and not worked (InputMa is my InputActionAsset generated class) InputActions InputMa InputMa.PlayerActions InputActionReferences this seems the correct option, but I don't know how to get the reference from the current input.


How to access network player from internet I just followed a guide about basic UNet tut Here, Its spawning network car player which can be controlled by local player. I can make or join server through Network Manager HUD which is provide by the unity. I am able to run and connect application on my LAN on different PCs but failed to connect it on other network. I don't know what are the reasons. Do I need to make or purchase a server for it or I am doing something wrong.


RaycastHit2D.point is acting weird when used with circlecast2d When I make circleCast2d intersects with another circle collider, I get a RaycastHit2D.point that doesn't point at the tip of the collision as it states in the documentation. Instead it always points at the centre of the intersected junction or pointC as shown in the figure below. I checked this numerous times with different values to make sure the error was not from my end. Is this intended? If so is there another way where I can actually find the closest point from collider(B) to the centre of collider(A) which corresponds to point(D) in the figure? This is a picture of what looks like A circleCast B collided object C where RaycastHit2D.point is pointing at D where I'd like it to point.


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.


How to reverse gravity in Unity I'm trying to figure out how script gravity reversal on collision with an object. How can I reverse gravity?


Unity mouse input not working in webplayer build I have a button script with the following code void OnMouseDown() animation.Play("button squish") enlarged true audio.PlayOneShot(buttonSound) void OnMouseUpAsButton() if (enlarged) SelectThisButton() enlarged false animation.Play("button return") void OnMouseExit() if (enlarged) enlarged false animation.Play("button return") It works great in the editor, but when I made a build and tested it in Chrome none of the buttons had any response. Further testing revealed that it did work in Firefox. Rather than telling people to change their browser if they want to play, I want to make the button code work. How else can I get the buttons to know when they're being pressed if the built in stuff isn't working?


Use a different target framework version in a unity c project, other than 4.6 I'm using a dll in my project which is built against a higher target framework (4.6.1 actually) I can't build or attach to Unity because of this. Visual Studio shows this error The primary reference "MQTTnet" could not be resolved because it was built against the ".NETFramework,Version v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version v4.6". The only option in player settings in Unity for API compatibility level is .NET 4.6 how can I change that to 4.6.1 in order to be able to build or attach to Unity?


Logging of method calls for recreation Some games have the option to let you play offline and sync with a server once you have internet again. To prevent cheating and validate if it was an authentic play, usually some sort of log of all input actions is sent and validated afterwards on the server. In my case I would be interested in a single MonoBehaviour and having all its method calls logged with the its parameters values. Giving this input, the game result output should be the same. (There is no random involved and no physics interaction) One way would be just a writer at the start of each method that logs the timestamp, method name and paramter Another would be maybe something like a multi delegate inbetween that calls both my method and a writer class Is there something build in in Unity that does this already like an annotation for the methods I want to track or something like an audit interface?


How to create a Unity Editor box grouping with a header and vertically stacked content inside? I am trying to do something like this with Unity Editor for my window but I am not sure how it is done. So it is basically a box ( a wrapper ) with a title at top. Beneath the title there are boxes or "cards" where you add text to it. Any help is appreciated!


Rotate camera around point of view I'm trying to rotate the camera around the view point of the camera. So when the user looks at a build the camera rotate around that building. But the camera does not need to have the building to rotate around. So therefore I want a camera that can rotate around his own point of view. So that the camera behave everywhere the same in the game. How can I achieve this in Unity 5.6?


In Unity, Image to show icon works on one scene but not the other I am trying to show an icon on the UI when the player is looking at an enemy. The raycasting code, etc all works, but on one scene, the icon shows successfully, the other, it doesn't. I have tried copying, recreating, using different Sprites, none of it works. using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CursorAffordance MonoBehaviour SerializeField private Sprite combatAffordance private CameraRaycaster raycaster private Image image Use this for initialization void Start () raycaster FindObjectOfType lt CameraRaycaster gt () image FindObjectOfType lt Image gt () Update is called once per frame void LateUpdate () if (Input.GetMouseButton(0)) print( raycaster.layerHit) switch ( raycaster.layerHit) case Layer.Enemy image.sprite combatAffordance image.enabled true break default image.sprite null image.enabled false break The only thing i can find from debugging is combatAffordance is somehow null the second run through , and stays null from then on, although in inspetor it still shows my Target sprite.


How can I create a height based volumetric fog? Recently, I have been looking for techniques to make volumetric fog on some Y position level of the game world. But all I have found are some fog made by using particle system or built in engine fog that doesn't really fit what I'm looking for. In my case, I need a fog that is both efficient and dense. It should be all over the gameworld, but obviously, for performance reasons, it can be rendered only as a part of a camera or shader and look like it's moving though it's just an illusion. I could set a particle system if it's the best choice, attach it to the camera and make it move. So the main question still stays how can I implement a volumetric fog that is both dense and performs efficiently? As a particular engine I'm using, it's Unity. As an example what I mean, here is the link to a game with the effect I'm looking for Astromike


Why does the volume not decrease when I move away from the AudioSource? I created a simple scene with an audio source and a player that can move. The main camera is a child object of the player. I set the audio source volume rolloff to "logarithmic rolloff". As far as I understand, this means that the sound should become weak very fast when the main camera moves away from the audio source. But this does not happen as I move the player (with the camera) away from the audio source, the volume remains the same. I see, in the rolloff graph of the audio source, a line denoted by "Listener", which moves to the right as the camera moves away from the source. But still, the volume remains the same. Why?