_id
int64
0
49
text
stringlengths
71
4.19k
0
Should a beta version of an engine be used to start a new project? Is it advisable to use a beta version of unity(2019.3b) to make an actual complete project? What are the disadvantages?
0
Building meshes conforming to terrain deformation I have an uneven terrain on which the player is supposed to build buildings. For most structures I can just fudge the foundations, have them extend through the terrain. For roads, pipes, tracks and such I do have however the problem how to make them line up. What techniques can I best use to make the meshes of adjacent pieces line up, making it conform to the terrain?
0
Unity finding force vector to separate colliders in OnTriggerStay events In Unity, I have Trigger Colliders, and catch the OnTriggerStay(Collider other) events. Once two Colliders are touching, how do I get the Force vector to make them want to separate again? In the example below, I have a Sphere and a Box Collider touching. The OnTriggerStay is being called for the Sphere. I cannot use the center positions of the transforms to get a direction, as that would not give me a very good force vector And I do not think I can use the Collider.ClosestPointOnBounds to figure out the Box touch position, because the point I look from (center of Sphere), could be inside the Box Collider itself, which I understand will just return me back the center of the Sphere again. I would not be able to resolve any force vector from that.
0
Unity Raycast not detecting layers I am having problems with layers detection using raycasts. Context I created a grid to use in a pathfinding algorithm on a 2D plane. I want to implement now different weights according to the layer each node of the grid is in e.g. a node in a normal terrain will have a "terrainPenalty" of 1 and more difficult terrains 2 or more. In order to detect the terrain type on the 2D plane, I am shooting a raycast on the node position for each node previously considered "walkable". The problem comes up now, because I observed that the paths created are neglecting such values, this is the slice of code which is giving me problems if (walkable) Ray ray new Ray(worldPoint Vector3.back 10, Vector3.forward) PROBLEM HERE (NOT DETECTING PENALTIES) RaycastHit hit walkableMask walkableMask if (Physics.Raycast(ray, out hit, 100, walkableMask)) walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty ) At first I thought that the problem was how the layers were called, because I created a LayerMask combining 2 layers using the bitwise OR operator, but then I tried to play around with all the layers (hence why there is walkableMask walkableMask now). The result was always a false output for Physics.Raycast(ray, out hit, 100, walkableMask). I thought that maybe I was getting the wrong coordinates for the ray, but I created some gizmos to actually check that the ray was piercing perpendicularly my plane and it did, as well as trying to change layers to see if anything worked, but the output is always false. What am I getting wrong? Here is the rest of the function, if needed I can upload the whole script as well void CreateGrid() grid new Node1 gridSizeX, gridSizeY Vector3 worldBottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.up gridWorldSize.y 2 for (int x 0 x lt gridSizeX x ) for (int y 0 y lt gridSizeY y ) Vector3 worldPoint worldBottomLeft Vector3.right (x nodeDiameter nodeRadius) Vector3.up (y nodeDiameter nodeRadius) bool walkable !(Physics2D.OverlapCircle(new Vector2(worldPoint.x, worldPoint.y), nodeRadius, unwalkableMask)) bool walkable !(Physics.CheckSphere(worldPoint, nodeRadius)) int terrainPenalty 0 if (walkable) Ray ray new Ray(worldPoint Vector3.back 10, Vector3.forward) PROBLEM HERE (NOT DETECTING PENALTIES) RaycastHit hit walkableMask walkableMask if (Physics.Raycast(ray, out hit, 100, walkableMask)) walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty ) grid x, y new Node1(walkable, worldPoint, x, y, terrainPenalty) EDIT Here is how I create the layerMask foreach (TerrainType region in walkableRegions) walkableMask.value region.terrainMask.value is the bitwise OR operation, I could have simplified by writing " " walkableRegionsDictionary.Add((int)Mathf.Log(region.terrainMask.value, 2), region.terrainPenalty) Where TerrainType is the following class System.Serializable public class TerrainType public LayerMask terrainMask public int terrainPenalty I basically create an array of TerrainType objects that will store their layerMask and penalty and then upon positive output from the raycast I access the dictionary to retrieve the terrain penalty. For the terrain and obstacles I am using a 2D BoxCollider and 2D PolygonCollider respectively, they do not interact with any other layer. Thanks for any possible hints, I don't know what else to try .
0
Issues using NetworkServer.Spawn with Unity and Mirror Networking I am using Mirror to handle the networking aspect When I spawn an object on the network, I Instantiate it on the server and then use NetworkServer.Spawn to notify all clients to spawn the object. However, when this object is eventually spawned on the client side, it seems to be spawned at the wrong position for a few seconds and then corrected itself and move to the correct position as is reflected by the server. Is there something I am not doing? Is this normal? Also I noticed if I changed the Network Sync Mode to 0, then it will only spawn in the wrong spot for a split second. using System.Collections using System.Collections.Generic using UnityEngine using Mirror public class EnemySpawner NetworkBehaviour public uint theId public int maxNumEnemies public int spawnDelay public GameObject enemyToSpawn float curSpawnTime BoxCollider2D boxColl Start is called before the first frame update public override void OnStartServer() curSpawnTime spawnDelay boxColl GetComponent lt BoxCollider2D gt () void Start() if (!isServer) return theId netId Update is called once per frame void Update() if (!isServer) return if (transform.childCount lt maxNumEnemies amp amp curSpawnTime lt 0.0f) Vector2 spawnPoint new Vector2(Random.Range(boxColl.bounds.min.x, boxColl.bounds.max.x),Random.Range(boxColl.bounds.min.y, boxColl.bounds.max.y)) curSpawnTime spawnDelay SpawnEnemies(spawnPoint,netId) else curSpawnTime Time.deltaTime Server void SpawnEnemies(Vector2 spawnPoint, uint theId) GameObject gobj Instantiate(enemyToSpawn, new Vector2(60.7f,1.3f), Quaternion.identity) gobj.GetComponent lt EnemyController gt ().parentNetId netId NetworkServer.Spawn(gobj) The way I've organized things, in the hierarchy I have Enemies Area1 Spider(Clone) Spider(Clone) Area1 has the EnemySpawner script. The spider is registered a spawnable prefab. Both Area1 and the Spider have a NetworkIdentity with no boxes checked. Additionally, the Spider has a NetworkTransform and NetworkAnimator.
0
Hide "No custom tool available" window I have this annoying window in the bottom right of the scene view. From the manual, it seems like I opened it by clicking on the wrench amp scribe button next to the movement buttons. How do I make it do away now? Restarting doesn't make a difference, neither does creating a brand new project. The documentation say this appears it I've clicked on the tools icon and there aren't any custom tools (which I'm sure I have done). Surely is should vanish after a while though.
0
Unity3d or WebGL Where should I go? I am interested in making a simple 3D game this summer, and I'd prefer if it were playable in a browser. My choices I am considering are Unity and WebGL. Currently I have no experience in either. But I have taken an introduction course to OpenGL. As well I will later be taking a course that will use Unity. I have some C experience, but no web background. The factors I'm considering are ease to learn and the penetration each has. I know Unity games can be uploaded to Kongregate, which seems like a pretty big deal if I made a game that would be somewhat successful. But of course that may not be the case at all. Which way should I lean? Personally I think learning WebGL would be the easiest transition, but I am not sure
0
How to make the character move along the axis using touch? I have the following code it works, but I don't know how it works. This is the code I found void Update() if UNITY ANDROID if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Moved ) Vector2 touchDeltaPosition Input.GetTouch(0).deltaPosition float offset touchDeltaPosition.x 40f 18 Mathf.Deg2Rad transform.position new Vector3(0f, 0f, offset) transform.position new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, 7.1f, 7.1f)) endif I need to move the player along the axis by touch, for example, like in the game Cube Surfer! What I want to get (I used android emulator) The code I wrote works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big. My code if (Input.touchCount gt 0) var t Input.GetTouch(0) var delta t.deltaPosition if (delta ! Vector2.zero) var offset transform.position offset.x delta.x Sensitivity Time.deltaTime offset.x Mathf.Clamp(offset.x, 4f, 4f) transform.position offset How to fix it? ScreenToWorldPoint this does not fit because the player moves along a spline. Thank for help
0
Subsurface Scattering Transmittance I have a question related to SSS and especially transmittance. I've looked at several papers about that topic, most of them from Jorge Jimenez, which are very interesting and, I admit, a bit hard for me. Here is one of the papers http www.iryoku.com translucency I have some difficulties to understand the way it works and the way it calculates the distance the light traveled through the object. I think that I understand the very big lines but I am also a bit confused as I am trying to integrate this into the Unity engine and I have some difficulties to match Unity engine available values such as the shadows maps, the shadows coords, etc... to make them fit the way they are used in the paper. So here it is, I am a bit lost in the "in between" and I hope that somebody might be able to help me. Thanks a lot. EDIT added the shader code from referenced paper float distance(float3 posW, float3 normalW, int i) Shrink the position to avoid artifacts on the silhouette posW posW 0.005 normalW Transform to light space float4 posL mul(float4(posW, 1.0), lights i .viewproj) Fetch depth from the shadow map (Depth from shadow maps is expected to be linear) float d1 shwmaps i .Sample(sampler, posL.xy posL.w) float d2 posL.z Calculate the difference return abs(d1 d2) This function can be precomputed for efficiency float3 T(float s) return float3(0.233, 0.455, 0.649) exp( s s 0.0064) float3(0.1, 0.336, 0.344) exp( s s 0.0484) float3(0.118, 0.198, 0.0) exp( s s 0.187) float3(0.113, 0.007, 0.007) exp( s s 0.567) float3(0.358, 0.004, 0.0) exp( s s 1.99) float3(0.078, 0.0, 0.0) exp( s s 7.41) The following is done for each light 'i'. Calculate the distance traveled by the light inside of the object ('strength' modulates the strength of the effect 'normalW' is the vertex normal) float s distance(posW, normalW, i) strength Estimate the irradiance on the back ('lightW' is the regular light vector) float irradiance max(0.3 dot( normalW, lightW), 0.0) Calculate transmitted light ('attenuation' and 'spot' are the usual spot light factors, as in regular reflected light) float3 transmittance T(s) lights i .color attenuation spot albedo.rgb irradiance Add the contribution of this light color transmittance reflectance
0
How to get light level (brightness) of a particular location? I'm making a 2D top down survival game similar to Rimworld, I'm trying to emulate a day night system. Many features depend on whether any tile is light (or dark) enough, based on time of day or other light sources such as torches, so I'm wondering if there's an easy way to detect how much light there is on a certain tile without making a whole system that tracks light on a per tile level (or maybe the latter option is better)? I am using Unity 2020.3.6f1 and the URP, which means I'm going to be using the 'new' 2D lights. EXAMPLE When it's nighttime, I'm going to disable the global light (sun) so those tiles will be pitch black. When it's daytime, the global light will have an intensity of 1 so that tile will have 100 brightness (look normal). When it's nighttime, but there's a torch, the tile where the torch is sitting on will have 100 brightness, and that will slowly fade to 0 over a span of 5 tiles. Making a system that updates every single tile in the game with information about the light level seems pretty expensive. Is there a way we can observe a block quot graphically quot , or in other words, literally look at the pixel on the screen, and determine it's alpha value to check for light level? Any suggestion is super welcome. EDIT Every tile does not need to know its brightness every frame, but they do need to know it less often. Some examples are A plant checking every couple of frames to see if it can grow A character checking every couple of frames to see if he's in the dark (and if he is, he needs to start panicking) More importantly, I need my characters to make decisions based on light amount. For an example, if there is a job that needs to be done at a certain location, a character should first check the light level of that location before going to do it.
0
Using coroutines and texture array for talking animation? I was thinking of having random textures from a texture array being chosen every 0.5 seconds through a coroutine to imitate talking if something like talking true. Not sure how I could set this up and such so I appreciate any help!
0
Change Camera Contrast in VR Game Hello there Firends , I'm developing a Virtual Reality game in Unity. As in every VR game , i have 2 cameras for stereo rendering. I want to show the same object in each camera having different color contrast ratio gt The effect is similar to the one shown in this image the grid in the center here is the same in each side but each camera is seeing it differently.i.e. its grey in the left and black in right (you will notice the black grid if you look closely) here is another example (source wired.co.uk) How do i get this effect ? Any suggestions ?
0
Adding more effects to a Unity3d mixer I recently started exploring the wonderfull world of audio in unity. I noticed that you can add a bunch of effect modules to a mixer. Now I'm wondering if you can add your own custom effects( for example export a plugin from a audio program or something) and add them to the list. I cant seem to find anything related to the question.
0
Restrict the rotation of the camera using button I've been trying to limit the Y axis of the camera rotation but I'm out of depth until now. I'd looked up many tutorials and I found the clamping method, but I seem can't get it to work on my code, and all the tutorials I found is using them in Update(), while I'm using a button to rotate the camera. Here's the code public void RotateLeft() cameraY Mathf.Clamp(cameraY, minAngle, maxAngle) if(cameraY gt minAngle) Camera.main.transform.Rotate(0, cameraY,0) public void RotateRight() cameraY Mathf.Clamp(cameraY, minAngle, maxAngle) if(cameraY lt maxAngle) Camera.main.transform.Rotate(0,cameraY,0) Does clamping works outside an Update()? What am I missing? Thank you in advance.
0
How can I get the borderSize s of a plane? public Texture2D gridImage public GameObject floor private int borderSize private void Start() GenerateGrid() void GenerateGrid() Color gridColor Color.cyan Color borderColor Color.black Collider floorCollider floor.GetComponent lt Collider gt () MeshRenderer floorRenderer floor.GetComponent lt MeshRenderer gt () floorRenderer.material.mainTexture gridImage floorRenderer.material.mainTextureScale new Vector2(floorCollider.bounds.size.x, floorCollider.bounds.size.z) floorRenderer.material.mainTextureOffset new Vector2(.5f, .5f) Vector3 foorSize new Vector3(floorCollider.bounds.size.x, floorCollider.bounds.size.z) for (int x 0 x lt gridImage.width x ) for (int y 0 y lt gridImage.height y ) if (x lt borderSize x gt gridImage.width borderSize y lt borderSize y gt gridImage.height borderSize) gridImage.SetPixel(x, y, new Color(borderColor.r, borderColor.g, borderColor.b, 50)) else gridImage.SetPixel(x, y, new Color(gridColor.r, gridColor.g, gridColor.b, 50)) gridImage.Apply() In the end I want to create something like this on a 3D Plane UI
0
What happens to deleted or added assets in your app when updating to a new version in the Google Play Store and iOS App Store? So let's say I used Unity and built an app and uploaded it to the android and iOS app store, it is 100 MB and lots of people downloaded it. So now I want to update it to the newer version, however along the way I decided a lot of features were unnecessary so I remove about 50 MB worth of assets and the new build is 50 MB so I uploaded it to the respective app stores. Will the people who already had my 100 MB app and now update to the new 50 MB version continue to have 100 MB of storage space taken up, even though the new one is half the size or will their app size be reduced to 5 MB according to the new build? Essentially, how does app store updating work? Is the whole old app deleted and new one downloaded? Are matching files and assets retained and only differences in files and assets deleted or updated? Or are new assets and files just piled on top? Additionally, for larger games, where the whole game is too big to be allowed on the app store, and where the player has to download more stuff once they have downloaded the game, how does it work? Is the additional, no longer needed content left on user's device kept there? Is it automatically removed?
0
GPU (render time) increase if screen size increase i create a simple 2d scene in unity 2017.3.1f1 I changed the size (height and width) in the Game View and proflie to see how it affects the rendering.. (below photo) I saw that the rendering time increases by increasing size, and now if this happens when playing the game on a different resolution android phone, each The higher the resolution of the phone, the more likely it is to get gpu bound !??? And i do not understand Cpu graph in the two situations in above photo(lower GPU gt higher CPU !!!) I tested my game on the quot huawei mate 10 lite quot (android device) with a resolution of 1080 x 2160 and it looks like there is a lot of rendering time.(a simple scene with only 5 sprite renderer) (unity dosen't show GPU profiling when game run on android device and we can't check these...) I did all the optimizations I heard, like DynamicBatching, Sprite Atlas , Quality Setting , sprite Texture Comprestion Override for Android.. What can be done to ensure that rendering time does not exceed a specified limit on different phones ??
0
Unity Sprite disappears completely when just a part of it is outside the camera's FOV I'm making a game in Unity, and when the player walks past a sprite, the sprite disappears, and when the player walks back toward it, it reappears. You can see a video of the problem here https www.youtube.com watch?v jgLN3m94tBo I've also included my camera script below if anyone wants to check that out. Any help on this matter would be more than appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class Camera MonoBehaviour private Transform target private float minX 7.99f private float minY 19.09f public float maxX, maxY void Start() target GameObject.Find("Player").transform void LateUpdate() transform.position new Vector3(Mathf.Clamp(target.position.x, minX, maxX), Mathf.Clamp(target.position.y, minY, maxY), transform.position.z) Here's a screenshot of my camera's settings
0
Unity gameobject design approach for item drops In a game like Minecraft, the player could have any of several hundred types of items in their inventory. Players can drop those items into the world, but obviously how they're rendered in the world differs from how they're rendered in the inventory. I'm trying to understand how to design for this scenario using Unity's GameObject concept. Individually, it seems like the expectation is that I would have one GameObject (with at least a SpriteRenderer) for every unique item that can appear in world. I would have one GameObject (with at least an Image component) for every unique item that can appear in inventories. With so many, I also need to come up with some sort of directory so that I can associate bulk prefab objects for use in game. Is this accurate? I feel like that's a lot of overhead. Would I be able to create one GameObject with both a SpriteRenderer and an Image and maybe toggle between then based on whether its in world or an inventory? I had also considered using one generic GameObject and replacing the sprite image based on the item needed, but that feels like it's misusing what GameObjects are meant for. It also likely subverts the benefit of pooling them, etc. Is there another approach I'm missing?
0
Unity Is type casting every frame too expensive? I have a state machine that controls my enemy AI. Each AI has a target which may be a Player, an obstacle, a shell, or even a Vector2 position. I'm trying to abstract my "target" member, and my first thought was to use GameObject, then downcast to whichever type I need for different enemies. Examples below class StateController MonoBehavior GameObject target FireAction action Update() action.Fire(this) class FireAction ScriptableObject public abstract void Fire(StateController c) Examples of different fire scripts class FireAtPlayer FireAction public override void Fire(StateController c) Player p c.target as Player use properties of Player object class FireAtPoint FireAction public override void Fire(StateController c) GameObject t c.target as Player use properties of GameObject object As you can see, my Fire methods would cast the target object at every call to Update. Will this negatively affect my game's performance? Note that I know for a fact what type of object the target is, so I'm not guessing when I'm casting. Thank you in advance of your help!
0
Is it possible to load asset bundle dependencies manually in Unity 5.0? Is it possible to tell Unity to not load asset bundle dependencies automatically so they can be loaded manually. If so, how can this be done?
0
Unity3d Position a gameobject such that its forms a right angled triangle with other two gameobjects How do I position C gameObject such that it forms a right angled triangle with A and B. I tried to use (B.transform.position.x,A.transform.position.z) but it still gives me something which is close to A (it takes it globally). I want the C to be along the local red axis of A and local green axis of B as seen in the picture. What do I do?
0
Day and Night mode according to user's real local time How do I make it so the texture of my plane is a black sky when it's night according to player's local time (say from 10 PM to 5 AM it's going to be black, and from 6 AM to 9 AM it's going to be a blue sky)? Blue sky texture name is "bluesky" Black sky texture name is "blacksky" Thanks.
0
When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0))
0
Handmade Terrain vs. Terrain Engine in Unity? I'm planning a game right now, to be made in Unity, and I'm trying to decide how I'll approach the basic level construction. Essentially, my game takes place on an island in an infinite ocean, very similar to Wuhu Island My question concerns all the stuff heightmaps can't handle. To use Wuhu Island as an example, note the lighthouse cliff, and the nearby similarly jutting out cliff. The volcano itself is also empty, and there are some tunnels through it on the other side. I was thinking I would just model the entire island myself in Cinema 4D, but as I read more about the terrain system, it seems Unity has special optimized rendering systems in place for terrain objects. Would I be shooting myself in the foot performance wise if I just built my island entirely by hand? This will be for mobile, so the little stuff might well count. Am I even approaching this question correctly if not, how would you best go about creating (something very close to) Wuhu Island as a level in Unity? Is there any reason for me to not do it as one mesh? I have effectively zero experience with 3D game dev only rendered 3D video stills for other applications, so this is a learning process.
0
How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?
0
Is it possible to import UV maps in Unity3D without manually importing the associated texture? When i import an object from Maya with a defined UV map i have to manually import the texture (image) and assign it to the material. Is there a way to keep the materials texture reference from Maya when importing into Unity?
0
Tile Palette problem in Unity I am working on isometric tilemap in Unity 2019.4.8f1. In the Tile Palette panel, the selection is always 1 block away. Please see this screenshot In the screenshot, apparently I selected an empty tile, but in fact I am select the green tile with flowers. How come? Every selection is one tile away. The same issue happens in the Tilemap selection mode too. I have to select the adjacent tile in order to select the tile I want. How do I fix it? It's quite annoying. UPDATE I have added the settings of Grid, Tilemap as well as the import settings of the tile sprite sheet below. UPDATE 2 Changed the Pivot in Sprite Editor to Bottom Center Recreated the Tile Palette, and it looks like hovering 0.5 unit up.
0
How can I find an animation's final compression size in Unity? I've been looking at animation compression, and the only way I can seem to find it's final size is to create a Build and check it in the Profiler. There must be an easier way?
0
Cannot overlay text? I'm trying to make text have a fixed position in world space and be overlayed in screen space at the same time. I have text in canvas with "Screen Space Overlay" which covers my text located in canvas (world space). What should I do? Is this a dead end? Please comment if you didn't understand (I know it's hard to get)
0
OnTriggerExit2D called multiple times when two triggers touch I have two GameObjects tagged "Point", each with a Collider 2D set to Is Trigger. I have another GameObject, "pencil", which also has a Collider2D set to Is Trigger I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point. My problem is that when the pencil hits a point, it calls OnTriggerExit2D multiple times. How can I only detect first contact with the point? Pencil script private void OnTriggerExit2D(Collider2D collision) if (!collision.isTrigger) if (collision.gameObject.tag "Point") writing !writing
0
Getting user id from one scene then to the next scene I'm new to multiplayer and photon so pardon me if this question is somewhat frequent. I have successfully set up my project to start from a main menu waiting room actual gameplay scene. However I couldn't search my way through getting a sort of user id from waiting room(ie order of user joined to waiting room) then use it in the gameplay scene to manipulate sort by score by hp etc. Perhaps I got the while concept of having to identify unique players via such variable? I'm not quite sure. I just got my foot in the multiplayer development realm, so please go easy on me. Edit Sorry for my initial question being quite vague. Basically, I'm trying to replicate this with Photon. I've got various things set up but was stuck at where designating individual players to individual player info panels as if captured(Get WHAT to connect to those UI elements I've got set up). It'd be simple enough even for me if this was a singleplayer, but since it's not I'm also refactoring a lot on the way as well. Thanks to both of the answers given so far I'm looking into Photon UtilityScripts(To a novice to anything simply directing where to look helps a ton, so thanks again), but since I'm not quite there yet I'll update my progress.
0
Export "Lite" and "Full" versions with different package names for Google Play Console On the Google Play Console, you can't have two games with the same package name. Is there a way to have two of the same game with different package names, exported from the same Unity project? For example, a quot lite version quot with ads and a quot full version quot without ads.
0
Unity Animation Controller and walking diagonally keeps switching between the two diagonals? Using Unity 2019.4.1f1 Personal. I have the above Animation Controller. When only walking in one direction at a time and when you stop you stay facing that direction, this works as planned. All of the transitions do not have an exit time and have a fixed duration of 0. I don't know what info to give as this is the first time I've used animation. Let me know and I'll add relevant details. Here's my update function that updates the variables in the animator void Update() float h Input.GetAxisRaw( quot Horizontal quot ) float v Input.GetAxisRaw( quot Vertical quot ) animator.SetFloat( quot Horizontal quot , h) animator.SetFloat( quot Vertical quot , v) if (Mathf.Abs(v) lt Mathf.Abs(h)) flips the renderer to reuse other handed image spriteRenderer.flipX h gt 0 no actual movement until I figure this out What I'm experiencing that I want to fix is when running diagonally It seems that when walking diagonally then the animator variables for Horizontal and Vertical are both either 1 or 1 and this causes the alternating of the sprites. What I'd like to happen is that the state machine would deterministically pick either N S sprites or E W sprites when moving diagonally. Turning on quot Can Transition To Self quot seems to properly pick a direction and stick to it but it fails to animate when only moving in a single direction. It looks like it's constantly transitioning to itself which starts over the cycle so I've left that unchecked on all transitions. I'm not sure what the best way to fix this is. Most attempts I've tried so far complicate the state machine to the point it's unmaintainable. I also couldn't find anything about introducing priorities in a way that fixed the jitter. What's the idiomatic Unity way to achieve clean diagonal movement in 2D?
0
How do i draw a ray in unity So i am trying to scrap together something for vr in which the locomotion is about the player holding the direction where he wants to go to(basically planning what he is going to do)while holding down the button a ray is beeing drawn and when the player lets go the character moves until he reaches the end of the ray i tried looking up something but couldnt find anything regarding something like this
0
How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction? Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead. It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre existing momentum will carry it wildly off course, and not straight toward PointB. It could turn exactly 180 around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions. It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course correcting so that it is now moving toward PointB. I'm trying to figure out how to calculate that quot specific direction quot that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed. Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc. Can anyone help me out?
0
How to use Facebook Web Hosting for my Unity Game for both WebGL and GameRoom As can be seen from the Facebook's official Docs It says that To have both a Gameroom and a Facebook Web Game, you should leave your Facebook Web Games URL (https) unchanged. For example, https friendsmashsample.herokuapp.com and also Otherwise, if you only have a Gameroom title, you should enter https localhost as shown here I wanted to know if there is a way to get both of them working instead of hosting WebGL game on my server and putting it's URL? I have even tried to enable the Simple Web Hosting but the toggle just reverts Back to off upon saving.
0
Is it possible to apply a texture to a 2D sprite in unity 2 d? I want to take an (animated) 2 d sprite and apply a texture to it. Basically, I want every non transparent pixel to be covered by the texture (color is disregarded). I understand I can probably accomplish this using masks but I am worried that may not be the most performant solution. I know you can put textures onto 3 d models, so I was wondering if there was a similar process for 2d sprites. Below I have a graphic demonstrating what I want. What I have tried so far I see there is an option to add a material to a sprite, so I tried creating various materials. 1. Default material When I tried applying this material to my sprite, the sprite disappeared entirely. I suspect because this default material type only works on 3D objects 2. Sprite Material I figured sprites probably expect sprite materials, so I tried creating one. However, there does not appear to be anywhere to upload an image to use as a texture. This appears to only be useful for adding tints to sprites.
0
When is the CheckResources() function called? This question is asked in the context of image effect shader implementations in Unity. Looking through the scripts for image effects in the standard assets package, I notice that initialization is generally done in the CheckResource() function. The following is a snippet of code from the BloomAndFlares image effect. public override bool CheckResources() CheckSupport(false) screenBlend CheckShaderAndCreateMaterial(screenBlendShader, screenBlend) lensFlareMaterial CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial) vignetteMaterial CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial) separableBlurMaterial CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial) addBrightStuffBlendOneOneMaterial CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial) hollywoodFlaresMaterial CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial) brightPassFilterMaterial CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial) if (!isSupported) ReportAutoDisable() return isSupported I am probably wrong in assuming that this is essentially the Start() or Awake() functions for PoseEffectsBase, but I decided to try implementing something simillar. public override bool CheckResources() saturationPassMat CheckShaderAndCreateMaterial(saturationPassFilter, saturationPassMat) if (!isSupported) ReportAutoDisable() return isSupported Unlike the standard asset scripts, CheckResources() does not seem to be called consistently for me. Unity console throws UnassignedReferenceExceptions every frame, for the object saturationPassMat. When is the CheckResources() function called? Should it be used for initialization just like Start()?
0
How to change Texture2D type to Sprite during runtime (Unity) How can we convert the Texture2D type to "Sprite" using the script (not in Editor)? It seems that the Texture2D retrieved from file is by default Normal Map. I need to convert the TextureType to "Sprite". Texture2D texture LoadPNG("D download.jpg") testPlaneRenderer.material.SetTexture(" source",texture) LoadPNG method code public static Texture2D LoadPNG(string filePath) Texture2D tex null byte fileData if (File.Exists(filePath)) fileData File.ReadAllBytes(filePath) tex new Texture2D(2, 2) tex.LoadImage(fileData) ..this will auto resize the texture dimensions. Debug.Log("File Exists!") else Debug.LogError("File not exists!") return tex It seems that this texture is set as "Default" or "Normal" Type when imported from file and then assigned to Material dynamically. As the particular shader I'm using, works best if the Texture Type is set to Sprite (I tested it by manually placing the texture file in Project and then assigning the texture to Material). I need to change Type of Texture to Sprite before assigning it to the material. I've seen options like "AssetImporter" but it only works in Editor. The effect of the shader (which takes two texture types a) Inverted amp Blurred Texture b) GrayScale Texture And then returns a Sketch Effect to the object. I convert the original image to inverted amp blurred, grayscale texture using some image processing code (C , Unity working around with GetPixels and SetPixels)... Output with Defualt Texture Type Output with Sprite Texture Type
0
Unity ScriptableObject Conversation Dialogue and Reading I'm unsure as to how I would reference a scriptable object's variables within a struct from another class. I know I'd have to make a public Conversation, but I'm stuck understanding how I could access it's struct, and how I could access individual variables such as the Position, or line string array. Is this method even viable or should I look at creating a different way of accomplishing a dialogue conversation scriptable object? Thanks for any insights and help My current code System.Serializable CreateAssetMenu(fileName quot New Conversation quot , menuName quot Create Conversation quot , order 1) public class Conversation ScriptableObject System.Serializable public struct LineData public string line public string option public enum Position BottomLeft, BottomCentre, BottomRight, MiddleLeft, MiddleCentre, MiddleRight, TopLeft, TopCentre, TopRight public Position position public enum TextSpeed Normal, Slow, Fast, UltraFast public TextSpeed textSpeed public LineData Line
0
In Unity3D, try to load a png into a Texture2D in an Editor script and then run PackTextures, but they need Readable flag to be set I am trying to automatically create a texture atlas from a set of generated png files in an Editor script. The problem is that I can't seem to be able to load a png into a Texture3D without it being inaccessible by the PackTextures method. I have tried a few different ways to load the PNGs, such as Resources.LoadAssetAtPath(...), AssetDatabase.LoadAssetAtPath(...) and a few more. Since all of this is done in OnPostprocessAllAssets, I don't want to have to do any manual editing of the textures. I just want to be able to drop a PNG into a certain folder and get an updated atlas. Answers such as this seem to suggest manual editing. The actual error message is "Texture atlas needs textures to have Readable flag set!". So the question is, is it possible to do this kind of post processing in Unity3D? Is there any way to import a PNG into a Texture2D with the Readable flag set, without having to manually change it?
0
How should I handle animation state systems in derived classes? I'm trying to get some kind of state system for my game objects. I have a base Actor class that is derived by classes like Policeman, Informant or Brawler. Each of those classes describes different functionality, but I want as much of the functionality to be shared. On of those is animation system. Each class has their own states (for example Policeman has Walking, Shouting and Shooting, while Informant has Idle and Whispering). What is the best way of handling such states? Do I have the Actor class have something like enum ActorState state1, state2, state3, ... And just map each behaviour of appropriate actor (Policeman, Informant, etc) to ActorState, so that the rendering system of ActorState can take over? Or maybe is there some better solution that people use. Game is 2D, sprite based, and I'm using Unity3D system, with Actor being a component to GameObjects.
0
Unity LWRP Projection Shader I recently added the Lightweight Render Pipeline to my project as I'd like to start experimenting with Shadergraph to see if I can get a better basic understanding of shaders. Everything has gone pretty smoothly except the Shader used by my Projectors, the Projection Shader Standard asset no longer works (does not project the texture) and I have very little experience with Shaders. The main concern for me is that I cannot find anyone else who seems to be having this problem. I have tried reading through the older shader and recreating it in ShaderGraph but I'm out of my depth. So could anyone provide me with a simple projection shader or materials on where I could learn to write one, or just learn more about them projection specifically. thanks edit To clarify I was using the Projectors to project a simple square texture on to each tile that I could tint, to show selectable current target tiles. Old shader that no longer works under Lightweight Render Pipeline From DevGuy Unity Forums Upgrade NOTE replaced ' Projector' with 'unity Projector' Upgrade NOTE replaced ' ProjectorClip' with 'unity ProjectorClip' Upgrade NOTE replaced 'mul(UNITY MATRIX MVP, )' with 'UnityObjectToClipPos( )' Shader "Projector AdditiveTint" Properties Color ("Tint Color", Color) (1,1,1,1) Attenuation ("Falloff", Range(0.0, 1.0)) 1.0 ShadowTex ("Cookie", 2D) "gray" Subshader Tags "Queue" "Transparent" Pass ZWrite Off ColorMask RGB Blend SrcAlpha One Additive blending Offset 1, 1 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct v2f float4 uvShadow TEXCOORD0 float4 pos SV POSITION float4x4 unity Projector float4x4 unity ProjectorClip v2f vert (float4 vertex POSITION) v2f o o.pos UnityObjectToClipPos (vertex) o.uvShadow mul (unity Projector, vertex) return o sampler2D ShadowTex fixed4 Color float Attenuation fixed4 frag (v2f i) SV Target Apply alpha mask fixed4 texCookie tex2Dproj ( ShadowTex, UNITY PROJ COORD(i.uvShadow)) fixed4 outColor Color texCookie.a Attenuation float depth i.uvShadow.z 1 (near), 1 (far) return outColor clamp(1.0 abs(depth) Attenuation, 0.0, 1.0) ENDCG
0
Touch to continue (coroutine) in unity When the object gets destroyed in my game, I want a touch to continue function after a delay. This is what I tried. this is the SceneManager class which is attached to the Main Camera public bool ttc public void NextLevel() StartCoroutine(Delay()) IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") ttc true My Object class void OnDestroy() Camera.main.GetComponent lt SceneManager gt ().NextLevel() if (Camera.main.GetComponent lt SceneManager gt ().ttc true) if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") I also tried this IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") side note I will change the 'KeyCode.V' to a mouse button later
0
How I randomise a list of audio clips in Unity and remove it from the list once the clip is finished? I have 4 audio clips. When I play a press a certain button in Unity, the data is sent to MAX MSP and the audio is played. I created a list a signals (As shown below in the code). What I want is that, the signal list is randomised. The user presses a button to listen to the audio (which works fine). Once the clip is finished the user presses Next Trial button. Once the Next Trial is pressed. The previous clip is removed from the list. Once all the clips are finished. A message is displayed in the Debug.Log( quot All trials finished quot ). I have the following problems One of the audio clips is repeated again. It appears that the audio clips are not removed from the list. How do I write the audioclip index to a csv file? Code public class SignalToMax MonoBehaviour private static int localPort private string IP define in init public int port 8050 define in init quot connection quot things IPEndPoint remoteEndPoint UdpClient client experiment case public string experimentCase quot A quot string strMessage quot quot public List lt int gt signals public static int stimIndex void Start() NextTrial GameObject.FindGameObjectWithTag( quot NextTrial quot ).GetComponent() signals new List lt int gt 1, 2, 3, 4 define IP quot 127.0.0.1 quot port 8050 Senden remoteEndPoint new IPEndPoint(IPAddress.Parse(IP), port) client new UdpClient() NextTrial.onClick.AddListener(Advance Trial) void Advance Trial() int signalIndex Random.Range(0, signals.Count) int currentSignal signals signalIndex stimIndex currentSignal signals.RemoveAt(signalIndex) string text signalIndex.ToString() byte data5 Encoding.ASCII.GetBytes(text) client.Send(data5, data5.Length, remoteEndPoint) Debug.Log( quot lt color magenta gt Current source signal is lt color gt quot currentSignal) if (signals.Count gt 0) Debug.Log( quot lt color blue gt Signal count before removal was lt color gt quot signals.Count) Debug.Log( quot lt color yellow gt Source signal removed lt color gt quot ) else Debug.Log( quot lt color green gt All Trials finished lt color gt quot )
0
ScreenToWorldPoint and ViewportToWorldPoint I'm currently following tutorials on Youtube to learn howto use Unity. My code runs perfectly as per the tutorial, but i just have some questions regarding the code, with regards to screenToWorldPoint amp viewportToWorldPoint. The purpose of the code is for a 2D platformer, where the character's arms will rotate and face where the mouse cursor is. Code using System.Collections using System.Collections.Generic using UnityEngine public class ArmRotation MonoBehaviour public int rotationOffset 0 Update is called once per frame void Update () Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position Gets the difference between difference.Normalize() Normalizing the vector float rotateZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(0f, 0f, rotateZ rotationOffset) I've done some googling and am aware of the difference between screenToWorldPoint and viewportToWorldPoint as per the answer here https answers.unity.com questions 168156 screen vs viewport what is the difference.html Where Screen from 0,0 to Screen.width, Screen.height Viewport from 0,0 to 1,1 Questions Why do we have to calculate the difference between the position of the mouse cursor and the position of the character's arm instead of just setting the following . Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) I've tried setting it to the position of the mouse cursor instead of using the difference between the arm amp the cursor and while the code still works and the arm is still able to rotate, it is a little "off" from the direction of the cursor. E.g A little higher than where the cursor is. Why does using the difference solve this issue? Why do we call difference.Normalize() ? To my understanding, Normalize returns a vector between 0 amp 1.However, Mathf.Atan2 returns the angle in radians whose Tan is calculated by y x. As such, calling Normalize and returning a vector to a value between 0 amp 1 makes no difference because the value calculated will be the same between a un normalised and normalised vector since the proportions are the same? When i use ViewportToWorldPoint instead of ScreenToWorldPoint, i do not use Normalize because to my understanding, the Vector returned by ViewportToWorldPoint should already be within 0 amp 1, hance we do not have to normalise it. However, when i test the code out in play mode,the arm barely rotates. Why is this so? I would appreciate any help or pointers in the right directions. Thanks! EDIT I had a look at the manual and realise that Normalize() returns a vector with the same direction, but magnitude 1, but i'm still just as confused
0
AndroidManifest file was deleted by accident I deleted the AndroidManifest file of my project which was located in Assets Plugins Android , so I tried creating new project and copying the Assets and everything but it seems that something is missing ,it's perfectly working in the editor , but as apk there are few things aren't working, I can't figure out why, and there isn't even a Plugins folder in my new project !
0
How to remove a component of an object in a script? I want to remove a Sphere Mesh Renderer component from a certain gameobject. I want to do this in a script. How do I do it? I do not want to destroy the sphere itself, just the component
0
On button click wait I have a button I got from google material design asset pack which has a ripple animation when pressed. I'm using the button's click option in the inspector that calls a method that switches scenes. But when I tap the button it switches the scene immediately and feels unnatural since the animation hasn't finished the button ripples animation. I tried using co routines. Made the button call a method in which I call a IEnumerator method (since the button can't directly call a co routine) and then switch the scene. But that doesn't work since it starts the co routine and switches the scene, the co routine never pauses the code and never finishes (probably because I loaded a new scene and the object that carries the script isn't transferred). Code example The method that gets called when I tap a button public void OnButtonTap() StartCoroutine(Wait(0.2f)) SceneManager.LoadScene("OnePlayerGameIntro") The wait coroutine public IEnumerator Wait(float seconds) yield return new WaitForSeconds(seconds)
0
Unity Seamless Terrain I am programmatically generating terrain using unity's terrain object and assigning height maps to it via the terrainData, the problem is that there are seams even when using the GroupingId(which is used for auto connect). I even tried creating a terrain object in the editor with neighbours, and modified their terrain data via script, seams still there. I have also tried SetConnectivityDirty after applying terrainData. Most people who have reported this seemed(lol) to have issues with their normals at the edges, I cant see that being the issue here, but if it is, how do i approach solving it given I am using unity terrains. If there is no good answer I will have to resort to custom meshes and lose all the nice terrain tool functionality. Edit Here is how I'm setting heights. var terrain GameObject.Find("test").GetComponent lt Terrain gt () var terrainData terrain.terrainData var noiseMap Tool Generators.GenerateNoiseMap(chunkSize, seed, scale, octaves, persistance, lacunarity, 0f, 0f) terrainData.SetHeights(0, 0, noiseMap) Then the actual noise generation is just a 2D array of heights, i have been using a simplified version with only 1 pass for testing. public static float , GenerateNoiseMap(int chunkSize, int seed, float scale, int octaves, float persistance, float lacunarity, float offsetX, float offsetY) float , noiseMap new float chunkSize, chunkSize for (int y 0 y lt chunkSize y ) for (int x 0 x lt chunkSize x ) float noiseHeight 0 float sampleX (x offsetX) scale float sampleY (y offsetY) scale noiseHeight Mathf.PerlinNoise(sampleX, sampleY) noiseMap y, x noiseHeight return noiseMap
0
Health zone heals player but I have a problem Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this? Here is the health zone script. public PlayerHealth playerHealth public float healthGain 2f void OnTriggerStay2D(Collider2D other) if (playerHealth.currentHealth lt playerHealth.maxHealth) playerHealth.currentHealth (int)healthGain playerHealth.healthBar.SetHealth(playerHealth.currentHealth) if (playerHealth.currentHealth gt playerHealth.maxHealth) playerHealth.currentHealth playerHealth.maxHealth playerHealth.healthBar.SetHealth(playerHealth.currentHealth)
0
pragma target 3.0 or 3.5? What is gained. What is lost for compatibility with older systems I've just designed an image based layering system shader. Multiple textures with Alphas overlay to create a fully dressed character, using 1 material. pragma target 3.0 is where I had started (suggested default in UnityProjects). After creating so many transparent overlay layers in my code, I got this Shader error in 'Custom Test' Too many texture interpolators would be used for ForwardBase pass (12 out of max 10) The fix seems to be to upgrade to pragma target 3.5 My game is going to be a Steam distributed game, PC only. What do I lose by using pragma target 3.5? Will only super dvanced PCs be compatible? Or should a fairly good average PC be able to run this? I don't know the intricacies of this subject.
0
How can I make a health bar a UI element part of a character prefab? Description I want my character prefabs to come with their own health bar, but I can't simply add one as part of the prefab, because it's a UI element and therefore goes into a Canvas. Potential Solution I could write a script that takes in a separate health bar prefab and instantiates it when the character prefab's instantiated, but it's one extra script. Is there a more conventional way to do this? I'd think this is a common problem.
0
Entity Interpolation (Lost Packets?) I'm working on a networked game for a while. I'm aware of client side prediction and lag compensation (shooting) but I'm not sure about entity interpolation client side. I'm sending update sync packets at 10fps from server and client interpolates from current position to newly received position. Interpolation takes 100ms (because of 10fps) to reach target position but what if new position arrives late or 2 3 packets drop? There will be no target position and sync'd (client side) entity will be idle until new position packet but entity continuously moving forward server side. Basically, I don't know what to do in this situation.
0
Unity Smoothing between two floats which are continuously changing I'm looking for some help with smoothing between an original float and a target float, where the original float is consistently changing (potentially interfering with interpolation techniques and or Mathf.SmoothDamp) I tried Mathf.SmoothDamp with the below (float rocketBoostPower is a global variable) float yVelocity 0.0F float tempForce rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f rocketBoostPower Mathf.SmoothDamp(rocketBoostPower , tempForce, ref yVelocity, 0.5f) This doesn't change the force at all however, it just stays locked in place. I'm currently using the below to change my power, however I want to smoothly change the power instead of just incrementing sharply on each Update frame rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f Please can someone help? I need the assumption that every update will receive a new rocketBoostPower value, whilst still smoothing its previous value.
0
How can I speed up Unity3D Substance texture generation? I'm working on an iOS Android project in Unity3D. We're seeing some incredibly long times for generating substances between testing runs. We can run the game, but once we shut down the playback, Unity begins to re import all off the substances built using Substance Designer. As we've got a lot of these in our game, it's starting to lead to 5 minute delays between testing runs just to test a small change. Any suggestions or parameters we should check that could possibly prevent Unity from needing to regenerate these substances every time? Shouldn't it be caching these things somewhere?
0
Why is there a difference in frame rate between my fps calculation and Unity's calculation So I wrote my own script for calculating framerate but it consistently comes out with a different value than Unitys idea of current framerate. This is my implementation void UpdateFPSStats() double frameTime new double() frameTime Time.deltaTime m times frameIndex frameTime frameIndex if (frameIndex m numberFrames) frameIndex 0 int numberSamples 0 double averageFrameTime 0.0f foreach(double t in m times) numberSamples averageFrameTime t if (numberSamples gt 0) averageFrameTime averageFrameTime numberSamples m frameRate 1 averageFrameTime where m frames is a list of the last 60 frames frame times and UpdateFPSStats is called in Unitys Update(dt) function. On average in my scene my fps calculation gives a steady 50fps, while Unity calculates a steady 80fps. Which is right and why?
0
Enemy clones don't target player In a small game that I'm making enemies multiply when you kill them, however when clones are instantiated they don't chase the player like the original prefabs do (example http gfycat.com VastActualElver) Here is relevant part of my code pragma strict var moveSpeed int 3 var player Transform var MaxDist 10 var MinDist 1 function Update () if(curhealth lt 0) Dead() transform.LookAt(player) if(Vector3.Distance(transform.position, player.position) gt MinDist) transform.position transform.forward moveSpeed Time.deltaTime function Dead () Destroy(gameObject) var posx Random.Range( 10, 10) var posz Random.Range( 10, 10) Instantiate(enemys, Vector3(posx, 0.5, posz), transform.rotation) What am I missing?
0
Admob is load failing by No Fill error I m using official admin plugin for Unity implementing Reward video. But it s only working for test unit id, when I replacing it to my own unit id, it just failing load by error No Fill . Even when I add test device, still happening the issue. How can I fix this?
0
How do I draw lines to a custom inspector? I have a custom editor to which I want to be able to draw a basic line graph. I have much of the functionality down, but I have only been able to test as much via the debug. I am yet to figure out how to draw the actual lines to the inspector. How do I draw lines to a custom inspector? I have found plenty of online resources, in regards to custom drawing to the editor. However, everything I find pertains specifically to drawing in the scene view nothing seems to work inside of an actual inspector. The two general methods I have found involve using Handles.DrawLine and the GL library. Neither appear to work however, I have only been able to test functionality with blind coordinates, so far. I can not find anything in regards to actually determining the local coordinates of the area on the inspector where I wish to draw. Perhaps I need to start with an initial "origin" position, Perhaps I need to start with a local area defined by a Rect. I simply don't know. It has also been a while since I had to use OpenGL, directly. It is entirely possible I am simply doing it wrong, to begin with. Here is my current graph method private void DrawVelocityGraph(float velocityValues, float minimumVelocity, float maximumVelocity) float velocityValue velocityValues 0 float increment 0 Vector3 lineStart Vector3.zero Vector3 lineEnd new Vector3(horizontalIncrement, velocityValue verticalIncrement) GL.Begin(GL.LINES) for(int i 1 i lt velocityValues.Length i ) if(velocityValue velocityValues i amp amp (velocityValue minimumVelocity velocityValue maximumVelocity)) Handles.color VelocityGrapherColours.outOfRangeColour else velocityValue velocityValues i Handles.color VelocityGrapherColours.lineColour lineStart lineEnd lineEnd.x increment lineEnd.y velocityValue verticalIncrement GL.Vertex(lineStart) GL.Vertex(lineEnd) GL.End()
0
Sea is higher than land when importing large real world terrain I am trying to import some real world terrain into Unity with the help of Global Mapper. The data I am using is download from CGIAR SRTM(http srtm.csi.cgiar.org ,http srtm.csi.cgiar.org srtmdata ). The land part works well but I am having trouble with the sea part. This is a larger view of that weird thing in the first image. This strange is actually the sea. This is happening because I am using the gradient shader. Lokks like The sea is represented with white, but when Unity reading the .raw file, the white means the highest part. Does anyone know how to deal with problems like this? Thanks very march.
0
Why do I have to set my Unity app to full screen manually on my phone When I open my unity app it doesn't go full screen until I change it in the settings, isn't there a way to do that... it actually isn't a scaling problem or an aspect ratio.... Because you can see how in the phone settings it is turned off Thanks in advance
0
How to generate mesh at runtime using raycast points? I'm trying to make a clone of the trail line renderer with the difference that everything is perfectly flat, i.e. the faces are not designed to face the camera. I'm using two raycasts to get the position of the edges of where I want those faces but now I'm struggling to generate the mesh...I've gone through the mesh docs but I don't really understand it. Could someone help me do this? Here is my code so far public Transform probes public float probeDistance public Vector3 newVertices public Vector2 newUV public int newTriangles void Update () Generating the mesh Mesh mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh mesh.vertices newVertices mesh.uv newUV mesh.triangles newTriangles Defining the rays Ray l ray new Ray(probes 0 .position, probes 0 .forward probeDistance) Ray r ray new Ray(probes 1 .position, probes 1 .forward probeDistance) RaycastHit l hit RaycastHit r hit Debug.DrawRay(probes 0 .position, probes 0 .forward probeDistance, Color.blue) Debug.DrawRay(probes 1 .position, probes 1 .forward probeDistance, Color.red) Getting the position of the left ray point if(Physics.Raycast(l ray, out l hit)) print (l hit.point) Getting the position of the right ray point if(Physics.Raycast(r ray, out r hit)) print (r hit.point)
0
How to use NGUI with Unity I feel like Im missing something really simple, but Ive read about all the events NGUI can generate from an object and just dont get where to recive (or handle) the event. Do I just attach it to a script on the object?
0
Can I Debug.Log() on Android without all the callstack spam? I get this I Unity ( 1908) Serialized file length 754 bytes. I Unity ( 1908) UnityEngine.Debug Internal Log(Int32, String, Object) I Unity ( 1908) UnityEngine.Debug Log(Object) I Unity ( 1908) SerializeTest Test() (at Z Pong Devel2010 Src UnityGames BhvrDemo BinarySerialization Assets Script SerializeTest.cs 64) I Unity ( 1908) UnityEngine.Events.InvokableCall Invoke(Object ) I Unity ( 1908) UnityEngine.Events.InvokableCallList Invoke(Object ) I Unity ( 1908) UnityEngine.Events.UnityEventBase Invoke(Object ) I Unity ( 1908) UnityEngine.Events.UnityEvent Invoke() I Unity ( 1908) UnityEngine.UI.Button Press() (at C BuildAgent work d63dfc6385190b60 Extensions guisystem guisystem UI Core Button.cs 36) I Unity ( 1908) UnityEngine.UI.Button OnPointerClick(PointerEventData) (at C BuildAgent work d63dfc6385190b60 Extensions guisystem guisystem UI Core Button.cs 45) I Unity ( 1908) UnityEngine.EventSystems.ExecuteEvents Execute(IPointerClickHandler, BaseEventData) (at C BuildAgent work d63dfc6385190b60 Extensions guisystem guisystem EventSystem ExecuteEvents.cs 52) I Unity ( 1908) UnityEngine.EventSystems.ExecuteEvents Execute(GameObject, BaseEventData, EventFunction 1) (at C BuildAgent work d63dfc6385190b6 but I would like this I Unity ( 1908) Serialized file length 754 bytes.
0
Detecting a mouse click While in a Trigger Why does the following code not working? (weird, sometimes it works sometimes not ) I want to move player by touching on the screen and change the color of gameObject when detect trigger and release mouse click. quot Drag and move quot script works correctly I just add following code and sometimes it works sometimes not private void OnTriggerStay2D(Collider2D colider) if (Input.GetMouseButtonUp(0) amp colider ! null) colider.gameObject.GetComponent lt SpriteRenderer gt ().material.color Color.blue There is a full script private Camera cam private Vector3 daragOfset SerializeField private float speed 4.55f private bool isEntered false void Update() if (Input.GetMouseButtonDown(0)) daragOfset transform.position GetMousePos() private void OnTriggerStay2D(Collider2D colider) if (Input.GetMouseButtonUp(0) amp colider ! null) colider.gameObject.GetComponent lt SpriteRenderer gt ().material.color Color.blue void Awake() cam Camera.main void OnMouseDrag() transform.position Vector3.MoveTowards(transform.position, GetMousePos() daragOfset, speed Time.deltaTime) Vector3 GetMousePos() var mousePos cam.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 return mousePos
0
In Unity, what does the camera script's "Behaviour missing" error mean? I started in Unity few days ago and made a cube with a tank control style. Now I'd like to create controls similar to 3D fighting games (Gunz, Blade Symphony, ) Control body direction with the mouse and walk with WASD. However, the Camera is giving me a error called "Behaviour missing" each time I try, with all the cameras scripts I saw. I think that is a error with tagging the character movement in the camera, but I don't know how to do that. What might be the problem?
0
How to make a class diagram and data model of a Unity3D game? I'm developing a 3D platformer video game on Unity3D and I've been asked to present its UML class diagram and data model. If I'm not mistaken Unity uses an entity component system, which necessarily doesn't use heritage. How would a class diagram from a Unity game look like, in that case? Also, I've been taught that usually data model refers to entity relationship models that represent a database. In the case my game doesn't use a database, how could I diagram the way the player's data is store on the game? I'm storing the player progress on a file in the user's computer.
0
Pixel art sprite distortion with 1 1 pixel ratio So I've been studying the Unity's PPU, pixel density, camera settings topic to make my game pixel perfect. I've set everything in a way that my screen pixel to sprite texel ratio equals 1. The art looks very good and crisp overall on the game view... But! There are still some minor distortions and I don't know where it comes from. Take a look at this example In this example my settings are Screen 870x510 PPU 100 Camera size 2.55 Pixel snap on Sprite material on The issue happens when I move the sprite manually by 0.001 values on the Y axis. Same happens on the X axis. Any ideas what's the problem?
0
Unity how to put a target under a character's feet that follows ground model contours? In my current projects, one of the power ups needs to place a target marker centered on the position of the player triggering it the actual design for this is TBC, but will be a circle with a radius of 10 units. The ground for the playing arena is a model, and not flat. Assuming that I use a texture to show this target area, how can I have this texture render following the contours of the ground? Alternatively, any other approach to solving this would be appreciated. Thank!
0
Switch Vector 3 x,y,z Components Based on Rotation I have a cube that moves by rotating on its edge. I want my code to also work for cuboids. The following code is what I'm using to rotate my cube turnPoint transform.position new Vector3(0.5f direction x, 0.5f, 0.5f direction z) Location of edge (resets every 90 degrees) transform.RotateAround(turnPoint, axis, rotateSpeed direction) Turn around the edge It works fine, however I want to get this to work when the cube is scaled to be a cuboid. I tried multiplying the new Vector3's x, y and z components by the objects respective x, y and z scale. This works, but only for the first rotation. Is there a way this could work for all future rotations without using if else for all 4 rotations?
0
How to access Lit shader properties through code? Currently i'm using HDRP in my project, so i have a question. How can i access Lit shader properties through code ? Or where i can see names of variables in this shader ? For example
0
How to simulate car drivetrain (in Unity)? One of my hobby projects involves cars. Up until now I had a quick and dirty "one class" implementation of engine gearbox wheels, but I thought that this is ugly, and I want to go a bit more realistic. Sadly I couldn't find much on Google (either wrong search terms or there really isn't anything that is what I want). It seems like Setup in scene Four wheelcolliders attached to a big boxcollider. Things that I want in the system Separate classes for engine, clutch, gearbox, differential and wheels (and whatever else does stuff with torque). Throttlecontrol with revlimiter (works!), steering (works too!), brakes (not yet made, but also not very complex and will likely work). First thing I tried Mainly this rotates around how I tell the engine that the wheels are actually using or giving (engine braking) power to the system. so first I created all the classes each with their own updatemethod (not called directly by mainloop, but from a fixedupdate of a controllerclass). updatemethod of engine calculates engine torque from throttle, torque curve (animation curve) and engine friction. This is then used to speed up the virtual crankshaft which has its own inertia. But before speeding up the shaft, I decided to put some feedback torques on the engine torque, so if the wheels can't keep up, the engine can't speed up, or even slows down. Such a feedback torque is added for example by the gearbox, which in turn also has feedback forces from the differential and with that the wheels. The wheels calculate the torque needed to spin up to the speed of the shaft coming out of the gearbox and then it propagates all back to the engine over a few updates. Problem was, the torque feedback didn't really do engine braking, but catapulted it to several million RPM in a split second. Dividing the feedback torque by 1000 did work, but then the car didn't move at all. So this is fail number 1. Fail number 2 Okay screw this, I thought, and tidied up all the stuff. This doesn't use several updatemethod anymore, but recursive updating. Basically I call update on the engine, which in turn then calculates what torque it has available. With that it tells the transmission that it has t torques at r RPMs. The gearbox changes the values according to the current gear and then again puts the values into the differential. The differential SHOULD split the torque between its outputs. To do this I calculate how much torque the output (in this case wheels) would need to speed up to r RPMs. I do this for each output and make a list of it for each output. I also save the sum of these values. With this I can get a value of 0...1 for each output, that determines how much torque each output gets in its updatemethod. Its basically an intelligent differential that gives the output which needs more torque, more torque. I guess modeling a real differential would involve some more complex stuff. Now the torque is at the wheels and gets put into the motorTorque property of the wheelcollider. Up until here it works. If I throttle up and then let go of it the wheels start turning backwards. It's basically another feedbackloop just like with the first try. So also fail And fail 3 Instead of returning the torque that's left, I tried backpropagating the RPMs to the engine instead. So I apply torque, and get RPMs back. But again everything tries to move the car in the opposite direction that I want it to go. Here is where I'm out of ideas. I want a relatively realistic drivetrain, that is modular and can do enginebraking. A bought asset will most probably not solve my problem, and I also want to understand how it works, and not just use it. Does anybody have experience with how to properly model a drivetrain? If I forgot to mention something, please ask.
0
How should asset bundles be divided? The only way to load an asset from an asset bundle into memory is to load the entire thing, decompress and pull out the asset you want, then unload the entire thing, except the assets you want. This seems impractical for sharing assets between bundles. For example, if asset bundle A wants a single asset from asset bundle B, it must load all of B, pull out the asset, then destroy B. The alternative to this is to extract the shared assets and create a new bundle call asset bundle C. The problem with this is that B must have been designed this way before being built, which it won't be if it was built before A (it has to be since A depends on B). Using the resources folder results in a huge blob of bytes that, from what I understand, cannot be changed after build, and is certainly not differ able for patches. Putting the pros of asset bundles and the resource folder together, I figure that having an asset bundle for every asset is the best of both worlds. Is there problems with this? Is my understanding of asset bundles or the resource folder flawed?
0
Asset opening wrong unity version I'm trying to open one of my assets in unity via my browser, but when I click open in unity it opens the 2017 version, when I want to add it to my newest one. How do i get this to work? (I need the 2017 version, so deleting it is not an option.)
0
Making only one side of a object receive light in Unity So I want to achieve a visial asthetic in my game that looks like this Meaning I dont want the outer parts of my dungeon walls to be affected by light. Now I know this is posible if the object itslef is created with 2 materials that way I can make the back material solid black. But I was wondering if there is a easy way to achieve this with a shader.
0
Unity Record real time game play in high quality using offline rendering? I'm looking to record Unity gameplay at really high quality (360 Stereo 8k 120 fps). I can't do this in real time due to the GPU resources required so I need to do offline rendering (frame perfect rendering). The problem is offline rendering by its nature doesn't accept user input, so I can't record live gameplay footage. I'm looking for a solution that lets me record live gameplay and then render it out at this higher quality. I considered recording the user input or the gameobjects properties and then playing them back while rendering the footage. I tried a number of assets like Ultimate Replay 2.0, Record and Play, GameObject Recorder, even tried Unity Recorder to an animation but none of them record all of the changes to components on a gameobject. I think I'll have to write my own code, although I'm not sure what the best method would be, I'm reluctant to sink to much development time into this if there's an easier solution that I've overlooked? Initially I'm looking for a solution that works inside the Unity editor but would love to be able to give this ability to end users.
0
Unity3d Delay between animation cycles trying to create simple 360 rotation animation on 2d object but can't understand delay between animation cycles, please check youtube video with issue https www.youtube.com watch?v JlLJLHvnkgo
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
How can I launch Visual Studio via a double click on a C script in Unity? This is my first time using Unity and I am following the tutorial for the 2D RogueLike Game. Everythings seems to be working properly, apart that I cant get Visual Studio to launch, if I'm double click my c scripts. What I have tried so far Checked my preferences, that External Script Editor says "Visual Studio 2017" Reinstalled Unity and Visual Studio. Unity Version 2019.3.0a2 Personal Hope somebody can help me. Additional information After double click, nothing seems to be happening, even my mouse doesnt show a load icon When I create a new project, the bug (dont know if bug, or my fault) is still there. I can open the .sln file from my project in Visual Studio. Visual Studio can even autocomplete unity based code then, before it was a "miscellaneous file" and didnt autocomplete code like for example "Transform" or "Rigidbody2D".
0
What's a simple way to send statistics from my game back to me? For example, I set up my game to keep track of how many times people play x, y, and z game modes, and also to keep track of how often players reach a certain point. What's a simple way to send this data to me so that I can see it?
0
Camera Movement Snap Camera back to origin in relation to the player object I am trying to implement camera movement like it is done in Guild Wars 2. Scenario is when A and D keys are pressed, the player rotates right left and the camera follows and stays behind the character player like this (Starts at 23 seconds) https www.youtube.com watch?v XkHJ2uSrLjE I can get the basic working fine, and I did it this way private void KeysRotateCameraAndPlayer() float keysOrbitingSpeed 120 this.player GameObject.FindWithTag("Player").transform if (Input.GetKey(KeyCode.A)) Debug.Log("Rotate Left") CenterPoint.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) player.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) else if (Input.GetKey(KeyCode.D)) Debug.Log("Rotate Right") CenterPoint.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) player.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) Now the next part I am trying to achieve , when the camera is rotated orbited around the player using the mouse and is left in a position that is not the origin i.e behind the player (in relation to player) when A and D keys are pressed, what happens in GW2 is the camera seems to snap back to the origin and then continue to follow the player from the back ( or its relation origin with regards to the player Object if that makes sense) This is what the game does (which I hope to achieve) https www.youtube.com watch?v qTTDaeuHl80 so at present moment with my current code https www.youtube.com watch?v a53lZ 0BDtg camera and player will continue to rotate (with A and D), from where the camera was last left during orbit. How can I add to this, to force the camera to snap back to origin like they have in Guild Wars 2?
0
unity3d Fire bullet using AddForce is very slow This is a top down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel. void Fire () float speed 80 GameObject projectile Instantiate (bullet, transform.position, transform.rotation) as GameObject projectile.GetComponent lt Rigidbody gt ().AddForce(transform.forward speed) coolDown Time.time I also tried this but in this case the bullet always moves in a fixed direction (North) projectile.GetComponent lt Rigidbody gt ().velocity Vector3.forward speed Bullet is an empty object and the actual bullet is it's child ( did that to overcome a rotation issue ), the problem is nomatter how high I turn up the speed the bullet travels very very slow. Both the parent and the bullet have Rigidbody.
0
Unity build shows wrong date I made a 3D game in Unity named Sniper Shot. I am facing a problem when I build the project at the end it shows the wrong date of build. I have tried many scripts resolving this issue but I did not find any accurate way to fix it. I completed this project on 4 march 2019 but this is showing me a wrong date, 23 July 2017.
0
How to use TensorFlow in Unity I am trying to implement a deep reinforcement learning IA with TensorFlow for a checker game in Unity. How can I do this? I've searched for it on Google and found a lot of videos and tutorials on how to use machine learning agents with Unity, and other people who explain how to import a TensorFlow trained neural network in Unity, but I didn't see anything related to using directly TensorFlow in Unity to create (and train) neural networks. If someone knows another package to create CNNs with C , I am interested.
0
How to obtain a camera stream from Unity without rendering it to the player's screen? I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen? One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player.
0
Why does this code not update my object's position? I am trying to move the object in my frame in Time.deltaTime. I have not taken care the speed yet but the problem is, the object is almost at position (0,0) after I have multiplied the x amp y axis with Time.deltaTime. I want it to appear randomly on the screen in a given range. The update function is given below function Update () var x Random.Range( 4.37,4.34) Time.deltaTime var y Random.Range(4.45, 4.66) Time.deltaTime var velocity Vector3(x, y, 0) transform.position velocity
0
In Unity, How to format Old RPCs into new "PunRPCs" In older unity versions you could simply used RPC. With newer verisons of Unity my code now doesn't work and it says that it needs to be transformed into "PunRPC" , Pun being "Photon Unity Networking." I am not sure how to reformat it to work with current unity versions. Can anyone shed light on this? My Code FXManager.cs 1 using UnityEngine 2 using System.Collections 3 4 public class FXManager MonoBehaviour 5 6 RPC 7 void SniperBulletFX( Vector3 startPos, Vector3 endPos ) 8 Debug.Log ("SniperBulletFX") 9 10 11 PlayerShooting.cs 1 using UnityEngine 2 using System.Collections 3 4 public class PlayerShooting MonoBehaviour 5 6 public float fireRate 0.5f 7 float cooldown 0 8 public float damage 25f 9 FXManager fxManager 10 11 void Start() 12 fxManager GameObject.FindObjectOfType lt FXManager gt () 13 14 if(fxManager null) 15 Debug.LogError("Couldn't find a FXManger.") 16 17 18 19 20 Update is called once per frame 21 void Update () 22 cooldown Time.deltaTime 23 24 if (Input.GetButton ("Fire1")) 25 Player wants to shoot...so. Shoot. 26 Fire () 27 28 29 30 void Fire() 31 32 if (cooldown gt 0) 33 return 34 35 36 Debug.Log ("Firing our gun") 37 38 Ray ray new Ray (Camera.main.transform.position, Camera.main.transform.forward) 39 Transform hitTransform 40 Vector3 hitPoint 41 42 hitTransform FindClosestHitObject (ray, out hitPoint) 43 44 if (hitTransform ! null) 45 Debug.Log ("We hit " hitTransform.name) 46 47 We could do a special effect at the hit location 48 DoRicochetEffectAt (hitPoint) 49 50 Health h hitTransform.GetComponent lt Health gt () 51 52 while (h null amp amp hitTransform.parent) 53 hitTransform hitTransform.parent 54 h hitTransform.GetComponent lt Health gt () 55 56 57 Once we reach here, hitTransform may not be the hitTransform we started with! 58 59 if (h ! null) 60 This next line is the equivalent of calling 61 h.takeDamage( damage) 62 Except more "networky" 63 PhotonView pv h.GetComponent lt PhotonView gt () 64 if (pv null) 65 Debug.LogError ("Freak out!") 66 else 67 h.GetComponent lt PhotonView gt ().RPC ("TakeDamage", PhotonTargets.AllBuffered, damage) 68 69 70 71 if (fxManager ! null) 72 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 73 74 75 else 76 We didn't hit anything (except empty space), but let's do a visual FX anyway 77 if (fxManager ! null) 78 hitPoint Camera.main.transform.position (Camera.main.transform.forward 100f) 79 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 80 81 82 83 cooldown fireRate 84 If anymore information is needed, please let me know, I would love to figure out how the new "PunRPC(Photon Unity Neworking)" works so I can use it in future projects. Edit This is the error I get "PhotonView with ID 2 has no method "SniperBulletFx" marked with the PunRPC or PunRPC(JS) property! Args Vector3, Vector3 UnityEngine.Debug LogError(Object)"
0
Accesing child GameObjects of GameObject I have already tried really much with all "GetChildren" and similar functions, but I haven't found out how to do it yet. I have a GameObject named "koffer". I have added several other GameObjects as children to it. I have added a script to "koffer" in which I try to retrieve the children. In this script I have stated this line string sThis this.name just for testing. "sThis" becomes "koffer", so it looks perfectly fine. foreach (GameObject g in this.GetComponentsInChildren lt GameObject gt ()) doesn't retrieve anything. So obviously I'm not doing it correctly. However this doesn't retrieve anything. Is this not the correct function for such a case? Is there any built in function to retrieve theses game obects? I have found several custom made functions from some years ago, and I don't know if they are still needed or if Unity has integrated some functions for that. What really bothers me is that there are so many custom made functions that deal with "Transform" instead of "GameObject". Why would somebody need Transform instead of GameObject? Thank you.
0
How to properly interact with game objects in Unity3D? I am trying to make a game where player will be placed in the scene and the goal is to explore it. He can interact with game objects that player can find in the environment, like picking object, examining, dropping and putting back. Basically it is something like first person exploration... So the problem is how to properly implement code regarding interaction. One way I see and saw it on the internet is Raycasting. So the idea would be to in Update() method place Raycast fire code and see what it hits. Also all game objects with which player can interact are placed on separate Layer and also limit length of Raycast (which is obvious thing to do as player cannot interact with objects that are like 10 meters from him)... So as I understand, game objects should have at least some kind of collider (I know box and sphere colliders are simple, but sometimes I will need to use more complex one)... That being said, I wonder is this right approach Separate layer for interactable objects Raycast that checks objects in that layer Raycast length limited to like 1 meter This approach should not be that much CPU consuming or is there any other way? I am also thinking to putting some invisible box area (trigger) where raycasting would make sense, but I am not sure will this be overhead or not.... So, at the end what would be the right approach to this?
0
Detect collisions for each instantiated objects I want to instantiate cube at a random position when I click mouse and do something (change color or freeze position ..) for each cube when detect collision on the plane. I tried first few steps public Rigidbody cube void OnCollisionEnter(Collision collision) if (collision.gameObject.name quot Plane quot ) Do somthing for each cube cube.constraints RigidbodyConstraints.FreezePositionY void Update() Vector3 position new Vector3(Random.Range( 5f, 5f), 8,Random.Range( 5, 5)) if (Input.GetMouseButtonDown(0)) Rigidbody clone clone Instantiate(cube,position, Quaternion.identity)
0
A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.Variable' engine unity coding language c I am trying to control CinemachineFreeLook maxSpeed from another script in the struct AxisStat public AxisState(float minValue, float maxValue, bool wrap, bool rangeLocked, float maxSpeed, float accelTime, float decelTime, string name, bool invert) It only accepts to type a number, but not a variable. Whenever I create a public float variable and place it in maxSpeed, it keeps sending the error error CS0236 A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.rSpeed' Here is the default unity CinemachineFreeLook script code the added code which I declare a float variable quot rSpeed quot at the beginning and added my variable in the AxisStat maxSpeed public class CinemachineFreeLook CinemachineVirtualCameraBase public float rSpeed 300f lt summary gt Object for the camera children to look at (the aim target) lt summary gt Tooltip( quot Object for the camera children to look at (the aim target). quot ) NoSaveDuringPlay public Transform m LookAt null lt summary gt Object for the camera children wants to move with (the body target) lt summary gt Tooltip( quot Object for the camera children wants to move with (the body target). quot ) NoSaveDuringPlay public Transform m Follow null lt summary gt If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used lt summary gt Tooltip( quot If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used quot ) FormerlySerializedAs( quot m UseCommonLensSetting quot ) public bool m CommonLens true lt summary gt Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active lt summary gt FormerlySerializedAs( quot m LensAttributes quot ) Tooltip( quot Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active quot ) LensSettingsProperty public LensSettings m Lens LensSettings.Default lt summary gt Collection of parameters that influence how this virtual camera transitions from other virtual cameras lt summary gt public TransitionParams m Transitions lt summary gt Legacy support lt summary gt SerializeField HideInInspector FormerlySerializedAs( quot m BlendHint quot ) FormerlySerializedAs( quot m PositionBlending quot ) private BlendHint m LegacyBlendHint lt summary gt The Vertical axis. Value is 0..1. Chooses how to blend the child rigs lt summary gt Header( quot Axis Control quot ) Tooltip( quot The Vertical axis. Value is 0..1. Chooses how to blend the child rigs quot ) AxisStateProperty public AxisState m YAxis new AxisState(0, 1, false, true, 2f, 0.2f, 0.1f, quot Mouse Y quot , false) lt summary gt Controls how automatic recentering of the Y axis is accomplished lt summary gt Tooltip( quot Controls how automatic recentering of the Y axis is accomplished quot ) public AxisState.Recentering m YAxisRecentering new AxisState.Recentering(false, 1, 2) lt summary gt The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component lt summary gt Tooltip( quot The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component quot ) AxisStateProperty public AxisState m XAxis new AxisState( 180, 180, true, false, rSpeed, 0.1f, 0.1f, quot Mouse X quot , true)
0
How can I set up a 3D camera for a top down game like Enter the Gungeon? DodgeRollGames, the developers of Enter the Gungeon, tweeted that the game was in fact made in 3D They tried to explain how they set their camera in this reddit post. Basically what they said was so the walls are tilted 45 degrees toward the camera, and the floors are tilted 45 degrees away from the camera, meaning that each should experience sqrt(2) distortion because of the additional length along the z axis. However, the vertical (y axis) floor length shouldn't be perceptually changed. The camera is not tilted at all. Camera 0 degree tilt. Walls 45 degrees tilt. Floor 45 degrees tilt. My question is What do they mean by quot However, the vertical (y axis) floor length shouldn't be perceptually changed quot . If I tilt the walls and floors by 45 degrees and 45 degrees as said, the sqrt(2) distorted walls (the walls have Z depth and are perpendicular to the ground) line up nicely, but the ground gets distorted (obviously). So I distort the ground tiles by sqrt(2) but this essentially stretches the ground by 40 so every vertical movement now has to be increased by 40 . Can somebody explain what's going on? Any help would be highly appreciated.
0
Why do asymmetric specular highlights appear in a scene with only ambient lighting in Unity? I have a scene in Unity (2019.3.0f3 Personal) using the High Definition Render Pipeline. There are no lights in the scene, and Baked Global Illumination is disabled. The skybox is a GradientSky. By all means, the lighting in the scene should be absolutely uniform, but instead there is a gradient from one side to the other. This is what the scene looks like Though the effect is faint, you can see that the right side of the plane is slightly lighter than the left. The ground shader is HDRP TesselationLit, and by bringing the Smoothness Remapping to max I can exaggerate this effect, as shown below. This is why I am under the impression the effect is specular in nature. Interestingly, if I switch the camera to the Isometric mode, the effect disappears Finally, the effect appears to occur in world rather than camera space, as shown by the changes in lighting when I rotate my camera in increments of 90 degrees What is causing this effect, and how can I disable it?
0
How do I draw individual pixels in the distance? Hello everyone I am working with unity3d and I am faced with a task. I have a list of 3D points and I want to draw a pixel for every point on the list that exists after my cameras frustums far plane. After I draw each of the pixels I would like to add a few simple effects to them. Sorry for the terminology I am new to unity! Any help is much appreciated.
0
How can I efficiently make a solid Texture2D? I am trying to programmatically make an Image to cover the entire screen. I create the Texture2D, then create a Sprite from the Texture2D, then apply the Sprite to my Image. This works, but it is slow. I suspect the issue is that I am setting each pixel individually for my Texture2D private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(Screen.width, Screen.height) for (int y 0 y lt texture.height y ) for (int x 0 x lt texture.width x ) texture.SetPixel(x, y, color) texture.Apply() return texture I have tried creating the Texture2D by resizing a Texture2D of a single pixel, but the color comes out as a translucent white, instead of the color passed private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(1, 1) texture.SetPixel(0, 0, color) texture.Resize(Screen.width, Screen.height) texture.Apply() return texture Why doesn't my second approach work? How can I efficiently create a screen sized Texture2D of a solid color?
0
How can I iterate over all entities with a particular component? I'm currently designing a game engine and want to implement my own ECS implementation, so I decided to look around for ideas. Unity has recently updated their engine and seems to be pushing towards using ECS, instead of their original components are systems design. I noticed that Unity has a method called "GetEntities", a generic method which can do something like this public struct SomeComponent IEntityComponent public string Message "Hello, World!" public struct Filter SomeComponent someComponent public MovementSystem EntitySystem public override Process() How can I accomplish something like this? foreach(var entity in GetEntities lt Filter gt ()) Console.WriteLine(entity.someComponent.Message) I like this style of iterating over entities, given a filter for a specific component they need to include. But I'm not sure how to accomplish something like this. If someone could shed some light on how something like this is even possible in C that would be great!
0
Why does WorldToScreenPoint return "strange" results? I would like to show a menu to the right side and at the same y coordinate as a certain gameobject (shown as a green cube in the screenshot). Therefore I'm trying to get the screen coordinates of the object in my scene using WorldToScreenPoint. The code I'm using is this Vector3 nPos new Vector3(GlowCube.position.x GlowCube.localScale.x, GlowCube.position.y, GlowCube.position.z) Vector3 nOff Camera.main.WorldToScreenPoint(nPos) The resulting values however don't look right to me. I have created a red rectangle in order to demonstrate where the coordinates "nOff" would actually be in the screen At first I thought I get these strange results because the GlowCube is parented to the case, but since I use GlowCube's world coordinates (GlowCube.postion...) and not its local coordinates (GlowCube.localPosition...), I thought that this wouldn't matter. What am I forgetting here? Thank you!
0
UNITY Huge amount of GRAPHICS in RTS Tiled game after year of development and week of unsuccessful optimization I turn for a help from you, guys. So, my game is turn based strategy with hexagon map. One hexagon consists of one texture for hexagon tile type and seven subtiles, which carry spriterenderer with graphics like piece of town. So if soldier steps on the subtile, the graphics of subtile hide. On good machines like mine, if I zoom out maximally (45 orthographic size) on 1920x1080 and have visible around 18x16 tiles I get solid 160 200 FPS at MAX details, but on my laptop I barely get 25FPS on 1280x720 and LOW details. Each tile has resolution of 636x499. I have tried Simple shader on SpriteRenderer supporting transparency, just merging texture with color (This had those best results of 160 250FPS at HIGH END and 25FPS on LOW END) Creating separate material for each subtile and replacing SpriteRenderer with Quad mesh, so those subtiles are statically batched or GPU batched (but I guess they did not batch at all, because frame debugger showed that sometimes more fo the same pieces got rendered and then sometimes just one) So this is just the 50x50 game, when I start large map, like 120x100, it's not really that worse, so I think the problem is just in the graphics and not in the amount of objects. What are your suggestions I should try to get better performance on LOW END devices? Do you think that manual GPU instancing would make it faster? I think, there would be a lot of trouble maintaining which graphic to render and which not.