_id
int64
0
49
text
stringlengths
71
4.19k
0
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.
0
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
0
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
0
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?
0
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
0
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.
0
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.
0
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.
0
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
0
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?
0
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 ?
0
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.
0
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?
0
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)
0
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?
0
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.
0
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
0
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.
0
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)
0
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.
0
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?
0
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
0
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
0
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?
0
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.
0
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
0
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...
0
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?
0
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)
0
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.
0
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!
0
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.
0
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.
0
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
0
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?
0
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.
0
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?
0
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
0
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
0
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?
0
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?
0
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.
0
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
0
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?
0
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?
0
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 )
0
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?
0
How to simulate a liquid like "The Cook" or "Bake it"? I want to make a simple liquid something like these gifs
0
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
0
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?
0
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.
0
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
0
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?
0
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)
0
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?
0
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 ?
0
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 ()
0
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
0
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
0
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
0
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.
0
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.
0
(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.
0
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)
0
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?
0
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?
0
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?
0
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!
0
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.
0
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.
0
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.
0
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.
0
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.
0
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.
0
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.
0
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,
0
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.
0
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?
0
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
0
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
0
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
0
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
0
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 ?
0
Unity 2D Input.gyro eulerAngles X value strange behaviour I am working on a project where I want to create an 'scrolling' effect using gyroscope on mobile devices. The basic idea is that I have an Image object in my Scene and I want to be able to show different part of it using gyroscope like for example you see the wall of a room and rotation your phone you see different parts of the room, but in 2D. For now I managed to move my Image using Input.gyro.attitude.eulerAngles.x from gyroscope like this protected void Update() var x transform.localPosition.x var gyroX Input.gyro.attitude.eulerAngles.x x gyroX Speed BackgroundImage.transform.localPosition new Vector3(x, transform.localPosition.y, transform.localPosition.z) The problem which I am seeing is that when Input.gyro.attitude.eulerAngles.x reaches 86.0 it starts decreasing and even if you are rotating your phone to right it changes it's direction. Checked the documentation, examples over internet, but didn't find anything about that. If you have any idea what can cause that issue and how can I fix it, or any other suggestions how can I achieve the thing which I want to create, pleae share your knowledge. Thanks in advance! Edit The only rotation axis which I am interested in is X, because the app will be in portrait mode and I want to be able to move the image only horizontal (by X). So the phone's rotation has to be similar to while taking an panoramic photo on your mobile as shown on the first picture
0
Should I use Coroutines to change variables in inspector smoothly? I want to change the aperture of the depth of field in the camera smoothly by using Mathf.SmoothDamp and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions? Code using System.Collections using UnityEngine using UnityEngine.UI using UnityStandardAssets.ImageEffects public class GameStartController MonoBehaviour public Button startButton public GameObject cubeSpawner Use this for initialization private void Start() startButton startButton.GetComponent lt Button gt () public void StartGame() EnableCubeSpawner() SpawnStartingCubes() HideStartMenu() StartCoroutine("FocusCamera") PlayBackgroundMusic() Enables the cube spawner, so it can start spawning cubes private void EnableCubeSpawner() cubeSpawner.SetActive(true) private void SpawnStartingCubes() cubeSpawner.GetComponent lt CubeSpawner gt ().GenerateStartingCubes() private void PlayBackgroundMusic() var audio GameObject.FindWithTag("Audio").GetComponent lt AudioController gt () audio.PlayBackgroundMusic() private void HideStartMenu() startButton.transform.parent.GetComponent lt CanvasGroup gt ().interactable false startButton.transform.parent.GetComponent lt CanvasGroup gt ().alpha 0f private IEnumerator FocusCamera() var camera GameObject.FindWithTag("MainCamera").GetComponent lt Camera gt () var velocity 0f while (Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture) gt 0.001f) Debug.Log(Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture)) camera.GetComponent lt DepthOfField gt ().aperture Mathf.SmoothDamp(camera.GetComponent lt DepthOfField gt ().aperture, 0f, ref velocity, 0.3f) yield return null camera.GetComponent lt DepthOfField gt ().aperture 0f
0
Internet Access is always set to required in unity android player settings I am using unity 2019.4.2f1, I want to remove the internet access permission from the final android manifest file created by unity but, because this option is locked I am not able to remove the permission. Let me know if there is any workaround to do so or disable this option somehow.
0
Code vs. Configuration in Unity I know a thing or two about Unity at this point, but I've still lots of subjective, best practice questions, Such as How do you decide what values are obtained via Start Awake initialization, and which values are explicitly serialized into the scene? In my current project, game objects and behaviors reference each other in a complex graph. Initially, I did this on Start(), programmatically, with lots of raycasts and GetComponent lt () and such. Now though, I just declared stuff public (violating encapsulation?), to simply serialize this information to the scene once generated by an Editor script... Which is more correct? Should my methodology be that anything that can be serialized should be serialized? Or is it better to write more initialization code which conveys some explanation why the values are what they are?
0
Determine if ray hits an edge of a model in Unity 3D How can i determine if a ray was hitting an edge of a mesh? The figure below shows what I want to achieve Any ideas?
0
How to use touch screen for movement instead of keyboard narrow keys I wrote this code and run the game on my desktop, now I need to build this game for android and I need to change to touch to move the player, what it should be changed in the following code and what is the necessary steps to build my desktop 2D game to be run on android device, the following is the player code pragma strict var speed int 5 function Start () function Update () if(Input.GetAxis("Horizontal") gt 0) if(collided with ! null) if(collided with.tag "Right") collided with null return transform.Translate(Vector3(Input.GetAxis("Horizontal") speed Time.deltaTime,0,0)) if(Input.GetAxis("Horizontal") lt 0) if(collided with ! null) if(collided with.tag "Left") collided with null return transform.Translate(Vector3(Input.GetAxis("Horizontal") speed Time.deltaTime,0,0))
0
How to change TPS camera angle in Unity I'm very new to Unity and this may simply be a failure of google fu but I hope someone here can help me out. I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts. I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code. using System.Collections using System.Collections.Generic using UnityEngine public class CameraFollowPlayer MonoBehaviour GameObject target Start is called before the first frame update void Start() target transform.parent.gameObject Update is called once per frame void Update() transform.LookAt(target.transform.position) The problem with this is the angle this leaves the camera pointing at in game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the LookAt instruction to result in a shallower X axis rotation of the camera?
0
Unity Lighting Problems I've got a problem with the settings of lighting in my unity scene. The objects have got "dark sides" and it doesn't look natural. You can see the screenshots and my light settings here The screenshot that shows the problem
0
How do you pass arguments with UnityEvents? I was inspired by a great talk at Unite by Ryan Hipple. https youtu.be raQ3iHhE Kk?t 28m His examples didn t cover passing arguments with UnityEvents Do I need to extend UnityEvent, GameEvent and GameEventListener from a generic base class for this to work properly? If so do I need to make a new set of classes for each Type and combination of Types that I want to pass? Game Event Scriptable Object CreateAssetMenu public class GameEvent ScriptableObject lt summary gt The list of listeners that this event will notify if it is raised. lt summary gt private readonly List lt GameEventListener gt eventListeners new List lt GameEventListener gt () public void Raise() for(int i eventListeners.Count 1 i gt 0 i ) eventListeners i .OnEventRaised() public void RegisterListener(GameEventListener listener) if (!eventListeners.Contains(listener)) eventListeners.Add(listener) public void UnregisterListener(GameEventListener listener) if (eventListeners.Contains(listener)) eventListeners.Remove(listener) Listener Class public class GameEventListener MonoBehaviour Tooltip("Event to register with.") public GameEvent Event Tooltip("Response to invoke when Event is raised.") public UnityEvent Response private void OnEnable() Event.RegisterListener(this) private void OnDisable() Event.UnregisterListener(this) public void OnEventRaised() Response.Invoke()
0
Why does my player walk animation take so long to begin? I'm new to Unity and after doing some tutorials and reading documentation from Unity, I've started a test project. The game is a 2.5D platformer and I wrote the PlayerController it looks like this using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float turnSmoothing 15f public float speedDampTime 0.1f private Animator anim private Rigidbody rb Use this for initialization void Start () anim GetComponent lt Animator gt () anim.SetLayerWeight(1, 1f) rb GetComponent lt Rigidbody gt () Update is called once per frame void Update () void FixedUpdate() float h Input.GetAxis("Horizontal") MovementManagement(h) void MovementManagement (float horizontal) if (horizontal ! 0.0f) anim.SetBool("Move", true) anim.SetFloat("Speed", 5.5f, speedDampTime, Time.deltaTime) Rotating(horizontal) else anim.SetFloat("Speed", 0.0f) anim.SetBool("Move", false) void Rotating (float horizontal) Vector3 targetDirection new Vector3(horizontal, 0.0f, 0.0f) Quaternion targetRotation Quaternion.LookRotation(targetDirection, Vector3.up) Quaternion newRotation Quaternion.Lerp(rb.rotation, targetRotation, turnSmoothing Time.deltaTime) rb.MoveRotation(newRotation) My AnimatorController has a BlendTree called Locomotion and looks like this When I run the game and use the keyboard or the controller the player starts walking, but it takes a long time (I can see the Speed parameter from the blend Tree that has to reach "5" to start walking) I think I'm not understanding something but I don't know what it is.
0
I have a problem rotating a 2D game object after collision I'm developing a simple flip game where a cube flips and the bar a it collides with should start rotating after collision. Most snips involve destroying an object, but that's not my case. Here is my code using UnityEngine public class CheckI MonoBehaviour float x public Rigidbody2D rb2d void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "bar") x Time.deltaTime 10 transform.rotation Quaternion.Euler(0, 0, x) How do I start rotation after collision?
0
Unity Anima2D IK Limb for leg not working I'm having an issue getting an IK limb to work using Anima2D in Unity. If I place a limb IK for the neck joint, the head moves as expected, however trying to place one for the leg seems to have no effect. A CCD IK seems to work, but only moving one bone of the leg, whereas I need both bones to move, like a real limb with a knee joint. Is there anything obvious I'm doing wrong? Thanks!
0
Predicted trajectory becomes less accurate in a side on collision In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball. If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line. However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate. Why is this and how can I fix it? This is the prediction code I use if (Input.GetMouseButton(0) amp amp cueBall) Vector2 mousePos cam.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.CircleCast(cueBall.position, radius, direction, Mathf.Infinity) if (hit) lineMain.Draw(cueBall.position, hit.point) ghostBall.SetPosition(hit.point (direction radius)) lineTarget.Draw(hit.point, hit.point hit.normal) This is the predicted trajectory.
0
how to prevent stretched vertical shadow in blob shadow which projected by Projector of Unity I feel it's a ridiculous because projector's rotation of X is 90. the projector is a orthographic. how can i prevent that long stretch shadow in vertical side of a platform?
0
Why is ScreenToWorldPoint always giving same coordinates with mouse position? Whenever I use ScreenToWorldPoint(Input.mousePosition) and display the output in console this always gives me the same coordinates. MyCode Vector3 screenToWorld void Update() screenToWorld Camera.main.ScreenToWorldPoint(Input.mousePosition) Debug.Log(screenToWorld)
0
Change value in arrays in array The title might be confusing and I don't think this short explanation is 100 accurate, but I will try my best to show the problem. So I have this hierarchy And I want to change quot measureOfTime quot value in all subWave in wave i , because I had no clue how to do this in a short way (at least I bet there is a shorter way) and I made this using UnityEngine public class EnemySpawner MonoBehaviour Header( quot Set this value here to set time to 1 wave quot ) public float timeUntilWave Header( quot Measure Time basically 0 quot ) public Wave waves public float waveTime public bool roundStarted public int wave private void Start() wave 1 roundStarted false private void Update() if (timeUntilWave gt 0) timeUntilWave timeUntilWave 1 Time.deltaTime else if (timeUntilWave lt 0) roundStarted true wave if (roundStarted true) waveTime waveTime 1 Time.deltaTime int subwaveLenght waves wave .subWave.Length int count 0 while (count lt subwaveLenght) waves wave .subWave count .measureOfTime waves wave .subWave count .measureOfTime 1 Time.deltaTime count And in lines 33 and 37 I see an error quot IndexOutOfRangeException Index was outside the bounds of the array. quot And here are 2 questions Why those errors appear here? Is there an easier way to raise the value in arrays in an array? I hope it's not too confusing, and thanks for your help!
0
How can I prevent pixel artifacts on programatically generated textures? In the game I'm developing, rooms can be of various sizes, which means I need to vary the size of the floor texture appropriately. The way I've solved this problem is to generate a Texture2D programatically, and set each pixel to be transparent (or not) as appropriate appropriately. I get something like this Where, if you look at the top left, you'll clearly see the pixel artifacts from the floor texture against the dark blue background. When I run into this with static textures, the fix is simple. Set the Texture's wrapmode to clamp instead of repeat. But when I try to do that programatically... (and change nothing else!) I get this I'm not quite sure what's happening, or why setting the wrapMode changes the results so markedly. Anyway I can avoid the pixel artifacts? I suppose it's possible to add an extra border around the generated texture (so that all edges can be transparent), but that doesn't seem a particularly clean solution. Code is here void DebugFloorTextureMerge() sizeVector makes up the rectangle circumscribing the room's parallelagram Vector2 sizeVector new Vector2(roomBounds.topRight.x roomBounds.bottomLeft.x, roomBounds.topLeft.y roomBounds.bottomLeft.y) get the texture of the filled sprite Texture2D patternTexture (Texture2D) floorTexture.image make a new texture of the size of the room. Texture2D fillTexture new Texture2D( (int) sizeVector.x, (int) sizeVector.y, TextureFormat.ARGB32, false) COMMENTING THIS LINE OUT MAKES THE TEXTURE WORK WITH ARTIFACTS fillTexture.wrapMode TextureWrapMode.Clamp LEAVING IT IN MAKES THE FOLLOWING CODE WORTHLESS int patternX 0, patternY 0 Vector2 pointVector Color transparent new Color(0,0,0,0) for(int x 0 x lt sizeVector.x x ) for(int y 0 y lt sizeVector.y y ) pointVector new Vector2(x,y) if(roomBounds.Contains(pointVector)) get the next pixel fillTexture.SetPixel(x,y, patternTexture.GetPixel(patternX, patternY)) else pixel was not in the room, so set it to transparent. fillTexture.SetPixel(x,y, transparent) resultx x resulty y increment the pattern counter and reset if necessary. if you only increment this when Contains is true, you'll warp the texture patternY if(patternY gt floorTexture.fillSize.y) patternY 0 increment the pattern counter and reset if necessary. also reset y, so the pattern will line up properly. patternY 0 patternX if(patternX gt floorTexture.fillSize.x) patternX 0 set the PixelChanges. fillTexture.Apply()