Keeping high scores on Unity web player I want the player to be able to save his score when she makes it into top 10 of high scores. Upon success, player will be asked for a name to submit. This does not need to be unique per player. I just want a basic global score board available for everyone who plays the game via web player (from github.io page of the project). When searched for how to keep high scores, I came across PlayerPrefs. On Web players, PlayerPrefs are stored in binary files in the following locations Mac OS X Library Preferences Unity WebPlayerPrefs Windows APPDATA Unity WebPlayerPrefs As far as I understood, the results are kept in local machine and won't be same for everyone. So it's good for keeping track of your own score, locally. As a placeholder in the current version of the game, I keep the scores in a local .txt file in the project directory. Can I succeed with this approach and use the github.io server to maintain a global scoreboard or do I necessarily need a database to achieve this goal?


Adding some new velocity to player in FixedUpdate. Should I use FixedDeltaTime or nothing? I am trying to learn how to move objects in Unity without using the built in features like AddForce etc. Some tutorials on Unity website (and other places) is where I have got most of my 'knowledge' so far from. This script for moving players (in topdown Space SHMUP) has been working fine for me and includes acceleration and artificial drag (basically 'smooth' movement, or like being on ice). I'm sure this code is overly long, bloated, inefficient and in most cases downright wrong, but it is written for me to understand it, rather than simply using Unity Prefabs and AssetPackages i download from Store. QUESTION Do I need the Time.fixedDeltaTime mutlipiers when calculating my 'delta v' values here. And also what about on the drag part at the bottom. As usual all help and comments are greatly appreciated. Thanks! public class Player Movement SpaceShooter TopDown MonoBehaviour public Vector2 maxVelocity public float drag public float moveForce private Rect moveBounds private Rigidbody2D rb private void Start() rb GetComponent lt Rigidbody2D gt () moveBounds Game Manager.instance.ScreenBounds private void FixedUpdate() float input h Input.GetAxis("Horizontal") float input v Input.GetAxis("Vertical") Vector2 delta v Vector2.zero delta v.x input h moveForce Time.fixedDeltaTime delta v.x Mathf.Clamp(delta v.x, maxVelocity.x, maxVelocity.x) delta v.y input v moveForce Time.fixedDeltaTime delta v.y Mathf.Clamp(delta v.y, maxVelocity.y, maxVelocity.y) Vector2 pos rb.position Vector2 vel rb.velocity if (pos.x lt moveBounds.xMin) pos.x moveBounds.xMin vel.x 0f if (pos.x gt moveBounds.xMax) pos.x moveBounds.xMax vel.x 0f if (pos.y lt moveBounds.yMin) pos.y moveBounds.yMin vel.y 0f if (pos.y gt moveBounds.yMax) pos.y moveBounds.yMax vel.y 0f rb.position pos rb.velocity vel delta v rb.velocity rb.velocity (1 Time.fixedDeltaTime drag) It appears to me that if FixedUpdate was somehow slowed down, the velocity would get changed slower, the same with the enemy movement but I don't know how that would effect the gameplay and if how the slowing down would occur


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.


Unity WebGL how to copy to clipboard text from an inputField? I would like to know if there is a solution to copy paste the text from to an InputField in a WebGl Unity app. Edit for security reason, Unity WebGL doesn't allow text copy and paste in from browser. Thanks


Why the transform.localPosition never equal to the begin position of the transform? using System.Collections using System.Collections.Generic using UnityEngine public class MoveScrollView MonoBehaviour float seconds Vector3 begin Vector3 end Vector3 difference public static bool go false public static bool goBack false public static bool atOriginPos false void Start() seconds 0.5f begin transform.localPosition end new Vector3(0, 1, 0) difference end begin void Update() if (go) if (transform.localPosition.x lt end.x) var mx transform.localPosition.x transform.localPosition new Vector3(mx seconds Time.unscaledTime, 1, 0) difference end transform.localPosition if(goBack) if (transform.localPosition.x gt begin.x) var mx transform.localPosition.x transform.localPosition new Vector3(mx seconds Time.unscaledTime, 1, 0) difference end transform.localPosition if(transform.localPosition begin amp amp goBack) atOriginPos true At the Start the begin position is ( 540.0, 1.0, 0.0) also the transform.localPosition is at the same position. Then at this line 39 if (transform.localPosition.x gt begin.x) The value of the x of the transform.localPosition is 3.039021 and the x of the begin is 540 So it's getting inside and move the transform. Then when the transform has finished moving I see on this line if (transform.localPosition.x gt begin.x) The transform.localPosition x value is 540.7267 and the x value of the begin is still 540 So now it will not get inside and will not move the transform anymore. But two wrong things happened The transform stopped moving but it didn't move to it's original position only close to it. Because it didn't move to it's exact original position then the localPosition x and the begin x are never equal so the this will never be true if(transform.localPosition begin amp amp goBack) And the flag atOriginPos is never true. I want the transform to move back to it's original position and then when it's reached the original position set the flag atOriginPos to true.


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


How do I run functional tests against my Unity3D game? Context I am continuing some legacy code for a game in Unity3d, and I want to write some functional tests meant for regression, to ensure I don't break things when implementing new things or when refactoring. I already know there is the 'Unit Test Tools' suite for Unity3d available as an asset. I have used it as a unit test suite, so I test my models (classes). Example of what kind of test I am thinking about For "functional test" I mean things like this Run the program When in the menu scene, assert there is a button that says "start" Click it Then assert a new scene is loaded Assert pixel XXX is red Click in coordinate XXX Assert now that the pixel changed to green etc. Questions Q1 How do I write and run functional tests for my game? Is this also typically done in the UnityTestTools (UTT)? Q2 If UTT is more for Unit Testing, then is there a separate suite for functional testing? Which one? Notes I'm targetting Android, and running Unity5.3.1f1


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


How is Unity's Command supposed to behave? Here's a very simple class call hierarchy public class NetworkPlayer NetworkBehaviour public static NetworkPlayer localPlayer get private set Command public void CmdTurnDone() Debug.Log("Turn done! isServer " isServer " isClient " isClient " isLocalPlr " isLocalPlayer) public class SomeMonoBehaviour MonoBehaviour void Update() NetworkPlayer.localPlayer.CmdTurnDone() When Update() gets executed on the host, it outputs as expected Turn done! isServer True isClient True isLocalPlr True Now, when Update() is executed on the remote client it outputs the following at the remote client's log only. However, the message does not appear at the server's logs Turn done! isServer False isClient True isLocalPlr True What puzzles me is why the message appears at the remote client's log only. If I'm not mistaken, calling CmdTurnDone() at the remote client should execute it on the server. But why does the log message appear at the remote client's log instead of on the server's logs where it is executed? Is it valid to call CmdTurnDone() from a MonoBehaviour? Do you have any ideas why it's behaving like this? Is this the intended behavior? Thank you.


How to displace a segmented line along a sine wave with Shader Graph? I have a mesh made of three identical cylinders (conceptually just line segments with a non zero thickness) crossed over each other at 60 degree angles, so the ends describe the points of a regular hexagon. The cylinders are divided into a lot of segments, which I'd like to displace in a sinewave pattern. The pivot is in the center of the mesh. My concept is pretty straightforward Subtract object position from vertex position to get vertex position relative to the pivot (VPR). Normalize VPR and swap the X and Y to get a vector in the XY plane perpendicular to the orientation of the cylinder. Take the magnitude of VPR, multiply by a V1 parameter (Waviness), then take the sine. Multiply the sine by the perpendicular orientation vector to get the displacement. Add the displacement to the vertex position. Assign result to master node's vertex position. This really feels like it should work. Each cylinder should be distorted along a sine wave, with the magnitude of the distortion increasing the further it gets from the center, so I end up with three wavy lines crossed over each other at 60 degree angles. Increasing Waviness should increase the frequency of the wave, as the base value is multiplied by it before feeding into the sine node. Instead, things curve just a little bit at a low Waviness, but as I increase it the cylinders get both thicker and longer, neither of which should be happening, and start wrapping themselves around the mesh in weird patterns. I have no idea what I'm doing wrong! Here's my graph setup, with the mesh assigned to the preview so you can see what a mess it's making of it Any ideas how I can fix this?


Unity Mesh and Collider not aligned on rotation I have a GameObject with a mesh and a collider. When I rotate the object the mesh and the colider do not act the same way and when the GameObject is rotate 65 degrees on the z axis the mesh and the colider are no longer aligned. This must affect game play. I don't understand why this happens and how it is supposed to be fixed.


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


How do I cover a plane in a bumpy foam material effect? I need to fill a weapon bag with foam material. This is what it should look lik The material in the upper part of the bag looks like this I'm using HDRP. How could I do this? Thank you! Edit I have played around with Parallax Occlusion mapping, and I got this result. Edit2 I am not sure if I use the Pixel Displacement as it has been suggested to me. Also, I'm not sure if I use it the correct way I have created a Height map and put it into the Height map slot. This doesn't create any effect. I have to put the same map into the Base map slot in order to see the effect. If I put a black image into the Base map slot or if I choose Black as the Base color, no effect is visible. I don't understand why this is so. I think even if my Base map is black, the Shader has pixels that it can move. This is my height map Edit 3 It was suggested that I should use a normal map. This doesn't look at all what I expected. The normal map was created from the Height map using an online tool By Philipp's answer I found out that the normal map alone is not enough.


How to pause audio playback when a breakpoint is hit or resume afterward? When my code hits a breakpoint, audio that was previously started (via an AudioSource) continues to play while the threads are paused. I'm using a coroutine to query the status of the AudioSource, and update my UI. Because the audio continues to play, then after I've spend some time stepping through code the next frame tick when Unity gets control back runs the next iteration of this coroutine, which updates the UI. I never get to see the in between states. Because it's a relativley short audio clip it's usually finished playing before I've finished stepping through the code. I'm using Unity 2018.4 with VSCode and the Debugger for Unity extension, if that helps. I'm quite lost at what to try here. Looking for issues with Unity's AudioSource and breakpoints yields a lot of varied information about audio issues in general in Unity. I've tried using Debug.Break(). It pauses the Unity editor, which can be useful but has the following caveats it requires extra effort on each breakpoint that requires enabling (if the call is not there already) it requires manual intervention to resume the editor once you've finished stepping through code because it is code, it cannot be added after Unity is playing, e.g. to additional breakpoints that are added once debugging has started Does Unity have a mechanism that enables this behaviour that I've just missed? If not, what's an appropriate alternative approach?


AudioSource.Play() outputs only noise from the sound clip I'm trying to reproduce a sound clip on the AudioSource of a game object by using the .Play method. What i'm trying to do is a card game of sorts, but with each card being a different section of a song of a genre. I combine different cards with different genres and when i press play, the combination should start playing, but now when the play button is pressed, only noise comes out. The code for the start method looks like this public class AudioStart MonoBehaviour AudioSource thisAudioSource Start is called before the first frame update void Start() thisAudioSource this.GetComponent lt AudioSource gt () Update is called once per frame void Update() if (playButton.playPressed) thisAudioSource.Play() else thisAudioSource.Stop() The way i'm doing it is by having a button that on click changes a bool to true or false depending if there is sound playing (the truth check on the if statement). The AudioSource outputs to an AudioMixer on a specific group under the master group (which group depends on the slot that the card is dropped in). The AudioStart script is attached to different game objects with a different audio clip each. I've also noticed that when i try to reproduce two cards, only one AudioSource gets played. Any help would be appreciated. Thanks!


Mute sound in editor in Unity Is it possible to mute sound in editor in Unity? I mean not in the game, but in the editor, so that when I am debugging there would be no sound whatsoever.


How can I get the vector3's names to gameobject name? void DrawBox() SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color) SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color) SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color) SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color) SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color) SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color) SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color) SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color) SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color) And the gameobjects name void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.name start.ToString() myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.endColor color lr.startWidth 0.03f lr.endWidth 0.03f lr.SetPosition(0, start) lr.SetPosition(1, end) The method SpawnLineGenerator get two vector3 and a color SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) In the SpawnLineGenerator i'm setting a name for each gameobject myLine.name start.ToString() This give me the name for example ( 2.1, 3.4, 4.9) Nut I want it be the name like this format v3FrontTopLeft ( 2.1, 3.4, 4.9) v3FrontTopRight ( 1.1, 3.4, 4.9) The problem is if there is a easy way to get the names v3FrontTopLeft and v3FrontTopRight and the rest from the method DrawBox instead typing each one. I want to know that ( 2.1, 3.4, 4.9) are the coordinates for v3FrontTopLeft


Jagged Edges Even With Anti Aliasing 8x Multi Sampling I have an interior scene where I have imported a model for the apartment and many of the interior objects such as lamps, windows, etc. Unfortunately I have a lot of jagged edges on almost all the objects in my scene even on Fantastic Quality settings with Anti Aliasing pushed to its maximum. What else can I do to reduce the jaggies seen here Here are my quality settings And here are my model import settings


AssetBundles for sprites, or download the images from my server? I need to host several sprites in my server, and then have Unity download and use them. I have tested two methods AssetBundles If I pack my sprites into an AssetBundle, the bundle is about 4MB. It works fine. Download the images If I download the image bytes from my server, you can use those bytes to create a Sprite. Curiously, this is much, much smaller than an AssetBundle (just like 1.5MB). Both methods work. It seems pretty obvious that the second one offers an advantage due to reduced memory size. My questions are Why is the second method so much smaller? Is there any reason I'd rather use AssetBundles?


How can I get find all the UI texts and TextMesh Pro in the hierarchy? When pausing resuming the game, I want to disable enable all UI texts. The following code works for finding UI texts, but I also want it to find TextMesh Pro text. How can I do this? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement using UnityEngine.UI public class BackToMainMenu MonoBehaviour ContextMenuItem( quot Fetch quot , nameof(FetchAllTexts)) public Text uiTexts Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (Time.timeScale 0) SceneManager.UnloadSceneAsync(0) DisableEnableUiTexts(false) Cursor.visible false Time.timeScale 1 else Time.timeScale 0 MenuController.LoadSceneForSavedGame false DisableEnableUiTexts(true) SceneManager.LoadScene(0, LoadSceneMode.Additive) Cursor.visible true private void FetchAllTexts() var tmp new List lt Text gt () foreach (var root in SceneManager.GetSceneAt(0).GetRootGameObjects()) tmp.AddRange(root.GetComponentsInChildren lt Text gt (true)) Text texts tmp.ToArray() uiTexts texts private void DisableEnableUiTexts(bool uiTextEnabled) if (uiTexts.Length gt 0) foreach (Text ui in uiTexts) ui.enabled uiTextEnabled


How to create JSON file in notepad that will hold my positional vector3 data for one type of object I'm trying to get my head around using JSON files to store level data . Specifically in this example is to make my walls. (its a top down game like pacman). Each wall prefab is a 1x1x1 cube. I just want the JSON to hold the x,y,z. I have seen tutorials about how best to deserialise the data into Unity and I think im fine doing that, but I am unsure of how exactly to word the JSON file. I see the example on Unity docs says the format is like this "level" 1,"timeElapsed" 47.5,"playerName" "Dr Charles Francis" so, I could just do something like "index" 0,"x" 5,"y" 1,"z" 0 but I know that there needs to be a bit above, similar to XML and of this im clueless of what it needs to contain. I looked on Json.org but i didnt really understand it still. This is one example "glossary" "title" "example glossary", "GlossDiv" "title" "S", "GlossList" "GlossEntry" "ID" "SGML", "SortAs" "SGML", "GlossTerm" "Standard Generalized Markup Language", "Acronym" "SGML", "Abbrev" "ISO 8879 1986", "GlossDef" "para" "A meta markup language, used to create markup languages such as DocBook.", "GlossSeeAlso" "GML", "XML" , "GlossSee" "markup" But what is 'Glossary' and 'title' in the context of my game? All I currently have is a cube called Wall, with a script attached called Wall.cs that currently does nothing, but I will be making an array of Wall and plan on using the deserialised data from the json file to lay the Walls out using my GameController.cs Once I know what to put above and below to open and close the JSON file off, im pretty sure I can get it working how I need it to. I hope that made some sense.


Unity3D and Photon Networking RPG Good time of the day. My question might sound stupid, due to the knowledge you might have, but here it is. I've purchased Diablo 3 a long time ago and been enjoying it since then. Since many of my friend are playing other Blizzard titles, i tried to convince them to purchase Diablo and to play all together. However, they don't want to invest money in the game they don't understand (yet). So i've decided to write a game, which will be similar to the Diablo in the way of interaction and gameplay, but will (obviously) have some unique points in it (since i'm not only doing this for them, but also to educate myself in the game development area). Other this is, i've decided to take Masters in the Game Development (later this march, just got my bachelors in computer security) and wanted to have some basic knowledge about game development. I used to make "RPG" games before, tho only browser style ones using LAMP stack, and have some basic knowledge on storing retrieving data to from server. In order to implement multiplayer part of the game, i've decided to use free package PUN (Photon Unity Networking). Had no problem with creating my first room and spawning a player prefab for every new connection (tho they all move no matter on which client action is performed). Now to the question(s) By using PUN, i'm able to create new room for players (limited to 5), is it possible to set room names BEFORE they are actually initialized by the player? (set of rooms might be stored on MySQL server and retrieved by the API call) Is it possible to save progression of the player on the server, and later pass it back to the spawned player (by PUN). This is my main concern, since i've no actual access to the data processed by the server. (Solution is to create another connection to the "storage" server, and keep both of them "online"?) Does PUN allows you to select which scene should be loaded upon first player entering the room, if so, a bit of pseudo code might be helpful. What will happen to the player, if there is no spots left to join the server (this is just theoretical question, since i'm not going to publish this game, and amount of friends playing games is less than 20) How would one deal with the item equipped, which is received during the gameplay? (This one links to the second question) What i'm talking about is, is it possible to restore player object with the set of data received form the server (if possible, ofcourse) I know, the first suggestion will be to go and to read documentation (i'm in the process of reading it, don't worry). But i've decided to write here, since there are many skilled people out there in this area, who can give me basic understanding on how this whole PUN system works. I would like to thank you for all of the responses, which you are about to post (or maybe not), and again, have a great day.


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


Where to put rigidbody on a car model ? I have a GameObject car like this MyCar Body with mesh collider Wheel Left with wheel collider Wheel Right with wheel collider ... and so on Where I have to put rigidbody ? Thanks


How can I update my materials to work with LWRP? I'm using Unity 2019.1.6f1. When I open a new scene with the LWRP template project, I see errors from all materials in the scene. For example, the Jigsaw appears in my scene but in console window I see a message telling me Jigsaw Mat material was not upgraded. There's no upgrader to convert Lightweight Render Pipeline Lit shader to selected pipeline UnityEditor.Rendering.LWRP.LightweightRenderPipelineMaterialUpgrader UpgradeProjectMaterials() All materials show this message, and I don't know what to do to fix these materials. How can I resolve this error?


Texture not appears? I make fat cube "fbx" with blender and export it to unity. this fat cube not allowed texture to appears ! i make a small cube by unity and texture pop up ! What is wrong ?


Creating a curve path for gameObject which reacts to Triggers I am trying to create a path for a gameObject which will bounce off other gameObjects if it hits them. Can I get an idea on how I could possibly get this curve path set up. Stuck on ideas. I don't want to use ITween and I can't simply define the entire path via ITween either. I need to account for whether it hit another gameObject and cause it to carry on the path or just fall through. Attached the image below for clarification. I need the circle(purple) gameObject to bounce along the white path provided the rectangle(green) gameObject is in place to cause a Trigger and let the path carry on or the circle gameObject just simply falls through. There is only 1 green gameObject at any point of time which moves to one of the 3 possible positions. Placed 2 just for clarification.


What causes this graphics quality difference between WebGL Build and Unity 5 Editor? The Editor version and WebGL version of my Minesweeper clone have some graphics quality differences. I chose 'Fast' option when building this deployment. Is this the difference between 'Fast' and 'Fastest' options of Optimization Level in Build Settings, meaning that if I choose the 'Fastest' option, the WebGL deployment will be the same as Editor version, unlike below? If not, why this happens?


Unity download image from Firebase database I am currently trying to download an image using Google Firebase. The database stores a URL to an image on Firebase storage, Unity pulls the URL from the DB and uses Unity WWW to download it. However the texture shows up as a red question mark texture. If I use a http URL from another website however it works, is Unity able to download from https addresses? This downloads the URL from Firebase and stores it in the data url variable void DownloadViaURL() Debug.Log("Called DownloadViaURL") FirebaseDatabase.DefaultInstance .GetReference("test image") .GetValueAsync().ContinueWith(task gt Debug.Log("Default Instance entered") if (task.IsFaulted) Debug.Log("Error retrieving data from server") else if (task.IsCompleted) DataSnapshot snapshot task.Result string data URL snapshot.GetValue(true).ToString() Start coroutine to download image StartCoroutine(AccessURL(data URL)) ) This uses Unity WWW to download from the URL IEnumerator AccessURL(string url) Debug.Log("Accessing texture URL in database") using (WWW www new WWW(url)) yield return www Renderer r GetComponent lt Renderer gt () r.material.mainTexture www.texture Debug.Log("Texture URL " www.url)


How to transition a coin to the middle of the screen then up when collecting it? I have a coin sprite that animates spinning in place, like this. When the player picks up the coin, I want to make a transition while keeping the animation. First moving towards middle, then much faster all the way up until it leaves the screen like this My question Is this done mostly via adjusting the Transform component component via scripting? Or are games implementing something like this in a different way?


Unity Shadergraph to CPU code? I read that you in theory can get vertex offsets from GPU shader in CPU by transpiling the shader to CPU callable code or creating a compute shader that calls the shader code (are there more ways?). I am wondering how one should approach this if one wants to use a shader from shadergraph. Can I get the same noise textures on CPU as on the nodes in shadergraph (GPU) for example? They can be important in driving the result. I think it is possible to export as hlsl so maybe transpiling can be done automatically.


Unity Set LightProbes to "Off" on Static objects Since I use Light Probes for Indoor Scenes only I only need them to work on Dynamic Objects. Objects in Indoor Scenes are all Lightmap Static and baked, objects in outdoor scenes rely on real time lighting. Most objects are not within range but sometimes the Lightprobes from inside interfere with Static objects outside and add light to them that should not be. It's really time consuming to disable LightProbes in every individual Mesh Renderer I sort all Prefabs amp Game Objects by Static, LightmapStatic and Dynamic. Turning Lightmapping on and off can be easily done in the hiearchy but turning off LightProbes needs to be done in every individual Mesh Renderer. Is that so, or am I overlooking something? If not this is really something that should get fixed. My Version is 2017.3.1f1


How do I deal with scale of the universe when generating a simulated universe? I have a dataset of 100,000 actual stars. I wish to create a game where I can fly between the stars and fly up to them and click on them etc. How do I go about dealing with the problem of the scaling of the universe, even If I were to allow fast as light travel it would be too vast. Should I cluster my data and then implement a subtle sort of scaling to move around? Sorry for the broad question but I'm rather stuck at the moment.


Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls)


Discard Transparent Pixels in Z Buffer I am building a 2D game using sprites. I'd like to use the z buffer to aid with shading. For that I need Unity to write only opaque pixels to the z buffer (aka depth buffer). In Unity, sprites are built up of polygons, and it is writing these entire polygons, including the transparent pixels, to the depth buffer. This is the shader I'm using (with some junk added while trying to get this to work) http pastebin.com khprCUA0 I have tried AlphaTest Greater 0 alphatest MyAlphaTestVar the discard keyword Cg's clip function I suspected that a lighting pass might be writing the depths so I added novertexlights and noambient I would suspect that AlphaTest prevents transparent pixels from having any effect on the frame or depth buffer (as suggested here), but they still do write to the depth buffer! The screenshot below shows the inaccurate shapes of objects in the Z buffer. The king and tree have become blobs because even their transparent pixels were updated in the Z buffer (drawn using http willychyr.com 2013 11 unity shaders depth and normal textures ) Compare this to the "correct" shape of the objects in the regular view How do I get Unity to not write transparent pixels to the z buffer? EDIT Unity 5's frame debugger is turning out to be a miracle! Turns out the "Depth Texture" is actually rendered in a separate pass before all other geometry. And I'm having trouble finding out how to use RenderType to include exclude certain objects from this pass.


How can I control ads frequency? This question was already asked a while ago, and I wanted to check the present situation Can I control ads frequency from the dashboard? (e.g. frequency capping in Admob) Can I control ads frequency through Unity IAP API? If not, does that mean that I need to implement all that "frequency control" functionality manually?


How to move player along navmesh link's curve? NavMesh Link creates a navigable link between two locations that use NavMeshes. This link can be from point to point or it can span a gap, in which case the Agent uses the nearest location along the entry edge to cross the link. I don't know why when I use navmesh link player move along horizontal plane (that I demonstrate it by red line) between gaps in navmesh link Is there a option that player jump along curve (that I demonstrate it green curve)? should I use force? you can see player move horizontally! that isn't interesting. Offmesh Links Unity Official Tutorials


How to calculate the post Rigidbody2D velocity vector before applying a specific force in Unity? I am trying to implement a space rocket in 2D. Whenever the player presses a button, a constant force (Both vertical and horizontal) is being added to that rocket. What I want to add is a maximum speed, the rocket cant exceed as the rocket will continue accelerating to infinity. The player can also choose not to accelerate, which can lead to the rocket starting to fall down due to gravity. Thus, I cant just Clamp the rigidbody.velocity of the rocket whenever the magnitude of it exceeds max speed as it will also limit the fall velocity which is not as limited. Thus, I am trying to predict whether the player will exceed the maximum velocity when trying to accelerate, in order not to add the force. So far, I have tried doing this but the velocity vector does not seem to change immediately, so vel is equal to postVel Vector2 vel rigidbody.velocity rigidbody.AddRelativeForce(Force) Add force Vector2 postVel rigidbody.velocity rigidbody.AddRelativeForce( Force) Undo force


Unity frame rate drops stall I have an issue where my game suddenly stops for a second and then continues. And I think it has something to do with my performance so I took at look at the profiler I tried to take a screenshot as soon as the crack happened However, since I am a bit new to optimization could anyone give me a helping hand on what might be the problem here?


Clipping speed when turning without using aggressive drag I have a Unity project in which I want to control a player in a similar way to Source games, and so far I am clipping each input to the speed in the player's coordinates, by using transform.InverseTransformDirection( GetComponent lt Rigidbody gt ().velocity ) after which I pass each of the player's input vector direction through this function private float FLSMF ( float aInputVelocity, float aMaximumVelocityOnAxis, float aSpeedOnAxis ) if ( Mod( aSpeedOnAxis ) gt aMaximumVelocityOnAxis ) if( Sign( aSpeedOnAxis ) ! Sign ( aInputVelocity ) ) if ( Mod( aSpeedOnAxis aInputVelocity ) gt aMaximumVelocityOnAxis ) return Sign ( aInputVelocity ) ( aMaximumVelocityOnAxis Mod( aSpeedOnAxis ) ) return aInputVelocity return 0 if( Mod( aSpeedOnAxis aInputVelocity ) gt aMaximumVelocityOnAxis ) return Sign( aInputVelocity ) ( aMaximumVelocityOnAxis Mod( aSpeedOnAxis ) ) return aInputVelocity There is only one problem whenever I turn and strafe and walk forwards or backwards, the speed increases dramatically. I tried solving it by comparing each processed velocity axis to the velocity rotated by the difference in the rotations between the last 2 FixedUpdate's. So far nothing worked, aside from driving the drag factor through the roof. My best guess is that when turning, the unclipped X axis of the vector bleeds into the Z axis when turning, which can't add anything, but cant stop the X axis from interfering because the forward key is pressed. There is no issue when only one of the input axis are used, the speed remaining consistent when turning. I tried to implement this function especially so I don't have to use any drag, to allow the player to be flung by other things, like grapples and explosions (this issue is present irrespective of said external factors). If you want to, I will share the entire code, but it's messy and I don't think it would help. Any ideas how to solve it? Edit yes, I have normalized the input vector. The speed increases to more than triple of the maximum, in as few as 2 turns.


admob ads problem in uity In unity 2019.1.3f I want to implement google admob ads in that game but after importing GoogleMobileAds v3.18.0.unitypackage in to my project I got a porblem. when I hit play button this window poped up. Please help me regarding the problem Thank you


Failed to get socket connection from UnityShaderCompiler.exe shader compiler! C Program Files Unity Editor Data Tools UnityShaderCompiler.exe When running a jenkins build using the Unity 3D plugin I get the following error repeatedly Failed to get socket connection from UnityShaderCompiler.exe shader compiler! C Program Files Unity Editor Data Tools UnityShaderCompiler.exe Not sure what's going on there, I tried giving a pass to the exe in windows firewall but it didn't help. I have Unity 2017.1 installed...


Changing alignment within a vertical layout group I have a vertical layout group that has text bubbles instantiated into it. Instantiating them always aligns them to "lower middle". However, I'd like to have them on opposite sides for a message app effect. Right now, I'm changing the anchoredPositions of each instantiated UI object in Update. Is there any better way of doing this?


Controlling Instantiation I have an problem where I instantiate a GameObject and it keeps on instantiating a million times over, even though I put the line of code under the start function. I am trying to have the player collide with the coin(then a point is added to your score) , then the coin deletes itself and then re instantiates at a random coordinate, but I cant get past the initial instantiation. using System.Collections using System.Collections.Generic using UnityEngine public class Coin MonoBehaviour public GameObject coins Vector2 randomPosition public UIScript UIScript Use this for initialization void Start () UIScript GameObject.FindWithTag("UI").GetComponent lt UIScript gt () randomPosition new Vector2(Random.Range( 8f, 8), Random.Range( 4f, 4f)) Instantiate(coins, randomPosition, Quaternion.identity) Update is called once per frame void Update () private void OnTriggerEnter2D(Collider2D coinCollision) switch(coinCollision.tag) case "Player" collisionWithPlayer() break private void collisionWithPlayer() UIScript.highScore UIScript.highScore 1 Object.Destroy(coins)


Unity3d "random" transform position values on editor Run into some strange behavior on editor position values. https youtu.be DUBpbOUkbfo As you can see we have two cube object with colliders on both and rigidbody on parent. After start play mode parent object editor values sets to some random numbers while transform.localPosition and transform.position is still (0,0,0). This somehow related to parent child physics hierarchy but can't understand how.


Unity's Box Collider isn't preventing an object from falling through the floor I'm working on a little "Tower of Hanoi" AR game in Unity using Vuforia, where the game is projected onto an image target. Now I wanted to make the rings "fall" into place, so I added an invisible ground floor plane, with a box collider, and added mesh collider and rigid body to my ring. Here are the settings Now there are quite a few questions about objects falling through the floor around and I tried many of the different suggestions (thickness of box collider, continuous instead of discrete collision detection,...) but none of them solved my issue. Since this is my second little Unity project, I guess the issue is obvious (maybe my ring is too small (few centimeters) or something, but I'm not sure. The problem is also, that I can't really see what is happening during runtime, since the camera has to find the image target first, after that the ring (currently testing only the bottom one) is gone and I just see the y value of it's position changing. Any help is much appreciated!


Limits of FixedJoint in Unity I've built towers of cubes where each cube is connected to the one before with a FixedJoint. At 30 high they flop about as expected, but at a certain point (demonstrated at 100 high) they explode and do something crazy, moving around at light speed. Video https www.loom.com share 8807d99f157c45a1899138b469b4dec3?from recorder 1 Is there a limit to the amount of force torque a FixedJoint can simulate properly? The forces are set to break at infinity.


How do I get parabolic movement in Unity using Rigidbody2d? EDIT It was the Animator after all. Apply Root Motion basically nullifies any physics based work. I "know" this answer but I can't figure out what can possibly be wrong. My code is in FixedUpdate(). My Rigidbody2D has a Gravity Scale of 4 and a Mass of 1. For whatever reason a Gravity Scale of 1 just isn't strong enough to keep it from floating away. In the pictures below the little cubes should be marking each frame. Using the below code I get a jagged leap movement. The object shoots upwards and falls like a feather. if(Game.inputManager.GetKey("Jump").KeyPressed()) yForce 1000f this.rigidbody2D.AddForce(Vector2.up yForce) And using another suggestion I distribute the force over a second of time. if(Game.inputManager.GetKey("Jump").KeyPressed()) addForceTimer 1 yForce 1000f addForceTimer Time.deltaTime if(addForceTimer gt 0) this.rigidbody2D.AddForce(Vector2.up yForce Time.deltaTime 4) And I get a more desirable but still just as wrong movement where there is no hang at the top of the jump. From what I thought I knew neither of these should be happening at all. The object shouldn't be falling at a constant speed like it is. Does anybody have any suggestions? The character is animated if that can possibly have some sort of effect but I don't imagine it would.


Unity parallel vectors and cross product, how to compare vectors I read this post explaining a method to understand if the angle between 2 given vectors and the normal to the plane described by them, is clockwise or anticlockwise public static AngleDir GetAngleDirection(Vector3 beginDir, Vector3 endDir, Vector3 upDir) Vector3 cross Vector3.Cross(beginDir, endDir) float dot Vector3.Dot(cross, upDir) if (dot gt 0.0f) return AngleDir.CLOCK else if (dot lt 0.0f) return AngleDir.ANTICLOCK return AngleDir.PARALLEL After having used it a little bit, I think it's wrong. If I supply the same vector as input (beginDir equal to endDir), the cross product is zero, but the dot product is a little bit more than zero. I think that to fix that I can simply check if the cross product is zero, means that the 2 vectors are parallel, but my code doesn't work. I tried the following solution Vector3 cross Vector3.Cross(beginDir, endDir) if (cross Vector.zero) return AngleDir.PARALLEL And it doesn't work because comparison between Vector.zero and cross is always different from zero (even if cross is actually 0.0f, 0.0f, 0.0f ). I tried also this Vector3 cross Vector3.Cross(beginDir, endDir) if (cross.magnitude 0.0f) return AngleDir.PARALLEL it also fails because magnitude is slightly more than zero. So my question is given 2 Vector3 in Unity, how to compare them? I need the elegant equivalent version of this if (beginDir.x endDir.x amp amp beginDir.y endDir.y amp amp beginDir.z endDir.z) return true


Main Camera re sizing in 2d My UI An UI from YouTube video Look my camera's size is 10 and his camera's size is only 5. But, my camera's width is larger than height. If you look at scale (x,y,z) (1,1,1). I tried to change them. But, nothing changes.I tried to change ViewPort Rect then, I am able to change the size of Main Camera. But, look at following image. His ViewPort Rect is 1 by 1 mine also. But, we have differences of width and height. How to fix it?


Unity and C Cube with random directions I want to create a similar line RigidObject in Unity c just like in the iOS game Circle So far I placed a cube object that is extended by length. So, how would you approach to create such an object? I tried with a for loop where I was trying to add a cube at the end of the other, but the rotation messed everything up. I don't want to create a prefab, since I want the lines to be random and different every time the player starts the game.


How do I disable fog on specific camera s I'm building an FPS with fog and I want to include a dynamic minimap, showing the locations of player and enemies in real time. This is utilized by a second camera which is orthographic and looks at the scene from above. In the minimap, I don't want to see the fog of course. I've hidden other things from the minimap by using layers and culling masks, however the fog does not belong into any specific layer. So, how do I disable the fog on just one (or some) camera?


Need help reducing my build's size I developed an Android game using Unity3D and successfully published it in Play Store. But the apk size almost 30MB which is pretty big for my game. When I checked the Editor Log after the build, this is what I found Textures 2.5 mb 20.1 Meshes 433.8 kb 3.4 Animations 2.2 kb 0.0 Sounds 3.9 mb 31.3 Shaders 191.3 kb 1.5 Other Assets 157.9 kb 1.2 Levels 166.9 kb 1.3 Scripts 1.2 mb 9.4 Included DLLs 3.9 mb 31.5 File headers 44.5 kb 0.3 Complete size 12.5 mb 100.0 I just don't understand how could the final build will weigh more than twice the size stated in the log


How to draw a 2D cross section of a 3D object? I am creating a game where I only want the user to see the 2D intersection of a plane with a 3D object. The goal of the game is to move this plane to a certain position and rotation, which gives a certain 2D shape. Here is a link to a website which illustrates the 2D slices of a 3D object. How do I approach this if I only want the player to see the slice. Just to be clear, the solution does not necessarily have to be in 3D, since the ui for the player is going to be 2D anyway


How to save options at the game? In my game main character can move using tap or hold finger on the screen. I wanna create at the menu options, and there button to change control type. How I can save player choose? Using Prefs?


how to android touch in Unity? I am creating simple game for android.I used touchphase.moved to power up my ball and touchphase.ended to throw the ball.But what happened is the ball is thrown when I moved my finger in both x and y direction.But I want the ball to be thrown only while swiping in y direction.How to do that Suggest me?


How can i get component script from FirstPersonCharacter? In the Hierarchy i have a FPSController and as child of it FirstPersonCharacter. I can get script that attached to the FPSController but not from the FirstPersonCharacter. What i want to get is the Blur script from the FirstPersonCharacter. using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class FadeScript MonoBehaviour public CharacterController firstPersonCharacter public FirstPersonController fpc public float fadeDuration 5 public float speed private Material material private float targetAlpha 0 private float lerpParam private float startAlpha 1 private bool rotated false void Start() material GetComponent lt Renderer gt ().material SetMaterialAlpha(1) fpc.enabled false void Update() lerpParam Time.deltaTime float alpha Mathf.Lerp(startAlpha, targetAlpha, lerpParam fadeDuration) SetMaterialAlpha(alpha) if (alpha 0) fpc.enabled true if (rotated false) fpc.GetComponent lt FirstPersonController gt ().enabled false fpc.transform.localRotation Quaternion.Slerp(fpc.transform.rotation, Quaternion.Euler(0, 0, 0), speed Time.deltaTime) if (fpc.transform.localRotation Quaternion.Euler(0,0,0)) fpc.GetComponent lt FirstPersonController gt ().enabled true firstPersonCharacter.GetComponent lt Blur gt rotated true public void FadeTo(float alpha, float duration) startAlpha material.color.a targetAlpha alpha fadeDuration duration lerpParam 0 private void SetMaterialAlpha(float alpha) Color color material.color color.a alpha material.color color I can get scripts from the FPSController like this fpc.GetComponent lt FirstPersonController gt ().enabled true But i can't get the Blur script from the firstPersonCharacter. I tried before instead public CharacterController firstPersonCharacter With GameObject public GameObject firstPersonCharacter But Blur is not exist. When i make GetComponent The Blur is not exist.


Spawning prefab on touch after previous spawn(s) had been destroyed I wrote a script which pawns an object (instantiated prefab) each time the player touches the screen. The maximum number of these spawned objects active in the scene at once is 3, and when they are not visible they will be destroyed. I need these prefabs to be able spawn again after they had been destroyed. I tried this but it does not work... This script is added to a game object called quot canCreator quot in my scene hierarchy public class CreatingCan MonoBehaviour public GameObject Can public int numberOfCans public bool canSpawn true private void Start() numberOfCans 0 void Update() if (Input.touchCount gt 0) Touch touch Input.GetTouch(0) Vector2 TouchPosition Camera.main.ScreenToWorldPoint(touch.position) if (touch.phase TouchPhase.Began amp amp canSpawn true) if (Instantiate(Can, TouchPosition, Quaternion.identity)) numberOfCans if (numberOfCans gt 3) canSpawn false This script is on my can prefab public class fallingCan MonoBehaviour CreatingCan CC private void Update() if (transform.position.x lt Camera.main.transform.position.x 10) Destroy(gameObject) CC.numberOfCans


Set up UnityEvent in script with string method name? I'm making a game that I'd like to be data driven. I've got a designer that can make levels using unity and saving them as a unity scene. What we're doing is exporting those levels as XML and loading them from a website into a single scene. This allows for rapid prototyping on devices the designer does not need to wait for me to push builds out or push his own out. Many of the scripts on the prefabs we're loading use UnityEvents, so I can allow my designer to trigger anything he wants in a given script. It gives him more freedom to design and stops my scripts from being too specific. Currently, I'm reducing these UnityEvents down to the object they are referencing and the function they are calling and storing them as string attributes in the XML. However, I'm unsure how to convert from the string function name into an actual function pointer for the UnityEvent, nor do I know how to set up a UnityEvent the way the inspector allows me to. See here you can attach an object and select a function to trigger, then simply call Invoke() on the UnityEvent, but the only documentation I can find on UnityEvent scripting only allows you to add listeners with methods within the script. Here I am getting the Type from a string and the MethodInfo from a string, but am unsure of how to set up the UnityEvent with this information Type type Type.GetType("ScriptName") MethodInfo theMethod type.GetMethod("FunctionName") UnityEvent myEvent new UnityEvent() myEvent.AddListener() Reference to Method goes here reference to the script goes where?


How to make a script's Gizmo toggleable in the Gizmos menu in Unity3D? I've implemented Gizmos for a few behaviours, and I'd like to make them toggleable in the Gizmos menu, just like the built in ones. Is this achievable?


Play and Stop Animation on Condition Unity I've applied a scale animation on Play button of my game. I want to stop animation when play button is not interactable. It stops playing animation, but animation is not playing again, even when play button gets interactable. Here is my snippet to Play and Stop Animation. if (!PlayButton.GetComponent lt Button gt ().IsInteractable()) PlayButtonAnimator.Stop () else if (PlayButton.GetComponent lt Button gt ().IsInteractable()) PlayButtonAnimator.Play ("Play Button Animation") What should i do to play animation again. Thanks in advance )


How to make a fan like behavior I am making a game in Unity. I have an object e.g. cube. I want to release air from it like fan so that when other cubes come closer, it throws them away. What velocity,force etc I will need to do that?


How to simulate a liquid like "The Cook" or "Bake it"? I want to make a simple liquid something like these gifs


New Unity Post Processing Default Project '3d With Extras' What effect is causing this transparency in distant objects? I've recently seen in Unity you can start a new project with Extras included. Which is basically some post processing to make it look nicer as standard, as well as some assets materials etc to get you started. I have started a new project like this. And you can drive a car around a fixed camera. But if the car goes a few metres (well maybe 10 30 metres or so) into the distance there is a sort of grey fog there and it makes much of the cars mesh become more and more transparent the further you go. It doesnt look nice at all because parts of the car (like the windscreen) can still be seen, whilst the car body is not visible. My question is, what is this effect called and where do I alter disable it


Why does unlocking cursor with keyup behave the same as unlocking it with keydown? To understand the difference, let me review a bit about the behavior of GetKeyUp and GetKeyDown with the following code snippet. void Update() if (Input.GetKeyDown(KeyCode.Escape)) Debug.Log("Escape Key Down") if (Input.GetKeyUp(KeyCode.Escape)) Debug.Log("Escape Key Up") Right after pressing the Esc key (and holding it), a message "Escape Key Down" is produced. Later right after releasing the key, a message "Escape Key Up" will show. The behavior does make sense. Now I apply this for toggling (locking unlocking) the mouse cursor. Here is my code snippet. void Update() if (Input.GetMouseButtonDown(0)) Cursor.lockState CursorLockMode.Locked Cursor.visible false if (Input.GetKeyUp(KeyCode.Escape)) Cursor.lockState CursorLockMode.None Cursor.visible true Right after clicking the left mouse button, the cursor becomes invisible. However, right after pressing down the Esc key, the cursor becomes visible again. The expected behavior is that the cursor will be visible right after releasing the Esc key rather than right after pressing the key. Question How to fix this abnormal behavior?


Why is my perspective layer is painted over ortho layer? The entire game takes place in ortho with the exception of the background layer which is drawn on a perspective camera. Everything seems to be working well except that the background is displaying over the orthographic layer. I've tried fidgeting with the layers, orders and depth of cameras but I'm coming up dry. Take a look at the pics and you may see what I mean.


How can I make item interactable for action? In this script when there is a detection I'm setting the flag detect to true and using in with other scripts. And using the clickForDescription flag and OnGui to display text description for each interactable item if there is a text for it. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public bool interactableObject false public Transform parentToSearch public static bool detected false private RaycastHit whatObjectHit private bool clickForDescription false private bool clickForAction false private int layerMask 1 lt lt 8 private void Start() private void Update() if (Input.GetMouseButtonDown(0)) clickForDescription true clickForAction true Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask)) detected true objectHit whatObjectHit.collider.gameObject.name interactableObject true print("Hit ! " whatObjectHit.collider.gameObject.name) else detected false clickForDescription false print("Not Hit !") private void OnGUI() if (clickForDescription true) ProcessOnGUI(parentToSearch) void ProcessOnGUI(Transform parent, int level 0) foreach (Transform child in parent) if (child.GetComponent lt ItemInformation gt () ! null) ItemInformation iteminformation child.GetComponent lt ItemInformation gt () if (child.name objectHit) var centeredStyle GUI.skin.GetStyle("Label") centeredStyle.alignment TextAnchor.UpperCenter GUI.Box(new Rect( Screen.width 2 50 20 level, lt INDENTATION Screen.height 2 25, 100, 50), iteminformation.description, centeredStyle) Process next deeper level ProcessOnGUI(child, level 1) public class ViewableObject MonoBehaviour public string displayText public bool isInteractable This is the ItemInformation using System.Collections using System.Collections.Generic using UnityEngine public class ItemInformation MonoBehaviour TextArea public string description Once object is tagged for Interactable and the ItemInformation is attached to it it will display some description for the item. Now I want to do something for action. For example if the item is Interactable and a script name ItemAction is attached to it do some action, For example move the object from side to side or rotate the object. The logic should be like the Information. It's just with the Action there might be many options then just displaying text. I'm not sure how to make some logic and how to work with the ItemAction. using System.Collections using System.Collections.Generic using UnityEngine public class ItemAction MonoBehaviour


Blender Unity Move texture with Bone in way that works with Unity? I created a character model in Blender with non spherical eyes. The only way I can make the eye movement look good is if I move the pupil Image Textures along the eye meshes. The way I've achieved the pupil movement in Blender is with modifiers, which Unity apparently doesn't work with. I've tried "UV Warp" controlled by bone and "UV Project" controlled by bone, and moving the eye bones in Unity does nothing. So, I'm kind of stumped and desperate for something that will work for my use case. Any ideas that will be Unity friendly, please?


How To Smoothly Animate From One Camera Position To Another The Question is basically self explanatory. I have a scene with many cameras and I'd like to smoothly switch from one to another. I am not looking for a cross fade effect but more to a camera moving and rotating the view in order to reach the next camera point of view and so on. To this end I have tried the following code firstCamera.transform.position.x Mathf.Lerp(firstCamera.transform.position.x, nextCamer.transform.position.x,Time.deltaTime smooth) firstCamera.transform.position.y Mathf.Lerp(firstCamera.transform.position.y, nextCamera.transform.position.y,Time.deltaTime smooth) firstCamera.transform.position.z Mathf.Lerp(firstCamera.transform.position.z, nextCamera.transform.position.z,Time.deltaTime smooth) firstCamera.transform.rotation.x Mathf.Lerp(firstCamera.transform.rotation.x, nextCamera.transform.rotation.x,Time.deltaTime smooth) firstCamera.transform.rotation.z Mathf.Lerp(firstCamera.transform.rotation.z, nextCamera.transform.rotation.z,Time.deltaTime smooth) firstCamera.transform.rotation.y Mathf.Lerp(firstCamera.transform.rotation.y, nextCamera.transform.rotation.y,Time.deltaTime smooth) But the result is actually not that good. Thank you all, I fixed it this way var pos Vector3 firstCamera.transform.position var rot Quaternion firstCamera.transform.rotation firstCamera.transform.position Vector3.Lerp(pos, nextCamera.transform.position,Time.deltaTime smooth) firstCamera.transform.rotation Quaternion.Lerp(rot, nextCamera.transform.rotation,Time.deltaTime smooth)


Queueing with Unity's NavMeshAgent I have created a strategy game where the units use Unity's NavAgent pathfinding and flocking algorithms. This works well. However, I need to add queueing so that units will queue sensibly. This works most of the time, but it isn't perfect and I want to know if there's a better way of doing it. My first draft was to simply check which unit is closest to the destination, but this caused issues because a group might be navigating around an obstacle and the unit closest is at the back of the queue... so the whole group stops. Second draft checked the distance to destination based upon the length of the path each unit had to take. This works far more often, but sometimes still has issues. Sometimes the same problem happens, but much less often. The one who is supposed to be moving stops, and so the entire group stops. There's also a problem I've noticed, where the waiting units could sometimes benefit from rotating, even if they shouldn't be moving. Unfortunately they sometimes get stuck and will wait before they can move, to rotate. If they could rotate when forbidden from moving it'd help considerably too. What I need to know... How can I make Unity NavAgent's queue, so that they will wait for the other agents closest to the destination to move first? How can I ensure that this does not stop agents from rotating while in a queue (rotating may move them into a better position in the queue). Code Unit Movement Function private void Movement() Unit is moving. if (moveVectors.Count gt 0) navAgent.isStopped false Check for whether to wait in queue. Vector3 nextVector transform.position nextVector transform.forward speed Time.deltaTime foreach (Unit unit in list) if (unit ! this amp amp unit.moveVectors.Count gt 0 amp amp Vector3.Distance(unit.transform.position, nextVector) lt (unit.footprint footprint) amp amp PathDistance(unit) lt PathDistance(this)) navAgent.isStopped true return There's a bit more to Movement, but it's not relevant so we'll ignore it for now. PathDistance Function private float PathDistance(Unit unit) Vector3 startPosition unit.transform.position Vector3 endPosition unit.moveVector Vector3 lastPosition startPosition Vector3 path unit.navAgent.path.corners float distance 0 for (int i 0 i lt path.Length i ) distance Vector3.Distance(lastPosition, path i ) lastPosition path i distance Vector3.Distance(lastPosition, endPosition) return distance Is there a better way of achieving the result I want?


How to make a string from the words of a file in Unity? I have .txt file containing all the English words separated by line breaks. I want to turn them to a string so I can easily pick a random one from them. The way I would do that in normal C is the File.ReadAllLines(path) function in the System.IO namespace. But, I don't think that I can use System.IO with Unity so the alternative that I could come up with is the TextAsset class which I can use to reference an imported text asset and get its text property as a string. But, if I have a giant string how can I simply split it up into individual words and store them as a string ?


How can I detect that the mouse is over a button so that I can display some UI text? I have a scene, where a panel containing 24 buttons. I need to show some piece of text when hover a mouse cursor over the button. For example, for detecting clicks, I'm using onClick event trigger, but I can't find anything related to something like a onHover event. I have Googled and read the docs, but could not find anything. Can anybody help me with that? Code var button panel.GetChild(0).GetComponent lt Button gt ()


Unity Error importing any video clip When I try to import a video file to play in a VideoPlayer component, I get the following errors in the Console WindowsVideoMedia error 0xc00d5212 while reading C Users Jonas OneDrive Projects Project1 Assets Videos output.mp4 Context Setting media type for first video stream Error details No suitable transform was found to encode or decode the content. Track types Audio Track, type U UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) Error while reading movie C Users Jonas OneDrive Projects Project1 Assets Videos output.mp4 UnityEditorInternal.InternalEditorUtility ProjectWindowDrag(HierarchyProperty, Boolean) UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) VideoClip import error for Assets Videos output.mp4 UnityEditorInternal.InternalEditorUtility ProjectWindowDrag(HierarchyProperty, Boolean) UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) WindowsVideoMedia error 0xc00d5212 while reading C Users Jonas OneDrive Projects Project1 Assets Videos output.mp4 Context Setting media type for first video stream Error details No suitable transform was found to encode or decode the content. Track types Audio Track, type UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) The video file is just an ordinary H.264 AAC MPEG 4 video file transcoded using ffmpeg. But I also tried the same format and H.264 AAC QuickTime MOV (both rendered from Blender) and AVI (JPEG) from Blender as well. System Details Unity 2018.4.12f1 (LTS) Personal Build target Android (Minimum API Level 25) Windows 7 Home Premium 64 Bit (SP1) Blender 2.80 ffmpeg version N 85588 g6108805 I tried to post this to the Unity Forums before, but as of writing this, the thread has yet to be greenlighted by moderation, so I might as well try posting it here, as you usally get an answer much more quickly


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


Why does AudioSource not initializes itself? Why does AudioSource not initializes itself? Here is my code using System using System.Collections using System.Collections.Generic using UnityEngine public class CameraConfig MonoBehaviour public GameObject objToFollow public bool followRabbit Use this for initialization void Start() followRabbit true LevelController.current.cameraWhichLooksForRabbit this setMusicSource() setSoundSources() public AudioClip music, rabbitWalksSound, rabbitDiesSound, rabbitFallsSound, enemyAttacksSound private AudioSource musicSrc, rabbitWalksSrc, rabbitDiesSrc, rabbitFallsSrc, enemyAttacksSrc private void setMusicSource() setClipForSrc(musicSrc, music, true) private void setSoundSources() setClipForSrc(rabbitWalksSrc, rabbitWalksSound, false) setClipForSrc(rabbitDiesSrc, rabbitDiesSound, false) setClipForSrc(rabbitFallsSrc, rabbitFallsSound, false) setClipForSrc(enemyAttacksSrc, enemyAttacksSound, false) private void setClipForSrc(AudioSource src, AudioClip clip, bool loop) src gameObject.AddComponent lt AudioSource gt () src.clip clip src.loop loop void Update() checkMusicAndStopOrStartIfNecessary() if (!followRabbit) return Transform rabit transform objToFollow.transform Transform camera transform this.transform Vector3 rabit position rabit transform.position Vector3 camera position camera transform.position camera position.x rabit position.x camera position.y rabit position.y camera transform.position camera position public void playSoundRabbitWalks() if (!rabbitWalksSrc.isPlaying) rabbitWalksSrc.Play() public void playSoundRabbitDies() rabbitDiesSrc.Play() public void playSoundRabbitFalls() rabbitFallsSrc.Play() public void playSoundEnemyAttacks() enemyAttacksSrc.Play() public void stopSoundRabbitWalks() if (rabbitWalksSrc.isPlaying) rabbitWalksSrc.Stop() public void stopSoundRabbitDies() rabbitDiesSrc.Stop() public void stopSoundRabbitFalls() rabbitFallsSrc.Stop() public void stopSoundEnemyAttacks() enemyAttacksSrc.Stop() private void checkMusicAndStopOrStartIfNecessary() if (SoundManager.Instance.isMusicOn() amp amp !musicSrc.isPlaying) musicSrc.Play() else if(!SoundManager.Instance.isMusicOn() amp amp musicSrc.isPlaying) musicSrc.Stop() Here are screenshot of the exceptions in console and inspector view


When creating a game, what are some architectural desgin concepts I can use to be able to port my game from single to multiplayer? I am a software developer but, I mostly develop games in Unity. I have experience creating single player games as well as multiplayer games. I am at a crossroads where I am in the middle of development of a proof of concept or small demo and all of a sudden I am asked to turn it into a multiplayer game without prior knowledge of this I turn around and say it would add 50 to development time because I basically have to start over from scratch because I didn't necessarily take into account that later down the road they might want to change the experience from single to multiplayer. So with all of that out of the way, are there any different methodologies out there that would make it easier on the developer to port a game from single player to multiplayer? I have thought of a possible way of doing this by just setting the game up as single player, however, making my functions where they are easily able to wrap them using Commands and RPCs. But I find this may or may not help me and is only dependent on what the requirements are. My biggest time killer when it comes to porting these PoC's is typically the UI. Most of the time my requirements are so that the UI will be the same shared UI for all clients and having to update it for each action performed on it and dealing with handling ClientAuthority. (Any tips for dealing with this would be greatly appreciated too) Think of this as something like, making something with Legos in multiplayer and having shared instructions based on the step the user is on. Summary What are different ways that I can design a small demo concept where I can easily port it to multiplayer later on, or make my game where it is "multiplayer friendly" ? Or should I try to stay away from this type of thinking altogether and just develop a single player aspect and just develop a multiplayer aspect, arguments for and against this concept are sought after.


How to fix lag in 64 bit Android devices My game's FPS drops to 30 8 FPS on any 64 bit Android device but is at 59 60 FPS on an even lesser 32 bit Android device. I've tried unchecking Development Build on Build settings and I've tried disabling debug calls on my game by using void Update () if UNITY EDITOR if(!Debug.unityLogger.logEnabled) Debug.unityLogger.logEnabled true else if(Debug.unityLogger.logEnabled) Debug.unityLogger.logEnabled false endif But there wasn't any change. And I tried setting all Stack Trace Log type to None(Edit gt Project Settings gt Player). Also no change. PS I used that update call because there are other imported assets that call the Debug class and I wouldn't want to mess around with their classes. EDIT As you can see in the screenshots below, the device that runs the game at less than 30 FPS(every 64 bit device) has Gfx.WaitForPresentOnGfxThread take 71.6 of the frames and RenderPipelineManager.DoRenderLoop Internal() takes up 51.1 . While the device that ran the game at 60FPS(every 32 bit device) has RenderPipelineManager.DoRenderLoop Internal() take up the most frames with 35.7 of the frame. How should I fix the frame rate drop on the 64 bit device? EDIT The 32 bit Android device is an Infinix Hot 4, 2GB RAM, 1.3GHz quad core MediaTek MT6580 CPU, OpenGLES2, Android 7.0, 1280x720. This reaches a maximum of 62FPS(Average 59FPS). The 64 bit Android devices are Cubot X19 4GB RAM, 8 core CPU 4x 2.3 GHz ARM Cortex A53, 4x 1.65 GHz ARM Cortex A53 , OpenGLES3, Vulkan supported, Android 9.0, 2160x1080. This reaches a maximum of 30 FPS(Average 25FPS). Qubo P19 3GB RAM, 1.5GHz Quad Core MT6739WA CPU, OpenGLES2, OpenGLES3 supported, Android 9.0, 1280x640. This reaches a maximum of 25FPS(Average 19FPS). I'm using Unity 2019.3.1f for my project.


(How exactly to use EventSystem?) Assigning string Name to UI Button in Unity without CrossPlatformInput? I'm trying to make a new game for Android. There is a Jump button i've added as UI button , this works fine as I have a method for Jump() which I can just add to the OnClick() method in the Button's Inspector tab. However, for my 'Pick Up' button I don't really want a method for pick up. I already have my item pickup handling code inside a OnTriggerEnter() method and what I was hoping to do was have an additional if condition into my code like if (Input.GetButtonDown("Pickup")) then it ok to pickup! This is how i did it in my other projects. But I had been importing the CrossPlatformInput namespace and then just copied and adapted the buttons from the Jump button that came as standard with that. So now, I can't see how to name my button as 'Pickup'. I tried looking at the code from CrossPlatformInput, it seems it takes the name you provide it, and passes it to VirtualInput (also in the CrossPlatformInput namespace), I couldnt see a copy of this class anywhere, it think its closed source maybe Of course, I could probably manually make a method to add to the OnClick() which just makes a bool true only when it's being clicked. But I feel like there must be a way to just add this UI button as 'Pickup' to the Input system (like you do with "Horizontal", "Vertical" or "Jump" for example). Again, I tried to read the docs, and also lots of forums and sites like this. I found that the EventSystem will (or should) have the part I need, but i am now stuck. I tried this EventSystem.current.currentSelectedGameObject.name ?????????? I read that will return the name of the most recent button pressed, but how would that method know that my new Button is called "Pickup", I dont see how I added it to that yet? Another reason why i'd like to do it this way is for Cross Platform compatibility. If I make it this way, I already now that there is a certain button on the keyboard mapped in Project Input to the same name (ie. "Pickup" Left Ctrl). And it seems cleaner to use the existing way of doing this if possible, im sure its just that I dont know how yet. Most options ive seen online involve the OnClick inspector function, or CrossPlatFormInput imported package. I hope this makes sense to someone, and that there is a way to do it. Thanks for any help as usual very much appreciated.


Unity3D Despite using Time.deltaTime, my camera and player move faster at higher framerates I'm pretty new to c and Unity so I wouldn't be surprised if I had made some stupid mistakes, but as far as I know, I don't think I misused Time.deltaTime. Any help would be greatly appreciated. Movement Script using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public CharacterController controller public float speed 12f public float gravity 9.81f public float jumpHeight 3f public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask private float crouchMultiplier 1f private Vector3 velocity private bool isGrounded private bool isCrouched private float velocityDecay 1f Update is called once per frame void Update() isGrounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if (isGrounded amp amp velocity.y lt 0) velocity.y 2f float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z controller.Move(move speed crouchMultiplier velocityDecay Time.deltaTime) Debug.Log(Time.deltaTime) if (Input.GetButtonDown( quot Jump quot ) amp amp isGrounded) velocity.y Mathf.Sqrt(jumpHeight 2f gravity) if (Input.GetKeyDown(KeyCode.LeftControl)) isCrouched true gameObject.transform.localScale new Vector3(1, 1f, 1) if (Input.GetKeyUp(KeyCode.LeftControl)) crouchMultiplier 1f gameObject.transform.localScale new Vector3(1, 2f, 1) velocityDecay 1 isCrouched false if (isCrouched) if (velocityDecay gt 0.2f amp amp isGrounded) crouchMultiplier 2.5f velocityDecay 0.995f velocity.y gravity Time.deltaTime controller.Move(velocity Time.deltaTime) Camera Script using System using System.Collections using System.Collections.Generic using UnityEngine public class MouseLook MonoBehaviour public Transform playerBody public float mouseSensitivity 100f float xRotation 0f Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked Cursor.visible false Update is called once per frame void Update() float mouseX Input.GetAxis( quot Mouse X quot ) mouseSensitivity Time.deltaTime float mouseY Input.GetAxis( quot Mouse Y quot ) mouseSensitivity Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX)


In Unity, can I load a local ( Resources folder) website to safari on an ipad In Unity, can I load a local ( Resources folder) website to safari on an ipad? This works fine on a Mac, opening up a wepage from my Resources folder. string path "file " (Application.dataPath) " Resources testsite.html" void OnGUI() if(GUI.Button(new Rect(20, 20, 100, 100), "site")) Application.OpenURL(path) but when I try to load this on an iPhone or iPad, it doesn't seem to work. Am I accessing the address incorrectly for iOS using "file "? If this is not possible, is there an alternative way I can load a locally stored website on an iOS device?


Geometry shader vertex position to point at camera I have a shader that takes an array of points. At each point, a geometry shader creates a quad oriented towards the camera. This works fine when the camera and point are at around the same Y value, however, looking up down upon the billboard results in it shrinking to a point the closer the camera approaches being directly above below. Example (Youtube) maxvertexcount(4) void geom(point v2g IN 1 , inout TriangleStream lt g2f gt triStream) Calculate some vectors float3 up float3(0, 1, 0) float3 look WorldSpaceCameraPos IN 0 .position look normalize(look) float3 right cross(up, look) And how far off centre our corners are float halfS 0.5f IN 0 .colorScale 1 Scale Calculate verts float4 v 4 v 0 UnityObjectToClipPos(IN 0 .position float4( halfS right halfS up, 1.0f)) v 1 UnityObjectToClipPos(IN 0 .position float4( halfS right halfS up, 1.0f)) v 2 UnityObjectToClipPos(IN 0 .position float4( halfS right halfS up, 1.0f)) v 3 UnityObjectToClipPos(IN 0 .position float4( halfS right halfS up, 1.0f)) pass through color texture lookup float2 color float2(IN 0 .colorScale 0 , .5) Start pushing verts g2f o o.position v 0 o.color color o.uv float2(1.0f, 0.0f) triStream.Append(o) ... I'm guessing my issue is related to the fact that my up and look are approaching coincidence, as the forward derives directly from the camera and the up is in world space, however, I'm uncertain of my diagnosis and unclear on how to generate an appropriately rotated up?


How do I go about ensuring a unique ID value? I am using Unity and coding in C . I have a game object called Enemy, which has a script called EnemyMotor. EnemyMotor has an int called ID. When EnemyMotor starts, I need to find an ID value that is not been using by any other instance of EnemyMotor. For example Enemy one spawns check if an ID value of 1 is not being used. Enemy two spawns check if an ID value of 1 is being been use. In this case, it is, so I need to find another ID value that is not being used. In this case, it should be 2. Continue with Enemy three, Enemy four and so on. How do I go about ensuring a unique ID value?


GPU instancing vs combining meshes for performance I have a relatively low poly procedurally generated scene in which I reuse a bunch of the same objects (walls, floors, etc). I've been writing some code to combine a room's floor tiles into one mesh, its wall tiles into another mesh, etc. However I came across this tutorial (http www.habrador.com tutorials unity mesh combining tutorial ) in which the author says that GPU instancing is essentially the same as mesh combining, but in fewer lines of code. Is this accurate? I tried GPU instancing and got a massive reduction on the GPU, but the CPU still spends a lot of time drawing. Will mesh combining provide more balanced performance for the CPU? I haven't finished my implementation yet and don't want to bother if it's effectively the same. Thanks for the help!


Load scene without being in build settings and without using AssetBundle This is the closest I've gotten EditorSceneManager.OpenScene( AssetDatabase.GUIDToAssetPath( AssetDatabase.FindAssets( "t SceneAsset " MenuSceneName, new string "Assets" ) 0 ) ) However this generates an error at runtime InvalidOperationException This cannot be used during play mode, please use SceneManager.LoadScene() SceneManager.LoadSceneAsync() instead. I can't follow its suggestion because those functions require the scene to be in build settings or an asset bundle. So, is there any other option? I wonder how (and if) Addressables achieve this? Note I'm not willing to switch to Addressables I'm quite enjoying working with AssetBundles. Why? My game uses AssetBundles for general loading of EVERYTHING, so there's only one blank scene in build settings. However, during development I'd rather not have to continuously build and load from AssetBundles, so I'm trying to dynamically load scenes WITHOUT having to add them to build settings.


Unity3D Multiplayer Networking I am making a multiplayer game using Unity3D, similar to SecondLife (but focusing on a particular gameplay task). Users will be able to register login directly in the game and their character will be spawned. So far, I have made the back end Rest ful API to manage users. I am able to use login and register from the unity itself ( Using REST Calls e.g. www.myDomain.com api login ) but how do I spawn the characters accordingly? Also, currently I am making a token based authentication system for the API ( much like Facebook, Twitter) as the API itself is state less. Should I be storing the tokens in playerprefs? I have gone through this tutorial but it doesn't seem to solve my problem. Any kind of direction will help. Thank you.


Unity3d Transform.position float range I thought floating point has a very large range, for example up to 3.4 10 38. However today I tried to set my player's Transform.position.x to 1000000 in the GUI and it gave me a warning "Due to floating point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range." Does that mean that my single scene has to be smaller than 1000000 1000000 1000000. Is this considered big enough? I will need multiple scenes if I want a larger world? When a new scene gets loaded, will my player's position be reseted? How do I manage the position data so that it doesn't go out of range? I'm using Unity3D Pro.


Unity Ragdoll moves away from parent So this is a weird one. I've looked it up but can't find anyone with similar issues. Basically I have a simple combat system and after the enemy health is zero I go through each rigidbody component in the enemy object and add a force to make it go flying on death. For some reason, the parent object isn't affected and stays still while the Skeleton goes flying. Does anybody know how to make the parent object follow the skeleton, or make the skeleton follow the parent because as of now they act as separate entities? I've tried just adding force to the parent but that only moves the parent object and none of the children. Would appreciate any advice! Thanks.


What is a proper way to handle player inputs based on different states? So, I have two ideas how to do that Use enum to define current state and check current state value before running certain method group in Update. Code void Update() switch(currentState) case 1 InputGroup1() break case 2 InputGroup2() break lt ... gt And so on. I don't think that this is a good idea because of possible performance drops. Same concept about current state, but instead of checking it and running method groups, "head" script will check current state and activate corresponding script, disabling others. For me it looks like best way in terms of performance and usability. And also, is it better to keep all input checks in one giant script component and call functions you need from it? Essentially creating centralized Input Manager.


how to sync clients and local avoidance in mobile RTS game? I have been making mobile RTS game in Unity look like Clash Royale similarly. Unfortunately, I faced to two big problems. First is two phones(clients) to be synchronized each other in game state. And second is "path finding" or "local avoidance"(collision check). To solve the path finding issue, I have searched about "Flow Field". Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"? If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients? Thank you in advance.


How to avoid material copying error message in Edit mode? I created a component called "AphaGroup" (an analog of the existing CanvasGroup for UI) which should be able to change alpha of the whole game object tree. My component finds all the MeshRenderer components, takes their material.color and changes its alpha. It should work both in play amp edit modes. When it's run in edit mode there is an error in the console when the material is copied for the first time Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMaterial instead. I've read most of the similar questions on the Internet but still haven't found the answer on how to manage this situation properly. How to avoid both this error message and memory leaks? I tried Renderer.material, Renderer.materials and Renderer.GetMaterials, but all they cause the same error.


Convert array of object to json in unity I need to convert the array of object to json. I have written code to convert object to json. How can I convert the object array to json format JSONClass jsonClass new JSONClass () jsonClass "Array" Array jsonClass "Array" new JSONClass () jsonClass "Array" "Value1" 1 jsonClass "Array" "Value2" 1 print (jsonClass.ToString("")) How to convert this to below format Here is my expected output "Array" "Value1", 1, "Value2", 5,


Breaking ocean waves simulation I am working on a project where I have to approximately simulate the ocean waves. Currently, I am using a mesh modification approach. I am able to simulate low amplitude waves using the following equation yVal Mathf.Sin(180 Mathf.Deg2Rad freqUpdated Time.time speedOFWave) halfWaveHeight Now, I want to extend this equation to simulate breaking waves for a high value of "wave height". Approach tried I tried creating code similar to this plugin but the smooth transition between low amplitude waves to these breaking waves is not possible with that approach. I have the following questions What kind of modification can be done to the above sin wave equation to simulate breaking waves? Are there any other mathematical techniques that can simulate low amplitude and breaking waves? Is it feasible to do this type of ocean simulation using water particles? I would appreciate any suggestions and thoughts on this topic. Thank you.


Enter in a match that is already started In my Unity mobile game, I need multiplayer online functionalities. All the players should be visible in the world at any given time (of course, with some filtering), and a player should be able to connect at any time. Let's say that, for the purpose of this question, only 100 players at the time will log into the game. My first try involved using Unity's built in NetworkManager, but the two problems that arose are that One player is always the host, meaning that if that player logs out all the other players. I did not manage to make it work on two different networks. The implementation I used comes from this tutorial. Next try was using an extension of NetworkLobbyManager, that allows through the Matchmaking system to solve problem 2. This is my implementation using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.Networking.Match using UnityEngine.SceneManagement public class AutoLobbyManager NetworkLobbyManager protected int currentPage 0 protected int previousPage 0 public void CreateOrJoin() StartMatchMaker() RequestPage(0) public void OnMatchListReceived(bool success, string extendedInfo, List lt MatchInfoSnapshot gt matches) if (matches.Count 0) Server does not exist yet. Create one. CreateMatch() return There is then a server. Join it. JoinMatch(matches 0 ) public void RequestPage(int page) matchMaker.ListMatches(page, 1, "", true, 0, 0, OnMatchListReceived) public void CreateMatch() matchMaker.CreateMatch( "Main Match", (uint)maxPlayers, true, "", "", "", 0, 0, OnMatchCreate) void JoinMatch(MatchInfoSnapshot match) matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, OnMatchJoined) public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) base.OnMatchCreate(success, extendedInfo, matchInfo) Debug.Log("Match created!") ServerChangeScene(playScene) public override void OnClientSceneChanged(NetworkConnection conn) string loadedSceneName SceneManager.GetSceneAt(0).name if (loadedSceneName lobbyScene) if (client.isConnected) CallOnClientEnterLobby() else CallOnClientExitLobby() OnLobbyClientSceneChanged(conn) void CallOnClientEnterLobby() OnLobbyClientEnter() foreach (var player in lobbySlots) if (player null) continue player.readyToBegin false player.OnClientEnterLobby() void CallOnClientExitLobby() OnLobbyClientExit() foreach (var player in lobbySlots) if (player null) continue player.OnClientExitLobby() This makes possible to create a Lobby if there is no Lobby, and join the first if there is. It works, if we remove the highlighted line here public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) base.OnMatchCreate(success, extendedInfo, matchInfo) Debug.Log("Match created!") ServerChangeScene(playScene) Because this starts the game. If that line is activated (since I want to start the game as soon as possible), when a client tries to connect, the Server logs NetworkLobbyManager can't accept new connection hostId 0 connectionId 1 isReady False channel count 2 , not in lobby and game already in progress. And the client is not added to the game. I understand that lobbies usually work like that, but 1. Is it possible to add a client after a game is added, with NetworkLobbyManager? 2. Is it the right approach to achieve a multiplayer, non lobby based, non host based, online game in Unity?


Rotate from Current Rotation to Another using Angular Velocity I am attempting to calculate an angular velocity that will get me from the current gameObject.transform.rotation to a given Quaternion rotation using angular velocity. I've tried several methods but all of them seem to cause oscillation (maybe due to the gimbal nature of Vector3 for angular velocity). Here are the pieces of code that I have tried Quaternion rotationDelta Quaternion.Inverse(gameObject.transform.rotation) remoteRotation return (rotationDelta.eulerAngles PlayerMovement.BROADCAST INTERVAL) Another attempt using toAngleAxis rotationDelta.ToAngleAxis(out angleInDegrees, out rotationAxis) Vector3 angularDisplacement rotationAxis angleInDegrees Mathf.Deg2Rad return angularDisplacement PlayerMovement.BROADCAST INTERVAL Using Eulers Vector3 difference new Vector3(Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.x, remoteRotation.eulerAngles.x), Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.y, remoteRotation.eulerAngles.y), Mathf.DeltaAngle(gameObject.transform.rotation.eulerAngles.z, remoteRotation.eulerAngles.z)) Vector3 differenceInRadians new Vector3(difference.x Mathf.Deg2Rad, difference.y Mathf.Deg2Rad, difference.z Mathf.Deg2Rad) return differenceInRadians PlayerMovement.BROADCAST INTERVAL


How to make the background tilemap in Unity3D have a "far away fog effect" filter in a sidescroller game? I would like my background made of the same tiles as my foreground but with a filter which makes it appear further away from the camera. Making the objects smaller is easy, I just have to decrease the scale of the tilemap. But I also want it to have a "fog effect". So for example if the sky is blue then the tiles will be as blueish as far they are from the camera. How could I implement this? Example for fog effect


Unity using 40 GPU for just a UI interface on ultra but 90 on low? So I made some software using unity for my FRC team. All this application is, is just a User Interface with labels, input fields, buttons, etc... When I choose the quality to be on Ultra, I will get about 50 GPU usage but when on very low, I got 90 , close to 100 . How can I optimize my software to use much less of the GPU(Preferably less than 15 )? I am measuring with the Task Manager Performance Menu


Why do 100 rect contain 400 tris? I am making a game targeted towards mobile, so I am experimenting around to know how I can boost performance. Now I have a rectangle with a road texture on it. This I made in Blender. And as expected it has 2 tris. I made a c script to add these rectangles together to make a long road. So if I make a road 100 unit long, I have 100 such rectangles, and I expect that their total tris count becomes 200. Now while running the game, Stats panel shows 8.2k tris for entire scene. And when I disable this 100 unit long road, Stats shows 7.8k tris. So why are there 400 tris for 100 rects? For each rectangle object, I have already turned off the "cast shadows" property. Link to blend file https drive.google.com file d 0BztX2HefTk wb1VuSUlONXVxaE0 view?usp sharing Link to texture file https drive.google.com file d 0BztX2HefTk wc3JvdTBJZmphRUU view?usp sharing EDIT (adding code for builder script) void createRoad() Vector3 rotation new Vector3(270, 0, 0) float z size Value assigned in CreateWizard() Object road item Assigned in CreateWizard() for (int i 0 i lt count i ) GameObject roadPiece (GameObject)Instantiate (road item) roadPiece.transform.parent ((GameObject)Selection.objects 0 ).transform roadPiece.transform.localPosition new Vector3 (0, 0, i z size) roadPiece.transform.localEulerAngles rotation roadPiece.name BASE NAME (i 1) Turn Off cast shadows roadPiece.GetComponent lt MeshRenderer gt ().shadowCastingMode UnityEngine.Rendering.ShadowCastingMode.Off


Pattern for modular ScriptableObject Database? Lets say we want to store game data inside of scriptableObjects and we have plenty of them... So we need to find a way to store them efficiently in a modular way. What pattern could we use to code a scriptableObject database for providing a substainable base for our game data scriptableObjects? And are there any patterns or structures for extending our game data scriptableObjects in order to construct them modular and flexible aswell ?